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:
Mario Toffia authored and GitHub committed 2026-10-25 07:55:54 -04:00
1 parent da9f7e93b1
commit bab7af3a21
19 files changed
+2684 -85

No files matched your search

@@ -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)));
}
}
@@ -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());
@@ -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);
}
}
@@ -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);
}
}