From 77587de2e66de561029bfb094300244c30511ee4 Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:08:46 +0000 Subject: [PATCH] feat(athena): support named queries (#8002) Closes #8000 Workgroup deletion bypassed saved-query storage and ignored RecursiveDeleteOption. Reject non-recursive deletion when saved queries exist, and remove saved queries and retry records before deleting the workgroup. Serialize deletion with named-query creation to prevent orphaned records. Vendor all Athena input constraints from pinned botocore and check requests through RequestConstraintCheck. Remove copied named-query bounds and type checks, allow creation without a client request token, and share workgroup scans and isolated test-client setup. Update required-field expectations and cover generation drift, nested constraints, Unicode bounds, and untokened creation. Move the standard member-constraint Messages implementation and formatter into RequestConstraintCheck, parameterized by error code. Migrate Athena, ECR, and both Payment Cryptography APIs and remove the redundant PaymentCryptographyShapeErrors class. Preserve HTTP 400, existing rule wording, operation-prefix removal, nested list paths, and each service error code with shared contract and service tests. --- Makefile | 7 + docs/services/athena.md | 45 +- docs/services/index.md | 2 +- .../core/common/RequestConstraintCheck.java | 45 + .../services/athena/AthenaJsonHandler.java | 56 +- .../athena/AthenaNamedQueryService.java | 136 ++ .../services/athena/AthenaRequestShapes.java | 21 + .../aws/services/athena/AthenaService.java | 2 +- .../aws/services/athena/model/NamedQuery.java | 14 + .../aws/services/ecr/EcrRequestShapes.java | 41 +- .../PaymentCryptographyDataRequestShapes.java | 2 +- .../PaymentCryptographyRequestShapes.java | 2 +- .../PaymentCryptographyShapeErrors.java | 59 - .../resources/aws/athena-request-shapes.json | 1552 +++++++++++++++++ .../common/RequestConstraintCheckTest.java | 42 + ...teWorkGroupPersistenceIntegrationTest.java | 14 +- .../AthenaDataCatalogIntegrationTest.java | 7 +- .../AthenaGetWorkGroupIntegrationTest.java | 7 +- .../athena/AthenaIntegrationTest.java | 8 +- .../AthenaNamedQueryIntegrationTest.java | 379 ++++ .../athena/AthenaNamedQueryServiceTest.java | 81 + .../athena/AthenaRequestShapesTest.java | 72 + ...estResourceEnforcementIntegrationTest.java | 22 +- tools/aws/regen_athena_shapes.py | 28 + tools/aws/request_shapes.py | 6 + tools/aws/test_request_shapes.py | 27 + 26 files changed, 2533 insertions(+), 144 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java create mode 100644 src/main/java/io/floci/aws/services/athena/AthenaRequestShapes.java create mode 100644 src/main/java/io/floci/aws/services/athena/model/NamedQuery.java delete mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyShapeErrors.java create mode 100644 src/main/resources/aws/athena-request-shapes.json create mode 100644 src/test/java/io/floci/aws/services/athena/AthenaNamedQueryIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/athena/AthenaNamedQueryServiceTest.java create mode 100644 src/test/java/io/floci/aws/services/athena/AthenaRequestShapesTest.java create mode 100644 tools/aws/regen_athena_shapes.py diff --git a/Makefile b/Makefile index 2c7302c07d..28861b3da0 100644 --- a/Makefile +++ b/Makefile @@ -25,6 +25,8 @@ # by tools/aws/regen_ecs_shapes.py. # src/main/resources/aws/ecr-request-shapes.json, the ECR request constraints, is generated # from botocore's ECR model by tools/aws/regen_ecr_shapes.py. +# Athena request constraints for every operation are generated from botocore's Athena model +# by tools/aws/regen_athena_shapes.py. # src/main/resources/aws/payment-cryptography-request-shapes.json, the Payment Cryptography # request constraints, is generated from botocore's model by # tools/aws/regen_payment_cryptography_shapes.py. @@ -279,6 +281,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s $(PYTHON) tools/aws/regen_resource_groups_shapes.py $(PYTHON) tools/aws/regen_logs_delivery_shapes.py $(PYTHON) tools/aws/regen_ecr_shapes.py + $(PYTHON) tools/aws/regen_athena_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_shapes.py $(PYTHON) tools/aws/regen_payment_cryptography_data_shapes.py $(PYTHON) tools/aws/regen_securityhub_shapes.py @@ -371,6 +374,10 @@ 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_athena_shapes.py --check || { \ + echo "error: Athena request shapes are out of date; run 'make aws-data-sync'."; \ + exit 1; \ + } @$(PYTHON) tools/aws/regen_payment_cryptography_shapes.py --check || { \ echo ""; \ echo "error: src/main/resources/aws/payment-cryptography-request-shapes.json is out of date."; \ diff --git a/docs/services/athena.md b/docs/services/athena.md index 5d7d55e19f..964c207096 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -10,6 +10,12 @@ Floci emulates Amazon Athena with **real SQL execution** powered by a [floci-duc | Action | Description | | --- | --- | +| `CreateNamedQuery` | Saves SQL text in a workgroup and returns its ID | +| `GetNamedQuery` | Returns a saved query's name, database, SQL text, description and workgroup | +| `BatchGetNamedQuery` | Returns up to 50 saved queries and per-ID errors for missing queries | +| `ListNamedQueries` | Lists saved query IDs in a workgroup with pagination | +| `UpdateNamedQuery` | Updates a saved query's name, SQL text and description | +| `DeleteNamedQuery` | Deletes a saved query | | `StartQueryExecution` | Submits a SQL query; executed asynchronously via DuckDB | | `GetQueryExecution` | Returns query status (`QUEUED`, `RUNNING`, `SUCCEEDED`, `FAILED`) | | `GetQueryResults` | Returns the result set for a completed query | @@ -33,11 +39,46 @@ Floci emulates Amazon Athena with **real SQL execution** powered by a [floci-duc | `DeleteWorkGroup` | Deletes a workgroup | +Named queries store SQL text without executing it or requiring the database to +exist. `CreateNamedQuery` defaults to the `primary` workgroup; a named workgroup +must already exist. `ClientRequestToken` is optional; requests without a token +create a new query each time. The AWS SDK and CLI supply a token automatically. +When supplied, it must contain 32 to 128 characters. Retrying the same token returns +the original ID, while changing its creation parameters returns +`InvalidRequestException`. Saved queries and retry requests use Athena's configured +storage mode and are isolated by account and region. + +Every request is checked by `RequestConstraintCheck` against the types, required +members, bounds, patterns and enums generated from botocore's Athena service model. +`tools/aws/regen_athena_shapes.py` vendors every operation's input constraints; +`make aws-data-sync` regenerates them and `make aws-data-check` checks for drift. + +`UpdateNamedQuery` changes the name, SQL text, and optionally the description; +the database and workgroup stay fixed. Omitting the description preserves it, +and an empty description clears it. A missing query returns +`InvalidRequestException` from get or update; batch get reports it under +`UnprocessedNamedQueryIds`. Deleting an absent query succeeds. + +`DeleteWorkGroup` rejects a workgroup containing saved queries unless +`RecursiveDeleteOption` is `true`. Recursive deletion removes the group's saved +queries and creation retry records in the caller's account and region before +removing the workgroup. Recreating the same workgroup name starts with no saved +queries. The `primary` workgroup cannot be deleted. + +`ListNamedQueries` defaults to `primary` and returns IDs in deterministic order. +`MaxResults` accepts 0 to 50; Floci uses 50 when it is omitted, null, or zero, +matching its `ListQueryExecutions` convention because AWS documents neither a +default nor the behavior of zero. Pass the opaque `NextToken` to continue; final +pages omit it. Tokens are scoped to the action, account, region, and workgroup, +and remain resumable after a cursor query is deleted. Invalid sizes or tokens +return `InvalidRequestException`. + `ListDataCatalogs` accepts `MaxResults` from 2 to 50. Floci uses 50 when it is omitted, since the API reference does not document a default. The built-in `AwsDataCatalog` stays first, followed by registered catalogs in name order. -`GetDataCatalog`, `ListDatabases`, `ListTableMetadata` and `GetTableMetadata` -read `AwsDataCatalog` when the request names no catalog or a JSON null. +`GetDataCatalog` requires `Name`; `ListDatabases`, `ListTableMetadata` and +`GetTableMetadata` require `CatalogName`. Name `AwsDataCatalog` explicitly to +read the built-in catalog. Pass the opaque `NextToken` to continue; final pages omit it. Tokens are scoped to the action, caller account, and request region and remain resumable after a cursor catalog is deleted. Malformed tokens, tokens outside the 1-to-1024 diff --git a/docs/services/index.md b/docs/services/index.md index 111dca1a0d..2ff3fa78d9 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -74,7 +74,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 | | [Amazon MQ](amazonmq.md) | `/v1/brokers/...` + RabbitMQ broker | REST JSON + AMQP | 5 | | [MWAA](mwaa.md) | `/` REST paths for environments + CLI/web proxy | REST JSON | 10 | -| [Athena](athena.md) | `POST /` + `X-Amz-Target: AmazonAthena.*` | JSON 1.1 | 21 | +| [Athena](athena.md) | `POST /` + `X-Amz-Target: AmazonAthena.*` | JSON 1.1 | 27 | | [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 135 | | [Lake Formation](lakeformation.md) | `POST /` | REST JSON | 16 | | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | diff --git a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java index 19f5e7e8bf..16e22ace8a 100644 --- a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java +++ b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java @@ -42,6 +42,46 @@ public final class RequestConstraintCheck { AwsException required(String path); } + /** Standard member-constraint messages, using the service's error code and HTTP 400. */ + public static Messages standardMessages(String errorCode) { + return new Messages() { + @Override + public AwsException type(String path, String type) { + return invalid(path, "Member must be a " + type); + } + + @Override + public AwsException bounds(String path, String type, Long min, Long max, long size) { + String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length"; + return min != null && size < min + ? invalid(path, "Member must have " + measure + " greater than or equal to " + min) + : invalid(path, "Member must have " + measure + " less than or equal to " + max); + } + + @Override + public AwsException pattern(String path, String pattern) { + return invalid(path, "must satisfy regular expression '" + pattern + "'"); + } + + @Override + public AwsException enumValue(String path, List values) { + return invalid(path, "Member must satisfy enum value set: " + values); + } + + @Override + public AwsException required(String path) { + return invalid(path, "Member must not be null"); + } + + private AwsException invalid(String path, String rule) { + int dot = path.indexOf('.'); + String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", ""); + return new AwsException(errorCode, + "Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400); + } + }; + } + private final JsonNode model; private final Map patterns = new HashMap<>(); private final Messages messages; @@ -66,6 +106,11 @@ public final class RequestConstraintCheck { return new RequestConstraintCheck(model, messages); } + /** Whether the vendored model declares an input for {@code operation}. */ + public boolean hasOperation(String operation) { + return model.path("operations").has(operation); + } + /** Checks {@code request}, the body of {@code operation}, against the operation's input shape. */ public void check(String operation, JsonNode request) { checkValue(model.path("operations").path(operation).asText(), request, operation); diff --git a/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java b/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java index 697c21977b..6c486c10b3 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java @@ -6,6 +6,7 @@ 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.athena.model.CreateWorkGroupRequest; +import io.floci.aws.services.athena.model.NamedQuery; import io.floci.aws.services.athena.model.QueryExecution; import io.floci.aws.services.athena.model.QueryExecutionContext; import io.floci.aws.services.athena.model.ResultConfiguration; @@ -25,16 +26,59 @@ import java.util.Map; public class AthenaJsonHandler { private final AthenaService athenaService; + private final AthenaNamedQueryService namedQueryService; private final ObjectMapper mapper; @Inject - public AthenaJsonHandler(AthenaService athenaService, ObjectMapper mapper) { + public AthenaJsonHandler(AthenaService athenaService, AthenaNamedQueryService namedQueryService, + ObjectMapper mapper) { this.athenaService = athenaService; + this.namedQueryService = namedQueryService; this.mapper = mapper; } public Response handle(String action, JsonNode request, String region) throws Exception { + AthenaRequestShapes.check(action, request); return switch (action) { + case "CreateNamedQuery" -> { + String id = namedQueryService.createNamedQuery(region, text(request, "Name"), + text(request, "Database"), text(request, "QueryString"), + text(request, "Description"), text(request, "WorkGroup"), + text(request, "ClientRequestToken")); + yield Response.ok(Map.of("NamedQueryId", id)).build(); + } + case "GetNamedQuery" -> Response.ok(Map.of("NamedQuery", + namedQueryService.getNamedQuery(region, text(request, "NamedQueryId")))).build(); + case "BatchGetNamedQuery" -> { + JsonNode ids = request.get("NamedQueryIds"); + List queryIds = new ArrayList<>(); + for (JsonNode id : ids) { + queryIds.add(id.textValue()); + } + yield Response.ok(namedQueryService.batchGetNamedQuery(region, queryIds)).build(); + } + case "ListNamedQueries" -> { + PaginatedResult page = namedQueryService.listNamedQueries(region, + text(request, "WorkGroup"), + Pagination.parseMaxResults(request, "MaxResults", "InvalidRequestException"), + Pagination.parseNextToken(request, "NextToken", "InvalidRequestException")); + Map response = new LinkedHashMap<>(); + response.put("NamedQueryIds", page.items().stream().map(NamedQuery::namedQueryId).toList()); + if (page.nextToken() != null) { + response.put("NextToken", page.nextToken()); + } + yield Response.ok(response).build(); + } + case "UpdateNamedQuery" -> { + namedQueryService.updateNamedQuery(region, text(request, "NamedQueryId"), + text(request, "Name"), text(request, "QueryString"), + text(request, "Description")); + yield Response.ok().build(); + } + case "DeleteNamedQuery" -> { + namedQueryService.deleteNamedQuery(region, text(request, "NamedQueryId")); + yield Response.ok().build(); + } case "StartQueryExecution" -> { String query = request.get("QueryString").asText(); String named = text(request, "WorkGroup"); @@ -173,14 +217,8 @@ public class AthenaJsonHandler { yield Response.ok(Map.of("Tags", athenaService.listTagsForResource(resourceArn))).build(); } case "DeleteWorkGroup" -> { - String wg = request.path("WorkGroup").asText(null); - if (wg == null || !wg.matches("[a-zA-Z0-9._-]{1,128}")) { - throw new AwsException("InvalidRequestException", "WorkGroup is required.", 400); - } - if ("primary".equals(wg)) { - throw new AwsException("InvalidRequestException", "The primary workgroup cannot be deleted.", 400); - } - athenaService.deleteWorkGroup(wg, region); + String wg = text(request, "WorkGroup"); + namedQueryService.deleteWorkGroup(region, wg, request.path("RecursiveDeleteOption").asBoolean(false)); yield Response.ok(Map.of()).build(); } default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400); diff --git a/src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java b/src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java new file mode 100644 index 0000000000..1d4d60a013 --- /dev/null +++ b/src/main/java/io/floci/aws/services/athena/AthenaNamedQueryService.java @@ -0,0 +1,136 @@ +package io.floci.aws.services.athena; + +import com.fasterxml.jackson.core.type.TypeReference; +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.core.common.RegionResolver; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.athena.model.NamedQuery; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +@ApplicationScoped +public class AthenaNamedQueryService { + + private final StorageBackend queries; + private final StorageBackend requests; + private final AthenaService athenaService; + private final RegionResolver regionResolver; + + @Inject + public AthenaNamedQueryService(StorageFactory storageFactory, AthenaService athenaService, + RegionResolver regionResolver) { + this.queries = storageFactory.create("athena", "athena-named-queries.json", new TypeReference<>() {}); + this.requests = storageFactory.create("athena", "athena-named-query-requests.json", new TypeReference<>() {}); + this.athenaService = athenaService; + this.regionResolver = regionResolver; + } + + public synchronized String createNamedQuery(String region, String name, String database, String queryString, + String description, String workGroup, String clientRequestToken) { + String group = resolveWorkGroup(workGroup); + NamedQuery previous = clientRequestToken == null ? null : requests.get(key(region, clientRequestToken)).orElse(null); + if (previous != null) { + if (!previous.name().equals(name) || !previous.database().equals(database) + || !previous.queryString().equals(queryString) || !Objects.equals(previous.description(), description) + || !previous.workGroup().equals(group)) { + throw invalid("ClientRequestToken has already been used with different parameters."); + } + return previous.namedQueryId(); + } + athenaService.getWorkGroup(group, region); + String id = UUID.randomUUID().toString(); + NamedQuery query = new NamedQuery(id, name, database, queryString, description, group); + queries.put(key(region, id), query); + if (clientRequestToken != null) { + requests.put(key(region, clientRequestToken), query); + } + return id; + } + + public NamedQuery getNamedQuery(String region, String id) { + return queries.get(key(region, id)) + .orElseThrow(() -> invalid("Named query " + id + " does not exist.")); + } + + public Map batchGetNamedQuery(String region, List ids) { + List found = new ArrayList<>(); + List> unprocessed = new ArrayList<>(); + for (String id : ids) { + NamedQuery query = queries.get(key(region, id)).orElse(null); + if (query == null) { + unprocessed.add(Map.of("NamedQueryId", id, "ErrorCode", "InvalidRequestException", + "ErrorMessage", "Named query " + id + " does not exist.")); + } else { + found.add(query); + } + } + return Map.of("NamedQueries", found, "UnprocessedNamedQueryIds", unprocessed); + } + + public PaginatedResult listNamedQueries(String region, String workGroup, + Integer maxResults, String nextToken) { + String group = resolveWorkGroup(workGroup); + athenaService.getWorkGroup(group, region); + int limit = maxResults == null || maxResults == 0 ? 50 : maxResults; + return Pagination.paginate(queriesInWorkGroup(region, group), NamedQuery::namedQueryId, limit, nextToken, + "ListNamedQueries:" + regionResolver.getAccountId() + ":" + region + ":" + group, + token -> invalid("Invalid NextToken.")); + } + + public synchronized void updateNamedQuery(String region, String id, String name, + String queryString, String description) { + NamedQuery previous = getNamedQuery(region, id); + queries.put(key(region, id), new NamedQuery(id, name, previous.database(), queryString, + description == null ? previous.description() : description, previous.workGroup())); + } + + public synchronized void deleteNamedQuery(String region, String id) { + queries.delete(key(region, id)); + } + + public synchronized void deleteWorkGroup(String region, String workGroup, boolean recursive) { + if ("primary".equals(workGroup)) { + throw invalid("The primary workgroup cannot be deleted."); + } + List contents = queriesInWorkGroup(region, workGroup); + if (!recursive && !contents.isEmpty()) { + throw invalid("WorkGroup contains named queries. Set RecursiveDeleteOption to true to delete it."); + } + for (NamedQuery query : contents) { + queries.delete(key(region, query.namedQueryId())); + } + for (String requestKey : requests.keys()) { + if (requestKey.startsWith(region + ":") && requests.get(requestKey) + .map(query -> workGroup.equals(query.workGroup())).orElse(false)) { + requests.delete(requestKey); + } + } + athenaService.removeWorkGroup(workGroup, region); + } + + private List queriesInWorkGroup(String region, String workGroup) { + return queries.scan(k -> k.startsWith(region + ":")).stream() + .filter(query -> workGroup.equals(query.workGroup())).toList(); + } + + private static String resolveWorkGroup(String workGroup) { + return workGroup == null ? "primary" : workGroup; + } + + private static String key(String region, String value) { + return region + ":" + value; + } + + private static AwsException invalid(String message) { + return new AwsException("InvalidRequestException", message, 400); + } +} diff --git a/src/main/java/io/floci/aws/services/athena/AthenaRequestShapes.java b/src/main/java/io/floci/aws/services/athena/AthenaRequestShapes.java new file mode 100644 index 0000000000..abf43a9e83 --- /dev/null +++ b/src/main/java/io/floci/aws/services/athena/AthenaRequestShapes.java @@ -0,0 +1,21 @@ +package io.floci.aws.services.athena; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.RequestConstraintCheck; + +/** Checks Athena requests against the constraints generated by {@code tools/aws/regen_athena_shapes.py}. */ +final class AthenaRequestShapes { + + private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( + "aws/athena-request-shapes.json", "Athena request shapes", + RequestConstraintCheck.standardMessages("InvalidRequestException")); + + private AthenaRequestShapes() { + } + + static void check(String operation, JsonNode request) { + if (CHECK.hasOperation(operation)) { + CHECK.check(operation, request); + } + } +} diff --git a/src/main/java/io/floci/aws/services/athena/AthenaService.java b/src/main/java/io/floci/aws/services/athena/AthenaService.java index 86cdf0384d..a1c2f4a538 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java @@ -326,7 +326,7 @@ public class AthenaService { workGroupStore.put(workGroupKey(region, workGroup.getName()), workGroup); } - public void deleteWorkGroup(String name, String region) { + void removeWorkGroup(String name, String region) { workGroupStore.delete(workGroupKey(region, name)); } diff --git a/src/main/java/io/floci/aws/services/athena/model/NamedQuery.java b/src/main/java/io/floci/aws/services/athena/model/NamedQuery.java new file mode 100644 index 0000000000..4a09393aa1 --- /dev/null +++ b/src/main/java/io/floci/aws/services/athena/model/NamedQuery.java @@ -0,0 +1,14 @@ +package io.floci.aws.services.athena.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public record NamedQuery( + @JsonProperty("NamedQueryId") String namedQueryId, + @JsonProperty("Name") String name, + @JsonProperty("Database") String database, + @JsonProperty("QueryString") String queryString, + @JsonProperty("Description") String description, + @JsonProperty("WorkGroup") String workGroup) { +} diff --git a/src/main/java/io/floci/aws/services/ecr/EcrRequestShapes.java b/src/main/java/io/floci/aws/services/ecr/EcrRequestShapes.java index d96f861f4b..29183194d8 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrRequestShapes.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrRequestShapes.java @@ -1,11 +1,8 @@ package io.floci.aws.services.ecr; import com.fasterxml.jackson.databind.JsonNode; -import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RequestConstraintCheck; -import java.util.List; - /** * Checks an ECR request against the constraints vendored in {@code aws/ecr-request-shapes.json} by * {@code tools/aws/regen_ecr_shapes.py}. A violation is {@code InvalidParameterException} in ECR's @@ -16,35 +13,7 @@ final class EcrRequestShapes { private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( "aws/ecr-request-shapes.json", "ECR request shapes", - new RequestConstraintCheck.Messages() { - @Override - public AwsException type(String path, String type) { - return invalid(path, "Member must be a " + type); - } - - @Override - public AwsException bounds(String path, String type, Long min, Long max, long size) { - String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length"; - return min != null && size < min - ? invalid(path, "Member must have " + measure + " greater than or equal to " + min) - : invalid(path, "Member must have " + measure + " less than or equal to " + max); - } - - @Override - public AwsException pattern(String path, String pattern) { - return invalid(path, "must satisfy regular expression '" + pattern + "'"); - } - - @Override - public AwsException enumValue(String path, List values) { - return invalid(path, "Member must satisfy enum value set: " + values); - } - - @Override - public AwsException required(String path) { - return invalid(path, "Member must not be null"); - } - }); + RequestConstraintCheck.standardMessages("InvalidParameterException")); private EcrRequestShapes() { } @@ -52,12 +21,4 @@ final class EcrRequestShapes { static void check(String operation, JsonNode request) { CHECK.check(operation, request); } - - /** The member's path below the operation, with list elements folded into their list. */ - private static AwsException invalid(String path, String rule) { - int dot = path.indexOf('.'); - String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", ""); - return new AwsException("InvalidParameterException", - "Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400); - } } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapes.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapes.java index 406265f425..296d49fc8f 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapes.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapes.java @@ -18,7 +18,7 @@ final class PaymentCryptographyDataRequestShapes { private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( "aws/payment-cryptography-data-request-shapes.json", "Payment Cryptography data plane request shapes", - PaymentCryptographyShapeErrors.MESSAGES); + RequestConstraintCheck.standardMessages("ValidationException")); private PaymentCryptographyDataRequestShapes() { } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java index 205a046c06..53c87d5757 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java @@ -17,7 +17,7 @@ final class PaymentCryptographyRequestShapes { private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load( "aws/payment-cryptography-request-shapes.json", "Payment Cryptography request shapes", - PaymentCryptographyShapeErrors.MESSAGES); + RequestConstraintCheck.standardMessages("ValidationException")); private PaymentCryptographyRequestShapes() { } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyShapeErrors.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyShapeErrors.java deleted file mode 100644 index 183624b4e4..0000000000 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyShapeErrors.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.floci.aws.services.paymentcryptography; - -import com.fasterxml.jackson.databind.JsonNode; -import io.floci.aws.core.common.AwsException; -import io.floci.aws.core.common.RequestConstraintCheck; - -import java.util.List; - -/** - * How a Payment Cryptography request that breaks a constraint is refused. - * - *

The control plane and the data plane are checked by the same machinery and are worded the - * same way, so the wording is here rather than in each of them. The path a violation names is the - * member's path below the operation, with the list elements folded into their list. - */ -final class PaymentCryptographyShapeErrors { - - /** The wording every constraint violation of this service is refused with. */ - static final RequestConstraintCheck.Messages MESSAGES = new RequestConstraintCheck.Messages() { - @Override - public AwsException type(String path, String type) { - return invalid(path, "Member must be a " + type); - } - - @Override - public AwsException bounds(String path, String type, Long min, Long max, long size) { - String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length"; - return min != null && size < min - ? invalid(path, "Member must have " + measure + " greater than or equal to " + min) - : invalid(path, "Member must have " + measure + " less than or equal to " + max); - } - - @Override - public AwsException pattern(String path, String pattern) { - return invalid(path, "must satisfy regular expression '" + pattern + "'"); - } - - @Override - public AwsException enumValue(String path, List values) { - return invalid(path, "Member must satisfy enum value set: " + values); - } - - @Override - public AwsException required(String path) { - return invalid(path, "Member must not be null"); - } - }; - - private PaymentCryptographyShapeErrors() { - } - - /** The violation, as the service refuses it. */ - static AwsException invalid(String path, String rule) { - int dot = path.indexOf('.'); - String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", ""); - return new AwsException("ValidationException", - "Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400); - } -} diff --git a/src/main/resources/aws/athena-request-shapes.json b/src/main/resources/aws/athena-request-shapes.json new file mode 100644 index 0000000000..aa5eb05555 --- /dev/null +++ b/src/main/resources/aws/athena-request-shapes.json @@ -0,0 +1,1552 @@ +{ + "_source": { + "generator": "tools/aws/regen_athena_shapes.py", + "botocore": "botocore 1.43.118 (installed package)" + }, + "operations": { + "BatchGetNamedQuery": "BatchGetNamedQueryInput", + "BatchGetPreparedStatement": "BatchGetPreparedStatementInput", + "BatchGetQueryExecution": "BatchGetQueryExecutionInput", + "CancelCapacityReservation": "CancelCapacityReservationInput", + "CreateCapacityReservation": "CreateCapacityReservationInput", + "CreateDataCatalog": "CreateDataCatalogInput", + "CreateNamedQuery": "CreateNamedQueryInput", + "CreateNotebook": "CreateNotebookInput", + "CreatePreparedStatement": "CreatePreparedStatementInput", + "CreatePresignedNotebookUrl": "CreatePresignedNotebookUrlRequest", + "CreateWorkGroup": "CreateWorkGroupInput", + "DeleteCapacityReservation": "DeleteCapacityReservationInput", + "DeleteDataCatalog": "DeleteDataCatalogInput", + "DeleteNamedQuery": "DeleteNamedQueryInput", + "DeleteNotebook": "DeleteNotebookInput", + "DeletePreparedStatement": "DeletePreparedStatementInput", + "DeleteWorkGroup": "DeleteWorkGroupInput", + "ExportNotebook": "ExportNotebookInput", + "GetCalculationExecution": "GetCalculationExecutionRequest", + "GetCalculationExecutionCode": "GetCalculationExecutionCodeRequest", + "GetCalculationExecutionStatus": "GetCalculationExecutionStatusRequest", + "GetCapacityAssignmentConfiguration": "GetCapacityAssignmentConfigurationInput", + "GetCapacityReservation": "GetCapacityReservationInput", + "GetDataCatalog": "GetDataCatalogInput", + "GetDatabase": "GetDatabaseInput", + "GetNamedQuery": "GetNamedQueryInput", + "GetNotebookMetadata": "GetNotebookMetadataInput", + "GetPreparedStatement": "GetPreparedStatementInput", + "GetQueryExecution": "GetQueryExecutionInput", + "GetQueryResults": "GetQueryResultsInput", + "GetQueryRuntimeStatistics": "GetQueryRuntimeStatisticsInput", + "GetResourceDashboard": "GetResourceDashboardRequest", + "GetSession": "GetSessionRequest", + "GetSessionEndpoint": "GetSessionEndpointRequest", + "GetSessionStatus": "GetSessionStatusRequest", + "GetTableMetadata": "GetTableMetadataInput", + "GetWorkGroup": "GetWorkGroupInput", + "ImportNotebook": "ImportNotebookInput", + "ListApplicationDPUSizes": "ListApplicationDPUSizesInput", + "ListCalculationExecutions": "ListCalculationExecutionsRequest", + "ListCapacityReservations": "ListCapacityReservationsInput", + "ListDataCatalogs": "ListDataCatalogsInput", + "ListDatabases": "ListDatabasesInput", + "ListEngineVersions": "ListEngineVersionsInput", + "ListExecutors": "ListExecutorsRequest", + "ListNamedQueries": "ListNamedQueriesInput", + "ListNotebookMetadata": "ListNotebookMetadataInput", + "ListNotebookSessions": "ListNotebookSessionsRequest", + "ListPreparedStatements": "ListPreparedStatementsInput", + "ListQueryExecutions": "ListQueryExecutionsInput", + "ListSessions": "ListSessionsRequest", + "ListTableMetadata": "ListTableMetadataInput", + "ListTagsForResource": "ListTagsForResourceInput", + "ListWorkGroups": "ListWorkGroupsInput", + "PutCapacityAssignmentConfiguration": "PutCapacityAssignmentConfigurationInput", + "StartCalculationExecution": "StartCalculationExecutionRequest", + "StartQueryExecution": "StartQueryExecutionInput", + "StartSession": "StartSessionRequest", + "StopCalculationExecution": "StopCalculationExecutionRequest", + "StopQueryExecution": "StopQueryExecutionInput", + "TagResource": "TagResourceInput", + "TerminateSession": "TerminateSessionRequest", + "UntagResource": "UntagResourceInput", + "UpdateCapacityReservation": "UpdateCapacityReservationInput", + "UpdateDataCatalog": "UpdateDataCatalogInput", + "UpdateNamedQuery": "UpdateNamedQueryInput", + "UpdateNotebook": "UpdateNotebookInput", + "UpdateNotebookMetadata": "UpdateNotebookMetadataInput", + "UpdatePreparedStatement": "UpdatePreparedStatementInput", + "UpdateWorkGroup": "UpdateWorkGroupInput" + }, + "shapes": { + "AclConfiguration": { + "type": "structure", + "required": [ + "S3AclOption" + ], + "members": { + "S3AclOption": "S3AclOption" + } + }, + "Age": { + "type": "integer", + "min": 0, + "max": 10080 + }, + "AmazonResourceName": { + "type": "string", + "min": 1, + "max": 1011 + }, + "AuthenticationType": { + "type": "string", + "enum": [ + "DIRECTORY_IDENTITY" + ] + }, + "AwsAccountId": { + "type": "string", + "min": 12, + "max": 12, + "pattern": "^[0-9]+$" + }, + "BatchGetNamedQueryInput": { + "type": "structure", + "required": [ + "NamedQueryIds" + ], + "members": { + "NamedQueryIds": "NamedQueryIdList" + } + }, + "BatchGetPreparedStatementInput": { + "type": "structure", + "required": [ + "PreparedStatementNames", + "WorkGroup" + ], + "members": { + "PreparedStatementNames": "PreparedStatementNameList", + "WorkGroup": "WorkGroupName" + } + }, + "BatchGetQueryExecutionInput": { + "type": "structure", + "required": [ + "QueryExecutionIds" + ], + "members": { + "QueryExecutionIds": "QueryExecutionIdList" + } + }, + "Boolean": { + "type": "boolean" + }, + "BoxedBoolean": { + "type": "boolean" + }, + "BytesScannedCutoffValue": { + "type": "long", + "min": 10000000 + }, + "CalculationConfiguration": { + "type": "structure", + "members": { + "CodeBlock": "CodeBlock" + } + }, + "CalculationExecutionId": { + "type": "string", + "min": 1, + "max": 36 + }, + "CalculationExecutionState": { + "type": "string", + "enum": [ + "CREATING", + "CREATED", + "QUEUED", + "RUNNING", + "CANCELING", + "CANCELED", + "COMPLETED", + "FAILED" + ] + }, + "CancelCapacityReservationInput": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "CapacityReservationName" + } + }, + "CapacityAssignment": { + "type": "structure", + "members": { + "WorkGroupNames": "WorkGroupNamesList" + } + }, + "CapacityAssignmentsList": { + "type": "list", + "member": "CapacityAssignment" + }, + "CapacityReservationName": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[a-zA-Z0-9._-]+" + }, + "CatalogNameString": { + "type": "string", + "min": 1, + "max": 256, + "pattern": "[\\u0020-\\uD7FF\\uE000-\\uFFFD\\uD800\\uDC00-\\uDBFF\\uDFFF\\t]*" + }, + "Classification": { + "type": "structure", + "members": { + "Name": "NameString", + "Properties": "ParametersMap" + } + }, + "ClassificationList": { + "type": "list", + "member": "Classification" + }, + "ClientRequestToken": { + "type": "string", + "min": 1, + "max": 36, + "pattern": "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}" + }, + "CloudWatchLoggingConfiguration": { + "type": "structure", + "required": [ + "Enabled" + ], + "members": { + "Enabled": "BoxedBoolean", + "LogGroup": "LogGroupName", + "LogStreamNamePrefix": "LogStreamNamePrefix", + "LogTypes": "LogTypesMap" + } + }, + "CodeBlock": { + "type": "string", + "max": 68000 + }, + "CoordinatorDpuSize": { + "type": "integer", + "min": 1, + "max": 1 + }, + "CreateCapacityReservationInput": { + "type": "structure", + "required": [ + "TargetDpus", + "Name" + ], + "members": { + "TargetDpus": "TargetDpusInteger", + "Name": "CapacityReservationName", + "Tags": "TagList" + } + }, + "CreateDataCatalogInput": { + "type": "structure", + "required": [ + "Name", + "Type" + ], + "members": { + "Name": "CatalogNameString", + "Type": "DataCatalogType", + "Description": "DescriptionString", + "Parameters": "ParametersMap", + "Tags": "TagList" + } + }, + "CreateNamedQueryInput": { + "type": "structure", + "required": [ + "Name", + "Database", + "QueryString" + ], + "members": { + "Name": "NameString", + "Description": "DescriptionString", + "Database": "DatabaseString", + "QueryString": "QueryString", + "ClientRequestToken": "IdempotencyToken", + "WorkGroup": "WorkGroupName" + } + }, + "CreateNotebookInput": { + "type": "structure", + "required": [ + "WorkGroup", + "Name" + ], + "members": { + "WorkGroup": "WorkGroupName", + "Name": "NotebookName", + "ClientRequestToken": "ClientRequestToken" + } + }, + "CreatePreparedStatementInput": { + "type": "structure", + "required": [ + "StatementName", + "WorkGroup", + "QueryStatement" + ], + "members": { + "StatementName": "StatementName", + "WorkGroup": "WorkGroupName", + "QueryStatement": "QueryString", + "Description": "DescriptionString" + } + }, + "CreatePresignedNotebookUrlRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId" + } + }, + "CreateWorkGroupInput": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "WorkGroupName", + "Configuration": "WorkGroupConfiguration", + "Description": "WorkGroupDescriptionString", + "Tags": "TagList" + } + }, + "CustomerContentEncryptionConfiguration": { + "type": "structure", + "required": [ + "KmsKey" + ], + "members": { + "KmsKey": "KmsKey" + } + }, + "DataCatalogType": { + "type": "string", + "enum": [ + "LAMBDA", + "GLUE", + "HIVE", + "FEDERATED" + ] + }, + "DatabaseString": { + "type": "string", + "min": 1, + "max": 255 + }, + "DefaultExecutorDpuSize": { + "type": "integer", + "min": 1, + "max": 1 + }, + "DeleteCapacityReservationInput": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "CapacityReservationName" + } + }, + "DeleteDataCatalogInput": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "CatalogNameString", + "DeleteCatalogOnly": "Boolean" + } + }, + "DeleteNamedQueryInput": { + "type": "structure", + "required": [ + "NamedQueryId" + ], + "members": { + "NamedQueryId": "NamedQueryId" + } + }, + "DeleteNotebookInput": { + "type": "structure", + "required": [ + "NotebookId" + ], + "members": { + "NotebookId": "NotebookId" + } + }, + "DeletePreparedStatementInput": { + "type": "structure", + "required": [ + "StatementName", + "WorkGroup" + ], + "members": { + "StatementName": "StatementName", + "WorkGroup": "WorkGroupName" + } + }, + "DeleteWorkGroupInput": { + "type": "structure", + "required": [ + "WorkGroup" + ], + "members": { + "WorkGroup": "WorkGroupName", + "RecursiveDeleteOption": "BoxedBoolean" + } + }, + "DescriptionString": { + "type": "string", + "min": 1, + "max": 1024 + }, + "EncryptionConfiguration": { + "type": "structure", + "required": [ + "EncryptionOption" + ], + "members": { + "EncryptionOption": "EncryptionOption", + "KmsKey": "String" + } + }, + "EncryptionOption": { + "type": "string", + "enum": [ + "SSE_S3", + "SSE_KMS", + "CSE_KMS" + ] + }, + "EngineConfiguration": { + "type": "structure", + "members": { + "CoordinatorDpuSize": "CoordinatorDpuSize", + "MaxConcurrentDpus": "MaxConcurrentDpus", + "DefaultExecutorDpuSize": "DefaultExecutorDpuSize", + "AdditionalConfigs": "ParametersMap", + "SparkProperties": "ParametersMap", + "Classifications": "ClassificationList" + } + }, + "EngineVersion": { + "type": "structure", + "members": { + "SelectedEngineVersion": "NameString", + "EffectiveEngineVersion": "NameString" + } + }, + "ExecutionParameter": { + "type": "string", + "min": 1, + "max": 1024 + }, + "ExecutionParameters": { + "type": "list", + "min": 1, + "member": "ExecutionParameter" + }, + "ExecutorState": { + "type": "string", + "enum": [ + "CREATING", + "CREATED", + "REGISTERED", + "TERMINATING", + "TERMINATED", + "FAILED" + ] + }, + "ExportNotebookInput": { + "type": "structure", + "required": [ + "NotebookId" + ], + "members": { + "NotebookId": "NotebookId" + } + }, + "ExpressionString": { + "type": "string", + "min": 0, + "max": 256 + }, + "FilterDefinition": { + "type": "structure", + "members": { + "Name": "NotebookName" + } + }, + "GetCalculationExecutionCodeRequest": { + "type": "structure", + "required": [ + "CalculationExecutionId" + ], + "members": { + "CalculationExecutionId": "CalculationExecutionId" + } + }, + "GetCalculationExecutionRequest": { + "type": "structure", + "required": [ + "CalculationExecutionId" + ], + "members": { + "CalculationExecutionId": "CalculationExecutionId" + } + }, + "GetCalculationExecutionStatusRequest": { + "type": "structure", + "required": [ + "CalculationExecutionId" + ], + "members": { + "CalculationExecutionId": "CalculationExecutionId" + } + }, + "GetCapacityAssignmentConfigurationInput": { + "type": "structure", + "required": [ + "CapacityReservationName" + ], + "members": { + "CapacityReservationName": "CapacityReservationName" + } + }, + "GetCapacityReservationInput": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "CapacityReservationName" + } + }, + "GetDataCatalogInput": { + "type": "structure", + "required": [ + "Name" + ], + "members": { + "Name": "CatalogNameString", + "WorkGroup": "WorkGroupName" + } + }, + "GetDatabaseInput": { + "type": "structure", + "required": [ + "CatalogName", + "DatabaseName" + ], + "members": { + "CatalogName": "CatalogNameString", + "DatabaseName": "NameString", + "WorkGroup": "WorkGroupName" + } + }, + "GetNamedQueryInput": { + "type": "structure", + "required": [ + "NamedQueryId" + ], + "members": { + "NamedQueryId": "NamedQueryId" + } + }, + "GetNotebookMetadataInput": { + "type": "structure", + "required": [ + "NotebookId" + ], + "members": { + "NotebookId": "NotebookId" + } + }, + "GetPreparedStatementInput": { + "type": "structure", + "required": [ + "StatementName", + "WorkGroup" + ], + "members": { + "StatementName": "StatementName", + "WorkGroup": "WorkGroupName" + } + }, + "GetQueryExecutionInput": { + "type": "structure", + "required": [ + "QueryExecutionId" + ], + "members": { + "QueryExecutionId": "QueryExecutionId" + } + }, + "GetQueryResultsInput": { + "type": "structure", + "required": [ + "QueryExecutionId" + ], + "members": { + "QueryExecutionId": "QueryExecutionId", + "NextToken": "Token", + "MaxResults": "MaxQueryResults", + "QueryResultType": "QueryResultType" + } + }, + "GetQueryRuntimeStatisticsInput": { + "type": "structure", + "required": [ + "QueryExecutionId" + ], + "members": { + "QueryExecutionId": "QueryExecutionId" + } + }, + "GetResourceDashboardRequest": { + "type": "structure", + "required": [ + "ResourceARN" + ], + "members": { + "ResourceARN": "AmazonResourceName" + } + }, + "GetSessionEndpointRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId" + } + }, + "GetSessionRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId" + } + }, + "GetSessionStatusRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId" + } + }, + "GetTableMetadataInput": { + "type": "structure", + "required": [ + "CatalogName", + "DatabaseName", + "TableName" + ], + "members": { + "CatalogName": "CatalogNameString", + "DatabaseName": "NameString", + "TableName": "NameString", + "WorkGroup": "WorkGroupName" + } + }, + "GetWorkGroupInput": { + "type": "structure", + "required": [ + "WorkGroup" + ], + "members": { + "WorkGroup": "WorkGroupName" + } + }, + "IdempotencyToken": { + "type": "string", + "min": 32, + "max": 128 + }, + "IdentityCenterConfiguration": { + "type": "structure", + "members": { + "EnableIdentityCenter": "BoxedBoolean", + "IdentityCenterInstanceArn": "IdentityCenterInstanceArn" + } + }, + "IdentityCenterInstanceArn": { + "type": "string", + "min": 0, + "max": 255, + "pattern": "^arn:(aws|aws-us-gov|aws-cn|aws-iso|aws-iso-b):sso:::instance/(sso)?ins-[a-zA-Z0-9-.]{16}$" + }, + "ImportNotebookInput": { + "type": "structure", + "required": [ + "WorkGroup", + "Name", + "Type" + ], + "members": { + "WorkGroup": "WorkGroupName", + "Name": "NotebookName", + "Payload": "Payload", + "Type": "NotebookType", + "NotebookS3LocationUri": "S3Uri", + "ClientRequestToken": "ClientRequestToken" + } + }, + "KeyString": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "[\\u0020-\\uD7FF\\uE000-\\uFFFD\\uD800\\uDC00-\\uDBFF\\uDFFF\\t]*" + }, + "KmsKey": { + "type": "string", + "min": 1, + "max": 2048, + "pattern": "^arn:aws[a-z\\-]*:kms:([a-z0-9\\-]+):\\d{12}:key/?[a-zA-Z_0-9+=,.@\\-_/]+$|^arn:aws[a-z\\-]*:kms:([a-z0-9\\-]+):\\d{12}:alias/?[a-zA-Z_0-9+=,.@\\-_/]+$|^alias/[a-zA-Z0-9/_-]+$|[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}" + }, + "ListApplicationDPUSizesInput": { + "type": "structure", + "members": { + "MaxResults": "MaxApplicationDPUSizesCount", + "NextToken": "Token" + } + }, + "ListCalculationExecutionsRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId", + "StateFilter": "CalculationExecutionState", + "MaxResults": "MaxCalculationsCount", + "NextToken": "SessionManagerToken" + } + }, + "ListCapacityReservationsInput": { + "type": "structure", + "members": { + "NextToken": "Token", + "MaxResults": "MaxCapacityReservationsCount" + } + }, + "ListDataCatalogsInput": { + "type": "structure", + "members": { + "NextToken": "Token", + "MaxResults": "MaxDataCatalogsCount", + "WorkGroup": "WorkGroupName" + } + }, + "ListDatabasesInput": { + "type": "structure", + "required": [ + "CatalogName" + ], + "members": { + "CatalogName": "CatalogNameString", + "NextToken": "Token", + "MaxResults": "MaxDatabasesCount", + "WorkGroup": "WorkGroupName" + } + }, + "ListEngineVersionsInput": { + "type": "structure", + "members": { + "NextToken": "Token", + "MaxResults": "MaxEngineVersionsCount" + } + }, + "ListExecutorsRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId", + "ExecutorStateFilter": "ExecutorState", + "MaxResults": "MaxListExecutorsCount", + "NextToken": "SessionManagerToken" + } + }, + "ListNamedQueriesInput": { + "type": "structure", + "members": { + "NextToken": "Token", + "MaxResults": "MaxNamedQueriesCount", + "WorkGroup": "WorkGroupName" + } + }, + "ListNotebookMetadataInput": { + "type": "structure", + "required": [ + "WorkGroup" + ], + "members": { + "Filters": "FilterDefinition", + "NextToken": "Token", + "MaxResults": "MaxNotebooksCount", + "WorkGroup": "WorkGroupName" + } + }, + "ListNotebookSessionsRequest": { + "type": "structure", + "required": [ + "NotebookId" + ], + "members": { + "NotebookId": "NotebookId", + "MaxResults": "MaxSessionsCount", + "NextToken": "Token" + } + }, + "ListPreparedStatementsInput": { + "type": "structure", + "required": [ + "WorkGroup" + ], + "members": { + "WorkGroup": "WorkGroupName", + "NextToken": "Token", + "MaxResults": "MaxPreparedStatementsCount" + } + }, + "ListQueryExecutionsInput": { + "type": "structure", + "members": { + "NextToken": "Token", + "MaxResults": "MaxQueryExecutionsCount", + "WorkGroup": "WorkGroupName" + } + }, + "ListSessionsRequest": { + "type": "structure", + "required": [ + "WorkGroup" + ], + "members": { + "WorkGroup": "WorkGroupName", + "StateFilter": "SessionState", + "MaxResults": "MaxSessionsCount", + "NextToken": "SessionManagerToken" + } + }, + "ListTableMetadataInput": { + "type": "structure", + "required": [ + "CatalogName", + "DatabaseName" + ], + "members": { + "CatalogName": "CatalogNameString", + "DatabaseName": "NameString", + "Expression": "ExpressionString", + "NextToken": "Token", + "MaxResults": "MaxTableMetadataCount", + "WorkGroup": "WorkGroupName" + } + }, + "ListTagsForResourceInput": { + "type": "structure", + "required": [ + "ResourceARN" + ], + "members": { + "ResourceARN": "AmazonResourceName", + "NextToken": "Token", + "MaxResults": "MaxTagsCount" + } + }, + "ListWorkGroupsInput": { + "type": "structure", + "members": { + "NextToken": "Token", + "MaxResults": "MaxWorkGroupsCount" + } + }, + "LogGroupName": { + "type": "string", + "min": 1, + "max": 512, + "pattern": "^[a-zA-Z0-9._/-]+$" + }, + "LogStreamNamePrefix": { + "type": "string", + "min": 1, + "max": 512, + "pattern": "^[^:*]*$" + }, + "LogTypeKey": { + "type": "string" + }, + "LogTypeValue": { + "type": "string" + }, + "LogTypeValuesList": { + "type": "list", + "member": "LogTypeValue" + }, + "LogTypesMap": { + "type": "map", + "key": "LogTypeKey", + "value": "LogTypeValuesList" + }, + "ManagedLoggingConfiguration": { + "type": "structure", + "required": [ + "Enabled" + ], + "members": { + "Enabled": "BoxedBoolean", + "KmsKey": "KmsKey" + } + }, + "ManagedQueryResultsConfiguration": { + "type": "structure", + "required": [ + "Enabled" + ], + "members": { + "Enabled": "Boolean", + "EncryptionConfiguration": "ManagedQueryResultsEncryptionConfiguration" + } + }, + "ManagedQueryResultsConfigurationUpdates": { + "type": "structure", + "members": { + "Enabled": "BoxedBoolean", + "EncryptionConfiguration": "ManagedQueryResultsEncryptionConfiguration", + "RemoveEncryptionConfiguration": "BoxedBoolean" + } + }, + "ManagedQueryResultsEncryptionConfiguration": { + "type": "structure", + "required": [ + "KmsKey" + ], + "members": { + "KmsKey": "KmsKey" + } + }, + "MaxApplicationDPUSizesCount": { + "type": "integer", + "min": 1, + "max": 100 + }, + "MaxCalculationsCount": { + "type": "integer", + "min": 1, + "max": 100 + }, + "MaxCapacityReservationsCount": { + "type": "integer", + "min": 1, + "max": 50 + }, + "MaxConcurrentDpus": { + "type": "integer", + "min": 2, + "max": 5000 + }, + "MaxDataCatalogsCount": { + "type": "integer", + "min": 2, + "max": 50 + }, + "MaxDatabasesCount": { + "type": "integer", + "min": 1, + "max": 50 + }, + "MaxEngineVersionsCount": { + "type": "integer", + "min": 1, + "max": 10 + }, + "MaxListExecutorsCount": { + "type": "integer", + "min": 1, + "max": 100 + }, + "MaxNamedQueriesCount": { + "type": "integer", + "min": 0, + "max": 50 + }, + "MaxNotebooksCount": { + "type": "integer", + "min": 1, + "max": 50 + }, + "MaxPreparedStatementsCount": { + "type": "integer", + "min": 1, + "max": 50 + }, + "MaxQueryExecutionsCount": { + "type": "integer", + "min": 0, + "max": 50 + }, + "MaxQueryResults": { + "type": "integer", + "min": 1, + "max": 1000 + }, + "MaxSessionsCount": { + "type": "integer", + "min": 1, + "max": 100 + }, + "MaxTableMetadataCount": { + "type": "integer", + "min": 1, + "max": 50 + }, + "MaxTagsCount": { + "type": "integer", + "min": 75 + }, + "MaxWorkGroupsCount": { + "type": "integer", + "min": 1, + "max": 50 + }, + "MonitoringConfiguration": { + "type": "structure", + "members": { + "CloudWatchLoggingConfiguration": "CloudWatchLoggingConfiguration", + "ManagedLoggingConfiguration": "ManagedLoggingConfiguration", + "S3LoggingConfiguration": "S3LoggingConfiguration" + } + }, + "NameString": { + "type": "string", + "min": 1, + "max": 128 + }, + "NamedQueryDescriptionString": { + "type": "string", + "min": 0, + "max": 1024 + }, + "NamedQueryId": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "\\S+" + }, + "NamedQueryIdList": { + "type": "list", + "min": 1, + "max": 50, + "member": "NamedQueryId" + }, + "NotebookId": { + "type": "string", + "min": 1, + "max": 36, + "pattern": "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}" + }, + "NotebookName": { + "type": "string", + "min": 1, + "max": 255, + "pattern": "(?!.*[/:\\\\])[\\u0020-\\uD7FF\\uE000-\\uFFFD\\uD800\\uDC00-\\uDBFF\\uDFFF\\t]+" + }, + "NotebookType": { + "type": "string", + "enum": [ + "IPYNB" + ] + }, + "ParametersMap": { + "type": "map", + "key": "KeyString", + "value": "ParametersMapValue" + }, + "ParametersMapValue": { + "type": "string", + "max": 51200 + }, + "Payload": { + "type": "string", + "min": 1, + "max": 10485760 + }, + "PreparedStatementNameList": { + "type": "list", + "member": "StatementName" + }, + "PutCapacityAssignmentConfigurationInput": { + "type": "structure", + "required": [ + "CapacityReservationName", + "CapacityAssignments" + ], + "members": { + "CapacityReservationName": "CapacityReservationName", + "CapacityAssignments": "CapacityAssignmentsList" + } + }, + "QueryExecutionContext": { + "type": "structure", + "members": { + "Database": "DatabaseString", + "Catalog": "CatalogNameString" + } + }, + "QueryExecutionId": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "\\S+" + }, + "QueryExecutionIdList": { + "type": "list", + "min": 1, + "max": 50, + "member": "QueryExecutionId" + }, + "QueryResultType": { + "type": "string", + "enum": [ + "DATA_MANIFEST", + "DATA_ROWS" + ] + }, + "QueryResultsS3AccessGrantsConfiguration": { + "type": "structure", + "required": [ + "EnableS3AccessGrants", + "AuthenticationType" + ], + "members": { + "EnableS3AccessGrants": "BoxedBoolean", + "CreateUserLevelPrefix": "BoxedBoolean", + "AuthenticationType": "AuthenticationType" + } + }, + "QueryString": { + "type": "string", + "min": 1, + "max": 262144 + }, + "ResultConfiguration": { + "type": "structure", + "members": { + "OutputLocation": "ResultOutputLocation", + "EncryptionConfiguration": "EncryptionConfiguration", + "ExpectedBucketOwner": "AwsAccountId", + "AclConfiguration": "AclConfiguration" + } + }, + "ResultConfigurationUpdates": { + "type": "structure", + "members": { + "OutputLocation": "ResultOutputLocation", + "RemoveOutputLocation": "BoxedBoolean", + "EncryptionConfiguration": "EncryptionConfiguration", + "RemoveEncryptionConfiguration": "BoxedBoolean", + "ExpectedBucketOwner": "AwsAccountId", + "RemoveExpectedBucketOwner": "BoxedBoolean", + "AclConfiguration": "AclConfiguration", + "RemoveAclConfiguration": "BoxedBoolean" + } + }, + "ResultOutputLocation": { + "type": "string" + }, + "ResultReuseByAgeConfiguration": { + "type": "structure", + "required": [ + "Enabled" + ], + "members": { + "Enabled": "Boolean", + "MaxAgeInMinutes": "Age" + } + }, + "ResultReuseConfiguration": { + "type": "structure", + "members": { + "ResultReuseByAgeConfiguration": "ResultReuseByAgeConfiguration" + } + }, + "RoleArn": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "^arn:aws[a-z\\-]*:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+$" + }, + "S3AclOption": { + "type": "string", + "enum": [ + "BUCKET_OWNER_FULL_CONTROL" + ] + }, + "S3LoggingConfiguration": { + "type": "structure", + "required": [ + "Enabled" + ], + "members": { + "Enabled": "BoxedBoolean", + "KmsKey": "KmsKey", + "LogLocation": "S3OutputLocation" + } + }, + "S3OutputLocation": { + "type": "string", + "max": 1024, + "pattern": "^s3://[a-z0-9][a-z0-9\\-]*[a-z0-9](/.*)?$" + }, + "S3Uri": { + "type": "string", + "max": 1024, + "pattern": "^(https|s3|S3)://([^/]+)/?(.*)$" + }, + "SessionId": { + "type": "string", + "min": 1, + "max": 256 + }, + "SessionIdleTimeoutInMinutes": { + "type": "integer", + "min": 1, + "max": 480 + }, + "SessionManagerToken": { + "type": "string", + "max": 2048 + }, + "SessionState": { + "type": "string", + "enum": [ + "CREATING", + "CREATED", + "IDLE", + "BUSY", + "TERMINATING", + "TERMINATED", + "DEGRADED", + "FAILED" + ] + }, + "StartCalculationExecutionRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId", + "Description": "DescriptionString", + "CalculationConfiguration": "CalculationConfiguration", + "CodeBlock": "CodeBlock", + "ClientRequestToken": "IdempotencyToken" + } + }, + "StartQueryExecutionInput": { + "type": "structure", + "required": [ + "QueryString" + ], + "members": { + "QueryString": "QueryString", + "ClientRequestToken": "IdempotencyToken", + "QueryExecutionContext": "QueryExecutionContext", + "ResultConfiguration": "ResultConfiguration", + "WorkGroup": "WorkGroupName", + "ExecutionParameters": "ExecutionParameters", + "ResultReuseConfiguration": "ResultReuseConfiguration", + "EngineConfiguration": "EngineConfiguration" + } + }, + "StartSessionRequest": { + "type": "structure", + "required": [ + "WorkGroup", + "EngineConfiguration" + ], + "members": { + "Description": "DescriptionString", + "WorkGroup": "WorkGroupName", + "EngineConfiguration": "EngineConfiguration", + "ExecutionRole": "RoleArn", + "MonitoringConfiguration": "MonitoringConfiguration", + "NotebookVersion": "NameString", + "SessionIdleTimeoutInMinutes": "SessionIdleTimeoutInMinutes", + "ClientRequestToken": "IdempotencyToken", + "Tags": "TagList", + "CopyWorkGroupTags": "BoxedBoolean" + } + }, + "StatementName": { + "type": "string", + "min": 1, + "max": 256, + "pattern": "[a-zA-Z_][a-zA-Z0-9_@:]{1,256}" + }, + "StopCalculationExecutionRequest": { + "type": "structure", + "required": [ + "CalculationExecutionId" + ], + "members": { + "CalculationExecutionId": "CalculationExecutionId" + } + }, + "StopQueryExecutionInput": { + "type": "structure", + "required": [ + "QueryExecutionId" + ], + "members": { + "QueryExecutionId": "QueryExecutionId" + } + }, + "String": { + "type": "string" + }, + "Tag": { + "type": "structure", + "members": { + "Key": "TagKey", + "Value": "TagValue" + } + }, + "TagKey": { + "type": "string", + "min": 1, + "max": 128 + }, + "TagKeyList": { + "type": "list", + "member": "TagKey" + }, + "TagList": { + "type": "list", + "member": "Tag" + }, + "TagResourceInput": { + "type": "structure", + "required": [ + "ResourceARN", + "Tags" + ], + "members": { + "ResourceARN": "AmazonResourceName", + "Tags": "TagList" + } + }, + "TagValue": { + "type": "string", + "min": 0, + "max": 256 + }, + "TargetDpusInteger": { + "type": "integer", + "min": 4 + }, + "TerminateSessionRequest": { + "type": "structure", + "required": [ + "SessionId" + ], + "members": { + "SessionId": "SessionId" + } + }, + "Token": { + "type": "string", + "min": 1, + "max": 1024 + }, + "UntagResourceInput": { + "type": "structure", + "required": [ + "ResourceARN", + "TagKeys" + ], + "members": { + "ResourceARN": "AmazonResourceName", + "TagKeys": "TagKeyList" + } + }, + "UpdateCapacityReservationInput": { + "type": "structure", + "required": [ + "TargetDpus", + "Name" + ], + "members": { + "TargetDpus": "TargetDpusInteger", + "Name": "CapacityReservationName" + } + }, + "UpdateDataCatalogInput": { + "type": "structure", + "required": [ + "Name", + "Type" + ], + "members": { + "Name": "CatalogNameString", + "Type": "DataCatalogType", + "Description": "DescriptionString", + "Parameters": "ParametersMap" + } + }, + "UpdateNamedQueryInput": { + "type": "structure", + "required": [ + "NamedQueryId", + "Name", + "QueryString" + ], + "members": { + "NamedQueryId": "NamedQueryId", + "Name": "NameString", + "Description": "NamedQueryDescriptionString", + "QueryString": "QueryString" + } + }, + "UpdateNotebookInput": { + "type": "structure", + "required": [ + "NotebookId", + "Payload", + "Type" + ], + "members": { + "NotebookId": "NotebookId", + "Payload": "Payload", + "Type": "NotebookType", + "SessionId": "SessionId", + "ClientRequestToken": "ClientRequestToken" + } + }, + "UpdateNotebookMetadataInput": { + "type": "structure", + "required": [ + "NotebookId", + "Name" + ], + "members": { + "NotebookId": "NotebookId", + "ClientRequestToken": "ClientRequestToken", + "Name": "NotebookName" + } + }, + "UpdatePreparedStatementInput": { + "type": "structure", + "required": [ + "StatementName", + "WorkGroup", + "QueryStatement" + ], + "members": { + "StatementName": "StatementName", + "WorkGroup": "WorkGroupName", + "QueryStatement": "QueryString", + "Description": "DescriptionString" + } + }, + "UpdateWorkGroupInput": { + "type": "structure", + "required": [ + "WorkGroup" + ], + "members": { + "WorkGroup": "WorkGroupName", + "Description": "WorkGroupDescriptionString", + "ConfigurationUpdates": "WorkGroupConfigurationUpdates", + "State": "WorkGroupState" + } + }, + "WorkGroupConfiguration": { + "type": "structure", + "members": { + "ResultConfiguration": "ResultConfiguration", + "ManagedQueryResultsConfiguration": "ManagedQueryResultsConfiguration", + "EnforceWorkGroupConfiguration": "BoxedBoolean", + "PublishCloudWatchMetricsEnabled": "BoxedBoolean", + "BytesScannedCutoffPerQuery": "BytesScannedCutoffValue", + "RequesterPaysEnabled": "BoxedBoolean", + "EngineVersion": "EngineVersion", + "AdditionalConfiguration": "NameString", + "ExecutionRole": "RoleArn", + "MonitoringConfiguration": "MonitoringConfiguration", + "EngineConfiguration": "EngineConfiguration", + "CustomerContentEncryptionConfiguration": "CustomerContentEncryptionConfiguration", + "EnableMinimumEncryptionConfiguration": "BoxedBoolean", + "IdentityCenterConfiguration": "IdentityCenterConfiguration", + "QueryResultsS3AccessGrantsConfiguration": "QueryResultsS3AccessGrantsConfiguration" + } + }, + "WorkGroupConfigurationUpdates": { + "type": "structure", + "members": { + "EnforceWorkGroupConfiguration": "BoxedBoolean", + "ResultConfigurationUpdates": "ResultConfigurationUpdates", + "ManagedQueryResultsConfigurationUpdates": "ManagedQueryResultsConfigurationUpdates", + "PublishCloudWatchMetricsEnabled": "BoxedBoolean", + "BytesScannedCutoffPerQuery": "BytesScannedCutoffValue", + "RemoveBytesScannedCutoffPerQuery": "BoxedBoolean", + "RequesterPaysEnabled": "BoxedBoolean", + "EngineVersion": "EngineVersion", + "RemoveCustomerContentEncryptionConfiguration": "BoxedBoolean", + "AdditionalConfiguration": "NameString", + "ExecutionRole": "RoleArn", + "CustomerContentEncryptionConfiguration": "CustomerContentEncryptionConfiguration", + "EnableMinimumEncryptionConfiguration": "BoxedBoolean", + "QueryResultsS3AccessGrantsConfiguration": "QueryResultsS3AccessGrantsConfiguration", + "MonitoringConfiguration": "MonitoringConfiguration", + "EngineConfiguration": "EngineConfiguration" + } + }, + "WorkGroupDescriptionString": { + "type": "string", + "min": 0, + "max": 1024 + }, + "WorkGroupName": { + "type": "string", + "pattern": "[a-zA-Z0-9._-]{1,128}" + }, + "WorkGroupNamesList": { + "type": "list", + "member": "WorkGroupName" + }, + "WorkGroupState": { + "type": "string", + "enum": [ + "ENABLED", + "DISABLED" + ] + } + } +} diff --git a/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java index ceb7839d84..16f84e5366 100644 --- a/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestConstraintCheckTest.java @@ -3,6 +3,8 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.util.List; @@ -120,4 +122,44 @@ class RequestConstraintCheckTest { // One emoji is two UTF-16 units but one code point, so it is under the minimum of 2. assertEquals("bounds Put.name string 2..5 1", violation("{\"name\":\"\\uD83D\\uDE00\"}")); } + + @ParameterizedTest + @ValueSource(strings = {"InvalidRequestException", "InvalidParameterException", "ValidationException"}) + void standardMessagesPreserveTheWireFormatForEachServiceCode(String errorCode) { + RequestConstraintCheck check = RequestConstraintCheck.of(json(MODEL), + RequestConstraintCheck.standardMessages(errorCode)); + String[][] cases = { + {"{}", "Invalid parameter at 'name' failed to satisfy constraint: 'Member must not be null'"}, + {"{\"name\":7}", "Invalid parameter at 'name' failed to satisfy constraint: 'Member must be a string'"}, + {"{\"name\":\"a\"}", "Invalid parameter at 'name' failed to satisfy constraint: " + + "'Member must have length greater than or equal to 2'"}, + {"{\"name\":\"abcdef\"}", "Invalid parameter at 'name' failed to satisfy constraint: " + + "'Member must have length less than or equal to 5'"}, + {"{\"name\":\"AB\"}", "Invalid parameter at 'name' failed to satisfy constraint: " + + "'must satisfy regular expression '[a-z]+''"}, + {"{\"name\":\"ab\",\"quoted\":\"AB\"}", "Invalid parameter at 'quoted' failed to satisfy constraint: " + + "'must satisfy regular expression '[a-z]*''"}, + {"{\"name\":\"ab\",\"count\":0}", "Invalid parameter at 'count' failed to satisfy constraint: " + + "'Member must have value greater than or equal to 1'"}, + {"{\"name\":\"ab\",\"count\":11}", "Invalid parameter at 'count' failed to satisfy constraint: " + + "'Member must have value less than or equal to 10'"}, + {"{\"name\":\"ab\",\"kind\":\"C\"}", "Invalid parameter at 'kind' failed to satisfy constraint: " + + "'Member must satisfy enum value set: [A, B]'"}, + {"{\"name\":\"ab\",\"items\":[{},{},{}]}", "Invalid parameter at 'items' failed to satisfy constraint: " + + "'Member must have length less than or equal to 2'"}, + {"{\"name\":\"ab\",\"items\":[{}]}", "Invalid parameter at 'items.id' failed to satisfy constraint: " + + "'Member must not be null'"}, + {"{\"name\":\"ab\",\"items\":[{\"id\":\"A1\"}]}", "Invalid parameter at 'items.id' failed to satisfy constraint: " + + "'must satisfy regular expression '[a-z]+''"}, + {"{\"name\":\"ab\",\"labels\":{\"K1\":\"ab\"}}", "Invalid parameter at 'labels.key' failed to satisfy constraint: " + + "'must satisfy regular expression '[a-z]+''"}, + {"[]", "Invalid parameter at '' failed to satisfy constraint: 'Member must be a structure'"} + }; + for (String[] example : cases) { + AwsException failure = assertThrows(AwsException.class, () -> check.check("Put", json(example[0]))); + assertEquals(errorCode, failure.getErrorCode(), example[0]); + assertEquals(400, failure.getHttpStatus(), example[0]); + assertEquals(example[1], failure.getMessage(), example[0]); + } + } } diff --git a/src/test/java/io/floci/aws/services/athena/AthenaCreateWorkGroupPersistenceIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaCreateWorkGroupPersistenceIntegrationTest.java index 3bad84ed86..ae94dacebe 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaCreateWorkGroupPersistenceIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaCreateWorkGroupPersistenceIntegrationTest.java @@ -276,7 +276,7 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest { } @Test - void createWorkGroupResolvesBlankSelectedEngineVersionToDefaultEffectiveVersion() throws Exception { + void createWorkGroupRejectsBlankSelectedEngineVersionWithoutPersistingIt() throws Exception { Files.deleteIfExists(WORKGROUPS_FILE); given() @@ -295,22 +295,14 @@ class AthenaCreateWorkGroupPersistenceIntegrationTest { .when() .post("/") .then() - .statusCode(200); - cleanup.register(() -> deleteWorkGroup("engine-blank-selected")); + .statusCode(400); PersistentStorage> store = new PersistentStorage<>( WORKGROUPS_FILE, new TypeReference>>() {}); store.load(); - Map persisted = store.get("000000000000/us-east-1:engine-blank-selected").orElseThrow(); - @SuppressWarnings("unchecked") - Map configuration = (Map) persisted.get("Configuration"); - @SuppressWarnings("unchecked") - Map engineVersion = (Map) configuration.get("EngineVersion"); - - assertEquals("AUTO", engineVersion.get("SelectedEngineVersion")); - assertEquals("Athena engine version 3", engineVersion.get("EffectiveEngineVersion")); + assertTrue(store.get("000000000000/us-east-1:engine-blank-selected").isEmpty()); } @Test diff --git a/src/test/java/io/floci/aws/services/athena/AthenaDataCatalogIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaDataCatalogIntegrationTest.java index 673be1d839..1321a60d0d 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaDataCatalogIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaDataCatalogIntegrationTest.java @@ -489,7 +489,7 @@ class AthenaDataCatalogIntegrationTest { @Test @Order(19) - void getDataCatalogNamingNullServesTheBuiltInGlueCatalog() { + void getDataCatalogRejectsNullRequiredName() { given() .header("X-Amz-Target", "AmazonAthena.GetDataCatalog") .contentType(CONTENT_TYPE) @@ -497,8 +497,7 @@ class AthenaDataCatalogIntegrationTest { .when() .post("/") .then() - .statusCode(200) - .body("DataCatalog.Name", equalTo("AwsDataCatalog")) - .body("DataCatalog.Type", equalTo("GLUE")); + .statusCode(400) + .body("__type", equalTo("InvalidRequestException")); } } diff --git a/src/test/java/io/floci/aws/services/athena/AthenaGetWorkGroupIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaGetWorkGroupIntegrationTest.java index 31204bc7f1..d6ac543982 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaGetWorkGroupIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaGetWorkGroupIntegrationTest.java @@ -39,7 +39,7 @@ class AthenaGetWorkGroupIntegrationTest { } @Test - void getWorkGroupNamingNullReturnsPrimary() { + void getWorkGroupRejectsNullRequiredName() { given() .header("X-Amz-Target", "AmazonAthena.GetWorkGroup") .contentType(CONTENT_TYPE) @@ -47,8 +47,9 @@ class AthenaGetWorkGroupIntegrationTest { .when() .post("/") .then() - .statusCode(200) - .body("WorkGroup.Name", equalTo("primary")); + .statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", containsString("WorkGroup")); } @Test diff --git a/src/test/java/io/floci/aws/services/athena/AthenaIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaIntegrationTest.java index 433fba5592..4819b667e6 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaIntegrationTest.java @@ -283,7 +283,7 @@ class AthenaIntegrationTest { .then() .statusCode(400) .body("__type", equalTo("InvalidRequestException")) - .body("message", equalTo("WorkGroup is required.")); + .body("message", containsString("WorkGroup")); given() .header("X-Amz-Target", "AmazonAthena.DeleteWorkGroup") @@ -294,7 +294,7 @@ class AthenaIntegrationTest { .then() .statusCode(400) .body("__type", equalTo("InvalidRequestException")) - .body("message", equalTo("WorkGroup is required.")); + .body("message", containsString("WorkGroup")); given() .header("X-Amz-Target", "AmazonAthena.DeleteWorkGroup") @@ -305,7 +305,7 @@ class AthenaIntegrationTest { .then() .statusCode(400) .body("__type", equalTo("InvalidRequestException")) - .body("message", equalTo("WorkGroup is required.")); + .body("message", containsString("WorkGroup")); given() .header("X-Amz-Target", "AmazonAthena.DeleteWorkGroup") @@ -316,7 +316,7 @@ class AthenaIntegrationTest { .then() .statusCode(400) .body("__type", equalTo("InvalidRequestException")) - .body("message", equalTo("WorkGroup is required.")); + .body("message", containsString("WorkGroup")); } @Test diff --git a/src/test/java/io/floci/aws/services/athena/AthenaNamedQueryIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaNamedQueryIntegrationTest.java new file mode 100644 index 0000000000..8f1ca17131 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaNamedQueryIntegrationTest.java @@ -0,0 +1,379 @@ +package io.floci.aws.services.athena; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.athena.AthenaClient; +import software.amazon.awssdk.services.athena.model.BatchGetNamedQueryResponse; +import software.amazon.awssdk.services.athena.model.CreateNamedQueryRequest; +import software.amazon.awssdk.services.athena.model.InvalidRequestException; +import software.amazon.awssdk.services.athena.model.ListNamedQueriesResponse; +import software.amazon.awssdk.services.athena.model.NamedQuery; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +class AthenaNamedQueryIntegrationTest { + + private static final String REGION = "eu-west-2"; + private static final AtomicLong ACCOUNTS = new AtomicLong(741680800000L); + private String account; + private AthenaClient client; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void openClient() { + account = Long.toString(ACCOUNTS.incrementAndGet()); + client = AwsTestClients.create(AthenaClient.builder(), account, Region.of(REGION)); + } + + @AfterEach + void closeClient() { + client.close(); + } + + @Test + void sdkCreatesReadsUpdatesAndDeletesASavedQueryWithoutExecutingSql() { + String id = client.createNamedQuery(request -> request.name("saved query").database("unregistered_db") + .queryString("select * from a_table_that_does_not_exist").description("original")).namedQueryId(); + assertDoesNotThrow(() -> UUID.fromString(id)); + NamedQuery saved = client.getNamedQuery(request -> request.namedQueryId(id)).namedQuery(); + assertEquals("saved query", saved.name()); + assertEquals("unregistered_db", saved.database()); + assertEquals("select * from a_table_that_does_not_exist", saved.queryString()); + assertEquals("original", saved.description()); + assertEquals("primary", saved.workGroup()); + assertEquals(id, saved.namedQueryId()); + assertTrue(client.listQueryExecutions().queryExecutionIds().isEmpty()); + + client.updateNamedQuery(request -> request.namedQueryId(id).name("renamed").queryString("select 2")); + NamedQuery updated = client.getNamedQuery(request -> request.namedQueryId(id)).namedQuery(); + assertEquals("renamed", updated.name()); + assertEquals("select 2", updated.queryString()); + assertEquals("original", updated.description()); + assertEquals(saved.database(), updated.database()); + assertEquals(saved.workGroup(), updated.workGroup()); + client.updateNamedQuery(request -> request.namedQueryId(id).name("renamed") + .queryString("select 2").description("")); + assertEquals("", client.getNamedQuery(request -> request.namedQueryId(id)).namedQuery().description()); + + client.deleteNamedQuery(request -> request.namedQueryId(id)); + assertTrue(client.listNamedQueries().namedQueryIds().isEmpty()); + InvalidRequestException missing = assertThrows(InvalidRequestException.class, + () -> client.getNamedQuery(request -> request.namedQueryId(id))); + assertTrue(missing.getMessage().contains("does not exist")); + assertDoesNotThrow(() -> client.deleteNamedQuery(request -> request.namedQueryId(id))); + assertThrows(InvalidRequestException.class, () -> client.updateNamedQuery(request -> request + .namedQueryId(id).name("missing").queryString("select 1"))); + } + + @Test + void retriesReturnTheOriginalIdAndRejectChangedParametersEvenAfterAnUpdate() { + CreateNamedQueryRequest request = CreateNamedQueryRequest.builder().name("retry").database("db") + .queryString("select 1").description("initial").clientRequestToken(UUID.randomUUID().toString()).build(); + String id = client.createNamedQuery(request).namedQueryId(); + assertEquals(id, client.createNamedQuery(request).namedQueryId()); + assertEquals(1, client.listNamedQueries().namedQueryIds().size()); + for (CreateNamedQueryRequest changed : List.of(request.toBuilder().name("other").build(), + request.toBuilder().database("other").build(), request.toBuilder().queryString("select 2").build(), + request.toBuilder().description("other").build(), request.toBuilder().workGroup("other").build())) { + assertThrows(InvalidRequestException.class, () -> client.createNamedQuery(changed)); + } + client.updateNamedQuery(update -> update.namedQueryId(id).name("updated").queryString("select 3")); + assertEquals(id, client.createNamedQuery(request).namedQueryId()); + assertEquals("updated", client.getNamedQuery(get -> get.namedQueryId(id)).namedQuery().name()); + assertNotEquals(id, client.createNamedQuery(request.toBuilder() + .clientRequestToken(UUID.randomUUID().toString()).build()).namedQueryId()); + } + + @ParameterizedTest + @ValueSource(strings = {"", ",\"ClientRequestToken\":null"}) + void requestsWithoutClientRequestTokensCreateIndependentQueries(String token) { + String body = "{\"Name\":\"untokened\",\"Database\":\"db\",\"QueryString\":\"select 1\"" + token + "}"; + List ids = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + ids.add(rawRequest("CreateNamedQuery", body).statusCode(200).extract().path("NamedQueryId")); + } + assertNotEquals(ids.getFirst(), ids.getLast()); + for (String id : ids) { + assertDoesNotThrow(() -> UUID.fromString(id)); + assertEquals("untokened", client.getNamedQuery(request -> request.namedQueryId(id)).namedQuery().name()); + } + } + + @Test + void batchGetReturnsSavedQueriesAndPerIdErrorsForMissingQueries() { + String first = create("primary"); + String second = create("primary"); + String missing = UUID.randomUUID().toString(); + BatchGetNamedQueryResponse response = client.batchGetNamedQuery(request -> request + .namedQueryIds(first, missing, second)); + assertEquals(List.of(first, second), response.namedQueries().stream().map(NamedQuery::namedQueryId).toList()); + assertEquals(1, response.unprocessedNamedQueryIds().size()); + assertEquals(missing, response.unprocessedNamedQueryIds().getFirst().namedQueryId()); + assertNotNull(response.unprocessedNamedQueryIds().getFirst().errorCode()); + assertNotNull(response.unprocessedNamedQueryIds().getFirst().errorMessage()); + assertTrue(client.batchGetNamedQuery(request -> request.namedQueryIds(first)).unprocessedNamedQueryIds().isEmpty()); + assertThrows(InvalidRequestException.class, + () -> client.batchGetNamedQuery(request -> request.namedQueryIds(List.of()))); + assertThrows(InvalidRequestException.class, () -> client.batchGetNamedQuery(request -> request + .namedQueryIds(Collections.nCopies(51, first)))); + } + + @Test + void sdkPagesAndPaginatorFilterByWorkGroupAndResumeAfterADeletedCursor() { + List ids = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + ids.add(create("primary")); + } + client.createWorkGroup(request -> request.name("other")); + String other = create("other"); + List paged = client.listNamedQueriesPaginator(request -> request.maxResults(1)).stream() + .flatMap(page -> page.namedQueryIds().stream()).toList(); + assertEquals(ids.stream().sorted().toList(), paged); + assertEquals(List.of(other), client.listNamedQueries(request -> request.workGroup("other")).namedQueryIds()); + + ListNamedQueriesResponse first = client.listNamedQueries(request -> request.maxResults(1)); + assertNotNull(first.nextToken()); + client.deleteNamedQuery(request -> request.namedQueryId(first.namedQueryIds().getFirst())); + ListNamedQueriesResponse last = client.listNamedQueries(request -> request.nextToken(first.nextToken())); + assertEquals(paged.subList(1, 3), last.namedQueryIds()); + assertNull(last.nextToken()); + assertThrows(InvalidRequestException.class, () -> client.listNamedQueries(request -> request + .workGroup("other").nextToken(first.nextToken()))); + } + + @Test + void omittedZeroAndMaximumPageSizesAreBounded() { + for (int i = 0; i < 51; i++) { + create("primary"); + } + for (Integer size : new Integer[]{null, 0, 50}) { + ListNamedQueriesResponse first = client.listNamedQueries(request -> request.maxResults(size)); + assertEquals(50, first.namedQueryIds().size()); + assertNotNull(first.nextToken()); + ListNamedQueriesResponse last = client.listNamedQueries(request -> request.nextToken(first.nextToken())); + assertEquals(1, last.namedQueryIds().size()); + assertNull(last.nextToken()); + } + } + + @Test + void queriesAndRetryTokensAreIsolatedByAccountAndRegion() { + CreateNamedQueryRequest request = CreateNamedQueryRequest.builder().name("isolated").database("db") + .queryString("select 1").clientRequestToken(UUID.randomUUID().toString()).build(); + String id = client.createNamedQuery(request).namedQueryId(); + withIsolatedClients(clients -> { + for (AthenaClient isolated : clients) { + assertTrue(isolated.listNamedQueries().namedQueryIds().isEmpty()); + assertThrows(InvalidRequestException.class, () -> isolated.getNamedQuery(get -> get.namedQueryId(id))); + assertThrows(InvalidRequestException.class, () -> isolated.updateNamedQuery(update -> update + .namedQueryId(id).name("stolen").queryString("select 2"))); + isolated.deleteNamedQuery(delete -> delete.namedQueryId(id)); + assertNotEquals(id, isolated.createNamedQuery(request).namedQueryId()); + } + }); + assertEquals("isolated", client.getNamedQuery(get -> get.namedQueryId(id)).namedQuery().name()); + } + + @Test + void paginationTokensCannotCrossAccountRegionOrAction() { + create("primary"); + create("primary"); + String token = client.listNamedQueries(request -> request.maxResults(1)).nextToken(); + withIsolatedClients(clients -> { + for (AthenaClient isolated : clients) { + assertThrows(InvalidRequestException.class, + () -> isolated.listNamedQueries(request -> request.nextToken(token))); + } + }); + assertThrows(InvalidRequestException.class, + () -> client.listQueryExecutions(request -> request.nextToken(token))); + } + + @Test + void rejectsMissingWorkGroups() { + assertThrows(InvalidRequestException.class, () -> create("missing")); + assertThrows(InvalidRequestException.class, + () -> client.listNamedQueries(request -> request.workGroup("missing"))); + } + + @Test + void unknownActionsStillReturnInvalidAction() { + rawRequest("UnknownAction", "{}").statusCode(400).body("__type", equalTo("InvalidAction")); + } + + @Test + void populatedWorkGroupRequiresRecursiveDeletion() { + client.createWorkGroup(request -> request.name("populated")); + String id = create("populated"); + assertThrows(InvalidRequestException.class, + () -> client.deleteWorkGroup(request -> request.workGroup("populated"))); + assertThrows(InvalidRequestException.class, () -> client.deleteWorkGroup(request -> request + .workGroup("populated").recursiveDeleteOption(false))); + assertEquals("populated", client.getWorkGroup(request -> request.workGroup("populated")).workGroup().name()); + assertEquals(id, client.getNamedQuery(request -> request.namedQueryId(id)).namedQuery().namedQueryId()); + } + + @Test + void recursiveDeletionRemovesSavedQueriesBeforeTheWorkGroupIsRecreated() { + client.createWorkGroup(request -> request.name("recreated")); + CreateNamedQueryRequest original = CreateNamedQueryRequest.builder().name("saved").database("db") + .queryString("select 1").workGroup("recreated").clientRequestToken(UUID.randomUUID().toString()).build(); + String first = client.createNamedQuery(original).namedQueryId(); + String second = create("recreated"); + String primary = create("primary"); + client.deleteWorkGroup(request -> request.workGroup("recreated").recursiveDeleteOption(true)); + assertThrows(InvalidRequestException.class, + () -> client.getWorkGroup(request -> request.workGroup("recreated"))); + for (String id : List.of(first, second)) { + assertThrows(InvalidRequestException.class, + () -> client.getNamedQuery(request -> request.namedQueryId(id))); + } + assertEquals(2, client.batchGetNamedQuery(request -> request.namedQueryIds(first, second)) + .unprocessedNamedQueryIds().size()); + client.createWorkGroup(request -> request.name("recreated")); + assertTrue(client.listNamedQueries(request -> request.workGroup("recreated")).namedQueryIds().isEmpty()); + assertEquals(List.of(primary), client.listNamedQueries().namedQueryIds()); + String recreated = client.createNamedQuery(original).namedQueryId(); + assertNotEquals(first, recreated); + assertEquals(recreated, client.getNamedQuery(request -> request.namedQueryId(recreated)).namedQuery().namedQueryId()); + } + + @Test + void recursiveDeletionIsIsolatedByAccountAndRegion() { + client.createWorkGroup(request -> request.name("scoped")); + String removed = create("scoped"); + withIsolatedClients(isolatedClients -> { + CreateNamedQueryRequest original = CreateNamedQueryRequest.builder().name("saved").database("db") + .queryString("select 1").workGroup("scoped").clientRequestToken(UUID.randomUUID().toString()).build(); + List preserved = new ArrayList<>(); + for (AthenaClient isolated : isolatedClients) { + isolated.createWorkGroup(request -> request.name("scoped")); + preserved.add(isolated.createNamedQuery(original).namedQueryId()); + } + client.deleteWorkGroup(request -> request.workGroup("scoped").recursiveDeleteOption(true)); + assertThrows(InvalidRequestException.class, + () -> client.getNamedQuery(request -> request.namedQueryId(removed))); + for (int i = 0; i < isolatedClients.size(); i++) { + AthenaClient isolated = isolatedClients.get(i); + String id = preserved.get(i); + assertEquals(List.of(id), isolated.listNamedQueries(request -> request.workGroup("scoped")).namedQueryIds()); + assertEquals(id, isolated.getNamedQuery(request -> request.namedQueryId(id)).namedQuery().namedQueryId()); + assertEquals(id, isolated.createNamedQuery(original).namedQueryId()); + } + }); + } + + @Test + void emptyWorkGroupCanBeDeletedWithoutTheRecursiveOption() { + client.createWorkGroup(request -> request.name("empty")); + client.deleteWorkGroup(request -> request.workGroup("empty")); + assertThrows(InvalidRequestException.class, + () -> client.getWorkGroup(request -> request.workGroup("empty"))); + } + + @ParameterizedTest + @ValueSource(strings = {"\"true\"", "1", "[]", "{}"}) + void deleteWorkGroupRejectsNonBooleanRecursiveOptions(String option) { + invalidRequest("DeleteWorkGroup", "{\"WorkGroup\":\"invalid-option\",\"RecursiveDeleteOption\":" + option + "}"); + } + + @ParameterizedTest + @ValueSource(strings = { + "{}", "{\"Name\":\"\"}", "{\"Name\":3}", "{\"Database\":\"\"}", "{\"Database\":[]}", + "{\"QueryString\":\"\"}", "{\"Description\":\"\"}", "{\"WorkGroup\":\"bad group\"}", + "{\"ClientRequestToken\":\"short\"}" + }) + void createRejectsInvalidInput(String overrides) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode body = mapper.createObjectNode(); + if (!overrides.equals("{}")) { + body.put("Name", "valid").put("Database", "db").put("QueryString", "select 1") + .put("ClientRequestToken", "12345678901234567890123456789012"); + body.setAll((ObjectNode) mapper.readTree(overrides)); + } + invalidRequest("CreateNamedQuery", body.toString()); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"MaxResults\":-1}", "{\"MaxResults\":51}", "{\"MaxResults\":1.5}", + "{\"MaxResults\":\"1\"}", "{\"MaxResults\":2147483648}", "{\"NextToken\":false}", + "{\"NextToken\":\"\"}", "{\"NextToken\":\"invalid\"}", "{\"WorkGroup\":4}"}) + void listRejectsInvalidInput(String body) { + invalidRequest("ListNamedQueries", body); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"NamedQueryIds\":[]}", "{\"NamedQueryIds\":\"id\"}", + "{\"NamedQueryIds\":[null]}", "{\"NamedQueryIds\":[1]}", "{\"NamedQueryIds\":[\"\"]}"}) + void batchRejectsInvalidInput(String body) { + invalidRequest("BatchGetNamedQuery", body); + } + + @Test + void rejectsInvalidIdsAndOversizedFields() { + for (String action : List.of("GetNamedQuery", "DeleteNamedQuery", "UpdateNamedQuery")) { + invalidRequest(action, "{}"); + invalidRequest(action, "{\"NamedQueryId\":\"has space\",\"Name\":\"n\",\"QueryString\":\"q\"}"); + } + for (CreateNamedQueryRequest request : List.of( + CreateNamedQueryRequest.builder().name("n".repeat(129)).database("db").queryString("q").build(), + CreateNamedQueryRequest.builder().name("n").database("d".repeat(256)).queryString("q").build(), + CreateNamedQueryRequest.builder().name("n").database("db").queryString("q".repeat(262145)).build(), + CreateNamedQueryRequest.builder().name("n").database("db").queryString("q") + .description("d".repeat(1025)).build())) { + assertThrows(InvalidRequestException.class, () -> client.createNamedQuery(request)); + } + assertThrows(InvalidRequestException.class, + () -> client.listNamedQueries(request -> request.nextToken("t".repeat(1025)))); + } + + private String create(String workGroup) { + return client.createNamedQuery(request -> request.name("saved").database("db") + .queryString("select 1").workGroup(workGroup)).namedQueryId(); + } + + private void invalidRequest(String action, String body) { + rawRequest(action, body).statusCode(400).body("__type", equalTo("InvalidRequestException")); + } + + private ValidatableResponse rawRequest(String action, String body) { + return given().header("X-Amz-Target", "AmazonAthena." + action) + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account + "/20261111/" + REGION + + "/athena/aws4_request, SignedHeaders=host, Signature=test") + .contentType("application/x-amz-json-1.1").body(body) + .when().post("/").then(); + } + + private void withIsolatedClients(Consumer> assertions) { + try (AthenaClient anotherAccount = AwsTestClients.create(AthenaClient.builder(), + Long.toString(ACCOUNTS.incrementAndGet()), Region.of(REGION)); + AthenaClient anotherRegion = AwsTestClients.create(AthenaClient.builder(), account, Region.US_WEST_2)) { + assertions.accept(List.of(anotherAccount, anotherRegion)); + } + } +} diff --git a/src/test/java/io/floci/aws/services/athena/AthenaNamedQueryServiceTest.java b/src/test/java/io/floci/aws/services/athena/AthenaNamedQueryServiceTest.java new file mode 100644 index 0000000000..08fdc430ba --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaNamedQueryServiceTest.java @@ -0,0 +1,81 @@ +package io.floci.aws.services.athena; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.PersistentStorage; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.athena.model.NamedQuery; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.Map; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class AthenaNamedQueryServiceTest { + + @TempDir + Path directory; + + @Test + void reloadRestoresQueriesAndTheOriginalIdempotencyRequest() { + AthenaNamedQueryService service = persistentService(); + String token = UUID.randomUUID().toString(); + String id = service.createNamedQuery("eu-west-2", "original", "db", "select 1", "description", null, token); + service.updateNamedQuery("eu-west-2", id, "updated", "select 2", ""); + + AthenaNamedQueryService reloaded = persistentService(); + NamedQuery saved = reloaded.getNamedQuery("eu-west-2", id); + assertEquals("updated", saved.name()); + assertEquals("db", saved.database()); + assertEquals("select 2", saved.queryString()); + assertEquals("", saved.description()); + assertEquals("primary", saved.workGroup()); + assertEquals(id, reloaded.createNamedQuery("eu-west-2", "original", "db", "select 1", "description", null, token)); + assertThrows(AwsException.class, () -> reloaded.createNamedQuery("eu-west-2", "updated", "db", "select 2", + "", null, token)); + assertEquals(1, reloaded.listNamedQueries("eu-west-2", null, null, null).items().size()); + + reloaded.deleteNamedQuery("eu-west-2", id); + AthenaNamedQueryService deleted = persistentService(); + assertThrows(AwsException.class, () -> deleted.getNamedQuery("eu-west-2", id)); + assertTrue(deleted.listNamedQueries("eu-west-2", null, null, null).items().isEmpty()); + } + + @Test + void recursiveWorkGroupDeletionPersistsAndRemovesItsRetryRequests() { + AthenaNamedQueryService service = persistentService(); + String token = UUID.randomUUID().toString(); + String removed = service.createNamedQuery("eu-west-2", "saved", "db", "select 1", null, "removed", token); + String preserved = service.createNamedQuery("eu-west-2", "saved", "db", "select 1", null, + "primary", UUID.randomUUID().toString()); + service.deleteWorkGroup("eu-west-2", "removed", true); + + AthenaNamedQueryService reloaded = persistentService(); + assertThrows(AwsException.class, () -> reloaded.getNamedQuery("eu-west-2", removed)); + assertEquals(preserved, reloaded.getNamedQuery("eu-west-2", preserved).namedQueryId()); + String recreated = reloaded.createNamedQuery("eu-west-2", "saved", "db", "select 1", null, "removed", token); + assertNotEquals(removed, recreated); + assertEquals(recreated, reloaded.getNamedQuery("eu-west-2", recreated).namedQueryId()); + } + + private AthenaNamedQueryService persistentService() { + StorageFactory factory = mock(StorageFactory.class); + when(factory.create(eq("athena"), anyString(), any())).thenAnswer(invocation -> { + Path file = directory.resolve(invocation.getArgument(1, String.class)); + PersistentStorage backend = new PersistentStorage<>(file, + new TypeReference>() {}); + backend.load(); + return new AccountAwareStorageBackend<>(backend, null, "741680800000"); + }); + RegionResolver resolver = mock(RegionResolver.class); + when(resolver.getAccountId()).thenReturn("741680800000"); + return new AthenaNamedQueryService(factory, mock(AthenaService.class), resolver); + } +} diff --git a/src/test/java/io/floci/aws/services/athena/AthenaRequestShapesTest.java b/src/test/java/io/floci/aws/services/athena/AthenaRequestShapesTest.java new file mode 100644 index 0000000000..da63e739c8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaRequestShapesTest.java @@ -0,0 +1,72 @@ +package io.floci.aws.services.athena; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +class AthenaRequestShapesTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void creationAllowsAnOmittedOrNullTokenAndValidatesProvidedTokens() throws Exception { + JsonNode request = json("{\"Name\":\"saved\",\"Database\":\"db\",\"QueryString\":\"select 1\"}"); + assertDoesNotThrow(() -> AthenaRequestShapes.check("CreateNamedQuery", request)); + assertDoesNotThrow(() -> AthenaRequestShapes.check("CreateNamedQuery", json( + "{\"Name\":\"saved\",\"Database\":\"db\",\"QueryString\":\"select 1\",\"ClientRequestToken\":null}"))); + refusal("CreateNamedQuery", "{\"Name\":\"saved\",\"Database\":\"db\",\"QueryString\":\"select 1\"," + + "\"ClientRequestToken\":\"short\"}"); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateNamedQuery", "GetNamedQuery", "BatchGetNamedQuery", "UpdateNamedQuery", + "DeleteNamedQuery", "GetWorkGroup", "GetDataCatalog", "ListDatabases", "GetTableMetadata"}) + void modelRequiredFieldsAreEnforced(String operation) throws Exception { + refusal(operation, "{}"); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "ListNamedQueries|{\"MaxResults\":51}", + "ListNamedQueries|{\"MaxResults\":\"1\"}", + "ListNamedQueries|{\"NextToken\":false}", + "ListNamedQueries|{\"WorkGroup\":\"bad group\"}", + "GetNamedQuery|{\"NamedQueryId\":\"has space\"}", + "BatchGetNamedQuery|{\"NamedQueryIds\":[]}", + "BatchGetNamedQuery|{\"NamedQueryIds\":[null]}", + "CreateWorkGroup|{\"Name\":\"team\",\"Configuration\":{\"EnforceWorkGroupConfiguration\":1}}", + "CreateWorkGroup|{\"Name\":\"team\",\"Tags\":[{\"Key\":4,\"Value\":\"value\"}]}", + "CreateDataCatalog|{\"Name\":\"catalog\",\"Type\":\"GLUE\",\"Parameters\":{\"catalog-id\":4}}", + "CreateDataCatalog|{\"Name\":\"catalog\",\"Type\":\"UNKNOWN\"}", + "DeleteWorkGroup|{\"WorkGroup\":\"team\",\"RecursiveDeleteOption\":\"true\"}", + "ListEngineVersions|{\"MaxResults\":\"1\"}" + }) + void typesBoundsPatternsAndEnumsAreCheckedAcrossAthenaOperations(String operation, String body) throws Exception { + refusal(operation, body); + } + + @Test + void modelStringLengthsCountUnicodeCodePoints() throws Exception { + String name = "\uD83D\uDE00".repeat(128); + assertDoesNotThrow(() -> AthenaRequestShapes.check("CreateNamedQuery", json( + "{\"Name\":\"" + name + "\",\"Database\":\"db\",\"QueryString\":\"select 1\"}"))); + refusal("CreateNamedQuery", "{\"Name\":\"" + name + "a\",\"Database\":\"db\",\"QueryString\":\"select 1\"}"); + } + + private static void refusal(String operation, String body) throws Exception { + JsonNode request = json(body); + AwsException failure = assertThrows(AwsException.class, () -> AthenaRequestShapes.check(operation, request)); + assertEquals("InvalidRequestException", failure.getErrorCode()); + assertEquals(400, failure.getHttpStatus()); + } + + private static JsonNode json(String body) throws Exception { + return MAPPER.readTree(body); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java index 99f5040479..3ba972305a 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -929,8 +929,11 @@ class IamRequestResourceEnforcementIntegrationTest { + allowOn("athena:StartQueryExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":" + "\"athena:StartQueryExecution\",\"Resource\":\"" + primary + "\"}"); send(user, "athena", "AmazonAthena.ListQueryExecutions", "1.1", "{}").statusCode(200); - send(user, "athena", "AmazonAthena.GetWorkGroup", "1.1", "{}").statusCode(200); - send(user, "athena", "AmazonAthena.GetWorkGroup", "1.1", "{\"WorkGroup\":null}").statusCode(200) + send(user, "athena", "AmazonAthena.GetWorkGroup", "1.1", "{}").statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + send(user, "athena", "AmazonAthena.GetWorkGroup", "1.1", "{\"WorkGroup\":null}").statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + send(user, "athena", "AmazonAthena.GetWorkGroup", "1.1", "{\"WorkGroup\":\"primary\"}").statusCode(200) .body("WorkGroup.Name", equalTo("primary")); refusedJson(send(user, "athena", "AmazonAthena.ListQueryExecutions", "1.1", "{\"WorkGroup\":\"res-other\"}"), "athena:ListQueryExecutions"); @@ -958,19 +961,22 @@ class IamRequestResourceEnforcementIntegrationTest { } /** - * An Athena catalog request naming no catalog, or a JSON null, is checked on {@code AwsDataCatalog}, the one - * {@code GetDataCatalog} answers and the catalog reads read, so a grant on it reaches them and a deny on it applies. + * Athena authorization checks the default Glue catalog before model validation rejects a missing required + * catalog name. A grant reaches validation; a deny still refuses the request before it. */ @Test void aCatalogRequestNamingNoCatalogIsCheckedOnTheGlueOne() { String glue = "arn:aws:athena:" + REGION + ":" + ACCOUNT + ":datacatalog/AwsDataCatalog"; User user = user("res-glue-catalog"); user.policy(allowOn("athena:GetDataCatalog", glue) + "," + allowOn("athena:ListDatabases", glue)); - send(user, "athena", "AmazonAthena.GetDataCatalog", "1.1", "{}").statusCode(200) + send(user, "athena", "AmazonAthena.GetDataCatalog", "1.1", "{}").statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + send(user, "athena", "AmazonAthena.GetDataCatalog", "1.1", "{\"Name\":null}").statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":null}").statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + send(user, "athena", "AmazonAthena.GetDataCatalog", "1.1", "{\"Name\":\"AwsDataCatalog\"}").statusCode(200) .body("DataCatalog.Name", equalTo("AwsDataCatalog")); - send(user, "athena", "AmazonAthena.GetDataCatalog", "1.1", "{\"Name\":null}").statusCode(200) - .body("DataCatalog.Name", equalTo("AwsDataCatalog")); - send(user, "athena", "AmazonAthena.ListDatabases", "1.1", "{\"CatalogName\":null}").statusCode(200); refusedJson(send(user, "athena", "AmazonAthena.GetDataCatalog", "1.1", "{\"Name\":\"res-other\"}"), "athena:GetDataCatalog"); User denied = user("res-glue-denied"); diff --git a/tools/aws/regen_athena_shapes.py b/tools/aws/regen_athena_shapes.py new file mode 100644 index 0000000000..a49e6987b4 --- /dev/null +++ b/tools/aws/regen_athena_shapes.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Vendor every Athena operation's request constraints from botocore's Apache-2.0 service model. + +AthenaRequestShapes checks each request through RequestConstraintCheck using the model's +types, required members, bounds, patterns and enums. + +Run from anywhere in the repo: + python3 tools/aws/regen_athena_shapes.py + python3 tools/aws/regen_athena_shapes.py --check +""" +from __future__ import annotations + +import sys +from pathlib import Path + +import request_shapes + +OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/athena-request-shapes.json" +MODEL = Path("athena/2017-05-18") + + +def main(argv: list[str] | None = None) -> int: + return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, + description=__doc__, constraints=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py index b26fca0633..bfcd54ba2f 100644 --- a/tools/aws/request_shapes.py +++ b/tools/aws/request_shapes.py @@ -151,6 +151,7 @@ def generator_name(script: str) -> str: def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str, outputs: bool = False, operations: tuple[str, ...] | None = None, + constraints: bool = False, prepare: Callable[[dict], dict] | None = None) -> int: """Drives one generator: parse the flags, read the model, write or check the vendored file. @@ -160,6 +161,9 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path, desc Query-protocol generators share this too rather than each repeating the flags and the staleness check. + `constraints=True` keeps constraints for every operation with an input, without maintaining + a separate operation list. + `prepare` is the one thing a generator may do to the model before any of that, for an operation it vendors in part: IAM reduces a paged request to its paging members, the rest of it keeping the reading it has today.""" @@ -173,6 +177,8 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path, desc loaded = load_model(data, model) if prepare is not None: loaded = prepare(loaded) + if constraints and operations is None: + operations = tuple(name for name, operation in sorted(loaded["operations"].items()) if "input" in operation) generator = generator_name(script) fresh = render(build_constraints(loaded, operations, provenance, generator) if operations is not None else build(loaded, provenance, generator, outputs)) diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index 8f70dbc8b3..734b173109 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -19,6 +19,7 @@ import pytest import regen_apigateway_documentation_shapes import regen_apigateway_shapes +import regen_athena_shapes import regen_dynamodb_shapes import regen_ecr_shapes import regen_ecs_shapes @@ -245,6 +246,32 @@ CONSTRAINED_MODEL = { } +def test_athena_generator_keeps_constraints_for_every_operation_and_detects_new_operations(tmp_path, monkeypatch): + output = tmp_path / "athena-request-shapes.json" + monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test")) + monkeypatch.setattr(r, "load_model", lambda data, model: CONSTRAINED_MODEL) + args = ["--output", str(output)] + + assert regen_athena_shapes.MODEL == Path("athena/2017-05-18") + assert regen_athena_shapes.main(args) == 0 + doc = json.loads(output.read_text()) + assert doc["operations"] == {"Put": "PutRequest", "Unused": "UnusedRequest"} + assert doc["shapes"]["Name"]["min"] == 1 + assert doc["shapes"]["Name"]["pattern"] == "[a-z]+" + assert doc["shapes"]["PutRequest"]["required"] == ["name"] + assert doc["shapes"]["Kind"]["enum"] == ["A", "B"] + assert doc["shapes"]["RuleList"]["max"] == 25 + assert doc["shapes"]["TagMap"]["key"] == "Name" + assert regen_athena_shapes.main(["--check", *args]) == 0 + + changed = {**CONSTRAINED_MODEL, "operations": {**CONSTRAINED_MODEL["operations"], + "NewOperation": {"input": {"shape": "PutRequest"}}}} + monkeypatch.setattr(r, "load_model", lambda data, model: changed) + assert regen_athena_shapes.main(["--check", *args]) == 1 + assert regen_athena_shapes.main(args) == 0 + assert "NewOperation" in json.loads(output.read_text())["operations"] + + def test_build_constraints_keeps_the_named_operations_with_their_constraints(): doc = r.build_constraints(CONSTRAINED_MODEL, ("Put",), "botocore test", "tools/aws/regen_x_shapes.py")