mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+352
-14
@@ -119,46 +119,71 @@ class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageWithAMethodThrottleIsMatchedByApiAndStage() {
|
||||
void patchesReachTheWireWithApiGatewaysErrors() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"stage-remove\",\"throttle\":{\"burstLimit\":20,\"rateLimit\":10},"
|
||||
.body("{\"name\":\"patched\",\"throttle\":{\"burstLimit\":20,\"rateLimit\":10},"
|
||||
+ "\"quota\":{\"limit\":1000,\"period\":\"MONTH\"},"
|
||||
+ "\"apiStages\":[{\"apiId\":\"a1\",\"stage\":\"v1\","
|
||||
+ "\"throttle\":{\"/pets/GET\":{\"burstLimit\":10,\"rateLimit\":5}}},"
|
||||
+ "{\"apiId\":\"a1\",\"stage\":\"v2\"}]}")
|
||||
+ "\"throttle\":{\"/pets/GET\":{\"burstLimit\":10,\"rateLimit\":5}}}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("throttle.burstLimit", equalTo(20))
|
||||
.body("quota.limit", equalTo(1000))
|
||||
.body("quota.offset", equalTo(0))
|
||||
.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\"}]}")
|
||||
.body("{\"patchOperations\":["
|
||||
+ "{\"op\":\"add\",\"path\":\"/apiStages\",\"value\":\"a1:v2\"},"
|
||||
+ "{\"op\":\"replace\",\"path\":\"/apiStages/a1:v1/throttle//pets/GET/burstLimit\",\"value\":\"8\"},"
|
||||
+ "{\"op\":\"remove\",\"path\":\"/quota\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(2))
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(10));
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(8))
|
||||
.body("apiStages[1].throttle", nullValue())
|
||||
.body("quota", nullValue());
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"add\",\"path\":\"/apiStages\",\"value\":\"a1:v2\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("ConflictException"))
|
||||
.body("message", equalTo("API Stage is already defined for Usage Plan: a1:v2"));
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/apiStages\",\"value\":\"a1:v9\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("NotFoundException"))
|
||||
.body("message", equalTo("Invalid API Stage {api: a1, stage: v9} specified for usageplan "
|
||||
+ usagePlanId));
|
||||
|
||||
// A refused patch leaves the plan as it was.
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(2));
|
||||
|
||||
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"));
|
||||
.statusCode(200);
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(1))
|
||||
.body("apiStages[0].stage", equalTo("v2"))
|
||||
.body("throttle.burstLimit", equalTo(20));
|
||||
}
|
||||
.body("apiStages[0].stage", equalTo("v2"));
|
||||
|
||||
@Test
|
||||
void anUnknownQuotaPeriodOnCreateIsAValidationException() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"bad-period\",\"quota\":{\"limit\":1,\"period\":\"day\"}}")
|
||||
.post("/usageplans")
|
||||
@@ -167,6 +192,49 @@ class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameAndDescriptionOnlyTakeReplace() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"replace-only\",\"description\":\"kept\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
// "apidId" is AWS's own spelling in these lists.
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"add\",\"path\":\"/name\",\"value\":\"renamed\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid patch path '/name' specified for op 'add'. Must be one of: "
|
||||
+ "[/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]"));
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/description\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid patch path '/description' specified for op 'remove'. "
|
||||
+ "Must be one of: [/apiStages, /quota, /throttle, /productCode, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle]"));
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("name", equalTo("replace-only"))
|
||||
.body("description", equalTo("kept"));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: GetUsagePlan and UpdateUsagePlan carry "tags": {}, CreateUsagePlan and
|
||||
// the GetUsagePlans items leave an empty map out.
|
||||
@Test
|
||||
@@ -208,6 +276,107 @@ class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
.body("message", equalTo("Invalid Usage Plan ID specified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOpOtherThanAddRemoveOrReplaceIsRefusedBeforeItsPath() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"ops-only\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
for (String operation : new String[] {
|
||||
"{\"op\":\"copy\",\"path\":\"/name\",\"value\":\"x\"}",
|
||||
"{\"op\":\"move\",\"path\":\"/name\",\"value\":\"x\"}",
|
||||
"{\"op\":\"test\",\"path\":\"/name\",\"value\":\"x\"}",
|
||||
"{\"path\":\"/name\",\"value\":\"x\"}",
|
||||
"{\"op\":\"move\"}"}) {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[" + operation + "]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid patch operation specified. Must be 'add'|'remove'|'replace'"));
|
||||
}
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("name", equalTo("ops-only"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProductCodeOpIsRefusedAsNotSupported() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"product-code\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
for (String operation : new String[] {
|
||||
"{\"op\":\"add\",\"path\":\"/productCode\",\"value\":\"code\"}",
|
||||
"{\"op\":\"replace\",\"path\":\"/productCode\",\"value\":\"code\"}",
|
||||
"{\"op\":\"remove\",\"path\":\"/productCode\"}"}) {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[" + operation + "]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Usage plan product codes are not supported"));
|
||||
}
|
||||
|
||||
// An op other than add, remove or replace is still refused before its path is read.
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"copy\",\"path\":\"/productCode\",\"value\":\"code\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid patch operation specified. Must be 'add'|'remove'|'replace'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValuelessOffsetOrNameIsRefusedAndLeavesThePlanAsItWas() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"valueless\",\"quota\":{\"limit\":1000,\"offset\":3,\"period\":\"MONTH\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/quota/offset\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Usage Plan quota offset must be numeric and less than the number of time "
|
||||
+ "units in the period"));
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Usage Plan name must be specified"));
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("name", equalTo("valueless"))
|
||||
.body("quota.offset", equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageWithoutAnApiIdIsRefusedAndNoPlanIsStored() {
|
||||
given().contentType(ContentType.JSON)
|
||||
@@ -375,6 +544,175 @@ class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
+ "constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]");
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a fractional burst limit is truncated, numeric text is taken, and a burst
|
||||
// limit outside the int range refuses the whole value.
|
||||
@Test
|
||||
void aStageThrottleValueIsReadAsApiGatewayReadsIt() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"stage-throttle-value\",\"throttle\":{\"burstLimit\":20,\"rateLimit\":10},"
|
||||
+ "\"apiStages\":[{\"apiId\":\"a1\",\"stage\":\"v1\","
|
||||
+ "\"throttle\":{\"/pets/GET\":{\"burstLimit\":10,\"rateLimit\":5}}}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/apiStages/a1:v1/throttle\","
|
||||
+ "\"value\":\"{\\\"/pets/GET\\\":{\\\"burstLimit\\\":1.5,\\\"rateLimit\\\":\\\"5.5\\\"}}\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(1))
|
||||
.body("apiStages[0].throttle['/pets/GET'].rateLimit", equalTo(5.5f));
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/apiStages/a1:v1/throttle\","
|
||||
+ "\"value\":\"{\\\"/pets/GET\\\":{\\\"burstLimit\\\":3000000000}}\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid API Stage throttle specified for usageplan"));
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(1));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: an op outside the model's enum is a ValidationException and leaves the plan as it was.
|
||||
@Test
|
||||
void anOpOutsideTheEnumIsAValidationExceptionAndLeavesThePlanAsItWas() {
|
||||
String usagePlanId = createNamedPlan("op-enum");
|
||||
for (String op : new String[] {"frobnicate", "ADD", ""}) {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"" + op + "\",\"path\":\"/name\",\"value\":\"changed\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value '" + op + "' at "
|
||||
+ "'updateUsagePlanInput.patchOperations.1.member.op' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [add, remove, move, test, replace, copy]"));
|
||||
assertPlanNamed(usagePlanId, "op-enum");
|
||||
}
|
||||
}
|
||||
|
||||
// Measured on API Gateway: an op that is a number is refused by the deserializer.
|
||||
@Test
|
||||
void aNumericOpIsASerializationExceptionAndLeavesThePlanAsItWas() {
|
||||
String usagePlanId = createNamedPlan("op-number");
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":5,\"path\":\"/name\",\"value\":\"changed\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("class com.amazon.coral.value.json.numbers.TruncatingBigNumber "
|
||||
+ "can not be converted to an String"));
|
||||
assertPlanNamed(usagePlanId, "op-number");
|
||||
}
|
||||
|
||||
// copy is in the model's enum, so it passes the input model and the usage plan refuses it.
|
||||
@Test
|
||||
void anOpInTheEnumThatAUsagePlanDoesNotTakeKeepsItsBusinessMessage() {
|
||||
String usagePlanId = createNamedPlan("op-copy");
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"copy\",\"path\":\"/name\",\"value\":\"changed\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid patch operation specified. Must be 'add'|'remove'|'replace'"));
|
||||
assertPlanNamed(usagePlanId, "op-copy");
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a refused op rolls back the whole request, the ops before it included.
|
||||
@Test
|
||||
void aRefusedPatchRollsBackEveryOpInTheRequest() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"compat10\",\"throttle\":{\"burstLimit\":20,\"rateLimit\":10},"
|
||||
+ "\"quota\":{\"limit\":1000,\"offset\":0,\"period\":\"MONTH\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":["
|
||||
+ "{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"compat10-renamed\"},"
|
||||
+ "{\"op\":\"replace\",\"path\":\"/throttle/burstLimit\",\"value\":\"30\"},"
|
||||
+ "{\"op\":\"replace\",\"path\":\"/quota/period\",\"value\":\"DAY\"},"
|
||||
+ "{\"op\":\"replace\",\"path\":\"/quota/offset\",\"value\":\"3\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Usage Plan quota offset must be zero in the DAY period"));
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("name", equalTo("compat10"))
|
||||
.body("throttle.burstLimit", equalTo(20))
|
||||
.body("quota.limit", equalTo(1000))
|
||||
.body("quota.offset", equalTo(0))
|
||||
.body("quota.period", equalTo("MONTH"));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: removing a method throttle path that names no method is an invalid path.
|
||||
@Test
|
||||
void removingAMethodThrottlePathThatNamesNoMethodIsAnInvalidPathAndLeavesTheStage() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"remove-no-method\",\"throttle\":{\"burstLimit\":20,\"rateLimit\":10},"
|
||||
+ "\"apiStages\":[{\"apiId\":\"a1\",\"stage\":\"v1\","
|
||||
+ "\"throttle\":{\"/pets/GET\":{\"burstLimit\":10,\"rateLimit\":5}}}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/apiStages/a1:v1/throttle/nope\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid patch path '/apiStages/a1:v1/throttle/nope' specified for op "
|
||||
+ "'remove'. Must be one of: [/apiStages, /quota, /throttle, /productCode, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle]"));
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(10));
|
||||
}
|
||||
|
||||
private static String createNamedPlan(String name) {
|
||||
return given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"" + name + "\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("id");
|
||||
}
|
||||
|
||||
private static void assertPlanNamed(String usagePlanId, String name) {
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("name", equalTo(name));
|
||||
}
|
||||
|
||||
private static int planCount() {
|
||||
return given().get("/usageplans").then().statusCode(200).extract().path("item.size()");
|
||||
}
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.TlsCertificateManager;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ApiGatewayUsagePlanServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final int REPLACEMENTS = 200_000;
|
||||
|
||||
private static ApiGatewayService service() {
|
||||
Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
|
||||
StorageFactory storageFactory = mock(StorageFactory.class);
|
||||
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(invocation ->
|
||||
stores.computeIfAbsent(invocation.getArgument(1, String.class),
|
||||
ignored -> AccountAwareStorageBackend.inMemory(ACCOUNT)));
|
||||
return new ApiGatewayService(storageFactory, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
|
||||
mock(TlsCertificateManager.class), new RegionResolver(REGION, ACCOUNT));
|
||||
}
|
||||
|
||||
// Every patch writes back the stages it read, so without serialising them concurrent adds drop each other.
|
||||
@Test
|
||||
void concurrentStagePatchesKeepEveryStage() throws Exception {
|
||||
ApiGatewayService service = service();
|
||||
String planId = service.createUsagePlan(REGION, Map.of("name", "concurrent")).getId();
|
||||
Set<String> expected = new HashSet<>();
|
||||
for (int i = 0; i < 128; i++) {
|
||||
expected.add("api:s" + i);
|
||||
}
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(8)) {
|
||||
List<Future<?>> writers = new ArrayList<>();
|
||||
for (int worker = 0; worker < 8; worker++) {
|
||||
int offset = worker * 16;
|
||||
writers.add(executor.submit(() -> {
|
||||
assertTrue(start.await(5, TimeUnit.SECONDS));
|
||||
for (int i = offset; i < offset + 16; i++) {
|
||||
service.updateUsagePlan(REGION, planId,
|
||||
List.of(Map.of("op", "add", "path", "/apiStages", "value", "api:s" + i)));
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
for (Future<?> writer : writers) {
|
||||
writer.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> stages = new HashSet<>();
|
||||
for (UsagePlan.ApiStage stage : service.getUsagePlan(REGION, planId).getApiStages()) {
|
||||
stages.add(stage.apiId() + ":" + stage.stage());
|
||||
}
|
||||
assertEquals(expected, stages);
|
||||
}
|
||||
|
||||
// applyLimits writes stages, throttle and quota one after another, so an unserialised read can mix two revisions.
|
||||
@Test
|
||||
void limitsReadDuringAReplaceAreOneRevision() throws Exception {
|
||||
UsagePlan.Limits a = new UsagePlan.Limits(
|
||||
List.of(new UsagePlan.ApiStage("api", "v1", Map.of("/pets/GET", new UsagePlan.Throttle(10, 5.0)))),
|
||||
new UsagePlan.Throttle(20, 10.0), new UsagePlan.Quota(1000, 0, "MONTH"));
|
||||
UsagePlan.Limits b = new UsagePlan.Limits(List.of(new UsagePlan.ApiStage("api", "v2")), null, null);
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.applyLimits(a);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
CountDownLatch written = new CountDownLatch(1);
|
||||
AtomicLong mixed = new AtomicLong();
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
Future<?> writer = executor.submit(() -> {
|
||||
assertTrue(start.await(5, TimeUnit.SECONDS));
|
||||
try {
|
||||
for (int i = 0; i < REPLACEMENTS; i++) {
|
||||
plan.applyLimits(i % 2 == 0 ? b : a);
|
||||
}
|
||||
} finally {
|
||||
written.countDown();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
Future<List<UsagePlan.Limits>> reader = executor.submit(() -> {
|
||||
List<UsagePlan.Limits> samples = new ArrayList<>();
|
||||
assertTrue(start.await(5, TimeUnit.SECONDS));
|
||||
while (written.getCount() > 0) {
|
||||
UsagePlan.Limits seen = plan.limits();
|
||||
if (!seen.equals(a) && !seen.equals(b)) {
|
||||
mixed.incrementAndGet();
|
||||
if (samples.size() < 3) {
|
||||
samples.add(seen);
|
||||
}
|
||||
}
|
||||
}
|
||||
return samples;
|
||||
});
|
||||
start.countDown();
|
||||
writer.get(60, TimeUnit.SECONDS);
|
||||
List<UsagePlan.Limits> samples = reader.get(60, TimeUnit.SECONDS);
|
||||
assertEquals(0L, mixed.get(), "limits mixing two revisions, for example " + samples);
|
||||
}
|
||||
}
|
||||
}
|
||||
+376
@@ -1,5 +1,6 @@
|
||||
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 io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
|
||||
@@ -12,6 +13,7 @@ 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 org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
@@ -25,9 +27,32 @@ 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;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class UsagePlanLimitsTest {
|
||||
|
||||
// "apidId" is AWS's own spelling in these lists.
|
||||
private static final String ADD_PATHS = "[/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]";
|
||||
private static final String REPLACE_PATHS = "[/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]";
|
||||
private static final String REMOVE_PATHS = "[/apiStages, /quota, /throttle, /productCode, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle/<resourcePath>/<httpMethod>, "
|
||||
+ "/apiStages/<apidId:stageName>/throttle]";
|
||||
|
||||
private static final String INVALID_OP = "Invalid patch operation specified. Must be 'add'|'remove'|'replace'";
|
||||
|
||||
/** API Gateway's message for a path the op does not allow; note the two spaces after "path". */
|
||||
private static String invalidPath(String op, String path, String allowed) {
|
||||
return "Invalid patch path '" + path + "' specified for op '" + op + "'. Must be one of: " + allowed;
|
||||
}
|
||||
|
||||
private static Map<String, Object> request(Object... keyValues) {
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
for (int i = 0; i < keyValues.length; i += 2) {
|
||||
@@ -235,6 +260,8 @@ class UsagePlanLimitsTest {
|
||||
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());
|
||||
assertEquals(new Throttle(0, 1.0), patch(fixture(), "replace", "/apiStages/a:v1/throttle///GET/rateLimit", "1")
|
||||
.apiStages().get(0).throttle().get("//GET"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,4 +277,353 @@ class UsagePlanLimitsTest {
|
||||
void createRefusesWhatApiGatewayRefuses(Map<String, Object> request, String code, int status, String message) {
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(request), code, status, message);
|
||||
}
|
||||
|
||||
/** id plan1; stage a:v1 with /pets/GET at 10/5.0; plan throttle 20/10.0; quota 1000/3/MONTH. */
|
||||
private static UsagePlan fixture() {
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId("plan1");
|
||||
plan.applyLimits(new Limits(List.of(new ApiStage("a", "v1", Map.of("/pets/GET", new Throttle(10, 5.0)))),
|
||||
new Throttle(20, 10.0), new Quota(1000, 3, "MONTH")));
|
||||
return plan;
|
||||
}
|
||||
|
||||
/** Applies op/path/value triples (value may be null) the way updateUsagePlan does. */
|
||||
private static Limits patch(UsagePlan plan, String... opPathValue) {
|
||||
UsagePlanLimits.Patch patch = new UsagePlanLimits.Patch(plan);
|
||||
for (int i = 0; i < opPathValue.length; i += 3) {
|
||||
assertTrue(patch.apply(opPathValue[i], opPathValue[i + 1], opPathValue[i + 2]), opPathValue[i + 1]);
|
||||
}
|
||||
return patch.result();
|
||||
}
|
||||
|
||||
@Test
|
||||
void addAndRemoveStagesInOneRequest() {
|
||||
Limits limits = patch(fixture(), "add", "/apiStages", "a:v2", "add", "/apiStages", "a:v3",
|
||||
"remove", "/apiStages", "a:v3");
|
||||
assertEquals(List.of(new ApiStage("a", "v1", Map.of("/pets/GET", new Throttle(10, 5.0))),
|
||||
new ApiStage("a", "v2")), limits.apiStages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttleFieldsCreateAPlanThrottleWhenThereIsNone() {
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId("p");
|
||||
assertEquals(new Throttle(30, 0.0), patch(plan, "replace", "/throttle/burstLimit", "30").throttle());
|
||||
assertEquals(new Throttle(30, 15.0), patch(plan, "replace", "/throttle/burstLimit", "30",
|
||||
"add", "/throttle/rateLimit", "15").throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQuotaIsBuiltFromSeparateOpsAndRemovedWithoutAValue() {
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId("p");
|
||||
assertEquals(new Quota(10, 0, "DAY"), patch(plan, "replace", "/quota/limit", "10",
|
||||
"replace", "/quota/period", "DAY").quota());
|
||||
assertNull(patch(fixture(), "replace", "/quota/limit", "5", "remove", "/quota", null).quota());
|
||||
assertNull(patch(plan, "remove", "/quota", null).quota());
|
||||
assertEquals(new Quota(2000, 1, "WEEK"), patch(fixture(), "replace", "/quota/limit", "2000",
|
||||
"replace", "/quota/period", "WEEK", "replace", "/quota/offset", "1").quota());
|
||||
}
|
||||
|
||||
@Test
|
||||
void methodThrottleOpsUseTheRawResourcePathAsKey() {
|
||||
Limits limits = patch(fixture(),
|
||||
"replace", "/apiStages/a:v1/throttle//pets/GET/burstLimit", "8",
|
||||
"add", "/apiStages/a:v1/throttle//pets/POST/rateLimit", "3");
|
||||
assertEquals(Map.of("/pets/GET", new Throttle(8, 5.0), "/pets/POST", new Throttle(0, 3.0)),
|
||||
limits.apiStages().get(0).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingTheLastMethodLeavesAnEmptyStageThrottle() {
|
||||
Limits limits = patch(fixture(), "remove", "/apiStages/a:v1/throttle//pets/GET", null);
|
||||
assertEquals(Map.of(), limits.apiStages().get(0).throttle());
|
||||
// An empty stage throttle is not fine-grain throttling, so the plan throttle can go.
|
||||
assertNull(patch(fixture(), "remove", "/apiStages/a:v1/throttle//pets/GET", null,
|
||||
"remove", "/throttle", null).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWholeStageThrottleIsReplacedAndRemoved() {
|
||||
assertEquals(Map.of("/a/GET", new Throttle(1, 2.0)), patch(fixture(), "replace", "/apiStages/a:v1/throttle",
|
||||
"{\"/a/GET\":{\"burstLimit\":1,\"rateLimit\":2}}").apiStages().get(0).throttle());
|
||||
assertNull(patch(fixture(), "remove", "/apiStages/a:v1/throttle", null,
|
||||
"remove", "/apiStages/a:v1/throttle", null).apiStages().get(0).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWholeStageThrottleIsReplacedOnlyWhereOneExists() {
|
||||
assertRefused(() -> patch(fixture(), "add", "/apiStages", "a:v2",
|
||||
"replace", "/apiStages/a:v2/throttle", "{\"/pets/POST\":{\"burstLimit\":3,\"rateLimit\":2}}"),
|
||||
"NotFoundException", 404, "API Stage throttle not found for usageplan plan1");
|
||||
assertEquals(Map.of("/pets/POST", new Throttle(3, 2.0)), patch(fixture(), "add", "/apiStages", "a:v2",
|
||||
"add", "/apiStages/a:v2/throttle", "{\"/pets/POST\":{\"burstLimit\":3,\"rateLimit\":2}}")
|
||||
.apiStages().get(1).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlanThrottleMayPassThroughANegativeValueWithinOnePatch() {
|
||||
assertEquals(new Throttle(20, 5.0), patch(fixture(), "replace", "/throttle/rateLimit", "-1",
|
||||
"replace", "/throttle/rateLimit", "5").throttle());
|
||||
assertEquals(new Throttle(5, 10.0), patch(fixture(), "replace", "/throttle/burstLimit", "-1",
|
||||
"replace", "/throttle/burstLimit", "5").throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlanThrottleIsNumericAtEachOpAndNonNegativeAtTheEnd() {
|
||||
String throttle = "Usage Plan throttle rate limit and burst limit must be numeric and greater than zero";
|
||||
assertRefused(() -> patch(fixture(), "replace", "/throttle/rateLimit", "5",
|
||||
"replace", "/throttle/rateLimit", "-1"), "BadRequestException", 400, throttle);
|
||||
assertRefused(() -> patch(fixture(), "replace", "/throttle/rateLimit", "-1"), "BadRequestException", 400,
|
||||
throttle);
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId("p");
|
||||
plan.applyLimits(new Limits(List.of(), new Throttle(20, 10.0), null));
|
||||
assertRefused(() -> patch(plan, "replace", "/throttle/burstLimit", "abc", "remove", "/throttle", null),
|
||||
"BadRequestException", 400, throttle);
|
||||
// A method throttle limit is checked in full at every op.
|
||||
assertRefused(() -> patch(fixture(), "replace", "/apiStages/a:v1/throttle//pets/GET/rateLimit", "-1",
|
||||
"replace", "/apiStages/a:v1/throttle//pets/GET/rateLimit", "5"), "BadRequestException", 400, throttle);
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingThePlanThrottleIsCheckedAgainstTheStagesAtThatOp() {
|
||||
assertRefused(() -> patch(fixture(), "remove", "/throttle", null, "replace", "/throttle/burstLimit", "5"),
|
||||
"BadRequestException", 400,
|
||||
"Can not remove usage plan throttling if fine grain throttling is defined for one or more api-stages.");
|
||||
Limits limits = patch(fixture(), "remove", "/apiStages", "a:v1", "remove", "/throttle", null);
|
||||
assertNull(limits.throttle());
|
||||
assertEquals(List.of(), limits.apiStages());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWholeStageThrottleAddRefusesAKeyWithoutAMethod() {
|
||||
assertRefused(() -> patch(fixture(), "add", "/apiStages", "a:v2", "add", "/apiStages/a:v2/throttle",
|
||||
"{\"\":{\"burstLimit\":1,\"rateLimit\":1}}"),
|
||||
"BadRequestException", 400, "Invalid method {resourcePath: ,method: } specified");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyWholeStageThrottleIsKeptAsAnEmptyMap() {
|
||||
assertEquals(Map.of(), patch(fixture(), "replace", "/apiStages/a:v1/throttle", "{}")
|
||||
.apiStages().get(0).throttle());
|
||||
assertEquals(Map.of(), patch(fixture(), "add", "/apiStages", "a:v2", "add", "/apiStages/a:v2/throttle", "{}")
|
||||
.apiStages().get(1).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValuelessStageThrottleAddIsRefused() {
|
||||
assertRefused(() -> patch(fixture(), "add", "/apiStages", "a:v2", "add", "/apiStages/a:v2/throttle", null),
|
||||
"BadRequestException", 400, "Invalid API Stage throttle specified for usageplan");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameAndDescriptionAreNotLimitPaths() {
|
||||
assertFalse(new UsagePlanLimits.Patch(fixture()).apply("replace", "/name", "x"));
|
||||
assertFalse(new UsagePlanLimits.Patch(fixture()).apply("replace", "/description", "x"));
|
||||
}
|
||||
|
||||
static Stream<Arguments> refusedPatches() {
|
||||
String throttle = "Usage Plan throttle rate limit and burst limit must be numeric and greater than zero";
|
||||
return Stream.of(
|
||||
Arguments.of("add", "/apiStages", "a:v1", "ConflictException", 409,
|
||||
"API Stage is already defined for Usage Plan: a:v1"),
|
||||
Arguments.of("remove", "/apiStages", "a:v9", "NotFoundException", 404,
|
||||
"Invalid API Stage {api: a, stage: v9} specified for usageplan plan1"),
|
||||
Arguments.of("add", "/apiStages", "bad", "BadRequestException", 400, "Invalid API Stage specified"),
|
||||
Arguments.of("replace", "/apiStages", "a:v2", "BadRequestException", 400,
|
||||
invalidPath("replace", "/apiStages", REPLACE_PATHS)),
|
||||
Arguments.of("remove", "/throttle", null, "BadRequestException", 400,
|
||||
"Can not remove usage plan throttling if fine grain throttling is defined for one or more "
|
||||
+ "api-stages."),
|
||||
Arguments.of("replace", "/throttle/burstLimit", "abc", "BadRequestException", 400, throttle),
|
||||
Arguments.of("replace", "/throttle/burstLimit", "-1", "BadRequestException", 400, throttle),
|
||||
Arguments.of("replace", "/throttle/burstLimit", "1.5", "BadRequestException", 400, throttle),
|
||||
Arguments.of("replace", "/quota/period", "YEAR", "BadRequestException", 400,
|
||||
"Invalid Usage Plan quota period specified. Must be one of [DAY, WEEK, MONTH]"),
|
||||
Arguments.of("replace", "/quota/period", "DAY", "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be zero in the DAY period"),
|
||||
Arguments.of("replace", "/quota/offset", "x", "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be numeric and less than the number of time units in the period"),
|
||||
Arguments.of("replace", "/quota/limit", "-5", "BadRequestException", 400,
|
||||
"Usage Plan quota limit must be a non-negative numeric"),
|
||||
Arguments.of("replace", "/quota/offset", null, "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be numeric and less than the number of time units in the period"),
|
||||
Arguments.of("add", "/apiStages", null, "BadRequestException", 400, "Invalid API Stage specified"),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle", null, "BadRequestException", 400,
|
||||
"Invalid API Stage throttle specified for usageplan"),
|
||||
// API Gateway answers this with a 500 InternalFailure, a fault rather than a contract, so it stays a 400.
|
||||
Arguments.of("replace", "/throttle/rateLimit", null, "BadRequestException", 400, throttle),
|
||||
Arguments.of("replace", "/quota", "x", "BadRequestException", 400,
|
||||
invalidPath("replace", "/quota", REPLACE_PATHS)),
|
||||
Arguments.of("replace", "/throttle", "x", "BadRequestException", 400,
|
||||
invalidPath("replace", "/throttle", REPLACE_PATHS)),
|
||||
Arguments.of("remove", "/throttle/rateLimit", null, "BadRequestException", 400,
|
||||
invalidPath("remove", "/throttle/rateLimit", REMOVE_PATHS)),
|
||||
Arguments.of("add", "/quota", "x", "BadRequestException", 400, invalidPath("add", "/quota", ADD_PATHS)),
|
||||
// Any op but add, remove and replace is refused before the path is looked at.
|
||||
Arguments.of("move", "/quota/limit", "1", "BadRequestException", 400, INVALID_OP),
|
||||
Arguments.of("copy", "/apiStages", "a:v2", "BadRequestException", 400, INVALID_OP),
|
||||
Arguments.of("test", "/apiStages/a:v1/throttle", "{}", "BadRequestException", 400, INVALID_OP),
|
||||
Arguments.of(null, "/throttle", null, "BadRequestException", 400, INVALID_OP),
|
||||
Arguments.of("move", "/nope", "x", "BadRequestException", 400, INVALID_OP),
|
||||
Arguments.of("replace", "/apiStages/a:v2/throttle//pets/GET/rateLimit", "1", "NotFoundException", 404,
|
||||
"Invalid API Stage {api: a, stage: v2} specified for usageplan plan1"),
|
||||
Arguments.of("add", "/apiStages/a:v1/throttle", "{\"/a/GET\":{\"burstLimit\":4}}", "ConflictException",
|
||||
409, "API Stage throttle is already defined for usageplan plan1"),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle", "not-json", "BadRequestException", 400,
|
||||
"Invalid API Stage throttle specified for usageplan"),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle", "{\"/a/GET\":5}", "BadRequestException", 400,
|
||||
"Invalid API Stage throttle specified for usageplan"),
|
||||
Arguments.of("remove", "/apiStages/a:v1/throttle//pets/GET/rateLimit", null, "BadRequestException", 400,
|
||||
invalidPath("remove", "/apiStages/a:v1/throttle//pets/GET/rateLimit", REMOVE_PATHS)),
|
||||
Arguments.of("remove", "/apiStages/a:v1/throttle//pets/GET/burstLimit", null, "BadRequestException",
|
||||
400, invalidPath("remove", "/apiStages/a:v1/throttle//pets/GET/burstLimit", REMOVE_PATHS)),
|
||||
Arguments.of("remove", "/apiStages/a:v1/throttle//pets/POST", null, "NotFoundException", 404,
|
||||
"Method throttle does not exist for {resourcePath: /pets, method: POST} for usageplan plan1"),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle//pets/GET/rateLimit", "abc", "BadRequestException",
|
||||
400, throttle),
|
||||
Arguments.of("replace", "/apiStages/a:v1/limits", "1", "BadRequestException", 400,
|
||||
invalidPath("replace", "/apiStages/a:v1/limits", REPLACE_PATHS)),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle", "{\"/GET\":{\"burstLimit\":1,\"rateLimit\":1}}",
|
||||
"BadRequestException", 400, "Invalid method {resourcePath: /GET,method: } specified"),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle//rateLimit", "1", "BadRequestException", 400,
|
||||
invalidPath("replace", "/apiStages/a:v1/throttle//rateLimit", REPLACE_PATHS)),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle/rateLimit", "1", "BadRequestException", 400,
|
||||
invalidPath("replace", "/apiStages/a:v1/throttle/rateLimit", REPLACE_PATHS)),
|
||||
Arguments.of("add", "/apiStages/a:v1/throttle//GET/burstLimit", "1", "BadRequestException", 400,
|
||||
invalidPath("add", "/apiStages/a:v1/throttle//GET/burstLimit", ADD_PATHS)),
|
||||
Arguments.of("replace", "/apiStages/a:v1/throttle//pets//rateLimit", "1", "BadRequestException", 400,
|
||||
invalidPath("replace", "/apiStages/a:v1/throttle//pets//rateLimit", REPLACE_PATHS)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("refusedPatches")
|
||||
void patchRefusesWhatApiGatewayRefuses(String op, String path, String value, String code, int status,
|
||||
String message) {
|
||||
assertRefused(() -> patch(fixture(), op, path, value), code, status, message);
|
||||
}
|
||||
|
||||
static Stream<Arguments> storedStageThrottleValues() {
|
||||
return Stream.of(
|
||||
Arguments.of("{\"burstLimit\":1.5,\"rateLimit\":2}", new Throttle(1, 2.0)),
|
||||
Arguments.of("{\"burstLimit\":1e1}", new Throttle(10, 0.0)),
|
||||
Arguments.of("{\"burstLimit\":2147483647}", new Throttle(Integer.MAX_VALUE, 0.0)),
|
||||
Arguments.of("{\"burstLimit\":\"7\"}", new Throttle(7, 0.0)),
|
||||
Arguments.of("{\"rateLimit\":\"5.5\"}", new Throttle(0, 5.5)),
|
||||
Arguments.of("{\"burstLimit\":1}", new Throttle(1, 0.0)),
|
||||
Arguments.of("{}", new Throttle(0, 0.0)),
|
||||
Arguments.of("{\"burstLimit\":null,\"rateLimit\":2}", new Throttle(0, 2.0)));
|
||||
}
|
||||
|
||||
// Measured on API Gateway with a replace of /apiStages/<apiId>:<stage>/throttle.
|
||||
@ParameterizedTest
|
||||
@MethodSource("storedStageThrottleValues")
|
||||
void aStageThrottleValueIsReadAsApiGatewayReadsIt(String settings, Throttle stored) {
|
||||
assertEquals(Map.of("/pets/GET", stored), patch(fixture(), "replace", "/apiStages/a:v1/throttle",
|
||||
"{\"/pets/GET\":" + settings + "}").apiStages().get(0).throttle());
|
||||
}
|
||||
|
||||
static Stream<Arguments> refusedStageThrottleValues() {
|
||||
String stageThrottle = "Invalid API Stage throttle specified for usageplan";
|
||||
String throttle = "Usage Plan throttle rate limit and burst limit must be numeric and greater than zero";
|
||||
return Stream.of(
|
||||
Arguments.of("{\"/pets/GET\":{\"burstLimit\":3000000000}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":{\"burstLimit\":-3000000000}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":{\"burstLimit\":\"7.5\"}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":{\"rateLimit\":\"abc\"}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":{\"burstLimit\":true}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":{\"rateLimit\":true}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":{\"burstLimit\":[]}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":{\"burstLimit\":1,\"rateLimit\":2,\"foo\":3}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":5}", stageThrottle),
|
||||
// API Gateway answers this with a 500 InternalFailure, a fault rather than a contract.
|
||||
Arguments.of("{\"/pets/GET\":{\"rateLimit\":1e400}}", stageThrottle),
|
||||
Arguments.of("{\"/pets/GET\":null}",
|
||||
"Invalid throttle setting specified for method {resourcePath: /pets,method: GET}"),
|
||||
Arguments.of("{\"/pets/GET\":{\"burstLimit\":-1}}", throttle),
|
||||
Arguments.of("{\"/pets/GET\":{\"rateLimit\":-2}}", throttle),
|
||||
Arguments.of("{\"/GET\":{\"burstLimit\":1}}",
|
||||
"Invalid method {resourcePath: /GET,method: } specified"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("refusedStageThrottleValues")
|
||||
void aStageThrottleValueApiGatewayCannotReadIsRefused(String value, String message) {
|
||||
assertRefused(() -> patch(fixture(), "replace", "/apiStages/a:v1/throttle", value), "BadRequestException",
|
||||
400, message);
|
||||
}
|
||||
|
||||
// Measured on API Gateway: unlike a create body, a whole-stage throttle value is read through a double, so
|
||||
// a burst limit just under a whole number rounds up and a negative fraction truncates to 0.
|
||||
@Test
|
||||
void aStageThrottleValueReadsItsNumbersThroughADouble() {
|
||||
assertEquals(Map.of("/pets/GET", new Throttle(2, 2.0)),
|
||||
replacedStageThrottle("{\"/pets/GET\":{\"burstLimit\":1.99999999999999999,\"rateLimit\":2}}"));
|
||||
assertEquals(Map.of("/pets/GET", new Throttle(Integer.MAX_VALUE, 0.0)),
|
||||
replacedStageThrottle("{\"/pets/GET\":{\"burstLimit\":2147483647.0000001}}"));
|
||||
assertEquals(Map.of("/pets/GET", new Throttle(0, 0.0)),
|
||||
replacedStageThrottle("{\"/pets/GET\":{\"burstLimit\":-0.5}}"));
|
||||
assertRefused(() -> replacedStageThrottle("{\"/pets/GET\":{\"burstLimit\":2147483647.9}}"),
|
||||
"BadRequestException", 400, "Invalid API Stage throttle specified for usageplan");
|
||||
}
|
||||
|
||||
/** The method throttles a replace of stage a:v1's whole throttle with {@code value} leaves. */
|
||||
private static Map<String, Throttle> replacedStageThrottle(String value) {
|
||||
return patch(fixture(), "replace", "/apiStages/a:v1/throttle", value).apiStages().get(0).throttle();
|
||||
}
|
||||
|
||||
// A single limit is read as before: outside the int range it is an invalid throttle, not a stage throttle.
|
||||
@Test
|
||||
void aSingleBurstLimitOutsideTheIntRangeIsAnInvalidThrottle() {
|
||||
assertRefused(() -> patch(fixture(), "replace", "/apiStages/a:v1/throttle//pets/GET/burstLimit",
|
||||
"3000000000"), "BadRequestException", 400,
|
||||
"Usage Plan throttle rate limit and burst limit must be numeric and greater than zero");
|
||||
}
|
||||
|
||||
// Measured on API Gateway: UpdateUsagePlan's input model lists every op outside its enum, by 1-based index.
|
||||
@Test
|
||||
void anOpOutsideTheModelsEnumIsAnInputModelViolation() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode operations = mapper.readTree("[{\"op\":\"frobnicate\"},{\"op\":\"replace\"},"
|
||||
+ "{\"op\":\"ADD\"},{\"path\":\"/name\"},{\"op\":\"\"},{\"op\":\"copy\"},{\"op\":null},null]");
|
||||
assertEquals(List.of(opViolation("frobnicate", 1), opViolation("ADD", 3), opViolation("", 5)),
|
||||
UsagePlanLimits.opViolations(operations));
|
||||
assertEquals(List.of(), UsagePlanLimits.opViolations(mapper.readTree("[]")));
|
||||
assertEquals(List.of(), UsagePlanLimits.opViolations(mapper.readTree("{}").path("patchOperations")));
|
||||
}
|
||||
|
||||
private static String opViolation(String op, int index) {
|
||||
return "Value '" + op + "' at 'updateUsagePlanInput.patchOperations." + index + ".member.op' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: [add, remove, move, test, replace, copy]";
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a remove whose method throttle path names no method is an invalid path, as for
|
||||
// add and replace, before the key is looked up.
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/nope", "//pets/", "/GET", "//GET", "/"})
|
||||
void removingAMethodThrottlePathThatNamesNoMethodIsAnInvalidPath(String suffix) {
|
||||
String path = "/apiStages/a:v1/throttle" + suffix;
|
||||
assertRefused(() -> patch(fixture(), "remove", path, null), "BadRequestException", 400,
|
||||
invalidPath("remove", path, REMOVE_PATHS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingAMethodThrottleThePlanLacksIsStillNotFound() {
|
||||
assertRefused(() -> patch(fixture(), "remove", "/apiStages/a:v1/throttle//pets/POST", null),
|
||||
"NotFoundException", 404,
|
||||
"Method throttle does not exist for {resourcePath: /pets, method: POST} for usageplan plan1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMethodThrottleNeedsAPlanThrottle() {
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId("p");
|
||||
plan.applyLimits(new Limits(List.of(new ApiStage("a", "v1")), null, null));
|
||||
assertRefused(() -> patch(plan, "replace", "/apiStages/a:v1/throttle//pets/GET/rateLimit", "1"),
|
||||
"BadRequestException", 400, "Can not define fine grain throttling if usage plan throttle is not defined.");
|
||||
assertRefused(() -> patch(plan, "add", "/apiStages/a:v1/throttle",
|
||||
"{\"/pets/GET\":{\"burstLimit\":3,\"rateLimit\":2}}"),
|
||||
"BadRequestException", 400, "Can not define fine grain throttling if usage plan throttle is not defined.");
|
||||
}
|
||||
}
|
||||
+19
@@ -173,6 +173,25 @@ class ApiGatewayUsagePlanCfnProvisionerTest {
|
||||
assertEquals("plan-1", r.getAttributes().get("Id"));
|
||||
}
|
||||
|
||||
// A stage's method throttle is not part of its identity, so a stage the template still lists stays on the
|
||||
// plan with its throttle rather than being removed and added again.
|
||||
@Test
|
||||
void aThrottledStageTheTemplateStillListsIsLeftInPlace() {
|
||||
UsagePlan existing = plan("plan-1", "gold", "old", Map.of(), new UsagePlan.ApiStage("api1", "dev",
|
||||
Map.of("/pets/GET", new UsagePlan.Throttle(10, 5.0))));
|
||||
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
|
||||
when(apiGateway.updateUsagePlan(eq(REGION), eq("plan-1"), anyList())).thenReturn(existing);
|
||||
|
||||
provisioner.provision(resource(PLAN, "Plan", "plan-1"), planProps("gold", "new", null, "api1:dev"),
|
||||
ctx("plan-1"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Map<String, String>>> patches = ArgumentCaptor.forClass(List.class);
|
||||
verify(apiGateway).updateUsagePlan(eq(REGION), eq("plan-1"), patches.capture());
|
||||
assertEquals(List.of(Map.of("op", "replace", "path", "/description", "value", "new")),
|
||||
patches.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnchangedUsagePlanUpdateTouchesNothing() {
|
||||
UsagePlan existing = plan("plan-1", "gold", "same", Map.of("stack", "v1"), new UsagePlan.ApiStage("api1", "dev"));
|
||||
|
||||
Reference in new issue
Block a user