mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(apigateway): return a usage plan's API stages, throttle and quota (#6360)
* fix(apigateway): return a usage plan's API stages, throttle and quota * fix(apigateway): refuse a usage plan create whose text or number member is a list, map or wrong scalar * fix(apigateway): refuse an unknown usage plan quota period before any other create check * fix(apigateway): check a usage plan create body against API Gateway's vendored request shapes * fix(apigateway): read a usage plan create body the way API Gateway does * fix(apigateway): truncate a usage plan's integer limits without a double rounding * refactor(apigateway): reuse SmithyValidationErrors and a shared request shape lookup
This commit is contained in:
1 parent
da9f7e93b1
commit
bab7af3a21
19 files changed
+2684
-85
No files matched your search
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RequestShapeCheck.ByPosition;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
@@ -22,10 +23,10 @@ class RequestShapeCheckTest {
|
||||
|
||||
private static final RequestShapeModel MODEL = parse("""
|
||||
{
|
||||
"operations": {},
|
||||
"operations": {"Put": "Request"},
|
||||
"shapes": {
|
||||
"Request": {"type": "structure", "members": {
|
||||
"Name": "Text", "Count": "Number", "On": "Flag", "Data": "Bytes", "When": "Time",
|
||||
"Name": "Text", "Count": "Number", "On": "Flag", "Data": "Bytes", "When": "Time", "Rate": "Fraction",
|
||||
"Nested": "Request", "Items": "Requests", "Names": "Texts", "Labels": "Labelled"}},
|
||||
"Requests": {"type": "list", "member": "Request"},
|
||||
"Texts": {"type": "list", "member": "Text"},
|
||||
@@ -34,7 +35,8 @@ class RequestShapeCheckTest {
|
||||
"Number": {"type": "integer"},
|
||||
"Flag": {"type": "boolean"},
|
||||
"Bytes": {"type": "blob"},
|
||||
"Time": {"type": "timestamp"}
|
||||
"Time": {"type": "timestamp"},
|
||||
"Fraction": {"type": "double"}
|
||||
}
|
||||
}
|
||||
""");
|
||||
@@ -98,16 +100,108 @@ class RequestShapeCheckTest {
|
||||
assertEquals("NUMBER_VALUE as Blob", blob.getMessage());
|
||||
}
|
||||
|
||||
private static void assertRefused(String body, String message) {
|
||||
@Test
|
||||
void aScalarNameReplacesTheTokenItIsGivenForAndOnlyThatToken() {
|
||||
RequestShapeCheck.Messages named = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
ByPosition.same("structure"), ByPosition.same("list"), ByPosition.same("map"), "%s as %s", true,
|
||||
"boolean text", "blob", Set.of("string", "integer"),
|
||||
Map.of("NUMBER_VALUE", "a number", "TRUE_VALUE", "a boolean"), Map.of(), false);
|
||||
assertRefused("{\"Name\": 5}", named, "a number as String");
|
||||
assertRefused("{\"Name\": true}", named, "a boolean as String");
|
||||
assertRefused("{\"Name\": 5.5}", named, "DECIMAL_VALUE as String");
|
||||
assertRefused("{\"Name\": false}", named, "FALSE_VALUE as String");
|
||||
assertRefused("{\"Count\": \"5\"}", named, "STRING_VALUE as Integer");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeWithItsOwnWordingReplacesTheConversionForThatTypeOnly() {
|
||||
RequestShapeCheck.Messages worded = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
ByPosition.same("structure"), ByPosition.same("list"), ByPosition.same("map"), "%s as %s", false,
|
||||
"boolean text", "blob", Set.of("string", "integer", "double"), Map.of("TRUE_VALUE", "a boolean"),
|
||||
Map.of("double", "%s is no %s here", "integer", "%s is not a count"), false);
|
||||
assertRefused("{\"Rate\": \"5.5\"}", worded, "STRING_VALUE is no Double here");
|
||||
assertRefused("{\"Rate\": true}", worded, "a boolean is no Double here");
|
||||
assertRefused("{\"Count\": \"5\"}", worded, "STRING_VALUE is not a count");
|
||||
assertRefused("{\"Name\": 5}", worded, "NUMBER_VALUE as String");
|
||||
assertAccepted("{\"Rate\": 5.5, \"Count\": 1.5}", worded);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortedMembersReportTheFirstBadMemberInNameOrderRatherThanBodyOrder() {
|
||||
RequestShapeCheck.Messages sorted = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
new ByPosition("structure member", "structure element"), new ByPosition("list member", "list element"),
|
||||
new ByPosition("map member", "map element"), "%s as %s", true, "boolean text", "blob",
|
||||
Set.of("string", "integer", "boolean", "blob"), Map.of(), Map.of(), true);
|
||||
String body = "{\"Name\": 5, \"Count\": \"5\"}";
|
||||
assertRefused(body, "NUMBER_VALUE as String");
|
||||
assertRefused(body, sorted, "STRING_VALUE as Integer");
|
||||
String nested = "{\"Nested\": {\"Name\": 5, \"Count\": \"5\"}, \"Items\": [{\"On\": 0, \"Data\": 5}]}";
|
||||
assertRefused(nested, "NUMBER_VALUE as String");
|
||||
assertRefused(nested, sorted, "blob");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sortedMembersReadAMapsEntriesInKeyOrderAndAListInItsOwnOrder() {
|
||||
RequestShapeCheck.Messages sorted = new RequestShapeCheck.Messages("Refused", "object", "list",
|
||||
ByPosition.same("structure"), ByPosition.same("list"), ByPosition.same("map"), "%s as %s", true,
|
||||
"boolean text", "blob", Set.of("string", "integer"), Map.of(), Map.of(), true);
|
||||
String map = "{\"Labels\": {\"z\": {\"Name\": 5}, \"a\": {\"Count\": \"5\"}}}";
|
||||
assertRefused(map, "NUMBER_VALUE as String");
|
||||
assertRefused(map, sorted, "STRING_VALUE as Integer");
|
||||
String list = "{\"Names\": [true, 5]}";
|
||||
assertRefused(list, "TRUE_VALUE as String");
|
||||
assertRefused(list, sorted, "TRUE_VALUE as String");
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsWalkTheInputShapeOfAKnownOperation() throws Exception {
|
||||
RequestShapeCheck.Operations operations =
|
||||
new RequestShapeCheck.Operations("aws/fixture-request-shapes.json", "fixture request shapes", MESSAGES);
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), MESSAGES), body);
|
||||
() -> operations.check(MODEL, "Put", MAPPER.readTree("{\"Name\": 5}")));
|
||||
assertEquals("Refused", e.getErrorCode());
|
||||
assertEquals("NUMBER_VALUE as String", e.getMessage());
|
||||
operations.check(MODEL, "Put", MAPPER.readTree("{\"Name\": \"n\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsAnswerAnUnknownOperationAsAnInternalFailure() {
|
||||
RequestShapeCheck.Operations operations =
|
||||
new RequestShapeCheck.Operations("aws/fixture-request-shapes.json", "fixture request shapes", MESSAGES);
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> operations.check(MODEL, "NoSuchOperation", MAPPER.readTree("{}")));
|
||||
assertEquals("InternalFailure", e.getErrorCode());
|
||||
assertEquals(500, e.getHttpStatus());
|
||||
assertEquals("The request processing has failed because of an unknown error.", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsLoadTheVendoredModelOnFirstCheckNotWhenBuilt() {
|
||||
RequestShapeCheck.Operations missing =
|
||||
new RequestShapeCheck.Operations("aws/no-such-request-shapes.json", "missing request shapes", MESSAGES);
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> missing.check("Put", MAPPER.readTree("{}")));
|
||||
assertEquals("missing request shapes resource not found: aws/no-such-request-shapes.json", e.getMessage());
|
||||
}
|
||||
|
||||
private static void assertRefused(String body, String message) {
|
||||
assertRefused(body, MESSAGES, message);
|
||||
}
|
||||
|
||||
private static void assertRefused(String body, RequestShapeCheck.Messages messages, String message) {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), messages), body);
|
||||
assertEquals("Refused", e.getErrorCode(), body);
|
||||
assertEquals(400, e.getHttpStatus(), body);
|
||||
assertEquals(message, e.getMessage(), body);
|
||||
}
|
||||
|
||||
private static void assertAccepted(String body) {
|
||||
assertDoesNotThrow(() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), MESSAGES), body);
|
||||
assertAccepted(body, MESSAGES);
|
||||
}
|
||||
|
||||
private static void assertAccepted(String body, RequestShapeCheck.Messages messages) {
|
||||
assertDoesNotThrow(() -> RequestShapeCheck.check(MODEL, "Request", MAPPER.readTree(body), messages), body);
|
||||
}
|
||||
|
||||
private static RequestShapeModel parse(String json) {
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import static org.hamcrest.Matchers.nullValue;
|
||||
*
|
||||
* <p>Each pair is {@code [used, remaining]}, not {@code [used, quota]}: on real API Gateway the
|
||||
* second element is the quota limit minus cumulative use. Both are zero here because nothing meters
|
||||
* requests per key and a usage plan stores no quota.
|
||||
* requests per key, so there is no use to report or to subtract from a plan's quota.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayGetUsageIntegrationTest {
|
||||
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** CreateUsagePlan bodies as measured with raw requests against API Gateway in eu-west-1. */
|
||||
class ApiGatewayRequestShapesTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String STRUCTURE = "Start of structure or map found where not expected.";
|
||||
private static final String LIST = "Start of list found where not expected";
|
||||
private static final String STRING_TO_INTEGER = "class java.lang.String can not be converted to an Integer";
|
||||
private static final String BOOLEAN_TO_INTEGER = "class java.lang.Boolean can not be converted to an Integer";
|
||||
private static final String STRING_TO_DOUBLE = "class java.lang.String is not an expected Json type";
|
||||
private static final String BOOLEAN_TO_DOUBLE = "class java.lang.Boolean is not an expected Json type";
|
||||
private static final String NUMBER_TO_STRING =
|
||||
"class com.amazon.coral.value.json.numbers.TruncatingBigNumber can not be converted to an String";
|
||||
private static final String BOOLEAN_TO_STRING = "class java.lang.Boolean can not be converted to an String";
|
||||
private static final String STAGE = "{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{\"/pets/GET\":%s}}";
|
||||
|
||||
@Test
|
||||
void anIntegerMemberTakesAnyJsonNumber() {
|
||||
assertAccepted("{\"quota\":{\"limit\":1.5,\"offset\":0,\"period\":\"DAY\"}}");
|
||||
assertAccepted("{\"quota\":{\"limit\":1e2,\"offset\":1.9,\"period\":\"WEEK\"}}");
|
||||
assertAccepted("{\"quota\":{\"limit\":3000000000,\"period\":\"DAY\"}}");
|
||||
assertAccepted("{\"throttle\":{\"burstLimit\":1.5}}");
|
||||
assertAccepted("{\"throttle\":{\"burstLimit\":3000000000}}");
|
||||
assertAccepted("{\"throttle\":{\"burstLimit\":-1e2}}");
|
||||
assertAccepted("{\"apiStages\":[" + STAGE.formatted("{\"burstLimit\":1.5}") + "]}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIntegerMemberRefusesTextEvenWhenItIsNumeric() {
|
||||
for (String text : new String[] {"\"100\"", "\"\"", "\"1.5\""}) {
|
||||
assertRejected("{\"quota\":{\"limit\":" + text + ",\"period\":\"DAY\"}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"quota\":{\"offset\":" + text + "}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":" + text + "}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("{\"burstLimit\":" + text + "}") + "]}",
|
||||
STRING_TO_INTEGER);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIntegerMemberRefusesABoolean() {
|
||||
assertRejected("{\"quota\":{\"limit\":true}}", BOOLEAN_TO_INTEGER);
|
||||
assertRejected("{\"quota\":{\"offset\":false}}", BOOLEAN_TO_INTEGER);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":true}}", BOOLEAN_TO_INTEGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDoubleMemberTakesAnyJsonNumberAndNamesWhatElseItGotAsAnUnexpectedType() {
|
||||
assertAccepted("{\"throttle\":{\"rateLimit\":5}}");
|
||||
assertAccepted("{\"throttle\":{\"rateLimit\":5.5}}");
|
||||
assertAccepted("{\"throttle\":{\"rateLimit\":1e1}}");
|
||||
for (String text : new String[] {"\"5.5\"", "\"abc\"", "\"1e1\""}) {
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":" + text + "}}", STRING_TO_DOUBLE);
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("{\"rateLimit\":" + text + "}") + "]}",
|
||||
STRING_TO_DOUBLE);
|
||||
}
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":true}}", BOOLEAN_TO_DOUBLE);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":false}}", BOOLEAN_TO_DOUBLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStringMemberRefusesANumberOrABoolean() {
|
||||
for (String number : new String[] {"5", "5.5", "1e2"}) {
|
||||
assertRejected("{\"name\":" + number + "}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"description\":" + number + "}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"quota\":{\"period\":" + number + "}}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":" + number + ",\"stage\":\"v1\"}]}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":" + number + "}]}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"tags\":{\"k\":" + number + "}}", NUMBER_TO_STRING);
|
||||
}
|
||||
assertRejected("{\"name\":true}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"description\":false}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"quota\":{\"period\":true}}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":true}]}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"tags\":{\"k\":false}}", BOOLEAN_TO_STRING);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStructureTakesOnlyAnObjectAsAMemberOrAnElement() {
|
||||
assertRejected("{\"quota\":\"invalid\"}", "Expected null");
|
||||
assertRejected("{\"quota\":5}", "Expected null");
|
||||
assertRejected("{\"throttle\":5}", "Expected null");
|
||||
assertRejected("{\"throttle\":true}", "Expected null");
|
||||
assertRejected("{\"apiStages\":[\"x\"]}", "Expected null");
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("5") + "]}", "Expected null");
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("\"x\"") + "]}", "Expected null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aListWhereNoneIsExpectedIsRefused() {
|
||||
assertRejected("{\"name\":[]}", LIST);
|
||||
assertRejected("{\"quota\":[]}", LIST);
|
||||
assertRejected("{\"throttle\":[]}", LIST);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":[]}}", LIST);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":[1]}}", LIST);
|
||||
assertRejected("{\"quota\":{\"period\":[\"DAY\"]}}", LIST);
|
||||
assertRejected("{\"tags\":[]}", LIST);
|
||||
assertRejected("{\"tags\":{\"k\":[]}}", LIST);
|
||||
assertRejected("{\"apiStages\":[[]]}", LIST);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":[],\"stage\":\"v1\"}]}", LIST);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":[]}]}", LIST);
|
||||
assertRejected("{\"apiStages\":[" + STAGE.formatted("[]") + "]}", LIST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anObjectWhereNoneIsExpectedIsRefused() {
|
||||
assertRejected("{\"name\":{}}", STRUCTURE);
|
||||
assertRejected("{\"description\":{\"a\":1}}", STRUCTURE);
|
||||
assertRejected("{\"apiStages\":{}}", STRUCTURE);
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"quota\":{\"period\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"tags\":{\"k\":{}}}", STRUCTURE);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":{},\"stage\":\"v1\"}]}", STRUCTURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aListOrAMapMemberRefusesAScalar() {
|
||||
assertRejected("{\"apiStages\":\"x\"}", "Expected list or null");
|
||||
assertRejected("{\"apiStages\":5}", "Expected list or null");
|
||||
assertRejected("{\"apiStages\":true}", "Expected list or null");
|
||||
assertRejected("{\"tags\":\"x\"}", "Expected map or null");
|
||||
assertRejected("{\"tags\":5}", "Expected map or null");
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":5}]}", "Expected map or null");
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":\"x\"}]}",
|
||||
"Expected map or null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullsAndUnknownMembersAreLeftToTheOperation() {
|
||||
assertAccepted("{\"name\":null,\"quota\":null,\"throttle\":null,\"apiStages\":null,\"tags\":null}");
|
||||
assertAccepted("{\"name\":\"p\",\"unknown\":[1,{}],\"productCode\":5,\"quota\":{\"other\":true}}");
|
||||
assertAccepted("{\"apiStages\":[null,{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{\"/pets/GET\":null}}]}");
|
||||
}
|
||||
|
||||
// Each pair is sent in both body orders; the member first by name is reported either way.
|
||||
@Test
|
||||
void topLevelMembersAreReadInNameOrder() {
|
||||
assertReportedInEitherOrder("\"apiStages\":\"x\"", "\"description\":5", "Expected list or null");
|
||||
assertReportedInEitherOrder("\"description\":5", "\"name\":true", NUMBER_TO_STRING);
|
||||
assertReportedInEitherOrder("\"name\":true", "\"quota\":\"x\"", BOOLEAN_TO_STRING);
|
||||
assertReportedInEitherOrder("\"quota\":\"x\"", "\"tags\":\"x\"", "Expected null");
|
||||
assertReportedInEitherOrder("\"tags\":\"x\"", "\"throttle\":[]", "Expected map or null");
|
||||
// botocore lists name before apiStages, so this is not the model's order either.
|
||||
assertReportedInEitherOrder("\"apiStages\":\"x\"", "\"name\":true", "Expected list or null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedMembersAreReadInNameOrder() {
|
||||
assertRejected("{\"throttle\":{\"burstLimit\":\"x\",\"rateLimit\":\"x\"}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"throttle\":{\"rateLimit\":\"x\",\"burstLimit\":\"x\"}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":true,\"stage\":5}]}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"apiStages\":[{\"stage\":5,\"apiId\":true}]}", BOOLEAN_TO_STRING);
|
||||
assertRejected("{\"quota\":{\"limit\":\"x\",\"period\":5}}", STRING_TO_INTEGER);
|
||||
assertRejected("{\"quota\":{\"period\":5,\"limit\":\"x\"}}", STRING_TO_INTEGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapEntriesAreReadInKeyOrder() {
|
||||
assertRejected("{\"tags\":{\"z\":true,\"a\":5}}", NUMBER_TO_STRING);
|
||||
assertRejected("{\"tags\":{\"a\":5,\"z\":true}}", NUMBER_TO_STRING);
|
||||
String z = "\"/z/GET\":{\"burstLimit\":true}";
|
||||
String a = "\"/a/GET\":{\"burstLimit\":\"s\"}";
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{" + z + "," + a + "}}]}",
|
||||
STRING_TO_INTEGER);
|
||||
assertRejected("{\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\",\"throttle\":{" + a + "," + z + "}}]}",
|
||||
STRING_TO_INTEGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownOperationIsAServerError() {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ApiGatewayRequestShapes.check("NoSuchOperation", json("{}")));
|
||||
assertEquals("InternalFailure", error.getErrorCode());
|
||||
assertEquals(500, error.getHttpStatus());
|
||||
}
|
||||
|
||||
private static void assertReportedInEitherOrder(String first, String second, String message) {
|
||||
assertRejected("{" + first + "," + second + "}", message);
|
||||
assertRejected("{" + second + "," + first + "}", message);
|
||||
}
|
||||
|
||||
private static void assertRejected(String body, String message) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ApiGatewayRequestShapes.check("CreateUsagePlan", json(body)), body);
|
||||
assertEquals("SerializationException", error.getErrorCode(), body);
|
||||
assertEquals(400, error.getHttpStatus(), body);
|
||||
assertEquals(message, error.getMessage(), body);
|
||||
}
|
||||
|
||||
private static void assertAccepted(String body) {
|
||||
assertDoesNotThrow(() -> ApiGatewayRequestShapes.check("CreateUsagePlan", json(body)), body);
|
||||
}
|
||||
|
||||
private static JsonNode json(String body) throws Exception {
|
||||
return MAPPER.readTree(body);
|
||||
}
|
||||
}
|
||||
+330
@@ -6,12 +6,21 @@ import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.anEmptyMap;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
@TestHTTPEndpoint(ApiGatewayController.class)
|
||||
class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
|
||||
private static final String NAME_NULL =
|
||||
"Value null at 'createUsagePlanInput.name' failed to satisfy constraint: Member must not be null";
|
||||
|
||||
@Test
|
||||
void testCreateAndRetrieveUsagePlan() {
|
||||
String usagePlanId = given()
|
||||
@@ -61,4 +70,325 @@ class ApiGatewayUsagePlanCrudIntegrationTest {
|
||||
.then()
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlanReportsItsStagesFromCreateAndBothReads() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"staged\",\"apiStages\":[{\"apiId\":\"a1\",\"stage\":\"v1\"}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiStages", hasSize(1))
|
||||
.body("apiStages[0].apiId", equalTo("a1"))
|
||||
.body("apiStages[0].stage", equalTo("v1"))
|
||||
.body("apiStages[0].throttle", nullValue())
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages[0].apiId", equalTo("a1"))
|
||||
.body("apiStages[0].stage", equalTo("v1"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.find { it.id == '" + usagePlanId + "' }.apiStages[0].stage", equalTo("v1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlanWithoutStagesReportsAnEmptyListAndNoLimits() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"bare\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiStages", hasSize(0))
|
||||
.body("throttle", nullValue())
|
||||
.body("quota", nullValue())
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageWithAMethodThrottleIsMatchedByApiAndStage() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"stage-remove\",\"throttle\":{\"burstLimit\":20,\"rateLimit\":10},"
|
||||
+ "\"apiStages\":[{\"apiId\":\"a1\",\"stage\":\"v1\","
|
||||
+ "\"throttle\":{\"/pets/GET\":{\"burstLimit\":10,\"rateLimit\":5}}},"
|
||||
+ "{\"apiId\":\"a1\",\"stage\":\"v2\"}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(10))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"add\",\"path\":\"/apiStages\",\"value\":\"a1:v1\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(2))
|
||||
.body("apiStages[0].throttle['/pets/GET'].burstLimit", equalTo(10));
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"remove\",\"path\":\"/apiStages\",\"value\":\"a1:v1\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(1))
|
||||
.body("apiStages[0].stage", equalTo("v2"));
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("apiStages", hasSize(1))
|
||||
.body("apiStages[0].stage", equalTo("v2"))
|
||||
.body("throttle.burstLimit", equalTo(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownQuotaPeriodOnCreateIsAValidationException() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"bad-period\",\"quota\":{\"limit\":1,\"period\":\"day\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: GetUsagePlan and UpdateUsagePlan carry "tags": {}, CreateUsagePlan and
|
||||
// the GetUsagePlans items leave an empty map out.
|
||||
@Test
|
||||
void getAndUpdateReportEmptyTagsWhileCreateAndListLeaveThemOut() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"untagged\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("$", not(hasKey("tags")))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags", anEmptyMap());
|
||||
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/name\",\"value\":\"untagged-renamed\"}]}")
|
||||
.patch("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags", anEmptyMap());
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.find { it.id == '" + usagePlanId + "' }", not(hasKey("tags")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownPlanIdIsNotFoundWithApiGatewaysMessage() {
|
||||
given().get("/usageplans/{usagePlanId}", "no-such-plan")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("NotFoundException"))
|
||||
.body("message", equalTo("Invalid Usage Plan ID specified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStageWithoutAnApiIdIsRefusedAndNoPlanIsStored() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"stage-without-api\",\"apiStages\":[{\"stage\":\"v1\"}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequestException"))
|
||||
.body("message", equalTo("Invalid API Stage specified"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.findAll { it.name == 'stage-without-api' }", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrongJsonTypeOnCreateIsASerializationError() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"wrong-type\",\"quota\":\"invalid\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("Expected null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStructuredStageIdentifierIsASerializationErrorAndStoresNoPlan() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"structured-stage\",\"apiStages\":[{\"apiId\":[],\"stage\":{}}]}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("Start of list found where not expected"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.findAll { it.name == 'structured-stage' }", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNumericStringForAnIntegerIsASerializationErrorAndStoresNoPlan() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"string-limit\",\"quota\":{\"limit\":\"100\",\"period\":\"DAY\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("class java.lang.String can not be converted to an Integer"));
|
||||
|
||||
given().get("/usageplans")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("item.findAll { it.name == 'string-limit' }", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFractionalQuotaLimitIsStoredTruncated() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"fractional-limit\",\"quota\":{\"limit\":1.5,\"period\":\"DAY\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("quota.limit", equalTo(1))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("quota.limit", equalTo(1));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: the limit is truncated from its decimal digits, not first rounded to 2.0 as a double.
|
||||
@Test
|
||||
void aLimitJustUnderAWholeNumberIsStoredTruncated() {
|
||||
String usagePlanId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"precise-limit\",\"quota\":{\"limit\":1.99999999999999999,\"period\":\"DAY\"}}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("quota.limit", equalTo(1))
|
||||
.extract()
|
||||
.path("id");
|
||||
|
||||
given().get("/usageplans/{usagePlanId}", usagePlanId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("quota.limit", equalTo(1));
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a negative fraction is refused, not truncated to 0.
|
||||
@Test
|
||||
void aNegativeFractionalLimitIsRefusedAndStoresNoPlan() {
|
||||
assertCreateRefused("{\"name\":\"negative-fraction-limit\",\"quota\":{\"limit\":-0.9,\"period\":\"DAY\"}}",
|
||||
"BadRequestException", "Usage Plan quota limit must be a non-negative numeric");
|
||||
}
|
||||
|
||||
// In body order the list throttle comes first; API Gateway reads quota before throttle by name.
|
||||
@Test
|
||||
void theFirstWrongJsonTypeInMemberNameOrderIsReported() {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"name-order\",\"throttle\":[],\"quota\":\"x\"}")
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SerializationException"))
|
||||
.body("message", equalTo("Expected null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aZeroByteBodyIsAMissingInput() {
|
||||
int before = planCount();
|
||||
given().contentType(ContentType.JSON)
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", equalTo("1 validation error detected: Value null at 'createUsagePlanInput' "
|
||||
+ "failed to satisfy constraint: Member must not be null"));
|
||||
assertEquals(before, planCount());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a SerializationException with no message.
|
||||
@Test
|
||||
void aBodyThatIsNotAJsonObjectOrArrayIsASerializationErrorWithoutAMessage() {
|
||||
for (String body : new String[] {" ", "{", "{\"name\":\"trailing-junk\"} x", "\"x\"", "5", "null"}) {
|
||||
assertCreateRefused(body, "SerializationException", null);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopLevelArrayIsAListWhereNoneIsExpected() {
|
||||
assertCreateRefused("[]", "SerializationException", "Start of list found where not expected");
|
||||
assertCreateRefused("[{}]", "SerializationException", "Start of list found where not expected");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingOrNullNameIsAValidationException() {
|
||||
for (String body : new String[] {"{}", "{\"description\":\"d\"}", "{\"name\":null}"}) {
|
||||
assertCreateRefused(body, "ValidationException", "1 validation error detected: " + NAME_NULL);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theInputModelListsAnInvalidPeriodBeforeAMissingName() {
|
||||
assertCreateRefused("{\"quota\":{\"limit\":1,\"period\":\"YEAR\"}}", "ValidationException",
|
||||
"2 validation errors detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]; " + NAME_NULL);
|
||||
}
|
||||
|
||||
// The empty name is API Gateway's own check: after the input model, before the limits.
|
||||
@Test
|
||||
void anEmptyNameIsABadRequestAfterTheInputModelAndBeforeTheLimits() {
|
||||
assertCreateRefused("{\"name\":\"\"}", "BadRequestException", "Usage Plan name must be specified");
|
||||
assertCreateRefused("{\"name\":\"\",\"quota\":{\"period\":\"DAY\"}}", "BadRequestException",
|
||||
"Usage Plan name must be specified");
|
||||
assertCreateRefused("{\"name\":\"\",\"quota\":{\"limit\":1,\"period\":\"YEAR\"}}", "ValidationException",
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]");
|
||||
}
|
||||
|
||||
private static int planCount() {
|
||||
return given().get("/usageplans").then().statusCode(200).extract().path("item.size()");
|
||||
}
|
||||
|
||||
/** Posts {@code body}, expects a 400 of {@code type} with {@code message}, and that no plan was stored. */
|
||||
private static void assertCreateRefused(String body, String type, String message) {
|
||||
int before = planCount();
|
||||
given().contentType(ContentType.JSON)
|
||||
.body(body)
|
||||
.post("/usageplans")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo(type))
|
||||
.body("message", equalTo(message));
|
||||
assertEquals(before, planCount(), body);
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
|
||||
import software.amazon.awssdk.services.apigateway.model.ApiStage;
|
||||
import software.amazon.awssdk.services.apigateway.model.CreateUsagePlanResponse;
|
||||
import software.amazon.awssdk.services.apigateway.model.GetUsagePlanResponse;
|
||||
import software.amazon.awssdk.services.apigateway.model.QuotaPeriodType;
|
||||
import software.amazon.awssdk.services.apigateway.model.QuotaSettings;
|
||||
import software.amazon.awssdk.services.apigateway.model.ThrottleSettings;
|
||||
import software.amazon.awssdk.services.apigateway.model.UsagePlan;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@QuarkusTest
|
||||
class ApiGatewayUsagePlanSdkIntegrationTest {
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
private ApiGatewayClient client() {
|
||||
return ApiGatewayClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesThrottleAndQuotaRoundTripThroughEveryRead() {
|
||||
try (ApiGatewayClient client = client()) {
|
||||
String apiId = client.createRestApi(r -> r.name("usage-plan-sdk")).id();
|
||||
ThrottleSettings planThrottle = ThrottleSettings.builder().burstLimit(20).rateLimit(10.0).build();
|
||||
QuotaSettings quota = QuotaSettings.builder().limit(1000).offset(3).period(QuotaPeriodType.MONTH).build();
|
||||
ApiStage v1 = ApiStage.builder().apiId(apiId).stage("v1")
|
||||
.throttle(Map.of("/pets/GET", ThrottleSettings.builder().burstLimit(10).rateLimit(5.0).build()))
|
||||
.build();
|
||||
ApiStage v2 = ApiStage.builder().apiId(apiId).stage("v2").build();
|
||||
CreateUsagePlanResponse created = client.createUsagePlan(r -> r.name("sdk-plan")
|
||||
.apiStages(v1, v2).throttle(planThrottle).quota(quota));
|
||||
try {
|
||||
assertEquals(List.of(v1, v2), created.apiStages());
|
||||
assertEquals(planThrottle, created.throttle());
|
||||
assertEquals(quota, created.quota());
|
||||
|
||||
GetUsagePlanResponse read = client.getUsagePlan(r -> r.usagePlanId(created.id()));
|
||||
assertEquals(List.of(v1, v2), read.apiStages());
|
||||
assertEquals(planThrottle, read.throttle());
|
||||
assertEquals(quota, read.quota());
|
||||
|
||||
UsagePlan listed = client.getUsagePlans(r -> r.limit(500)).items().stream()
|
||||
.filter(plan -> plan.id().equals(created.id())).findFirst().orElseThrow();
|
||||
assertEquals(List.of(v1, v2), listed.apiStages());
|
||||
assertEquals(planThrottle, listed.throttle());
|
||||
assertEquals(quota, listed.quota());
|
||||
} finally {
|
||||
client.deleteUsagePlan(r -> r.usagePlanId(created.id()));
|
||||
client.deleteRestApi(r -> r.restApiId(apiId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.ApiStage;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Limits;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Quota;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan.Throttle;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
|
||||
class UsagePlanLimitsTest {
|
||||
|
||||
private static Map<String, Object> request(Object... keyValues) {
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
for (int i = 0; i < keyValues.length; i += 2) {
|
||||
request.put((String) keyValues[i], keyValues[i + 1]);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static void assertRefused(Executable call, String code, int status, String message) {
|
||||
AwsException e = assertThrows(AwsException.class, call);
|
||||
assertEquals(code, e.getErrorCode());
|
||||
assertEquals(status, e.getHttpStatus());
|
||||
assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestWithoutLimitsHasNoStagesThrottleOrQuota() {
|
||||
assertEquals(new Limits(List.of(), null, null), UsagePlanLimits.fromRequest(request("name", "p")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttleFieldsLeftOutReadAsZero() {
|
||||
assertEquals(new Throttle(10, 0.0),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("burstLimit", 10))).throttle());
|
||||
assertEquals(new Throttle(0, 5.5),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("rateLimit", "5.5"))).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotaOffsetDefaultsToZeroAndNumbersMayBeStrings() {
|
||||
assertEquals(new Quota(100, 0, "WEEK"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 100, "period", "WEEK"))).quota());
|
||||
assertEquals(new Quota(100, 2, "WEEK"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", "100", "offset", "2", "period", "WEEK"))).quota());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stagesKeepTheirMethodThrottlesAndAnEmptyOneIsDropped() {
|
||||
Limits limits = UsagePlanLimits.fromRequest(request(
|
||||
"throttle", Map.of("burstLimit", 20, "rateLimit", 10),
|
||||
"apiStages", List.of(
|
||||
Map.of("apiId", "a", "stage", "v1",
|
||||
"throttle", Map.of("/pets/GET", Map.of("burstLimit", 10, "rateLimit", 5))),
|
||||
Map.of("apiId", "a", "stage", "v2", "throttle", Map.of()))));
|
||||
|
||||
assertEquals(List.of(new ApiStage("a", "v1", Map.of("/pets/GET", new Throttle(10, 5.0))),
|
||||
new ApiStage("a", "v2")), limits.apiStages());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a positive JSON number for an int member is truncated and clamped.
|
||||
@Test
|
||||
void aJsonNumberIsTruncatedTowardZeroAndClampedToTheIntRange() {
|
||||
assertEquals(new Quota(1, 0, "DAY"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 1.5, "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(1, 0.0),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("burstLimit", 1.5))).throttle());
|
||||
assertEquals(new Quota(100, 0, "DAY"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 100.0, "period", "DAY"))).quota());
|
||||
assertEquals(new Quota(Integer.MAX_VALUE, 0, "DAY"),
|
||||
UsagePlanLimits.fromRequest(request("quota", Map.of("limit", 3000000000L, "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(0, 2.5),
|
||||
UsagePlanLimits.fromRequest(request("throttle", Map.of("rateLimit", 2.5))).throttle());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: the decimal digits are kept, so a value just under a whole number is not rounded up.
|
||||
@Test
|
||||
void aJsonNumberIsTruncatedFromItsDecimalDigitsWithoutRoundingThroughADouble() {
|
||||
assertEquals(new Quota(1, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("1.99999999999999999"), "period", "DAY"))).quota());
|
||||
assertEquals(new Quota(1, 0, "DAY"), UsagePlanLimits.fromRequest(request("quota",
|
||||
Map.of("limit", 1, "offset", new BigDecimal("0.99999999999999999"), "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(2, 0.0), UsagePlanLimits.fromRequest(
|
||||
request("throttle", Map.of("burstLimit", new BigDecimal("2.99999999999999999")))).throttle());
|
||||
assertEquals(new Quota(Integer.MAX_VALUE, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("2147483647.9"), "period", "DAY"))).quota());
|
||||
assertEquals(new Throttle(0, 1.0), UsagePlanLimits.fromRequest(
|
||||
request("throttle", Map.of("rateLimit", new BigDecimal("1.00000000000000000001")))).throttle());
|
||||
}
|
||||
|
||||
// Measured on API Gateway: a negative fraction is refused as negative, not truncated to 0.
|
||||
@Test
|
||||
void aNegativeFractionIsRefusedAsNegative() {
|
||||
String limit = "Usage Plan quota limit must be a non-negative numeric";
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("-0.9"), "period", "DAY"))),
|
||||
"BadRequestException", 400, limit);
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(request("quota", Map.of("limit", -0.9, "period", "DAY"))),
|
||||
"BadRequestException", 400, limit);
|
||||
}
|
||||
|
||||
// The int bounds are compared before rounding, so an extreme exponent is never expanded into its digits.
|
||||
@Test
|
||||
void anExtremeExponentIsReadWithoutExpandingIt() {
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
|
||||
assertEquals(new Quota(Integer.MAX_VALUE, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("1e1000000000"), "period", "DAY"))).quota());
|
||||
assertEquals(new Quota(0, 0, "DAY"), UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("1e-1000000000"), "period", "DAY"))).quota());
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(
|
||||
request("quota", Map.of("limit", new BigDecimal("-1e-1000000000"), "period", "DAY"))),
|
||||
"BadRequestException", 400, "Usage Plan quota limit must be a non-negative numeric");
|
||||
});
|
||||
}
|
||||
|
||||
// CreateUsagePlan's input model: the service lists this with a missing name in one ValidationException.
|
||||
@Test
|
||||
void aPeriodOutsideTheEnumIsAnInputModelViolation() {
|
||||
assertEquals("Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [MONTH, WEEK, DAY]",
|
||||
UsagePlanLimits.periodViolation(request("quota", Map.of("limit", 1, "period", "YEAR"))));
|
||||
assertNull(UsagePlanLimits.periodViolation(request("quota", Map.of("limit", 1, "period", "DAY"))));
|
||||
assertNull(UsagePlanLimits.periodViolation(request("quota", Map.of("limit", 1))));
|
||||
assertNull(UsagePlanLimits.periodViolation(request("name", "p")));
|
||||
}
|
||||
|
||||
// The storage backends persist plans with a plain ObjectMapper, so this is the shape on disk.
|
||||
@Test
|
||||
void aPlanSurvivesTheStorageJsonRoundTripAndOlderPlansStillLoad() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId("p");
|
||||
plan.applyLimits(new Limits(List.of(new ApiStage("a", "v1", Map.of("/pets/GET", new Throttle(10, 5.0))),
|
||||
new ApiStage("a", "v2")), new Throttle(20, 10.0), new Quota(1000, 3, "MONTH")));
|
||||
|
||||
String json = mapper.writeValueAsString(plan);
|
||||
assertFalse(json.contains("\"limits\""), json);
|
||||
assertEquals(plan.limits(), mapper.readValue(json, UsagePlan.class).limits());
|
||||
|
||||
UsagePlan older = mapper.readValue(
|
||||
"{\"id\":\"p\",\"name\":\"n\",\"apiStages\":[{\"apiId\":\"a\",\"stage\":\"v1\"}]}", UsagePlan.class);
|
||||
assertEquals(new Limits(List.of(new ApiStage("a", "v1")), null, null), older.limits());
|
||||
}
|
||||
|
||||
static Stream<Arguments> refusedCreates() {
|
||||
String throttle = "Usage Plan throttle rate limit and burst limit must be numeric and greater than zero";
|
||||
String limit = "Usage Plan quota limit must be a non-negative numeric";
|
||||
return Stream.of(
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 100)), "BadRequestException", 400,
|
||||
"Invalid Usage Plan quota period specified. Must be one of [DAY, WEEK, MONTH]"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 100, "period", "YEAR")), "ValidationException", 400,
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]"),
|
||||
// The input model's period check outranks every other check, measured on API Gateway.
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "YEAR"), "throttle", Map.of("burstLimit", -1)),
|
||||
"ValidationException", 400,
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "YEAR"), "apiStages", List.of(
|
||||
Map.of("apiId", "a", "stage", "v1"), Map.of("apiId", "a", "stage", "v1"))),
|
||||
"ValidationException", 400,
|
||||
"1 validation error detected: Value 'YEAR' at 'createUsagePlanInput.quota.period' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: [MONTH, WEEK, DAY]"),
|
||||
Arguments.of(Map.of("quota", Map.of("period", "DAY")), "BadRequestException", 400, limit),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", -1, "period", "DAY")), "BadRequestException", 400, limit),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "DAY", "offset", 1)), "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be zero in the DAY period"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "WEEK", "offset", 7)), "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be between 0 and 6 inclusive in the WEEK period"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "WEEK", "offset", -1)), "BadRequestException", 400,
|
||||
"Usage Plan quota offset must be between 0 and 6 inclusive in the WEEK period"),
|
||||
Arguments.of(Map.of("quota", Map.of("limit", 1, "period", "MONTH", "offset", 28)), "BadRequestException",
|
||||
400, "Usage Plan quota offset must be between 0 and 27 inclusive in the MONTH period"),
|
||||
Arguments.of(Map.of("throttle", Map.of("burstLimit", -1, "rateLimit", 1)), "BadRequestException", 400,
|
||||
throttle),
|
||||
// Text is parsed as written, so a fraction is refused; a JSON number would be truncated.
|
||||
Arguments.of(Map.of("throttle", Map.of("burstLimit", "1.5")), "BadRequestException", 400, throttle),
|
||||
Arguments.of(Map.of("throttle", Map.of("rateLimit", "abc")), "BadRequestException", 400, throttle),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a", "stage", "v1",
|
||||
"throttle", Map.of("/pets/GET", Map.of("burstLimit", 1))))), "BadRequestException", 400,
|
||||
"Can not define fine grain throttling if usage plan throttle is not defined."),
|
||||
Arguments.of(Map.of("throttle", Map.of("burstLimit", 1), "apiStages", List.of(Map.of("apiId", "a",
|
||||
"stage", "v1", "throttle", Map.of("/pets/GET", Map.of("burstLimit", -1))))),
|
||||
"BadRequestException", 400, throttle),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a", "stage", "v1"),
|
||||
Map.of("apiId", "a", "stage", "v1"))), "ConflictException", 409,
|
||||
"API Stage is already defined for Usage Plan: a:v1"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("stage", "v1"))), "BadRequestException", 400,
|
||||
"Invalid API Stage specified"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a"))), "BadRequestException", 400,
|
||||
"Invalid API Stage specified"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "", "stage", "v1"))), "BadRequestException",
|
||||
400, "Invalid API Stage specified"),
|
||||
Arguments.of(Map.of("apiStages", List.of(Map.of("apiId", "a", "stage", ""))), "BadRequestException",
|
||||
400, "Invalid API Stage specified"),
|
||||
Arguments.of(stageThrottle("/GET"), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: /GET,method: } specified"),
|
||||
Arguments.of(stageThrottle(""), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: ,method: } specified"),
|
||||
Arguments.of(stageThrottle("/pets/"), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: /pets/,method: } specified"),
|
||||
Arguments.of(stageThrottle("GET"), "BadRequestException", 400,
|
||||
"Invalid method {resourcePath: GET,method: } specified"));
|
||||
}
|
||||
|
||||
/** A create request with a plan throttle and stage a:v1 throttling {@code methodKey}. */
|
||||
private static Map<String, Object> stageThrottle(String methodKey) {
|
||||
return Map.of("throttle", Map.of("burstLimit", 20, "rateLimit", 10), "apiStages", List.of(Map.of("apiId", "a",
|
||||
"stage", "v1", "throttle", Map.of(methodKey, Map.of("burstLimit", 5, "rateLimit", 2)))));
|
||||
}
|
||||
|
||||
// Floci does not check that the method exists, so keys AWS refuses for that reason are kept.
|
||||
@Test
|
||||
void aMethodKeyIsOnlyCheckedForHavingAMethod() {
|
||||
assertEquals(Map.of("//GET", new Throttle(5, 2.0)),
|
||||
UsagePlanLimits.fromRequest(stageThrottle("//GET")).apiStages().get(0).throttle());
|
||||
assertEquals(Map.of("/pets/GET/extra", new Throttle(5, 2.0)),
|
||||
UsagePlanLimits.fromRequest(stageThrottle("/pets/GET/extra")).apiStages().get(0).throttle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonNullReadsAsAbsent() {
|
||||
assertEquals(new Limits(List.of(), null, null),
|
||||
UsagePlanLimits.fromRequest(request("throttle", null, "quota", null, "apiStages", null)));
|
||||
assertEquals(List.of(new ApiStage("a", "v1")), UsagePlanLimits.fromRequest(
|
||||
request("apiStages", List.of(request("apiId", "a", "stage", "v1", "throttle", null)))).apiStages());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("refusedCreates")
|
||||
void createRefusesWhatApiGatewayRefuses(Map<String, Object> request, String code, int status, String message) {
|
||||
assertRefused(() -> UsagePlanLimits.fromRequest(request), code, status, message);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user