mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(apigateway): patch a usage plan's throttle, quota and stage throttles (#6418)
* fix(apigateway): patch a usage plan's throttle, quota and stage throttles * fix(apigateway): parse a usage plan stage throttle patch value as API Gateway does * fix(apigateway): validate an UpdateUsagePlan op as API Gateway does * test(apigateway): pin how a usage plan stage throttle patch reads numbers and rolls back * fix(apigateway): refuse removing a usage plan method throttle path that names no method * fix(cloudformation): keep a stage's throttle when a usage plan update leaves the stage in place
This commit is contained in:
1 parent
3e3ba5ba63
commit
74cab790f2
10 files changed
+1400
-80
No files matched your search
+24
@@ -913,11 +913,35 @@ public class ApiGatewayController {
|
||||
@Path("/usageplans/{usagePlanId}")
|
||||
public Response updateUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
checkUpdateUsagePlanInput(body);
|
||||
List<Map<String, String>> patchOperations = parsePatchOperations(body);
|
||||
UsagePlan plan = service.updateUsagePlan(region, usagePlanId, patchOperations);
|
||||
return Response.ok(toUsagePlanNode(plan, true).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateUsagePlan's input model, measured on API Gateway: a member of the wrong JSON type is a
|
||||
* SerializationException, then every op outside the model's enum is listed in one
|
||||
* ValidationException. A body that is not a JSON object is left to {@link #parsePatchOperations}.
|
||||
*/
|
||||
private void checkUpdateUsagePlanInput(String body) {
|
||||
JsonNode node;
|
||||
try {
|
||||
node = objectMapper.readTree(body);
|
||||
} catch (JsonProcessingException | IllegalArgumentException expected) {
|
||||
// parsePatchOperations answers a body that is not JSON, as it does for every PATCH operation.
|
||||
return;
|
||||
}
|
||||
if (node == null || !node.isObject()) {
|
||||
return;
|
||||
}
|
||||
ApiGatewayRequestShapes.check("UpdateUsagePlan", node);
|
||||
List<String> violations = UsagePlanLimits.opViolations(node.path("patchOperations"));
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationException(violations);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/usageplans/{usagePlanId}")
|
||||
public Response deleteUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) {
|
||||
|
||||
+48
-49
@@ -132,6 +132,11 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
*/
|
||||
private final Object domainNameLock = new Object();
|
||||
private final Object vpcLinkTagLock = new Object();
|
||||
/**
|
||||
* Guards a usage plan patch. A patch writes back the stages, throttle and quota it read, so two at
|
||||
* once would restore one another's stale values.
|
||||
*/
|
||||
private final Object usagePlanLock = new Object();
|
||||
private final TlsCertificateManager certificateManager;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
@@ -1541,62 +1546,56 @@ public class ApiGatewayService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public UsagePlan updateUsagePlan(String region, String usagePlanId, List<Map<String, String>> patchOperations) {
|
||||
UsagePlan plan = getUsagePlan(region, usagePlanId);
|
||||
// The store hands back live objects, so every op is validated against pending values first and
|
||||
// only applied once the whole patch is known to be good.
|
||||
String newName = plan.getName();
|
||||
String newDescription = plan.getDescription();
|
||||
List<UsagePlan.ApiStage> newApiStages = new ArrayList<>(plan.getApiStages());
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
if (op == null) {
|
||||
throw new AwsException("BadRequestException", "Invalid patch operation", 400);
|
||||
}
|
||||
String opType = op.get("op");
|
||||
String path = op.get("path");
|
||||
String value = op.get("value");
|
||||
if (path == null || value == null) {
|
||||
throw new AwsException("BadRequestException", "Missing path or value", 400);
|
||||
}
|
||||
if ("/apiStages".equals(path)) {
|
||||
// AWS models stage membership as add/remove of an "apiId:stage" pair.
|
||||
if (!"add".equals(opType) && !"remove".equals(opType)) {
|
||||
throw new AwsException("BadRequestException", "Invalid operation", 400);
|
||||
synchronized (usagePlanLock) {
|
||||
UsagePlan plan = getUsagePlan(region, usagePlanId);
|
||||
// The store hands back live objects, so every op is validated against pending values first and
|
||||
// the plan only changes once the whole patch is known to be good.
|
||||
String newName = plan.getName();
|
||||
String newDescription = plan.getDescription();
|
||||
UsagePlanLimits.Patch limits = new UsagePlanLimits.Patch(plan);
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
if (op == null) {
|
||||
throw new AwsException("BadRequestException", "Invalid patch operation", 400);
|
||||
}
|
||||
String[] parts = value.split(":", 2);
|
||||
if (parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty()) {
|
||||
String opType = op.get("op");
|
||||
String path = op.get("path");
|
||||
String value = op.get("value");
|
||||
UsagePlanLimits.requirePatchOp(opType);
|
||||
if (path == null) {
|
||||
throw new AwsException("BadRequestException", "Missing path or value", 400);
|
||||
}
|
||||
// A remove of /throttle, /quota or a stage throttle carries no value, so only the name
|
||||
// and description ops below insist on one.
|
||||
if (limits.apply(opType, path, value)) {
|
||||
continue;
|
||||
}
|
||||
// API Gateway allows /productCode on add, remove and replace; Floci has no product codes to set.
|
||||
if ("/productCode".equals(path)) {
|
||||
throw new AwsException("BadRequestException", "Usage plan product codes are not supported", 400);
|
||||
}
|
||||
// API Gateway takes /name and /description through replace only.
|
||||
if (!"replace".equals(opType) || (!"/name".equals(path) && !"/description".equals(path))) {
|
||||
throw UsagePlanLimits.invalidPatchPath(opType, path);
|
||||
}
|
||||
if (value == null) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"apiStages value must be in the form apiId:stage", 400);
|
||||
"/name".equals(path) ? "Usage Plan name must be specified" : "Missing path or value", 400);
|
||||
}
|
||||
// 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 (index < 0) {
|
||||
newApiStages.add(new UsagePlan.ApiStage(parts[0], parts[1]));
|
||||
}
|
||||
} else if (index >= 0) {
|
||||
newApiStages.remove(index);
|
||||
if ("/name".equals(path)) {
|
||||
newName = value;
|
||||
} else {
|
||||
newDescription = value;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!"add".equals(opType) && !"replace".equals(opType)) {
|
||||
throw new AwsException("BadRequestException", "Invalid operation", 400);
|
||||
}
|
||||
if ("/name".equals(path)) {
|
||||
newName = value;
|
||||
} else if ("/description".equals(path)) {
|
||||
newDescription = value;
|
||||
} else {
|
||||
throw new AwsException("BadRequestException", "Unsupported path: " + path, 400);
|
||||
}
|
||||
}
|
||||
UsagePlan.Limits newLimits = limits.result();
|
||||
plan.setName(newName);
|
||||
plan.setDescription(newDescription);
|
||||
plan.applyLimits(newLimits);
|
||||
usagePlanStore.put(usagePlanKey(region, usagePlanId), plan);
|
||||
return plan;
|
||||
}
|
||||
plan.setName(newName);
|
||||
plan.setDescription(newDescription);
|
||||
// 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;
|
||||
}
|
||||
|
||||
public List<UsagePlan> getUsagePlans(String region) {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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;
|
||||
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;
|
||||
@@ -16,8 +20,9 @@ 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.
|
||||
* A usage plan's API stages, throttle and quota: read from a {@code CreateUsagePlan} request and
|
||||
* patched by {@code UpdateUsagePlan}, with the errors API Gateway answers. Every message was
|
||||
* measured against API Gateway in eu-west-1.
|
||||
*/
|
||||
public final class UsagePlanLimits {
|
||||
|
||||
@@ -32,6 +37,29 @@ public final class UsagePlanLimits {
|
||||
"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 static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final String STAGE_THROTTLE_INVALID = "Invalid API Stage throttle specified for usageplan";
|
||||
private static final String PLAN_THROTTLE_UNDER_FINE_GRAIN =
|
||||
"Can not remove usage plan throttling if fine grain throttling is defined for one or more api-stages.";
|
||||
private static final String STAGES_PREFIX = "/apiStages/";
|
||||
private static final String STAGE_THROTTLE = "/throttle";
|
||||
/** The input model's op enum, in the order its violation lists it. */
|
||||
private static final List<String> OP_ENUM = List.of("add", "remove", "move", "test", "replace", "copy");
|
||||
/** The paths UpdateUsagePlan allows per op, verbatim from API Gateway's error ("apidId" is AWS's own spelling). */
|
||||
private static final Map<String, String> PATCH_PATHS = Map.of(
|
||||
"add", "[/apiStages, /productCode, /quota/period, /quota/limit, /quota/offset, /throttle/rateLimit, "
|
||||
+ "/throttle/burstLimit, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>/rateLimit, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>/burstLimit, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle]",
|
||||
"replace", "[/name, /description, /productCode, /quota/period, /quota/limit, /quota/offset, "
|
||||
+ "/throttle/rateLimit, /throttle/burstLimit, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>/rateLimit, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>/burstLimit, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle]",
|
||||
"remove", "[/apiStages, /quota, /throttle, /productCode, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle]");
|
||||
|
||||
private UsagePlanLimits() {
|
||||
}
|
||||
@@ -46,7 +74,8 @@ public final class UsagePlanLimits {
|
||||
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.
|
||||
// CreateUsagePlan's input model refuses an unknown period before any of API Gateway's own checks;
|
||||
// UpdateUsagePlan has no such model and answers with quota()'s message instead.
|
||||
throw SmithyValidationErrors.validationException(periodViolation);
|
||||
}
|
||||
Throttle throttle = request.get("throttle") instanceof Map<?, ?> settings ? throttle(settings) : null;
|
||||
@@ -112,15 +141,19 @@ public final class UsagePlanLimits {
|
||||
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);
|
||||
throw new AwsException(BAD_REQUEST, "Invalid method " + methodRef(resourcePathAndMethod) + " specified",
|
||||
400);
|
||||
}
|
||||
methods.put(entry.getKey(), throttle(entry.getValue()));
|
||||
}
|
||||
return methods;
|
||||
}
|
||||
|
||||
/** {@code {resourcePath: <path>,method: <method>}}, with no space after the comma: API Gateway's own formatting. */
|
||||
private static String methodRef(String[] resourcePathAndMethod) {
|
||||
return "{resourcePath: " + resourcePathAndMethod[0] + ",method: " + resourcePathAndMethod[1] + "}";
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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
|
||||
@@ -168,16 +201,34 @@ public final class UsagePlanLimits {
|
||||
}
|
||||
|
||||
static int burstLimit(Object value) {
|
||||
Integer burst = value == null ? null : intValue(value);
|
||||
if (burst == null || burst < 0) {
|
||||
int burst = numericBurstLimit(value);
|
||||
if (burst < 0) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
return burst;
|
||||
}
|
||||
|
||||
static double rateLimit(Object value) {
|
||||
double rate = numericRateLimit(value);
|
||||
if (rate < 0) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
return rate;
|
||||
}
|
||||
|
||||
/** A whole number, negative or not; the sign is the caller's to check. */
|
||||
static int numericBurstLimit(Object value) {
|
||||
Integer burst = value == null ? null : intValue(value);
|
||||
if (burst == null) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
return burst;
|
||||
}
|
||||
|
||||
/** A finite number, negative or not; the sign is the caller's to check. */
|
||||
static double numericRateLimit(Object value) {
|
||||
Double rate = value == null ? null : doubleValue(value);
|
||||
if (rate == null || rate < 0) {
|
||||
if (rate == null) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
return rate;
|
||||
@@ -201,6 +252,368 @@ public final class UsagePlanLimits {
|
||||
"API Stage is already defined for Usage Plan: " + apiId + ":" + stage, 409);
|
||||
}
|
||||
|
||||
/**
|
||||
* The stage, throttle and quota part of one {@code UpdateUsagePlan} request. Ops apply in order to
|
||||
* pending values and {@link #result()} validates what they add up to, the way API Gateway accepts a
|
||||
* quota built from separate limit and period ops. Nothing touches the plan itself.
|
||||
*/
|
||||
public static final class Patch {
|
||||
|
||||
private final String usagePlanId;
|
||||
private final List<ApiStage> stages;
|
||||
private Throttle throttle;
|
||||
private boolean hasQuota;
|
||||
private Object quotaLimit;
|
||||
private Object quotaOffset;
|
||||
private Object quotaPeriod;
|
||||
|
||||
public Patch(UsagePlan plan) {
|
||||
usagePlanId = plan.getId();
|
||||
stages = new ArrayList<>(plan.getApiStages());
|
||||
throttle = plan.getThrottle();
|
||||
Quota quota = plan.getQuota();
|
||||
hasQuota = quota != null;
|
||||
if (hasQuota) {
|
||||
quotaLimit = quota.limit();
|
||||
quotaOffset = quota.offset();
|
||||
quotaPeriod = quota.period();
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies one op; false when {@code path} is not a stage, throttle or quota path. */
|
||||
public boolean apply(String op, String path, String value) {
|
||||
requirePatchOp(op);
|
||||
if ("/apiStages".equals(path)) {
|
||||
applyStage(op, value);
|
||||
} else if (path.startsWith(STAGES_PREFIX)) {
|
||||
applyStageThrottle(op, path, value);
|
||||
} else if ("/throttle".equals(path) || path.startsWith("/throttle/")) {
|
||||
applyThrottle(op, path, value);
|
||||
} else if ("/quota".equals(path) || path.startsWith("/quota/")) {
|
||||
applyQuota(op, path, value);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Limits result() {
|
||||
Quota quota = hasQuota ? quota(quotaLimit, quotaOffset, quotaPeriod) : null;
|
||||
// A plan throttle field may go negative between ops, as on API Gateway; only the outcome must not.
|
||||
if (throttle != null && (throttle.burstLimit() < 0 || throttle.rateLimit() < 0)) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
if (throttle == null && hasMethodThrottles(stages)) {
|
||||
throw new AwsException(BAD_REQUEST, FINE_GRAIN_WITHOUT_PLAN_THROTTLE, 400);
|
||||
}
|
||||
return new Limits(stages, throttle, quota);
|
||||
}
|
||||
|
||||
private void applyStage(String op, String value) {
|
||||
if (!"add".equals(op) && !"remove".equals(op)) {
|
||||
throw invalidPatchPath(op, "/apiStages");
|
||||
}
|
||||
String[] ref = stageRef(value);
|
||||
if ("add".equals(op)) {
|
||||
if (indexOf(stages, ref[0], ref[1]) >= 0) {
|
||||
throw alreadyDefined(ref[0], ref[1]);
|
||||
}
|
||||
stages.add(new ApiStage(ref[0], ref[1]));
|
||||
} else {
|
||||
stages.remove(stageIndex(ref));
|
||||
}
|
||||
}
|
||||
|
||||
private void applyStageThrottle(String op, String path, String value) {
|
||||
String rest = path.substring(STAGES_PREFIX.length());
|
||||
int slash = rest.indexOf('/');
|
||||
String suffix = slash < 0 ? "" : rest.substring(slash);
|
||||
if (!STAGE_THROTTLE.equals(suffix) && !suffix.startsWith(STAGE_THROTTLE + "/")) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
// A method throttle comes off whole: remove takes no single rateLimit or burstLimit of it.
|
||||
String last = path.substring(path.lastIndexOf('/') + 1);
|
||||
if ("remove".equals(op) && suffix.startsWith(STAGE_THROTTLE + "/")
|
||||
&& ("rateLimit".equals(last) || "burstLimit".equals(last))) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
int index = stageIndex(stageRef(rest.substring(0, slash)));
|
||||
ApiStage stage = stages.get(index);
|
||||
Map<String, Throttle> methods = stage.throttle() == null ? null : new LinkedHashMap<>(stage.throttle());
|
||||
if (STAGE_THROTTLE.equals(suffix)) {
|
||||
methods = switch (op == null ? "" : op) {
|
||||
case "add" -> {
|
||||
if (methods != null) {
|
||||
throw new AwsException("ConflictException",
|
||||
"API Stage throttle is already defined for usageplan " + usagePlanId, 409);
|
||||
}
|
||||
yield methodThrottles(value);
|
||||
}
|
||||
case "replace" -> {
|
||||
if (methods == null) {
|
||||
throw new AwsException("NotFoundException",
|
||||
"API Stage throttle not found for usageplan " + usagePlanId, 404);
|
||||
}
|
||||
yield methodThrottles(value);
|
||||
}
|
||||
case "remove" -> null;
|
||||
default -> throw invalidPatchPath(op, path);
|
||||
};
|
||||
} else {
|
||||
methods = patchMethodThrottle(methods, op, path, suffix.substring(STAGE_THROTTLE.length() + 1), value);
|
||||
}
|
||||
stages.set(index, new ApiStage(stage.apiId(), stage.stage(), methods));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code target} is {@code <resourcePath>/<httpMethod>[/<limit>]}; the key is the raw text, so
|
||||
* {@code //pets/GET/rateLimit} after {@code /throttle} names {@code /pets/GET} and {@code ~1} is
|
||||
* not decoded, as on API Gateway.
|
||||
*/
|
||||
private Map<String, Throttle> patchMethodThrottle(Map<String, Throttle> methods, String op, String path,
|
||||
String target, String value) {
|
||||
Map<String, Throttle> patched = methods == null ? new LinkedHashMap<>() : methods;
|
||||
int slash = target.lastIndexOf('/');
|
||||
if ("remove".equals(op)) {
|
||||
// As for add and replace, a path that names no method is invalid, before any key is looked up.
|
||||
if (methodKey(target)[1].isEmpty()) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
if (patched.remove(target) == null) {
|
||||
throw new AwsException("NotFoundException", "Method throttle does not exist for {resourcePath: "
|
||||
+ (slash < 0 ? target : target.substring(0, slash)) + ", method: "
|
||||
+ (slash < 0 ? "" : target.substring(slash + 1)) + "} for usageplan " + usagePlanId, 404);
|
||||
}
|
||||
return patched;
|
||||
}
|
||||
requireAddOrReplace(op, path);
|
||||
String field = slash < 0 ? "" : target.substring(slash + 1);
|
||||
if (!"burstLimit".equals(field) && !"rateLimit".equals(field)) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
String key = target.substring(0, slash);
|
||||
if (methodKey(key)[1].isEmpty()) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
Throttle current = patched.getOrDefault(key, new Throttle(0, 0.0));
|
||||
patched.put(key, "burstLimit".equals(field)
|
||||
? new Throttle(burstLimit(value), current.rateLimit())
|
||||
: new Throttle(current.burstLimit(), rateLimit(value)));
|
||||
return patched;
|
||||
}
|
||||
|
||||
private void applyThrottle(String op, String path, String value) {
|
||||
switch (path) {
|
||||
case "/throttle" -> {
|
||||
if (!"remove".equals(op)) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
// Checked against the stages as they stand at this op, not at the end of the patch.
|
||||
if (hasMethodThrottles(stages)) {
|
||||
throw new AwsException(BAD_REQUEST, PLAN_THROTTLE_UNDER_FINE_GRAIN, 400);
|
||||
}
|
||||
throttle = null;
|
||||
}
|
||||
case "/throttle/burstLimit", "/throttle/rateLimit" -> {
|
||||
requireAddOrReplace(op, path);
|
||||
Throttle current = throttle == null ? new Throttle(0, 0.0) : throttle;
|
||||
throttle = path.endsWith("burstLimit")
|
||||
? new Throttle(numericBurstLimit(value), current.rateLimit())
|
||||
: new Throttle(current.burstLimit(), numericRateLimit(value));
|
||||
}
|
||||
default -> throw invalidPatchPath(op, path);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyQuota(String op, String path, String value) {
|
||||
if ("/quota".equals(path)) {
|
||||
if (!"remove".equals(op)) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
hasQuota = false;
|
||||
quotaLimit = null;
|
||||
quotaOffset = null;
|
||||
quotaPeriod = null;
|
||||
return;
|
||||
}
|
||||
requireAddOrReplace(op, path);
|
||||
switch (path) {
|
||||
case "/quota/limit" -> quotaLimit = value;
|
||||
case "/quota/offset" -> {
|
||||
// Without a value API Gateway refuses the op rather than resetting the offset to 0.
|
||||
if (value == null) {
|
||||
throw new AwsException(BAD_REQUEST, QUOTA_OFFSET_NOT_NUMERIC, 400);
|
||||
}
|
||||
quotaOffset = value;
|
||||
}
|
||||
case "/quota/period" -> quotaPeriod = value;
|
||||
default -> throw invalidPatchPath(op, path);
|
||||
}
|
||||
hasQuota = true;
|
||||
}
|
||||
|
||||
/** The index of the plan's stage named by {@code ref}, or API Gateway's 404 when the plan has none. */
|
||||
private int stageIndex(String[] ref) {
|
||||
int index = indexOf(stages, ref[0], ref[1]);
|
||||
if (index < 0) {
|
||||
throw new AwsException("NotFoundException", "Invalid API Stage {api: " + ref[0] + ", stage: "
|
||||
+ ref[1] + "} specified for usageplan " + usagePlanId, 404);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code /apiStages/<apiId>:<stage>/throttle} value: a JSON map of method key to limits, read as
|
||||
* API Gateway reads it, which is not how a create body's numbers are read. A burst limit takes a
|
||||
* JSON number in int range, truncated, or whole-number text; a rate limit takes a finite number or
|
||||
* numeric text. Anything else, an unknown member included, refuses the whole value. Every value is
|
||||
* read before any key is checked, then each key's method before its limits and their sign.
|
||||
*/
|
||||
private static Map<String, Throttle> methodThrottles(String json) {
|
||||
JsonNode root;
|
||||
try {
|
||||
root = json == null ? null : JSON.readTree(json);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
if (root == null || !root.isObject()) {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
Map<String, Throttle> read = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, JsonNode> entry : root.properties()) {
|
||||
JsonNode settings = entry.getValue();
|
||||
if (!settings.isNull() && !settings.isObject()) {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
read.put(entry.getKey(), settings.isNull() ? null : stageThrottle(settings));
|
||||
}
|
||||
Map<String, Throttle> methods = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Throttle> entry : read.entrySet()) {
|
||||
String[] resourcePathAndMethod = methodKey(entry.getKey());
|
||||
if (resourcePathAndMethod[1].isEmpty()) {
|
||||
throw new AwsException(BAD_REQUEST, "Invalid method " + methodRef(resourcePathAndMethod) + " specified",
|
||||
400);
|
||||
}
|
||||
Throttle throttle = entry.getValue();
|
||||
if (throttle == null) {
|
||||
throw new AwsException(BAD_REQUEST,
|
||||
"Invalid throttle setting specified for method " + methodRef(resourcePathAndMethod), 400);
|
||||
}
|
||||
if (throttle.burstLimit() < 0 || throttle.rateLimit() < 0) {
|
||||
throw new AwsException(BAD_REQUEST, THROTTLE_INVALID, 400);
|
||||
}
|
||||
methods.put(entry.getKey(), throttle);
|
||||
}
|
||||
return methods;
|
||||
}
|
||||
|
||||
/** One method's limits in a stage throttle value, sign unchecked; a limit left out or null reads 0. */
|
||||
private static Throttle stageThrottle(JsonNode settings) {
|
||||
for (Map.Entry<String, JsonNode> member : settings.properties()) {
|
||||
if (!"burstLimit".equals(member.getKey()) && !"rateLimit".equals(member.getKey())) {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
}
|
||||
JsonNode burst = settings.path("burstLimit");
|
||||
JsonNode rate = settings.path("rateLimit");
|
||||
return new Throttle(burst.isMissingNode() || burst.isNull() ? 0 : stageBurstLimit(burst),
|
||||
rate.isMissingNode() || rate.isNull() ? 0.0 : stageRateLimit(rate));
|
||||
}
|
||||
|
||||
private static int stageBurstLimit(JsonNode value) {
|
||||
if (value.isNumber() && value.canConvertToInt()) {
|
||||
return value.intValue();
|
||||
}
|
||||
if (value.isTextual()) {
|
||||
try {
|
||||
return Integer.parseInt(value.textValue());
|
||||
} catch (NumberFormatException e) {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
}
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
|
||||
private static double stageRateLimit(JsonNode value) {
|
||||
double rate;
|
||||
if (value.isNumber()) {
|
||||
rate = value.doubleValue();
|
||||
} else if (value.isTextual()) {
|
||||
try {
|
||||
rate = Double.parseDouble(value.textValue());
|
||||
} catch (NumberFormatException e) {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
} else {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
// API Gateway answers a rate beyond the double range, such as 1e400, with a 500 InternalFailure, a
|
||||
// fault rather than a contract; Floci refuses it as an invalid stage throttle instead.
|
||||
if (!Double.isFinite(rate)) {
|
||||
throw stageThrottleInvalid();
|
||||
}
|
||||
return rate;
|
||||
}
|
||||
|
||||
private static AwsException stageThrottleInvalid() {
|
||||
return new AwsException(BAD_REQUEST, STAGE_THROTTLE_INVALID, 400);
|
||||
}
|
||||
|
||||
/** {@code apiId:stage} split in two, or API Gateway's 400 for anything else. */
|
||||
private static String[] stageRef(String value) {
|
||||
String[] parts = value == null ? new String[0] : value.split(":", 2);
|
||||
if (parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty()) {
|
||||
throw new AwsException(BAD_REQUEST, "Invalid API Stage specified", 400);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
private static void requireAddOrReplace(String op, String path) {
|
||||
if (!"add".equals(op) && !"replace".equals(op)) {
|
||||
throw invalidPatchPath(op, path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateUsagePlan's input-model violations, one per op outside the model's enum, each at its
|
||||
* 1-based index, as API Gateway lists them before its own op check. A missing or null op is not
|
||||
* one; {@link #requirePatchOp} refuses it.
|
||||
*/
|
||||
public static List<String> opViolations(JsonNode patchOperations) {
|
||||
List<String> violations = new ArrayList<>();
|
||||
for (int i = 0; i < patchOperations.size(); i++) {
|
||||
JsonNode op = patchOperations.get(i).path("op");
|
||||
if (op.isTextual() && !OP_ENUM.contains(op.textValue())) {
|
||||
violations.add(SmithyValidationErrors.notInEnum(op.textValue(),
|
||||
"updateUsagePlanInput.patchOperations." + (i + 1) + ".member.op", OP_ENUM));
|
||||
}
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
/** API Gateway refuses any op but add, remove and replace, a missing one included, before it reads the path. */
|
||||
public static void requirePatchOp(String op) {
|
||||
if (op == null || !PATCH_PATHS.containsKey(op)) {
|
||||
throw invalidPatchOp();
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalidPatchOp() {
|
||||
return new AwsException(BAD_REQUEST, "Invalid patch operation specified. Must be 'add'|'remove'|'replace'", 400);
|
||||
}
|
||||
|
||||
/** API Gateway's 400 for a path {@code op} does not allow, listing the paths it does. */
|
||||
public static AwsException invalidPatchPath(String op, String path) {
|
||||
String allowed = op == null ? null : PATCH_PATHS.get(op);
|
||||
if (allowed == null) {
|
||||
return invalidPatchOp();
|
||||
}
|
||||
// Two spaces after "path", as API Gateway writes it.
|
||||
return new AwsException(BAD_REQUEST,
|
||||
"Invalid patch path '" + path + "' specified for op '" + op + "'. Must be one of: " + allowed, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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
|
||||
|
||||
@@ -42,12 +42,16 @@ public class UsagePlan {
|
||||
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() {
|
||||
/**
|
||||
* The plan's stages, throttle and quota as one value, for comparing and replacing them together.
|
||||
* Synchronised with {@link #applyLimits} so a reader never sees parts of two revisions.
|
||||
*/
|
||||
public synchronized Limits limits() {
|
||||
return new Limits(List.copyOf(apiStages), throttle, quota);
|
||||
}
|
||||
|
||||
public void applyLimits(Limits limits) {
|
||||
/** Synchronised with {@link #limits} because it writes three fields that are only valid together. */
|
||||
public synchronized void applyLimits(Limits limits) {
|
||||
this.apiStages = new ArrayList<>(limits.apiStages());
|
||||
this.throttle = limits.throttle();
|
||||
this.quota = limits.quota();
|
||||
|
||||
+11
-2
@@ -117,12 +117,12 @@ public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner
|
||||
List<UsagePlan.ApiStage> desired = apiStages(props, ctx);
|
||||
List<UsagePlan.ApiStage> current = List.copyOf(existing.getApiStages());
|
||||
for (UsagePlan.ApiStage stage : current) {
|
||||
if (!desired.contains(stage)) {
|
||||
if (!listsStage(desired, stage)) {
|
||||
patches.add(patch("remove", "/apiStages", stage.apiId() + KEY_ID_SEPARATOR + stage.stage()));
|
||||
}
|
||||
}
|
||||
for (UsagePlan.ApiStage stage : desired) {
|
||||
if (!current.contains(stage)) {
|
||||
if (!listsStage(current, stage)) {
|
||||
patches.add(patch("add", "/apiStages", stage.apiId() + KEY_ID_SEPARATOR + stage.stage()));
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,15 @@ public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner
|
||||
recordPlan(r, plan);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code stages} lists {@code stage}'s API and stage. A stage's method throttle is not part of
|
||||
* its identity, so a stage throttled through UpdateUsagePlan still matches the template's.
|
||||
*/
|
||||
private static boolean listsStage(List<UsagePlan.ApiStage> stages, UsagePlan.ApiStage stage) {
|
||||
return stages.stream().anyMatch(listed -> Objects.equals(listed.apiId(), stage.apiId())
|
||||
&& Objects.equals(listed.stage(), stage.stage()));
|
||||
}
|
||||
|
||||
/** The template's ApiStages as (apiId, stage) pairs, in template order. */
|
||||
private static List<UsagePlan.ApiStage> apiStages(JsonNode props, ProvisionContext ctx) {
|
||||
List<UsagePlan.ApiStage> stages = new ArrayList<>();
|
||||
|
||||
Reference in new issue
Block a user