mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(apigateway): return a usage plan's API stages, throttle and quota (#6360)
* fix(apigateway): return a usage plan's API stages, throttle and quota * fix(apigateway): refuse a usage plan create whose text or number member is a list, map or wrong scalar * fix(apigateway): refuse an unknown usage plan quota period before any other create check * fix(apigateway): check a usage plan create body against API Gateway's vendored request shapes * fix(apigateway): read a usage plan create body the way API Gateway does * fix(apigateway): truncate a usage plan's integer limits without a double rounding * refactor(apigateway): reuse SmithyValidationErrors and a shared request shape lookup
This commit is contained in:
1 parent
da9f7e93b1
commit
bab7af3a21
19 files changed
+2684
-85
No files matched your search
@@ -19,6 +19,8 @@
|
||||
# API Gateway integration types come from the public service model via tools/aws/regen_apigateway_types.py.
|
||||
# src/main/resources/aws/sesv2-request-shapes.json is generated from botocore's SES v2 model
|
||||
# by tools/aws/regen_sesv2_shapes.py.
|
||||
# src/main/resources/aws/apigateway-request-shapes.json is generated from botocore's API Gateway
|
||||
# model by tools/aws/regen_apigateway_shapes.py.
|
||||
# src/main/resources/aws/ecs-request-shapes.json is generated from botocore's ECS model
|
||||
# by tools/aws/regen_ecs_shapes.py.
|
||||
# src/main/resources/aws/ecr-request-shapes.json, the ECR request constraints, is generated
|
||||
@@ -226,6 +228,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
|
||||
$(PYTHON) tools/aws/regen_ecr_shapes.py
|
||||
$(PYTHON) tools/aws/regen_apigateway_types.py
|
||||
$(PYTHON) tools/aws/regen_sesv2_shapes.py
|
||||
$(PYTHON) tools/aws/regen_apigateway_shapes.py
|
||||
$(PYTHON) tools/aws/regen_ecs_shapes.py
|
||||
$(PYTHON) tools/aws/regen_emr_serverless_shapes.py
|
||||
$(PYTHON) tools/aws/regen_query_services.py
|
||||
@@ -277,6 +280,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_apigateway_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/apigateway-request-shapes.json is out of date."; \
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_ecs_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/ecs-request-shapes.json is out of date."; \
|
||||
|
||||
@@ -576,6 +576,38 @@ aws apigateway create-deployment \
|
||||
curl http://localhost:4566/restapis/$API_ID/dev/_user_request_/users
|
||||
```
|
||||
|
||||
### Usage plan stages, throttle and quota
|
||||
|
||||
`CreateUsagePlan`, `GetUsagePlan`, `GetUsagePlans` and `UpdateUsagePlan` return a plan's `apiStages`,
|
||||
as `[]` for a plan with none, with each stage's per-method `throttle`, and the plan's `throttle` and
|
||||
`quota`. `CreateUsagePlan` validates them with API Gateway's messages: a quota needs a `DAY`, `WEEK`
|
||||
or `MONTH` period and an offset inside it, a per-method throttle needs a plan throttle, and listing a
|
||||
stage twice is a `ConflictException`.
|
||||
|
||||
Floci does not check that a stage's API, stage or method exists, does not filter `GetUsagePlans` by
|
||||
`keyId`, and does not enforce throttles or quotas.
|
||||
|
||||
A `CreateUsagePlan` body member of the wrong JSON type is a `SerializationException` with API
|
||||
Gateway's deserializer message, before anything else is validated. The message names the Java class
|
||||
API Gateway read, such as `class java.lang.String can not be converted to an Integer` for
|
||||
`"limit": "100"` or `class java.lang.String is not an expected Json type` for a text `rateLimit`. When
|
||||
several members are wrong, the one reported is the first in member-name order, and a map's entries
|
||||
are read in key order, at every level, whatever order the body has. An integer member (`limit`,
|
||||
`offset`, `burstLimit`) reads any JSON number, truncated from its decimal digits and clamped to the int
|
||||
range, so `1.5` and `1.99999999999999999` are stored as `1` and `3000000000` as `2147483647`. A
|
||||
negative fraction such as `-0.9` is refused as negative rather than truncated to `0`, and a numeric
|
||||
string such as `"100"` is refused.
|
||||
|
||||
A zero-byte body is a `ValidationException` (`Value null at 'createUsagePlanInput'`). A whitespace-only
|
||||
body, malformed JSON, trailing content after the object, and a body that is a string, a number or
|
||||
`null` are a `SerializationException` without a message, and a top-level array is `Start of list found
|
||||
where not expected`. A missing or `null` `name` is a `ValidationException`, listed after an invalid quota
|
||||
period in the same message (`2 validation errors detected: ...; ...`), and an empty `name` is a
|
||||
`BadRequestException` `Usage Plan name must be specified`, checked before the throttle and quota.
|
||||
|
||||
The body shapes are vendored in `src/main/resources/aws/apigateway-request-shapes.json`, generated by
|
||||
`tools/aws/regen_apigateway_shapes.py` from the botocore release pinned in `tools/aws/requirements.txt`.
|
||||
|
||||
### Usage reporting
|
||||
|
||||
`GetUsage` returns the real response envelope: a `values` map of API key id to one `[used, remaining]`
|
||||
@@ -596,11 +628,9 @@ The lower bound is a deliberate divergence: real API Gateway answers `limit=0` a
|
||||
an `InternalFailure`, which is a fault rather than a contract, so a page size below one is rejected
|
||||
as a `BadRequestException` instead of reproducing a 500.
|
||||
|
||||
**Both numbers are always zero.** Nothing meters requests per API key, and a usage plan stores no
|
||||
quota to subtract from, so there is no limit to report against. Throttle settings are likewise
|
||||
accepted and stored but never enforced. Storing a quota on the usage plan and counting on the
|
||||
execute path are the two pieces still missing; a caller that sums the used counts gets zero, which
|
||||
is what it already got before the action existed, without having to special-case a missing endpoint.
|
||||
**Both numbers are always zero.** Nothing meters requests per API key, so there is no use to report
|
||||
or to subtract from a plan's quota. Throttle settings and quotas are stored and returned but never
|
||||
enforced.
|
||||
|
||||
### Usage Plan Tags and Custom IDs
|
||||
|
||||
|
||||
@@ -2,21 +2,29 @@ package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeModel.Shape;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* Walks a request value against a {@link RequestShapeModel} as AWS's JSON deserializers read a body,
|
||||
* before an operation validates anything, and refuses the first member of the wrong JSON type. The
|
||||
* walk is the same for every service: a JSON null is an absent member (a null list element is left
|
||||
* to the operation), a member the model does not know is skipped, a structure's values are read as
|
||||
* members and a list's or a map's as elements, a boolean also reads from "true" or "false" in any
|
||||
* case, and a scalar of the wrong kind is named by its JSON token ({@code NUMBER_VALUE},
|
||||
* {@code TRUE_VALUE}, ...). What a service's deserializer says at each point is its {@link Messages}.
|
||||
* members and a list's or a map's as elements, and a boolean also reads from "true" or "false" in
|
||||
* any case. What a service's deserializer says at each point is its {@link Messages}. They also say
|
||||
* how it names a scalar of the wrong kind, by its JSON token ({@code NUMBER_VALUE},
|
||||
* {@code TRUE_VALUE}, ...) unless the service gives it another name, and whether it reads a
|
||||
* structure's members and a map's entries in body order or in name order, which decides the value
|
||||
* reported when several are wrong. A list is always read in its own order. A service that checks
|
||||
* whole request bodies holds its model and messages in an {@link Operations}.
|
||||
*/
|
||||
public final class RequestShapeCheck {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RequestShapeCheck.class);
|
||||
|
||||
/** A message that depends on whether the value was read as a member or as an element. */
|
||||
public record ByPosition(String member, String element) {
|
||||
|
||||
@@ -39,9 +47,10 @@ public final class RequestShapeCheck {
|
||||
* @param scalarForStructure a scalar where a structure is expected
|
||||
* @param scalarForList a scalar where a list is expected
|
||||
* @param scalarForMap a scalar where a map is expected
|
||||
* @param conversion a scalar of the wrong kind, formatted with its token and the target
|
||||
* type ({@code String}, {@code Integer}, {@code Long}, {@code Double},
|
||||
* {@code Date}, {@code Boolean}, {@code Blob})
|
||||
* @param conversion a scalar of the wrong kind, formatted with its name (its token, or its
|
||||
* {@code scalarNames} entry) and the target type ({@code String},
|
||||
* {@code Integer}, {@code Long}, {@code Double}, {@code Date},
|
||||
* {@code Boolean}, {@code Blob})
|
||||
* @param decimalToken whether a non-integral number is {@code DECIMAL_VALUE} rather than
|
||||
* {@code NUMBER_VALUE}
|
||||
* @param invalidBoolean text other than true or false where a boolean is expected
|
||||
@@ -49,11 +58,87 @@ public final class RequestShapeCheck {
|
||||
* it as {@code conversion} does
|
||||
* @param scalarTypes the scalar shape types the service was measured on; a value of any
|
||||
* other scalar type passes unchecked
|
||||
* @param scalarNames how a scalar of the wrong kind is named in a conversion message, keyed
|
||||
* by its JSON token ({@code NUMBER_VALUE}, {@code DECIMAL_VALUE},
|
||||
* {@code TRUE_VALUE}, {@code FALSE_VALUE}, {@code STRING_VALUE}); a
|
||||
* token the map leaves out is named by itself
|
||||
* @param conversionByType a conversion wording per scalar shape type, such as {@code double},
|
||||
* used in place of {@code conversion} for that type and formatted the
|
||||
* same way, with the name and then the target; a wording may leave the
|
||||
* target out
|
||||
* @param sortedMembers whether a structure's members and a map's entries are read in name
|
||||
* order (Java {@code String} order) rather than body order, so that the
|
||||
* first bad value by name is reported
|
||||
*/
|
||||
public record Messages(String errorCode, String objectNotExpected, String listNotExpected,
|
||||
ByPosition scalarForStructure, ByPosition scalarForList, ByPosition scalarForMap,
|
||||
String conversion, boolean decimalToken, String invalidBoolean, String blobNotText,
|
||||
Set<String> scalarTypes) {
|
||||
Set<String> scalarTypes, Map<String, String> scalarNames,
|
||||
Map<String, String> conversionByType, boolean sortedMembers) {
|
||||
|
||||
public Messages(String errorCode, String objectNotExpected, String listNotExpected,
|
||||
ByPosition scalarForStructure, ByPosition scalarForList, ByPosition scalarForMap,
|
||||
String conversion, boolean decimalToken, String invalidBoolean, String blobNotText,
|
||||
Set<String> scalarTypes) {
|
||||
this(errorCode, objectNotExpected, listNotExpected, scalarForStructure, scalarForList, scalarForMap,
|
||||
conversion, decimalToken, invalidBoolean, blobNotText, scalarTypes, Map.of(), Map.of(), false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One service's request bodies: its vendored model, loaded on first use, and its {@link Messages}.
|
||||
* A body is walked against the input shape of the operation it was sent to. An operation the model
|
||||
* does not know is a wiring defect in Floci, so it is logged and answered as AWS answers a fault,
|
||||
* a 500 {@code InternalFailure}.
|
||||
*/
|
||||
public static final class Operations {
|
||||
|
||||
private final String resourceName;
|
||||
private final String description;
|
||||
private final Messages messages;
|
||||
private volatile RequestShapeModel model;
|
||||
|
||||
/**
|
||||
* @param resourceName the vendored model on the classpath, such as
|
||||
* {@code aws/sesv2-request-shapes.json}
|
||||
* @param description names the model in a failure to load it
|
||||
* @param messages the service's deserializer wording
|
||||
*/
|
||||
public Operations(String resourceName, String description, Messages messages) {
|
||||
this.resourceName = resourceName;
|
||||
this.description = description;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
/** Checks {@code request} against the input shape of {@code operation} in the vendored model. */
|
||||
public void check(String operation, JsonNode request) {
|
||||
check(model(), operation, request);
|
||||
}
|
||||
|
||||
/** Checks {@code request} against the input shape of {@code operation} in {@code model}. */
|
||||
public void check(RequestShapeModel model, String operation, JsonNode request) {
|
||||
String input = model.operations().get(operation);
|
||||
if (input == null) {
|
||||
LOG.errorv("No input shape for operation {0} in {1}", operation, resourceName);
|
||||
throw new AwsException("InternalFailure",
|
||||
"The request processing has failed because of an unknown error.", 500);
|
||||
}
|
||||
RequestShapeCheck.check(model, input, request, messages);
|
||||
}
|
||||
|
||||
private RequestShapeModel model() {
|
||||
RequestShapeModel loaded = model;
|
||||
if (loaded == null) {
|
||||
synchronized (this) {
|
||||
loaded = model;
|
||||
if (loaded == null) {
|
||||
loaded = RequestShapeModel.load(resourceName, description);
|
||||
model = loaded;
|
||||
}
|
||||
}
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Map<String, String> TARGETS = Map.of("string", "String", "integer", "Integer",
|
||||
@@ -88,7 +173,7 @@ public final class RequestShapeCheck {
|
||||
if (!value.isObject()) {
|
||||
throw refusal(messages, messages.scalarForStructure().at(member));
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
for (Map.Entry<String, JsonNode> field : fields(value, messages)) {
|
||||
String memberShape = shape.members().get(field.getKey());
|
||||
if (memberShape != null) {
|
||||
checkValue(model, model.shapes().get(memberShape), field.getValue(), true, messages);
|
||||
@@ -96,6 +181,18 @@ public final class RequestShapeCheck {
|
||||
}
|
||||
}
|
||||
|
||||
/** An object's fields, in body order or, with {@code sortedMembers}, in name order. */
|
||||
private static Iterable<Map.Entry<String, JsonNode>> fields(JsonNode value, Messages messages) {
|
||||
if (!messages.sortedMembers()) {
|
||||
return value.properties();
|
||||
}
|
||||
Map<String, JsonNode> byName = new TreeMap<>();
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
byName.put(field.getKey(), field.getValue());
|
||||
}
|
||||
return byName.entrySet();
|
||||
}
|
||||
|
||||
private static void checkList(RequestShapeModel model, Shape shape, JsonNode value, boolean member,
|
||||
Messages messages) {
|
||||
if (value.isObject()) {
|
||||
@@ -115,7 +212,10 @@ public final class RequestShapeCheck {
|
||||
if (!value.isObject()) {
|
||||
throw refusal(messages, messages.scalarForMap().at(member));
|
||||
}
|
||||
checkElements(model, shape, value, messages);
|
||||
Shape element = model.shapes().get(shape.element());
|
||||
for (Map.Entry<String, JsonNode> entry : fields(value, messages)) {
|
||||
checkValue(model, element, entry.getValue(), false, messages);
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkElements(RequestShapeModel model, Shape shape, JsonNode value, Messages messages) {
|
||||
@@ -168,7 +268,10 @@ public final class RequestShapeCheck {
|
||||
|
||||
private static void requireToken(boolean accepted, JsonNode value, String type, Messages messages) {
|
||||
if (!accepted) {
|
||||
throw refusal(messages, messages.conversion().formatted(token(value, messages), TARGETS.get(type)));
|
||||
String token = token(value, messages);
|
||||
String format = messages.conversionByType().getOrDefault(type, messages.conversion());
|
||||
throw refusal(messages, format.formatted(messages.scalarNames().getOrDefault(token, token),
|
||||
TARGETS.get(type)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+79
-18
@@ -3,12 +3,15 @@ package io.github.hectorvent.floci.services.apigateway;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.io.JsonStringEncoder;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService.StoredMapping;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
|
||||
@@ -99,6 +102,7 @@ public class ApiGatewayController {
|
||||
|
||||
private static final TypeReference<List<Map<String, String>>> PATCH_OPERATIONS =
|
||||
new TypeReference<>() { };
|
||||
private static final TypeReference<Map<String, Object>> JSON_OBJECT = new TypeReference<>() { };
|
||||
|
||||
/**
|
||||
* The {@code op} enum, verbatim from the model. Wider than what any one handler implements on
|
||||
@@ -853,14 +857,36 @@ public class ApiGatewayController {
|
||||
@Path("/usageplans")
|
||||
public Response createUsagePlan(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
UsagePlan plan = service.createUsagePlan(region, request);
|
||||
return Response.status(201).entity(toUsagePlanNode(plan).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
JsonNode node = readCreateUsagePlanBody(body);
|
||||
ApiGatewayRequestShapes.check("CreateUsagePlan", node);
|
||||
Map<String, Object> request = objectMapper.convertValue(node, JSON_OBJECT);
|
||||
UsagePlan plan = service.createUsagePlan(region, request);
|
||||
return Response.status(201).entity(toUsagePlanNode(plan, false).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* A CreateUsagePlan body as API Gateway reads it, measured: a zero-byte body is a missing input,
|
||||
* and malformed JSON, trailing content or a body that is neither a JSON object nor an array is a
|
||||
* SerializationException without a message. An array is left to the shape check. A fraction is
|
||||
* read as a BigDecimal, which the conversion to the request map keeps, so an integer member is
|
||||
* truncated from its decimal digits rather than from a double.
|
||||
*/
|
||||
private JsonNode readCreateUsagePlanBody(String body) {
|
||||
if (body == null || body.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("createUsagePlanInput"));
|
||||
}
|
||||
JsonNode node;
|
||||
try {
|
||||
node = objectMapper.reader()
|
||||
.with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
|
||||
.readTree(body);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
if (node == null || !node.isContainerNode()) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -870,7 +896,7 @@ public class ApiGatewayController {
|
||||
List<UsagePlan> plans = service.getUsagePlans(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
plans.forEach(p -> items.add(toUsagePlanNode(p)));
|
||||
plans.forEach(p -> items.add(toUsagePlanNode(p, false)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@@ -879,7 +905,7 @@ public class ApiGatewayController {
|
||||
public Response getUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
UsagePlan plan = service.getUsagePlan(region, usagePlanId);
|
||||
ObjectNode node = toUsagePlanNode(plan);
|
||||
ObjectNode node = toUsagePlanNode(plan, true);
|
||||
return Response.ok(node.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@@ -889,7 +915,7 @@ public class ApiGatewayController {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Map<String, String>> patchOperations = parsePatchOperations(body);
|
||||
UsagePlan plan = service.updateUsagePlan(region, usagePlanId, patchOperations);
|
||||
return Response.ok(toUsagePlanNode(plan).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
return Response.ok(toUsagePlanNode(plan, true).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@@ -923,11 +949,11 @@ public class ApiGatewayController {
|
||||
*
|
||||
* <p>Each pair is {@code [used, remaining]}, not {@code [used, quota]}: measured against real
|
||||
* API Gateway, the second element is the quota limit minus the cumulative use so far in the
|
||||
* period. Both elements are {@code 0} here because the emulator neither meters requests per API
|
||||
* key nor stores a quota on a usage plan. Once a quota lives on {@code UsagePlan} and the
|
||||
* execute path counts per key, this method is where both feed in; until then a caller that sums
|
||||
* the used counts gets the same zero it already gets from an unsupported action, without having
|
||||
* to special-case a missing endpoint.
|
||||
* period. Both elements are {@code 0} here because the emulator does not meter requests per API
|
||||
* key, so there is no use to report or to subtract from a plan's quota. Once the execute path
|
||||
* counts per key, this method is where the count feeds in; until then a caller that sums the
|
||||
* used counts gets the same zero it already gets from an unsupported action, without having to
|
||||
* special-case a missing endpoint.
|
||||
*/
|
||||
@GET
|
||||
@Path("/usageplans/{usagePlanId}/usage")
|
||||
@@ -2456,20 +2482,55 @@ public class ApiGatewayController {
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toUsagePlanNode(UsagePlan p) {
|
||||
/**
|
||||
* {@code alwaysTags} writes {@code "tags": {}} for a plan without tags, which GetUsagePlan and
|
||||
* UpdateUsagePlan do on API Gateway; CreateUsagePlan and the GetUsagePlans items leave it out.
|
||||
*/
|
||||
private ObjectNode toUsagePlanNode(UsagePlan p, boolean alwaysTags) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", p.getId());
|
||||
node.put("name", p.getName());
|
||||
if (p.getDescription() != null) {
|
||||
node.put("description", p.getDescription());
|
||||
}
|
||||
if (p.getTags() != null && !p.getTags().isEmpty()) {
|
||||
// One revision of the stages, throttle and quota, so a concurrent update cannot mix two in a response.
|
||||
UsagePlan.Limits limits = p.limits();
|
||||
// API Gateway always reports apiStages, as [] for a plan with none.
|
||||
ArrayNode stages = node.putArray("apiStages");
|
||||
for (UsagePlan.ApiStage stage : limits.apiStages()) {
|
||||
ObjectNode stageNode = stages.addObject();
|
||||
stageNode.put("apiId", stage.apiId());
|
||||
stageNode.put("stage", stage.stage());
|
||||
if (stage.throttle() != null) {
|
||||
ObjectNode methods = stageNode.putObject("throttle");
|
||||
stage.throttle().forEach((method, throttle) -> putThrottle(methods.putObject(method), throttle));
|
||||
}
|
||||
}
|
||||
UsagePlan.Throttle throttle = limits.throttle();
|
||||
if (throttle != null) {
|
||||
putThrottle(node.putObject("throttle"), throttle);
|
||||
}
|
||||
UsagePlan.Quota quota = limits.quota();
|
||||
if (quota != null) {
|
||||
node.putObject("quota")
|
||||
.put("limit", quota.limit())
|
||||
.put("offset", quota.offset())
|
||||
.put("period", quota.period());
|
||||
}
|
||||
if (alwaysTags || (p.getTags() != null && !p.getTags().isEmpty())) {
|
||||
ObjectNode tags = node.putObject("tags");
|
||||
p.getTags().forEach(tags::put);
|
||||
if (p.getTags() != null) {
|
||||
p.getTags().forEach(tags::put);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static void putThrottle(ObjectNode node, UsagePlan.Throttle throttle) {
|
||||
node.put("burstLimit", throttle.burstLimit());
|
||||
node.put("rateLimit", throttle.rateLimit());
|
||||
}
|
||||
|
||||
private ObjectNode toUsagePlanKeyNode(UsagePlanKey k) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", k.getId());
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeCheck;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Rejects an API Gateway request body member of the wrong JSON type with the SerializationException
|
||||
* API Gateway answers before it validates anything. The body shapes come from the vendored
|
||||
* {@code aws/apigateway-request-shapes.json}, generated from botocore's API Gateway model by
|
||||
* {@code tools/aws/regen_apigateway_shapes.py}, and are walked by {@link RequestShapeCheck}.
|
||||
*
|
||||
* <p>The messages were measured with raw {@code CreateUsagePlan} requests against API Gateway in
|
||||
* eu-west-1 on 2026-10-24. Its deserializer differs from SES v2's in two ways. It names the Java
|
||||
* class it read rather than the JSON token: a JSON number is a
|
||||
* {@code com.amazon.coral.value.json.numbers.TruncatingBigNumber}, text a {@code java.lang.String}
|
||||
* and true or false a {@code java.lang.Boolean}, and a double member words the refusal as "is not an
|
||||
* expected Json type". And it reads a structure's members in member-name order, at every level, so
|
||||
* the first bad member by name is reported whatever order the body has. An integer member takes any
|
||||
* JSON number but refuses a numeric string such as {@code "100"}; the operation truncates the number
|
||||
* from its decimal digits, clamps it to the int range and refuses a negative fraction as negative. A
|
||||
* double member refuses text too. Only string, integer and double members were probed, so a member
|
||||
* of another scalar type is left to the operation.
|
||||
*/
|
||||
final class ApiGatewayRequestShapes {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/apigateway-request-shapes.json";
|
||||
|
||||
private static final String NUMBER = "class com.amazon.coral.value.json.numbers.TruncatingBigNumber";
|
||||
private static final String BOOLEAN = "class java.lang.Boolean";
|
||||
|
||||
private static final RequestShapeCheck.Messages MESSAGES = new RequestShapeCheck.Messages(
|
||||
"SerializationException",
|
||||
"Start of structure or map found where not expected.",
|
||||
"Start of list found where not expected",
|
||||
ByPosition.same("Expected null"),
|
||||
ByPosition.same("Expected list or null"),
|
||||
ByPosition.same("Expected map or null"),
|
||||
"%s can not be converted to an %s",
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
Set.of("string", "integer", "double"),
|
||||
Map.of("NUMBER_VALUE", NUMBER, "DECIMAL_VALUE", NUMBER, "TRUE_VALUE", BOOLEAN, "FALSE_VALUE", BOOLEAN,
|
||||
"STRING_VALUE", "class java.lang.String"),
|
||||
Map.of("double", "%s is not an expected Json type"),
|
||||
true);
|
||||
|
||||
private static final RequestShapeCheck.Operations OPERATIONS =
|
||||
new RequestShapeCheck.Operations(RESOURCE_NAME, "API Gateway request shapes", MESSAGES);
|
||||
|
||||
private ApiGatewayRequestShapes() {
|
||||
}
|
||||
|
||||
/** Checks an API Gateway request body against the body shape of {@code operation}. */
|
||||
static void check(String operation, JsonNode request) {
|
||||
OPERATIONS.check(operation, request);
|
||||
}
|
||||
}
|
||||
+31
-21
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.CloudFrontEdgeDomain;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ReservedTags;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
@@ -1498,6 +1499,22 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
// ──────────────────────────── Usage Plans ────────────────────────────
|
||||
|
||||
public UsagePlan createUsagePlan(String region, Map<String, Object> request) {
|
||||
// CreateUsagePlan's input model reports every violation in one message, the period's before the name's.
|
||||
List<String> violations = new ArrayList<>();
|
||||
String periodViolation = UsagePlanLimits.periodViolation(request);
|
||||
if (periodViolation != null) {
|
||||
violations.add(periodViolation);
|
||||
}
|
||||
if (request.get("name") == null) {
|
||||
violations.add(SmithyValidationErrors.notNull("createUsagePlanInput.name"));
|
||||
}
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(violations);
|
||||
}
|
||||
if (String.valueOf(request.get("name")).isEmpty()) {
|
||||
throw new AwsException("BadRequestException", "Usage Plan name must be specified", 400);
|
||||
}
|
||||
UsagePlan.Limits limits = UsagePlanLimits.fromRequest(request);
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
if (request.get("tags") instanceof Map<?, ?> rawTags) {
|
||||
rawTags.forEach((key, value) -> tags.put(String.valueOf(key), String.valueOf(value)));
|
||||
@@ -1511,14 +1528,7 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
plan.setName((String) request.get("name"));
|
||||
plan.setDescription((String) request.get("description"));
|
||||
plan.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> apiStages = (List<Map<String, Object>>) request.get("apiStages");
|
||||
if (apiStages != null) {
|
||||
for (Map<String, Object> as : apiStages) {
|
||||
plan.getApiStages().add(new UsagePlan.ApiStage((String) as.get("apiId"), (String) as.get("stage")));
|
||||
}
|
||||
}
|
||||
plan.applyLimits(limits);
|
||||
|
||||
usagePlanStore.put(usagePlanKey(region, plan.getId()), plan);
|
||||
LOG.infov("Created Usage Plan {0}", plan.getId());
|
||||
@@ -1527,7 +1537,7 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
|
||||
public UsagePlan getUsagePlan(String region, String usagePlanId) {
|
||||
return usagePlanStore.get(usagePlanKey(region, usagePlanId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Usage Plan not found", 404));
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid Usage Plan ID specified", 404));
|
||||
}
|
||||
|
||||
public UsagePlan updateUsagePlan(String region, String usagePlanId, List<Map<String, String>> patchOperations) {
|
||||
@@ -1558,13 +1568,14 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
throw new AwsException("BadRequestException",
|
||||
"apiStages value must be in the form apiId:stage", 400);
|
||||
}
|
||||
UsagePlan.ApiStage stage = new UsagePlan.ApiStage(parts[0], parts[1]);
|
||||
// Matched by API and stage alone: a stage's method throttle is not part of its identity.
|
||||
int index = UsagePlanLimits.indexOf(newApiStages, parts[0], parts[1]);
|
||||
if ("add".equals(opType)) {
|
||||
if (!newApiStages.contains(stage)) {
|
||||
newApiStages.add(stage);
|
||||
if (index < 0) {
|
||||
newApiStages.add(new UsagePlan.ApiStage(parts[0], parts[1]));
|
||||
}
|
||||
} else {
|
||||
newApiStages.remove(stage);
|
||||
} else if (index >= 0) {
|
||||
newApiStages.remove(index);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -1582,8 +1593,8 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
}
|
||||
plan.setName(newName);
|
||||
plan.setDescription(newDescription);
|
||||
plan.getApiStages().clear();
|
||||
plan.getApiStages().addAll(newApiStages);
|
||||
// A new list, not an in-place refill, so a concurrent read copies either the old stages or the new ones.
|
||||
plan.setApiStages(newApiStages);
|
||||
usagePlanStore.put(usagePlanKey(region, usagePlanId), plan);
|
||||
return plan;
|
||||
}
|
||||
@@ -1659,10 +1670,9 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
* {@code [used, remaining]} pair per day of the inclusive range. {@code position} is absent
|
||||
* when there is no further page, which is what stops a caller's pagination loop.
|
||||
*
|
||||
* <p><strong>Both numbers are zero.</strong> Nothing counts requests per API key, and a
|
||||
* {@link UsagePlan} carries no quota, so there is no limit to subtract from. Storing a quota on
|
||||
* the usage plan and counting on the execute path are the two pieces still missing; this method
|
||||
* is where they would surface.
|
||||
* <p><strong>Both numbers are zero.</strong> Nothing counts requests per API key, so there is no
|
||||
* use to report or to subtract from a plan's quota. Counting on the execute path is the piece
|
||||
* still missing; this method is where it would surface.
|
||||
*/
|
||||
public UsageReport getUsage(String region, String usagePlanId, String startDate, String endDate,
|
||||
String keyId, Integer limit, String position) {
|
||||
@@ -1708,7 +1718,7 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
for (UsagePlanKey key : page) {
|
||||
List<long[]> perDay = new ArrayList<>();
|
||||
for (int day = 0; day < days; day++) {
|
||||
// [used, remaining]: nothing is metered, and no quota is stored to subtract from.
|
||||
// [used, remaining]: nothing is metered, so there is no use to report or subtract from a quota.
|
||||
perDay.add(new long[] {0L, 0L});
|
||||
}
|
||||
items.put(key.getId(), perDay);
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.ApiStage;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Limits;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Quota;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Throttle;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A usage plan's API stages, throttle and quota: read from a {@code CreateUsagePlan} request, with
|
||||
* the errors API Gateway answers. Every message was measured against API Gateway in eu-west-1.
|
||||
*/
|
||||
public final class UsagePlanLimits {
|
||||
|
||||
/** In the model's order, which an input-model enum violation lists. */
|
||||
private static final List<String> PERIODS = List.of("MONTH", "WEEK", "DAY");
|
||||
private static final BigDecimal INT_MIN = BigDecimal.valueOf(Integer.MIN_VALUE);
|
||||
private static final BigDecimal INT_MAX = BigDecimal.valueOf(Integer.MAX_VALUE);
|
||||
private static final String BAD_REQUEST = "BadRequestException";
|
||||
private static final String THROTTLE_INVALID =
|
||||
"Usage Plan throttle rate limit and burst limit must be numeric and greater than zero";
|
||||
private static final String FINE_GRAIN_WITHOUT_PLAN_THROTTLE =
|
||||
"Can not define fine grain throttling if usage plan throttle is not defined.";
|
||||
private static final String QUOTA_OFFSET_NOT_NUMERIC =
|
||||
"Usage Plan quota offset must be numeric and less than the number of time units in the period";
|
||||
|
||||
private UsagePlanLimits() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The stages, throttle and quota of a {@code CreateUsagePlan} request whose JSON types
|
||||
* {@link ApiGatewayRequestShapes} has checked. A JSON number is read as API Gateway reads it, and
|
||||
* text, which only CloudFormation's template values send, is parsed as written.
|
||||
*/
|
||||
public static Limits fromRequest(Map<String, Object> request) {
|
||||
Map<?, ?> quotaSettings = request.get("quota") instanceof Map<?, ?> settings ? settings : null;
|
||||
Object period = quotaSettings == null ? null : quotaSettings.get("period");
|
||||
String periodViolation = periodViolation(request);
|
||||
if (periodViolation != null) {
|
||||
// CreateUsagePlan's input model refuses an unknown period before any of API Gateway's own checks.
|
||||
throw SmithyValidationErrors.validationException(periodViolation);
|
||||
}
|
||||
Throttle throttle = request.get("throttle") instanceof Map<?, ?> settings ? throttle(settings) : null;
|
||||
Quota quota = quotaSettings == null
|
||||
? null
|
||||
: quota(quotaSettings.get("limit"), quotaSettings.get("offset"), period);
|
||||
List<ApiStage> stages = new ArrayList<>();
|
||||
if (request.get("apiStages") instanceof List<?> entries) {
|
||||
for (Object entry : entries) {
|
||||
if (!(entry instanceof Map<?, ?> stage)) {
|
||||
throw new AwsException(BAD_REQUEST, "Invalid API Stage specified", 400);
|
||||
}
|
||||
String apiId = stage.get("apiId") == null ? null : String.valueOf(stage.get("apiId"));
|
||||
String stageName = stage.get("stage") == null ? null : String.valueOf(stage.get("stage"));
|
||||
if (apiId == null || apiId.isEmpty() || stageName == null || stageName.isEmpty()) {
|
||||
throw new AwsException(BAD_REQUEST, "Invalid API Stage specified", 400);
|
||||
}
|
||||
if (indexOf(stages, apiId, stageName) >= 0) {
|
||||
throw alreadyDefined(apiId, stageName);
|
||||
}
|
||||
// A stage throttle with no methods is dropped on create, as API Gateway does.
|
||||
Map<String, Throttle> methods = stage.get("throttle") instanceof Map<?, ?> raw && !raw.isEmpty()
|
||||
? methodThrottles(raw, THROTTLE_INVALID)
|
||||
: null;
|
||||
stages.add(new ApiStage(apiId, stageName, methods));
|
||||
}
|
||||
}
|
||||
if (throttle == null && hasMethodThrottles(stages)) {
|
||||
throw new AwsException(BAD_REQUEST, FINE_GRAIN_WITHOUT_PLAN_THROTTLE, 400);
|
||||
}
|
||||
return new Limits(stages, throttle, quota);
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateUsagePlan's input-model violation for a quota period outside the enum, as
|
||||
* {@link SmithyValidationErrors#notInEnum} words it, or null when the period is absent or valid.
|
||||
*/
|
||||
static String periodViolation(Map<String, Object> request) {
|
||||
Object period = request.get("quota") instanceof Map<?, ?> settings ? settings.get("period") : null;
|
||||
if (period == null || PERIODS.contains(String.valueOf(period))) {
|
||||
return null;
|
||||
}
|
||||
return SmithyValidationErrors.notInEnum(String.valueOf(period), "createUsagePlanInput.quota.period", PERIODS);
|
||||
}
|
||||
|
||||
/** A field API Gateway leaves out reads 0. */
|
||||
static Throttle throttle(Map<?, ?> settings) {
|
||||
Object burst = settings.get("burstLimit");
|
||||
Object rate = settings.get("rateLimit");
|
||||
return new Throttle(burst == null ? 0 : burstLimit(burst), rate == null ? 0.0 : rateLimit(rate));
|
||||
}
|
||||
|
||||
/** Every value's shape is checked before any key, then each key before its limits. */
|
||||
static Map<String, Throttle> methodThrottles(Map<?, ?> raw, String invalidMessage) {
|
||||
Map<String, Map<?, ?>> settingsByKey = new LinkedHashMap<>();
|
||||
for (Map.Entry<?, ?> entry : raw.entrySet()) {
|
||||
if (!(entry.getValue() instanceof Map<?, ?> settings)) {
|
||||
throw new AwsException(BAD_REQUEST, invalidMessage, 400);
|
||||
}
|
||||
settingsByKey.put(String.valueOf(entry.getKey()), settings);
|
||||
}
|
||||
Map<String, Throttle> methods = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Map<?, ?>> entry : settingsByKey.entrySet()) {
|
||||
String[] resourcePathAndMethod = methodKey(entry.getKey());
|
||||
if (resourcePathAndMethod[1].isEmpty()) {
|
||||
// No space after the comma: API Gateway's own formatting.
|
||||
throw new AwsException(BAD_REQUEST, "Invalid method {resourcePath: " + resourcePathAndMethod[0]
|
||||
+ ",method: " + resourcePathAndMethod[1] + "} specified", 400);
|
||||
}
|
||||
methods.put(entry.getKey(), throttle(entry.getValue()));
|
||||
}
|
||||
return methods;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code [resourcePath, method]} of a method throttle key, split as API Gateway splits it: at the
|
||||
* last slash, unless that slash leads or ends the key, which leaves the method empty. Floci does
|
||||
* not check that the method exists, so {@code //GET} and {@code /pets/GET/extra} pass.
|
||||
*/
|
||||
static String[] methodKey(String key) {
|
||||
int slash = key.lastIndexOf('/');
|
||||
if (slash <= 0 || slash == key.length() - 1) {
|
||||
return new String[] {key, ""};
|
||||
}
|
||||
return new String[] {key.substring(0, slash), key.substring(slash + 1)};
|
||||
}
|
||||
|
||||
/** Validated in API Gateway's order: period, then limit, then offset. */
|
||||
static Quota quota(Object limit, Object offset, Object period) {
|
||||
String periodName = period == null ? null : String.valueOf(period);
|
||||
if (periodName == null || !PERIODS.contains(periodName)) {
|
||||
throw new AwsException(BAD_REQUEST,
|
||||
"Invalid Usage Plan quota period specified. Must be one of [DAY, WEEK, MONTH]", 400);
|
||||
}
|
||||
Integer parsedLimit = limit == null ? null : intValue(limit);
|
||||
if (parsedLimit == null || parsedLimit < 0) {
|
||||
throw new AwsException(BAD_REQUEST, "Usage Plan quota limit must be a non-negative numeric", 400);
|
||||
}
|
||||
int parsedOffset = 0;
|
||||
if (offset != null) {
|
||||
Integer value = intValue(offset);
|
||||
if (value == null) {
|
||||
throw new AwsException(BAD_REQUEST, QUOTA_OFFSET_NOT_NUMERIC, 400);
|
||||
}
|
||||
parsedOffset = value;
|
||||
}
|
||||
int units = switch (periodName) {
|
||||
case "WEEK" -> 7;
|
||||
case "MONTH" -> 28;
|
||||
default -> 1;
|
||||
};
|
||||
if (parsedOffset < 0 || parsedOffset >= units) {
|
||||
throw new AwsException(BAD_REQUEST, units == 1
|
||||
? "Usage Plan quota offset must be zero in the DAY period"
|
||||
: "Usage Plan quota offset must be between 0 and " + (units - 1) + " inclusive in the "
|
||||
+ periodName + " period", 400);
|
||||
}
|
||||
return new Quota(parsedLimit, parsedOffset, periodName);
|
||||
}
|
||||
|
||||
static int burstLimit(Object value) {
|
||||
Integer burst = value == null ? null : intValue(value);
|
||||
if (burst == null || burst < 0) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
return burst;
|
||||
}
|
||||
|
||||
static double rateLimit(Object value) {
|
||||
Double rate = value == null ? null : doubleValue(value);
|
||||
if (rate == null || rate < 0) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
return rate;
|
||||
}
|
||||
|
||||
static int indexOf(List<ApiStage> stages, String apiId, String stage) {
|
||||
for (int i = 0; i < stages.size(); i++) {
|
||||
if (Objects.equals(stages.get(i).apiId(), apiId) && Objects.equals(stages.get(i).stage(), stage)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static boolean hasMethodThrottles(List<ApiStage> stages) {
|
||||
return stages.stream().anyMatch(stage -> stage.throttle() != null && !stage.throttle().isEmpty());
|
||||
}
|
||||
|
||||
static AwsException alreadyDefined(String apiId, String stage) {
|
||||
return new AwsException("ConflictException",
|
||||
"API Stage is already defined for Usage Plan: " + apiId + ":" + stage, 409);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code value} as an int, or null when it is not one. A number is read from its decimal digits,
|
||||
* rounded toward negative infinity and clamped to the int range, as API Gateway reads a JSON
|
||||
* number; text must be a whole number in int range.
|
||||
*/
|
||||
private static Integer intValue(Object value) {
|
||||
try {
|
||||
if (value instanceof Number number) {
|
||||
return floorToInt(new BigDecimal(number.toString()));
|
||||
}
|
||||
return Integer.valueOf(String.valueOf(value).trim());
|
||||
} catch (NumberFormatException expected) {
|
||||
// The caller reports a non-integer, or a NaN or infinite double, with API Gateway's message for the field.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code value} rounded toward negative infinity and clamped to the int range. The bounds and a
|
||||
* fraction below one are settled before any rounding, so an exponent such as {@code 1e1000000000}
|
||||
* or {@code 1e-1000000000} is never expanded into its digits.
|
||||
*/
|
||||
private static int floorToInt(BigDecimal value) {
|
||||
if (value.compareTo(INT_MAX) >= 0) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
if (value.compareTo(INT_MIN) <= 0) {
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
if (value.abs().compareTo(BigDecimal.ONE) < 0) {
|
||||
return value.signum() < 0 ? -1 : 0;
|
||||
}
|
||||
// FLOOR: positive values truncate and negative ones stay negative, so they are refused, as on API Gateway.
|
||||
return value.setScale(0, RoundingMode.FLOOR).intValue();
|
||||
}
|
||||
|
||||
/** {@code value} as a finite double, or null when it is not one. */
|
||||
private static Double doubleValue(Object value) {
|
||||
try {
|
||||
double parsed = value instanceof Number number
|
||||
? number.doubleValue()
|
||||
: Double.parseDouble(String.valueOf(value).trim());
|
||||
return Double.isFinite(parsed) ? parsed : null;
|
||||
} catch (NumberFormatException expected) {
|
||||
// The caller reports a non-number with API Gateway's message for the field.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ public class UsagePlan {
|
||||
private String description;
|
||||
private List<ApiStage> apiStages = new ArrayList<>();
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private Throttle throttle;
|
||||
private Quota quota;
|
||||
|
||||
public UsagePlan() {}
|
||||
|
||||
@@ -34,6 +36,39 @@ public class UsagePlan {
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new HashMap<>(); }
|
||||
|
||||
public Throttle getThrottle() { return throttle; }
|
||||
public void setThrottle(Throttle throttle) { this.throttle = throttle; }
|
||||
|
||||
public Quota getQuota() { return quota; }
|
||||
public void setQuota(Quota quota) { this.quota = quota; }
|
||||
|
||||
/** The plan's stages, throttle and quota as one value, for comparing and replacing them together. */
|
||||
public Limits limits() {
|
||||
return new Limits(List.copyOf(apiStages), throttle, quota);
|
||||
}
|
||||
|
||||
public void applyLimits(Limits limits) {
|
||||
this.apiStages = new ArrayList<>(limits.apiStages());
|
||||
this.throttle = limits.throttle();
|
||||
this.quota = limits.quota();
|
||||
}
|
||||
|
||||
/** {@code throttle} maps {@code <resourcePath>/<httpMethod>} to its limits; null when the stage has none. */
|
||||
@RegisterForReflection
|
||||
public record ApiStage(String apiId, String stage) {}
|
||||
public record ApiStage(String apiId, String stage, Map<String, Throttle> throttle) {
|
||||
/** A stage with no per-method throttle, which is what an {@code add /apiStages} patch creates. */
|
||||
public ApiStage(String apiId, String stage) {
|
||||
this(apiId, stage, null);
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record Throttle(int burstLimit, double rateLimit) {}
|
||||
|
||||
@RegisterForReflection
|
||||
public record Quota(int limit, int offset, String period) {}
|
||||
|
||||
/** A plan's stages, throttle and quota as one value. */
|
||||
@RegisterForReflection
|
||||
public record Limits(List<ApiStage> apiStages, Throttle throttle, Quota quota) {}
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeCheck;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeModel;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@@ -32,8 +29,6 @@ final class SesV2RequestShapes {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/sesv2-request-shapes.json";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesV2RequestShapes.class);
|
||||
|
||||
private static final RequestShapeCheck.Messages MESSAGES = new RequestShapeCheck.Messages(
|
||||
SesV2Json.SERIALIZATION_EXCEPTION,
|
||||
SesV2Json.OBJECT_NOT_EXPECTED,
|
||||
@@ -47,25 +42,14 @@ final class SesV2RequestShapes {
|
||||
null,
|
||||
Set.of("string", "blob"));
|
||||
|
||||
private static final class Holder {
|
||||
static final RequestShapeModel MODEL = RequestShapeModel.load(RESOURCE_NAME, "SES v2 request shapes");
|
||||
}
|
||||
private static final RequestShapeCheck.Operations OPERATIONS =
|
||||
new RequestShapeCheck.Operations(RESOURCE_NAME, "SES v2 request shapes", MESSAGES);
|
||||
|
||||
private SesV2RequestShapes() {
|
||||
}
|
||||
|
||||
/** Checks an SES v2 request body against the body shape of {@code operation}. */
|
||||
static void check(String operation, JsonNode request) {
|
||||
check(Holder.MODEL, operation, request);
|
||||
}
|
||||
|
||||
static void check(RequestShapeModel model, String operation, JsonNode request) {
|
||||
String input = model.operations().get(operation);
|
||||
if (input == null) {
|
||||
LOG.errorv("No SES v2 input shape for operation {0} in {1}", operation, RESOURCE_NAME);
|
||||
throw new AwsException("InternalFailure",
|
||||
"The request processing has failed because of an unknown error.", 500);
|
||||
}
|
||||
RequestShapeCheck.check(model, input, request, MESSAGES);
|
||||
OPERATIONS.check(operation, request);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
@@ -22,10 +23,10 @@ class RequestShapeCheckTest {
|
||||
|
||||
private static final RequestShapeModel MODEL = parse("""
|
||||
{
|
||||
"operations": {},
|
||||
"operations": {"Put": "Request"},
|
||||
"shapes": {
|
||||
"Request": {"type": "structure", "members": {
|
||||
"Name": "Text", "Count": "Number", "On": "Flag", "Data": "Bytes", "When": "Time",
|
||||
"Name": "Text", "Count": "Number", "On": "Flag", "Data": "Bytes", "When": "Time", "Rate": "Fraction",
|
||||
"Nested": "Request", "Items": "Requests", "Names": "Texts", "Labels": "Labelled"}},
|
||||
"Requests": {"type": "list", "member": "Request"},
|
||||
"Texts": {"type": "list", "member": "Text"},
|
||||
@@ -34,7 +35,8 @@ class RequestShapeCheckTest {
|
||||
"Number": {"type": "integer"},
|
||||
"Flag": {"type": "boolean"},
|
||||
"Bytes": {"type": "blob"},
|
||||
"Time": {"type": "timestamp"}
|
||||
"Time": {"type": "timestamp"},
|
||||
"Fraction": {"type": "double"}
|
||||
}
|
||||
}
|
||||
""");
|
||||
@@ -98,16 +100,108 @@ class RequestShapeCheckTest {
|
||||
assertEquals("NUMBER_VALUE as Blob", blob.getMessage());
|
||||
}
|
||||
|
||||
private static void assertRefused(String body, String message) {
|
||||
@Test
|
||||
void aScalarNameReplacesTheTokenItIsGivenForAndOnlyThatToken() {
|
||||
RequestShapeCheck.Messages named = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
ByPosition.same("structure"), ByPosition.same("list"), ByPosition.same("map"), "%s as %s", true,
|
||||
"boolean text", "blob", Set.of("string", "integer"),
|
||||
Map.of("NUMBER_VALUE", "a number", "TRUE_VALUE", "a boolean"), Map.of(), false);
|
||||
assertRefused("{\"Name\": 5}", named, "a number as String");
|
||||
assertRefused("{\"Name\": true}", named, "a boolean as String");
|
||||
assertRefused("{\"Name\": 5.5}", named, "DECIMAL_VALUE as String");
|
||||
assertRefused("{\"Name\": false}", named, "FALSE_VALUE as String");
|
||||
assertRefused("{\"Count\": \"5\"}", named, "STRING_VALUE as Integer");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeWithItsOwnWordingReplacesTheConversionForThatTypeOnly() {
|
||||
RequestShapeCheck.Messages worded = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
ByPosition.same("structure"), ByPosition.same("list"), ByPosition.same("map"), "%s as %s", false,
|
||||
"boolean text", "blob", Set.of("string", "integer", "double"), Map.of("TRUE_VALUE", "a boolean"),
|
||||
Map.of("double", "%s is no %s here", "integer", "%s is not a count"), false);
|
||||
assertRefused("{\"Rate\": \"5.5\"}", worded, "STRING_VALUE is no Double here");
|
||||
assertRefused("{\"Rate\": true}", worded, "a boolean is no Double here");
|
||||
assertRefused("{\"Count\": \"5\"}", worded, "STRING_VALUE is not a count");
|
||||
assertRefused("{\"Name\": 5}", worded, "NUMBER_VALUE as String");
|
||||
assertAccepted("{\"Rate\": 5.5, \"Count\": 1.5}", worded);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortedMembersReportTheFirstBadMemberInNameOrderRatherThanBodyOrder() {
|
||||
RequestShapeCheck.Messages sorted = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
new ByPosition("structure member", "structure element"), new ByPosition("list member", "list element"),
|
||||
new ByPosition("map member", "map element"), "%s as %s", true, "boolean text", "blob",
|
||||
Set.of("string", "integer", "boolean", "blob"), Map.of(), Map.of(), true);
|
||||
String body = "{\"Name\": 5, \"Count\": \"5\"}";
|
||||
assertRefused(body, "NUMBER_VALUE as String");
|
||||
assertRefused(body, sorted, "STRING_VALUE as Integer");
|
||||
String nested = "{\"Nested\": {\"Name\": 5, \"Count\": \"5\"}, \"Items\": [{\"On\": 0, \"Data\": 5}]}";
|
||||
assertRefused(nested, "NUMBER_VALUE as String");
|
||||
assertRefused(nested, sorted, "blob");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortedMembersReadAMapsEntriesInKeyOrderAndAListInItsOwnOrder() {
|
||||
RequestShapeCheck.Messages sorted = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
ByPosition.same("structure"), ByPosition.same("list"), ByPosition.same("map"), "%s as %s", true,
|
||||
"boolean text", "blob", Set.of("string", "integer"), Map.of(), Map.of(), true);
|
||||
String map = "{\"Labels\": {\"z\": {\"Name\": 5}, \"a\": {\"Count\": \"5\"}}}";
|
||||
assertRefused(map, "NUMBER_VALUE as String");
|
||||
assertRefused(map, sorted, "STRING_VALUE as Integer");
|
||||
String list = "{\"Names\": [true, 5]}";
|
||||
assertRefused(list, "TRUE_VALUE as String");
|
||||
assertRefused(list, sorted, "TRUE_VALUE as String");
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsWalkTheInputShapeOfAKnownOperation() throws Exception {
|
||||
RequestShapeCheck.Operations operations =
|
||||
new RequestShapeCheck.Operations("aws/fixture-request-shapes.json", "fixture request shapes", MESSAGES);
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), MESSAGES), body);
|
||||
() -> operations.check(MODEL, "Put", MAPPER.readTree("{\"Name\": 5}")));
|
||||
assertEquals("Refused", e.getErrorCode());
|
||||
assertEquals("NUMBER_VALUE as String", e.getMessage());
|
||||
operations.check(MODEL, "Put", MAPPER.readTree("{\"Name\": \"n\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsAnswerAnUnknownOperationAsAnInternalFailure() {
|
||||
RequestShapeCheck.Operations operations =
|
||||
new RequestShapeCheck.Operations("aws/fixture-request-shapes.json", "fixture request shapes", MESSAGES);
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> operations.check(MODEL, "NoSuchOperation", MAPPER.readTree("{}")));
|
||||
assertEquals("InternalFailure", e.getErrorCode());
|
||||
assertEquals(500, e.getHttpStatus());
|
||||
assertEquals("The request processing has failed because of an unknown error.", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsLoadTheVendoredModelOnFirstCheckNotWhenBuilt() {
|
||||
RequestShapeCheck.Operations missing =
|
||||
new RequestShapeCheck.Operations("aws/no-such-request-shapes.json", "missing request shapes", MESSAGES);
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> missing.check("Put", MAPPER.readTree("{}")));
|
||||
assertEquals("missing request shapes resource not found: aws/no-such-request-shapes.json", e.getMessage());
|
||||
}
|
||||
|
||||
private static void assertRefused(String body, String message) {
|
||||
assertRefused(body, MESSAGES, message);
|
||||
}
|
||||
|
||||
private static void assertRefused(String body, RequestShapeCheck.Messages messages, String message) {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), messages), body);
|
||||
assertEquals("Refused", e.getErrorCode(), body);
|
||||
assertEquals(400, e.getHttpStatus(), body);
|
||||
assertEquals(message, e.getMessage(), body);
|
||||
}
|
||||
|
||||
private static void assertAccepted(String body) {
|
||||
assertDoesNotThrow(() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), MESSAGES), body);
|
||||
assertAccepted(body, MESSAGES);
|
||||
}
|
||||
|
||||
private static void assertAccepted(String body, RequestShapeCheck.Messages messages) {
|
||||
assertDoesNotThrow(() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), messages), body);
|
||||
}
|
||||
|
||||
private static RequestShapeModel parse(String json) {
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import static org.hamcrest.Matchers.nullValue;
|
||||
*
|
||||
* <p>Each pair is {@code [used, remaining]}, not {@code [used, quota]}: on real API Gateway the
|
||||
* second element is the quota limit minus cumulative use. Both are zero here because nothing meters
|
||||
* requests per key and a usage plan stores no quota.
|
||||
* requests per key, so there is no use to report or to subtract from a plan's quota.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayGetUsageIntegrationTest {
|
||||
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** CreateUsagePlan bodies as measured with raw requests against API Gateway in eu-west-1. */
|
||||
class ApiGatewayRequestShapesTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String STRUCTURE = "Start of structure or map found where not expected.";
|
||||
private static final String LIST = "Start of list found where not expected";
|
||||
private static final String STRING_TO_INTEGER = "class java.lang.String can not be converted to an Integer";
|
||||
private static final String BOOLEAN_TO_INTEGER = "class java.lang.Boolean can not be converted to an Integer";
|
||||
private static final String STRING_TO_DOUBLE = "class java.lang.String is not an expected Json type";
|
||||
private static final String BOOLEAN_TO_DOUBLE = "class java.lang.Boolean is not an expected Json type";
|
||||
private static final String NUMBER_TO_STRING =
|
||||
"class com.amazon.coral.value.json.numbers.TruncatingBigNumber can not be converted to an String";
|
||||
private static final String BOOLEAN_TO_STRING = "class java.lang.Boolean can not be converted to an String";
|
||||
private static final String STAGE = "{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{\"/pets/GET\":%s}}";
|
||||
|
||||
@Test
|
||||
void anIntegerMemberTakesAnyJsonNumber() {
|
||||
assertAccepted("{\"quota\":{\"limit\":1.5,\"offset\":0,\"period\":\"DAY\"}}");
|
||||
assertAccepted("{\"quota\":{\"limit\":1e2,\"offset\":1.9,\"period\":\"WEEK\"}}");
|
||||
assertAccepted("{\"quota\":{\"limit\":3000000000,\"period\":\"DAY\"}}");
|
||||
assertAccepted("{\"throttle\":{\"burstLimit\":1.5}}");
|
||||
assertAccepted("{\"throttle\":{\"burstLimit\":3000000000}}");
|
||||
assertAccepted("{\"throttle\":{\"burstLimit\":-1e2}}");
|
||||
assertAccepted("{\"apiStages\":[" + STAGE.formatted("{\"burstLimit\":1.5}") + "]}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIntegerMemberRefusesTextEvenWhenItIsNumeric() {
|
||||
for (String text : new String[] {"\"100\"", "\"\"", "\"1.5\""}) {
|
||||
assertRejected("{\"quota\":{\"limit\":" + text + ",\"period\":\"DAY\"}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"quota\":{\"offset\":" + text + "}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":" + text + "}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("{\"burstLimit\":" + text + "}") + "]}",
|
||||
STRING_TO_INTEGER);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIntegerMemberRefusesABoolean() {
|
||||
assertRejected("{\"quota\":{\"limit\":true}}", BOOLEAN_TO_INTEGER);
|
||||
assertRejected("{\"quota\":{\"offset\":false}}", BOOLEAN_TO_INTEGER);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":true}}", BOOLEAN_TO_INTEGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDoubleMemberTakesAnyJsonNumberAndNamesWhatElseItGotAsAnUnexpectedType() {
|
||||
assertAccepted("{\"throttle\":{\"rateLimit\":5}}");
|
||||
assertAccepted("{\"throttle\":{\"rateLimit\":5.5}}");
|
||||
assertAccepted("{\"throttle\":{\"rateLimit\":1e1}}");
|
||||
for (String text : new String[] {"\"5.5\"", "\"abc\"", "\"1e1\""}) {
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":" + text + "}}", STRING_TO_DOUBLE);
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("{\"rateLimit\":" + text + "}") + "]}",
|
||||
STRING_TO_DOUBLE);
|
||||
}
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":true}}", BOOLEAN_TO_DOUBLE);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":false}}", BOOLEAN_TO_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStringMemberRefusesANumberOrABoolean() {
|
||||
for (String number : new String[] {"5", "5.5", "1e2"}) {
|
||||
assertRejected("{\"name\":" + number + "}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"description\":" + number + "}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"quota\":{\"period\":" + number + "}}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":" + number + ",\"stage\":\"v1\"}]}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":" + number + "}]}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"tags\":{\"k\":" + number + "}}", NUMBER_TO_STRING);
|
||||
}
|
||||
assertRejected("{\"name\":true}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"description\":false}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"quota\":{\"period\":true}}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":true}]}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"tags\":{\"k\":false}}", BOOLEAN_TO_STRING);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStructureTakesOnlyAnObjectAsAMemberOrAnElement() {
|
||||
assertRejected("{\"quota\":\"invalid\"}", "Expected null");
|
||||
assertRejected("{\"quota\":5}", "Expected null");
|
||||
assertRejected("{\"throttle\":5}", "Expected null");
|
||||
assertRejected("{\"throttle\":true}", "Expected null");
|
||||
assertRejected("{\"apiStages\":[\"x\"]}", "Expected null");
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("5") + "]}", "Expected null");
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("\"x\"") + "]}", "Expected null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aListWhereNoneIsExpectedIsRefused() {
|
||||
assertRejected("{\"name\":[]}", LIST);
|
||||
assertRejected("{\"quota\":[]}", LIST);
|
||||
assertRejected("{\"throttle\":[]}", LIST);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":[]}}", LIST);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":[1]}}", LIST);
|
||||
assertRejected("{\"quota\":{\"period\":[\"DAY\"]}}", LIST);
|
||||
assertRejected("{\"tags\":[]}", LIST);
|
||||
assertRejected("{\"tags\":{\"k\":[]}}", LIST);
|
||||
assertRejected("{\"apiStages\":[[]]}", LIST);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":[],\"stage\":\"v1\"}]}", LIST);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":[]}]}", LIST);
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("[]") + "]}", LIST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anObjectWhereNoneIsExpectedIsRefused() {
|
||||
assertRejected("{\"name\":{}}", STRUCTURE);
|
||||
assertRejected("{\"description\":{\"a\":1}}", STRUCTURE);
|
||||
assertRejected("{\"apiStages\":{}}", STRUCTURE);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"quota\":{\"period\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"tags\":{\"k\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":{},\"stage\":\"v1\"}]}", STRUCTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aListOrAMapMemberRefusesAScalar() {
|
||||
assertRejected("{\"apiStages\":\"x\"}", "Expected list or null");
|
||||
assertRejected("{\"apiStages\":5}", "Expected list or null");
|
||||
assertRejected("{\"apiStages\":true}", "Expected list or null");
|
||||
assertRejected("{\"tags\":\"x\"}", "Expected map or null");
|
||||
assertRejected("{\"tags\":5}", "Expected map or null");
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":5}]}", "Expected map or null");
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":\"x\"}]}",
|
||||
"Expected map or null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullsAndUnknownMembersAreLeftToTheOperation() {
|
||||
assertAccepted("{\"name\":null,\"quota\":null,\"throttle\":null,\"apiStages\":null,\"tags\":null}");
|
||||
assertAccepted("{\"name\":\"p\",\"unknown\":[1,{}],\"productCode\":5,\"quota\":{\"other\":true}}");
|
||||
assertAccepted("{\"apiStages\":[null,{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{\"/pets/GET\":null}}]}");
|
||||
}
|
||||
|
||||
// Each pair is sent in both body orders; the member first by name is reported either way.
|
||||
@Test
|
||||
void topLevelMembersAreReadInNameOrder() {
|
||||
assertReportedInEitherOrder("\"apiStages\":\"x\"", "\"description\":5", "Expected list or null");
|
||||
assertReportedInEitherOrder("\"description\":5", "\"name\":true", NUMBER_TO_STRING);
|
||||
assertReportedInEitherOrder("\"name\":true", "\"quota\":\"x\"", BOOLEAN_TO_STRING);
|
||||
assertReportedInEitherOrder("\"quota\":\"x\"", "\"tags\":\"x\"", "Expected null");
|
||||
assertReportedInEitherOrder("\"tags\":\"x\"", "\"throttle\":[]", "Expected map or null");
|
||||
// botocore lists name before apiStages, so this is not the model's order either.
|
||||
assertReportedInEitherOrder("\"apiStages\":\"x\"", "\"name\":true", "Expected list or null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedMembersAreReadInNameOrder() {
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":\"x\",\"rateLimit\":\"x\"}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":\"x\",\"burstLimit\":\"x\"}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":true,\"stage\":5}]}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"stage\":5,\"apiId\":true}]}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"quota\":{\"limit\":\"x\",\"period\":5}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"quota\":{\"period\":5,\"limit\":\"x\"}}", STRING_TO_INTEGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapEntriesAreReadInKeyOrder() {
|
||||
assertRejected("{\"tags\":{\"z\":true,\"a\":5}}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"tags\":{\"a\":5,\"z\":true}}", NUMBER_TO_STRING);
|
||||
String z = "\"/z/GET\":{\"burstLimit\":true}";
|
||||
String a = "\"/a/GET\":{\"burstLimit\":\"s\"}";
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{" + z + "," + a + "}}]}",
|
||||
STRING_TO_INTEGER);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{" + a + "," + z + "}}]}",
|
||||
STRING_TO_INTEGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownOperationIsAServerError() {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ApiGatewayRequestShapes.check("NoSuchOperation", json("{}")));
|
||||
assertEquals("InternalFailure", error.getErrorCode());
|
||||
assertEquals(500, error.getHttpStatus());
|
||||
}
|
||||
|
||||
private static void assertReportedInEitherOrder(String first, String second, String message) {
|
||||
assertRejected("{" + first + "," + second + "}", message);
|
||||
assertRejected("{" + second + "," + first + "}", message);
|
||||
}
|
||||
|
||||
private static void assertRejected(String body, String message) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ApiGatewayRequestShapes.check("CreateUsagePlan", json(body)), body);
|
||||
assertEquals("SerializationException", error.getErrorCode(), body);
|
||||
assertEquals(400, error.getHttpStatus(), body);
|
||||
assertEquals(message, error.getMessage(), body);
|
||||
}
|
||||
|
||||
private static void assertAccepted(String body) {
|
||||
assertDoesNotThrow(() -> ApiGatewayRequestShapes.check("CreateUsagePlan", json(body)), body);
|
||||
}
|
||||
|
||||
private static JsonNode json(String body) throws Exception {
|
||||
return MAPPER.readTree(body);
|
||||
}
|
||||
}
|
||||
+330
@@ -6,12 +6,21 @@ import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.anEmptyMap;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
@TestHTTPEndpoint(ApiGatewayController.class)
|
||||
class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
|
||||
private static final String NAME_NULL =
|
||||
"Value null at 'createUsagePlanInput.name' failed to satisfy constraint: Member must not be null";
|
||||
|
||||
@Test
|
||||
void testCreateAndRetrieveUsagePlan() {
|
||||
String usagePlanId = given()
|
||||
@@ -61,4 +70,325 @@ class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
.then()
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlanReportsItsStagesFromCreateAndBothReads() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"staged\",\"apiStages\":[{\"apiId\":\"a1\",\"stage\":\"v1\"}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiStages", hasSize(1))
|
||||
.body("apiStages[0].apiId", equalTo("a1"))
|
||||
.body("apiStages[0].stage", equalTo("v1"))
|
||||
.body("apiStages[0].throttle", nullValue())
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages[0].apiId", equalTo("a1"))
|
||||
.body("apiStages[0].stage", equalTo("v1"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.find { it.id == '" + usagePlanId + "' }.apiStages[0].stage", equalTo("v1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlanWithoutStagesReportsAnEmptyListAndNoLimits() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"bare\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiStages", hasSize(0))
|
||||
.body("throttle", nullValue())
|
||||
.body("quota", nullValue())
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageWithAMethodThrottleIsMatchedByApiAndStage() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"stage-remove\",\"throttle\":{\"burstLimit\":20,\"rateLimit\":10},"
|
||||
+ "\"apiStages\":[{\"apiId\":\"a1\",\"stage\":\"v1\","
|
||||
+ "\"throttle\":{\"/pets/GET\":{\"burstLimit\":10,\"rateLimit\":5}}},"
|
||||
+ "{\"apiId\":\"a1\",\"stage\":\"v2\"}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(10))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"add\",\"path\":\"/apiStages\",\"value\":\"a1:v1\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(2))
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(10));
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/apiStages\",\"value\":\"a1:v1\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(1))
|
||||
.body("apiStages[0].stage", equalTo("v2"));
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(1))
|
||||
.body("apiStages[0].stage", equalTo("v2"))
|
||||
.body("throttle.burstLimit", equalTo(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownQuotaPeriodOnCreateIsAValidationException() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"bad-period\",\"quota\":{\"limit\":1,\"period\":\"day\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: GetUsagePlan and UpdateUsagePlan carry "tags": {}, CreateUsagePlan and
|
||||
// the GetUsagePlans items leave an empty map out.
|
||||
@Test
|
||||
void getAndUpdateReportEmptyTagsWhileCreateAndListLeaveThemOut() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"untagged\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("$", not(hasKey("tags")))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags", anEmptyMap());
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"untagged-renamed\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags", anEmptyMap());
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.find { it.id == '" + usagePlanId + "' }", not(hasKey("tags")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownPlanIdIsNotFoundWithApiGatewaysMessage() {
|
||||
given().get("/usageplans/{usagePlanId}", "no-such-plan")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("NotFoundException"))
|
||||
.body("message", equalTo("Invalid Usage Plan ID specified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageWithoutAnApiIdIsRefusedAndNoPlanIsStored() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"stage-without-api\",\"apiStages\":[{\"stage\":\"v1\"}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid API Stage specified"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.findAll { it.name == 'stage-without-api' }", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrongJsonTypeOnCreateIsASerializationError() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"wrong-type\",\"quota\":\"invalid\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("Expected null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStructuredStageIdentifierIsASerializationErrorAndStoresNoPlan() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"structured-stage\",\"apiStages\":[{\"apiId\":[],\"stage\":{}}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("Start of list found where not expected"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.findAll { it.name == 'structured-stage' }", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNumericStringForAnIntegerIsASerializationErrorAndStoresNoPlan() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"string-limit\",\"quota\":{\"limit\":\"100\",\"period\":\"DAY\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("class java.lang.String can not be converted to an Integer"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.findAll { it.name == 'string-limit' }", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFractionalQuotaLimitIsStoredTruncated() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"fractional-limit\",\"quota\":{\"limit\":1.5,\"period\":\"DAY\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("quota.limit", equalTo(1))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("quota.limit", equalTo(1));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: the limit is truncated from its decimal digits, not first rounded to 2.0 as a double.
|
||||
@Test
|
||||
void aLimitJustUnderAWholeNumberIsStoredTruncated() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"precise-limit\",\"quota\":{\"limit\":1.99999999999999999,\"period\":\"DAY\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("quota.limit", equalTo(1))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("quota.limit", equalTo(1));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a negative fraction is refused, not truncated to 0.
|
||||
@Test
|
||||
void aNegativeFractionalLimitIsRefusedAndStoresNoPlan() {
|
||||
assertCreateRefused("{\"name\":\"negative-fraction-limit\",\"quota\":{\"limit\":-0.9,\"period\":\"DAY\"}}",
|
||||
"BadRequestException", "Usage Plan quota limit must be a non-negative numeric");
|
||||
}
|
||||
|
||||
// In body order the list throttle comes first; API Gateway reads quota before throttle by name.
|
||||
@Test
|
||||
void theFirstWrongJsonTypeInMemberNameOrderIsReported() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"name-order\",\"throttle\":[],\"quota\":\"x\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("Expected null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aZeroByteBodyIsAMissingInput() {
|
||||
int before = planCount();
|
||||
given().contentType(ContentType.JSON)
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value null at 'createUsagePlanInput' "
|
||||
+ "failed to satisfy constraint: Member must not be null"));
|
||||
assertEquals(before, planCount());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a SerializationException with no message.
|
||||
@Test
|
||||
void aBodyThatIsNotAJsonObjectOrArrayIsASerializationErrorWithoutAMessage() {
|
||||
for (String body : new String[] {" ", "{", "{\"name\":\"trailing-junk\"} x", "\"x\"", "5", "null"}) {
|
||||
assertCreateRefused(body, "SerializationException", null);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopLevelArrayIsAListWhereNoneIsExpected() {
|
||||
assertCreateRefused("[]", "SerializationException", "Start of list found where not expected");
|
||||
assertCreateRefused("[{}]", "SerializationException", "Start of list found where not expected");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingOrNullNameIsAValidationException() {
|
||||
for (String body : new String[] {"{}", "{\"description\":\"d\"}", "{\"name\":null}"}) {
|
||||
assertCreateRefused(body, "ValidationException", "1 validation error detected: " + NAME_NULL);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInputModelListsAnInvalidPeriodBeforeAMissingName() {
|
||||
assertCreateRefused("{\"quota\":{\"limit\":1,\"period\":\"YEAR\"}}", "ValidationException",
|
||||
"2 validation errors detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]; " + NAME_NULL);
|
||||
}
|
||||
|
||||
// The empty name is API Gateway's own check: after the input model, before the limits.
|
||||
@Test
|
||||
void anEmptyNameIsABadRequestAfterTheInputModelAndBeforeTheLimits() {
|
||||
assertCreateRefused("{\"name\":\"\"}", "BadRequestException", "Usage Plan name must be specified");
|
||||
assertCreateRefused("{\"name\":\"\",\"quota\":{\"period\":\"DAY\"}}", "BadRequestException",
|
||||
"Usage Plan name must be specified");
|
||||
assertCreateRefused("{\"name\":\"\",\"quota\":{\"limit\":1,\"period\":\"YEAR\"}}", "ValidationException",
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]");
|
||||
}
|
||||
|
||||
private static int planCount() {
|
||||
return given().get("/usageplans").then().statusCode(200).extract().path("item.size()");
|
||||
}
|
||||
|
||||
/** Posts {@code body}, expects a 400 of {@code type} with {@code message}, and that no plan was stored. */
|
||||
private static void assertCreateRefused(String body, String type, String message) {
|
||||
int before = planCount();
|
||||
given().contentType(ContentType.JSON)
|
||||
.body(body)
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo(type))
|
||||
.body("message", equalTo(message));
|
||||
assertEquals(before, planCount(), body);
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
|
||||
import software.amazon.awssdk.services.apigateway.model.ApiStage;
|
||||
import software.amazon.awssdk.services.apigateway.model.CreateUsagePlanResponse;
|
||||
import software.amazon.awssdk.services.apigateway.model.GetUsagePlanResponse;
|
||||
import software.amazon.awssdk.services.apigateway.model.QuotaPeriodType;
|
||||
import software.amazon.awssdk.services.apigateway.model.QuotaSettings;
|
||||
import software.amazon.awssdk.services.apigateway.model.ThrottleSettings;
|
||||
import software.amazon.awssdk.services.apigateway.model.UsagePlan;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class ApiGatewayUsagePlanSdkIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
private ApiGatewayClient client() {
|
||||
return ApiGatewayClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesThrottleAndQuotaRoundTripThroughEveryRead() {
|
||||
try (ApiGatewayClient client = client()) {
|
||||
String apiId = client.createRestApi(r -> r.name("usage-plan-sdk")).id();
|
||||
ThrottleSettings planThrottle = ThrottleSettings.builder().burstLimit(20).rateLimit(10.0).build();
|
||||
QuotaSettings quota = QuotaSettings.builder().limit(1000).offset(3).period(QuotaPeriodType.MONTH).build();
|
||||
ApiStage v1 = ApiStage.builder().apiId(apiId).stage("v1")
|
||||
.throttle(Map.of("/pets/GET", ThrottleSettings.builder().burstLimit(10).rateLimit(5.0).build()))
|
||||
.build();
|
||||
ApiStage v2 = ApiStage.builder().apiId(apiId).stage("v2").build();
|
||||
CreateUsagePlanResponse created = client.createUsagePlan(r -> r.name("sdk-plan")
|
||||
.apiStages(v1, v2).throttle(planThrottle).quota(quota));
|
||||
try {
|
||||
assertEquals(List.of(v1, v2), created.apiStages());
|
||||
assertEquals(planThrottle, created.throttle());
|
||||
assertEquals(quota, created.quota());
|
||||
|
||||
GetUsagePlanResponse read = client.getUsagePlan(r -> r.usagePlanId(created.id()));
|
||||
assertEquals(List.of(v1, v2), read.apiStages());
|
||||
assertEquals(planThrottle, read.throttle());
|
||||
assertEquals(quota, read.quota());
|
||||
|
||||
UsagePlan listed = client.getUsagePlans(r -> r.limit(500)).items().stream()
|
||||
.filter(plan -> plan.id().equals(created.id())).findFirst().orElseThrow();
|
||||
assertEquals(List.of(v1, v2), listed.apiStages());
|
||||
assertEquals(planThrottle, listed.throttle());
|
||||
assertEquals(quota, listed.quota());
|
||||
} finally {
|
||||
client.deleteUsagePlan(r -> r.usagePlanId(created.id()));
|
||||
client.deleteRestApi(r -> r.restApiId(apiId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.ApiStage;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Limits;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Quota;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Throttle;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
|
||||
class UsagePlanLimitsTest {
|
||||
|
||||
private static Map<String, Object> request(Object... keyValues) {
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
for (int i = 0; i < keyValues.length; i += 2) {
|
||||
request.put((String) keyValues[i], keyValues[i + 1]);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static void assertRefused(Executable call, String code, int status, String message) {
|
||||
AwsException e = assertThrows(AwsException.class, call);
|
||||
assertEquals(code, e.getErrorCode());
|
||||
assertEquals(status, e.getHttpStatus());
|
||||
assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestWithoutLimitsHasNoStagesThrottleOrQuota() {
|
||||
assertEquals(new Limits(List.of(), null, null), UsagePlanLimits.fromRequest(request("name", "p")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttleFieldsLeftOutReadAsZero() {
|
||||
assertEquals(new Throttle(10, 0.0),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("burstLimit", 10))).throttle());
|
||||
assertEquals(new Throttle(0, 5.5),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("rateLimit", "5.5"))).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotaOffsetDefaultsToZeroAndNumbersMayBeStrings() {
|
||||
assertEquals(new Quota(100, 0, "WEEK"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 100, "period", "WEEK"))).quota());
|
||||
assertEquals(new Quota(100, 2, "WEEK"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", "100", "offset", "2", "period", "WEEK"))).quota());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesKeepTheirMethodThrottlesAndAnEmptyOneIsDropped() {
|
||||
Limits limits = UsagePlanLimits.fromRequest(request(
|
||||
"throttle", Map.of("burstLimit", 20, "rateLimit", 10),
|
||||
"apiStages", List.of(
|
||||
Map.of("apiId", "a", "stage", "v1",
|
||||
"throttle", Map.of("/pets/GET", Map.of("burstLimit", 10, "rateLimit", 5))),
|
||||
Map.of("apiId", "a", "stage", "v2", "throttle", Map.of()))));
|
||||
|
||||
assertEquals(List.of(new ApiStage("a", "v1", Map.of("/pets/GET", new Throttle(10, 5.0))),
|
||||
new ApiStage("a", "v2")), limits.apiStages());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a positive JSON number for an int member is truncated and clamped.
|
||||
@Test
|
||||
void aJsonNumberIsTruncatedTowardZeroAndClampedToTheIntRange() {
|
||||
assertEquals(new Quota(1, 0, "DAY"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 1.5, "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(1, 0.0),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("burstLimit", 1.5))).throttle());
|
||||
assertEquals(new Quota(100, 0, "DAY"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 100.0, "period", "DAY"))).quota());
|
||||
assertEquals(new Quota(Integer.MAX_VALUE, 0, "DAY"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 3000000000L, "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(0, 2.5),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("rateLimit", 2.5))).throttle());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: the decimal digits are kept, so a value just under a whole number is not rounded up.
|
||||
@Test
|
||||
void aJsonNumberIsTruncatedFromItsDecimalDigitsWithoutRoundingThroughADouble() {
|
||||
assertEquals(new Quota(1, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("1.99999999999999999"), "period", "DAY"))).quota());
|
||||
assertEquals(new Quota(1, 0, "DAY"), UsagePlanLimits.fromRequest(request("quota",
|
||||
Map.of("limit", 1, "offset", new BigDecimal("0.99999999999999999"), "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(2, 0.0), UsagePlanLimits.fromRequest(
|
||||
request("throttle", Map.of("burstLimit", new BigDecimal("2.99999999999999999")))).throttle());
|
||||
assertEquals(new Quota(Integer.MAX_VALUE, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("2147483647.9"), "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(0, 1.0), UsagePlanLimits.fromRequest(
|
||||
request("throttle", Map.of("rateLimit", new BigDecimal("1.00000000000000000001")))).throttle());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a negative fraction is refused as negative, not truncated to 0.
|
||||
@Test
|
||||
void aNegativeFractionIsRefusedAsNegative() {
|
||||
String limit = "Usage Plan quota limit must be a non-negative numeric";
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("-0.9"), "period", "DAY"))),
|
||||
"BadRequestException", 400, limit);
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(request("quota", Map.of("limit", -0.9, "period", "DAY"))),
|
||||
"BadRequestException", 400, limit);
|
||||
}
|
||||
|
||||
// The int bounds are compared before rounding, so an extreme exponent is never expanded into its digits.
|
||||
@Test
|
||||
void anExtremeExponentIsReadWithoutExpandingIt() {
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
assertEquals(new Quota(Integer.MAX_VALUE, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("1e1000000000"), "period", "DAY"))).quota());
|
||||
assertEquals(new Quota(0, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("1e-1000000000"), "period", "DAY"))).quota());
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("-1e-1000000000"), "period", "DAY"))),
|
||||
"BadRequestException", 400, "Usage Plan quota limit must be a non-negative numeric");
|
||||
});
|
||||
}
|
||||
|
||||
// CreateUsagePlan's input model: the service lists this with a missing name in one ValidationException.
|
||||
@Test
|
||||
void aPeriodOutsideTheEnumIsAnInputModelViolation() {
|
||||
assertEquals("Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [MONTH, WEEK, DAY]",
|
||||
UsagePlanLimits.periodViolation(request("quota", Map.of("limit", 1, "period", "YEAR"))));
|
||||
assertNull(UsagePlanLimits.periodViolation(request("quota", Map.of("limit", 1, "period", "DAY"))));
|
||||
assertNull(UsagePlanLimits.periodViolation(request("quota", Map.of("limit", 1))));
|
||||
assertNull(UsagePlanLimits.periodViolation(request("name", "p")));
|
||||
}
|
||||
|
||||
// The storage backends persist plans with a plain ObjectMapper, so this is the shape on disk.
|
||||
@Test
|
||||
void aPlanSurvivesTheStorageJsonRoundTripAndOlderPlansStillLoad() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId("p");
|
||||
plan.applyLimits(new Limits(List.of(new ApiStage("a", "v1", Map.of("/pets/GET", new Throttle(10, 5.0))),
|
||||
new ApiStage("a", "v2")), new Throttle(20, 10.0), new Quota(1000, 3, "MONTH")));
|
||||
|
||||
String json = mapper.writeValueAsString(plan);
|
||||
assertFalse(json.contains("\"limits\""), json);
|
||||
assertEquals(plan.limits(), mapper.readValue(json, UsagePlan.class).limits());
|
||||
|
||||
UsagePlan older = mapper.readValue(
|
||||
"{\"id\":\"p\",\"name\":\"n\",\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\"}]}", UsagePlan.class);
|
||||
assertEquals(new Limits(List.of(new ApiStage("a", "v1")), null, null), older.limits());
|
||||
}
|
||||
|
||||
static Stream<Arguments> refusedCreates() {
|
||||
String throttle = "Usage Plan throttle rate limit and burst limit must be numeric and greater than zero";
|
||||
String limit = "Usage Plan quota limit must be a non-negative numeric";
|
||||
return Stream.of(
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 100)), "BadRequestException", 400,
|
||||
"Invalid Usage Plan quota period specified. Must be one of [DAY, WEEK, MONTH]"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 100, "period", "YEAR")), "ValidationException", 400,
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]"),
|
||||
// The input model's period check outranks every other check, measured on API Gateway.
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "YEAR"), "throttle", Map.of("burstLimit", -1)),
|
||||
"ValidationException", 400,
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "YEAR"), "apiStages", List.of(
|
||||
Map.of("apiId", "a", "stage", "v1"), Map.of("apiId", "a", "stage", "v1"))),
|
||||
"ValidationException", 400,
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]"),
|
||||
Arguments.of(Map.of("quota", Map.of("period", "DAY")), "BadRequestException", 400, limit),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", -1, "period", "DAY")), "BadRequestException", 400, limit),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "DAY", "offset", 1)), "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be zero in the DAY period"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "WEEK", "offset", 7)), "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be between 0 and 6 inclusive in the WEEK period"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "WEEK", "offset", -1)), "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be between 0 and 6 inclusive in the WEEK period"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "MONTH", "offset", 28)), "BadRequestException",
|
||||
400, "Usage Plan quota offset must be between 0 and 27 inclusive in the MONTH period"),
|
||||
Arguments.of(Map.of("throttle", Map.of("burstLimit", -1, "rateLimit", 1)), "BadRequestException", 400,
|
||||
throttle),
|
||||
// Text is parsed as written, so a fraction is refused; a JSON number would be truncated.
|
||||
Arguments.of(Map.of("throttle", Map.of("burstLimit", "1.5")), "BadRequestException", 400, throttle),
|
||||
Arguments.of(Map.of("throttle", Map.of("rateLimit", "abc")), "BadRequestException", 400, throttle),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a", "stage", "v1",
|
||||
"throttle", Map.of("/pets/GET", Map.of("burstLimit", 1))))), "BadRequestException", 400,
|
||||
"Can not define fine grain throttling if usage plan throttle is not defined."),
|
||||
Arguments.of(Map.of("throttle", Map.of("burstLimit", 1), "apiStages", List.of(Map.of("apiId", "a",
|
||||
"stage", "v1", "throttle", Map.of("/pets/GET", Map.of("burstLimit", -1))))),
|
||||
"BadRequestException", 400, throttle),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a", "stage", "v1"),
|
||||
Map.of("apiId", "a", "stage", "v1"))), "ConflictException", 409,
|
||||
"API Stage is already defined for Usage Plan: a:v1"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("stage", "v1"))), "BadRequestException", 400,
|
||||
"Invalid API Stage specified"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a"))), "BadRequestException", 400,
|
||||
"Invalid API Stage specified"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "", "stage", "v1"))), "BadRequestException",
|
||||
400, "Invalid API Stage specified"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a", "stage", ""))), "BadRequestException",
|
||||
400, "Invalid API Stage specified"),
|
||||
Arguments.of(stageThrottle("/GET"), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: /GET,method: } specified"),
|
||||
Arguments.of(stageThrottle(""), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: ,method: } specified"),
|
||||
Arguments.of(stageThrottle("/pets/"), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: /pets/,method: } specified"),
|
||||
Arguments.of(stageThrottle("GET"), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: GET,method: } specified"));
|
||||
}
|
||||
|
||||
/** A create request with a plan throttle and stage a:v1 throttling {@code methodKey}. */
|
||||
private static Map<String, Object> stageThrottle(String methodKey) {
|
||||
return Map.of("throttle", Map.of("burstLimit", 20, "rateLimit", 10), "apiStages", List.of(Map.of("apiId", "a",
|
||||
"stage", "v1", "throttle", Map.of(methodKey, Map.of("burstLimit", 5, "rateLimit", 2)))));
|
||||
}
|
||||
|
||||
// Floci does not check that the method exists, so keys AWS refuses for that reason are kept.
|
||||
@Test
|
||||
void aMethodKeyIsOnlyCheckedForHavingAMethod() {
|
||||
assertEquals(Map.of("//GET", new Throttle(5, 2.0)),
|
||||
UsagePlanLimits.fromRequest(stageThrottle("//GET")).apiStages().get(0).throttle());
|
||||
assertEquals(Map.of("/pets/GET/extra", new Throttle(5, 2.0)),
|
||||
UsagePlanLimits.fromRequest(stageThrottle("/pets/GET/extra")).apiStages().get(0).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonNullReadsAsAbsent() {
|
||||
assertEquals(new Limits(List.of(), null, null),
|
||||
UsagePlanLimits.fromRequest(request("throttle", null, "quota", null, "apiStages", null)));
|
||||
assertEquals(List.of(new ApiStage("a", "v1")), UsagePlanLimits.fromRequest(
|
||||
request("apiStages", List.of(request("apiId", "a", "stage", "v1", "throttle", null)))).apiStages());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("refusedCreates")
|
||||
void createRefusesWhatApiGatewayRefuses(Map<String, Object> request, String code, int status, String message) {
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(request), code, status, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate src/main/resources/aws/apigateway-request-shapes.json from botocore's API Gateway model.
|
||||
|
||||
API Gateway rejects a request body member of the wrong JSON type with a SerializationException
|
||||
before it validates anything. The Java side (`ApiGatewayRequestShapes`) needs each operation's body
|
||||
shapes to do the same, so this script keeps only what that check reads: the input shape of every
|
||||
operation, reduced to the members carried in the JSON body, and for every shape reachable from
|
||||
one, its type and the shapes of its members, list elements or map values.
|
||||
|
||||
Members bound to the URI, the query string or a header are left out: they never reach the body.
|
||||
|
||||
The model is botocore's `apigateway/2015-07-09/service-2.json` (Apache-2.0,
|
||||
https://github.com/boto/botocore). It is located, in order, at `--botocore-data`, the
|
||||
`local/aws/botocore` checkout, then the installed `botocore` package, which `requirements.txt`
|
||||
pins so CI regenerates the same bytes.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_apigateway_shapes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_apigateway_shapes.py --check # exit 1 when the vendored file is stale
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import request_shapes
|
||||
|
||||
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/apigateway-request-shapes.json"
|
||||
MODEL = Path("apigateway/2015-07-09")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,7 +1,8 @@
|
||||
"""Shared generator for the vendored request shapes a service's request check reads.
|
||||
|
||||
`regen_dynamodb_shapes.py`, `regen_sesv2_shapes.py` and `regen_ecs_shapes.py` each name a botocore
|
||||
model and an output file and hand the rest to `main()`. `regen_resource_groups_shapes.py` and
|
||||
`regen_dynamodb_shapes.py`, `regen_sesv2_shapes.py`, `regen_apigateway_shapes.py` and
|
||||
`regen_ecs_shapes.py` each name a botocore model and an output file and hand the rest to
|
||||
`main()`. `regen_resource_groups_shapes.py` and
|
||||
`regen_ecr_shapes.py` vendor constraints as well, through `build_constraints()`. The output keeps only what `RequestShapeModel` reads: the input
|
||||
shape of every operation, reduced to the members carried in the JSON body, and for every shape
|
||||
reachable from one, its type and the shapes of its members, list elements or map values.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Tests for request_shapes, the generator behind regen_dynamodb_shapes, regen_sesv2_shapes, regen_ecs_shapes and
|
||||
regen_emr_serverless_shapes, and of the constraints regen_resource_groups_shapes and regen_ecr_shapes vendor.
|
||||
"""Tests for request_shapes, the generator behind regen_dynamodb_shapes, regen_sesv2_shapes, regen_apigateway_shapes,
|
||||
regen_ecs_shapes and regen_emr_serverless_shapes, and of the constraints regen_resource_groups_shapes and
|
||||
regen_ecr_shapes vendor.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make aws-data-test)
|
||||
"""
|
||||
@@ -11,6 +12,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import regen_apigateway_shapes
|
||||
import regen_dynamodb_shapes
|
||||
import regen_ecr_shapes
|
||||
import regen_ecs_shapes
|
||||
@@ -167,6 +169,7 @@ def test_output_is_stable():
|
||||
def test_generator_name_is_the_scripts_path_from_the_repository_root():
|
||||
assert r.generator_name(regen_dynamodb_shapes.__file__) == "tools/aws/regen_dynamodb_shapes.py"
|
||||
assert r.generator_name(regen_sesv2_shapes.__file__) == "tools/aws/regen_sesv2_shapes.py"
|
||||
assert r.generator_name(regen_apigateway_shapes.__file__) == "tools/aws/regen_apigateway_shapes.py"
|
||||
assert r.generator_name(regen_ecs_shapes.__file__) == "tools/aws/regen_ecs_shapes.py"
|
||||
|
||||
|
||||
@@ -191,6 +194,7 @@ def test_load_model_without_a_service_model_exits(tmp_path):
|
||||
@pytest.mark.parametrize("script, model, output", [
|
||||
(regen_dynamodb_shapes, "dynamodb/2012-08-10", "dynamodb-request-shapes.json"),
|
||||
(regen_sesv2_shapes, "sesv2/2019-09-27", "sesv2-request-shapes.json"),
|
||||
(regen_apigateway_shapes, "apigateway/2015-07-09", "apigateway-request-shapes.json"),
|
||||
(regen_ecs_shapes, "ecs/2014-11-13", "ecs-request-shapes.json"),
|
||||
])
|
||||
def test_each_script_runs_the_shared_main_with_its_model_and_output(script, model, output, monkeypatch):
|
||||
|
||||
Reference in new issue
Block a user