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.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-11 14:08:46 -04:00
1 parent 475fb1822a
commit 77587de2e6
26 files changed
+2533 -144

No files matched your search

+7
View File
@@ -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."; \
+43 -2
View File
@@ -10,6 +10,12 @@ Floci emulates Amazon Athena with **real SQL execution** powered by a [floci-duc
<!-- floci:actions:start -->
| 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 |
<!-- floci:actions:end -->
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
+1 -1
View File
@@ -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 /<Action>` | REST JSON | 16 |
| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 |
@@ -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<String> 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<String, Pattern> 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);
@@ -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<String> queryIds = new ArrayList<>();
for (JsonNode id : ids) {
queryIds.add(id.textValue());
}
yield Response.ok(namedQueryService.batchGetNamedQuery(region, queryIds)).build();
}
case "ListNamedQueries" -> {
PaginatedResult<NamedQuery> page = namedQueryService.listNamedQueries(region,
text(request, "WorkGroup"),
Pagination.parseMaxResults(request, "MaxResults", "InvalidRequestException"),
Pagination.parseNextToken(request, "NextToken", "InvalidRequestException"));
Map<String, Object> 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);
@@ -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<String, NamedQuery> queries;
private final StorageBackend<String, NamedQuery> 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<String, Object> batchGetNamedQuery(String region, List<String> ids) {
List<NamedQuery> found = new ArrayList<>();
List<Map<String, String>> 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<NamedQuery> 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<NamedQuery> 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<NamedQuery> 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);
}
}
@@ -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);
}
}
}
@@ -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));
}
@@ -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) {
}
@@ -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<String> 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);
}
}
@@ -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() {
}
@@ -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() {
}
@@ -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.
*
* <p>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<String> 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);
}
}
File diff suppressed because it is too large. Load diff
@@ -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]);
}
}
}
@@ -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<String, Map<String, Object>> store = new PersistentStorage<>(
WORKGROUPS_FILE,
new TypeReference<Map<String, Map<String, Object>>>() {});
store.load();
Map<String, Object> persisted = store.get("000000000000/us-east-1:engine-blank-selected").orElseThrow();
@SuppressWarnings("unchecked")
Map<String, Object> configuration = (Map<String, Object>) persisted.get("Configuration");
@SuppressWarnings("unchecked")
Map<String, Object> engineVersion = (Map<String, Object>) 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
@@ -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"));
}
}
@@ -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
@@ -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
@@ -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<String> 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<String> 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<String> 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<String> 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<List<AthenaClient>> 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));
}
}
}
@@ -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.<NamedQuery>create(eq("athena"), anyString(), any())).thenAnswer(invocation -> {
Path file = directory.resolve(invocation.getArgument(1, String.class));
PersistentStorage<String, NamedQuery> backend = new PersistentStorage<>(file,
new TypeReference<Map<String, NamedQuery>>() {});
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);
}
}
@@ -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);
}
}
@@ -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");
+28
View File
@@ -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())
+6
View File
@@ -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))
+27
View File
@@ -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")