mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(apigateway): count usage plan calls per key and enforce quota and throttle (#7665)
This commit is contained in:
1 parent
a1f5b9b21f
commit
c44a8722f8
10 files changed
+793
-66
No files matched your search
@@ -101,6 +101,7 @@ class ApiGatewayDeploymentModelTest {
|
||||
private ApiGatewayService service(Path directory) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.storage().persistentPath()).thenReturn(directory.toString());
|
||||
when(config.storage().wal().compactionIntervalMs()).thenReturn(3_600_000L);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
|
||||
when(access.storageMode(anyString())).thenReturn("persistent");
|
||||
|
||||
+3
-2
@@ -21,8 +21,9 @@ import static org.hamcrest.Matchers.nullValue;
|
||||
* no {@code position} when there is no further page.
|
||||
*
|
||||
* <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, so there is no use to report or to subtract from a plan's quota.
|
||||
* second element is the quota limit minus cumulative use. The plans here have no quota and see no
|
||||
* calls, so every pair is zero; metered counts are covered by
|
||||
* {@link ApiGatewayUsageMeteringIntegrationTest}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ApiGatewayGetUsageIntegrationTest {
|
||||
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
package io.floci.aws.services.apigateway;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* Usage plan metering on the execute-api data plane, measured on a REST API in eu-west-1: a call made
|
||||
* with a key of the stage's usage plan counts toward the key's quota on every method, even when it then
|
||||
* fails request validation, a refused call does not, and the plan's quota and throttle answer 429 with
|
||||
* the AWS default gateway responses.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class ApiGatewayUsageMeteringIntegrationTest {
|
||||
|
||||
private static String apiId;
|
||||
private static String quotaPlanId;
|
||||
private static String quotaKeyId;
|
||||
private static String quotaKeyValue;
|
||||
private static String throttlePlanId;
|
||||
private static String throttleKeyId;
|
||||
private static String throttleKeyValue;
|
||||
private static String validatedPlanId;
|
||||
private static String validatedKeyId;
|
||||
private static String validatedKeyValue;
|
||||
|
||||
@Inject
|
||||
Clock clock;
|
||||
|
||||
@Test @Order(1)
|
||||
void setupApiPlansAndKeys() {
|
||||
apiId = given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"usage-metering-api\"}")
|
||||
.when().post("/restapis")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
String rootId = given().when().get("/restapis/" + apiId + "/resources")
|
||||
.then().statusCode(200)
|
||||
.extract().path("item[0].id");
|
||||
mockMethod(rootId, "secret", "\"apiKeyRequired\":true");
|
||||
mockMethod(rootId, "open", "\"apiKeyRequired\":false");
|
||||
String validatorId = given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"params\",\"validateRequestParameters\":true}")
|
||||
.when().post("/restapis/" + apiId + "/requestvalidators")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
mockMethod(rootId, "checked", "\"requestValidatorId\":\"" + validatorId
|
||||
+ "\",\"requestParameters\":{\"method.request.querystring.q\":true}");
|
||||
|
||||
String deploymentId = given().contentType(ContentType.JSON)
|
||||
.body("{}")
|
||||
.when().post("/restapis/" + apiId + "/deployments")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
for (String stage : List.of("prod", "throttled", "validated")) {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"stageName\":\"" + stage + "\",\"deploymentId\":\"" + deploymentId + "\"}")
|
||||
.when().post("/restapis/" + apiId + "/stages")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
quotaPlanId = plan("prod", "\"quota\":{\"limit\":2,\"period\":\"DAY\"}");
|
||||
quotaKeyId = keyOn(quotaPlanId);
|
||||
quotaKeyValue = keyValue(quotaKeyId);
|
||||
throttlePlanId = plan("throttled", "\"throttle\":{\"burstLimit\":1,\"rateLimit\":0}");
|
||||
throttleKeyId = keyOn(throttlePlanId);
|
||||
throttleKeyValue = keyValue(throttleKeyId);
|
||||
validatedPlanId = plan("validated", "\"quota\":{\"limit\":1,\"period\":\"DAY\"}");
|
||||
validatedKeyId = keyOn(validatedPlanId);
|
||||
validatedKeyValue = keyValue(validatedKeyId);
|
||||
}
|
||||
|
||||
// Measured: a key of the stage's plan is metered on a method that does not require one, too.
|
||||
@Test @Order(2)
|
||||
void quotaCountsEveryMethodAndRefusesTheCallOverTheLimit() {
|
||||
call("prod", "secret", quotaKeyValue).then().statusCode(200);
|
||||
assertUsage(quotaPlanId, quotaKeyId, 1, 1);
|
||||
call("prod", "open", quotaKeyValue).then().statusCode(200);
|
||||
assertUsage(quotaPlanId, quotaKeyId, 2, 0);
|
||||
|
||||
call("prod", "secret", quotaKeyValue).then().statusCode(429)
|
||||
.header("x-amzn-ErrorType", "LimitExceededException")
|
||||
.body("message", equalTo("Limit Exceeded"));
|
||||
assertUsage(quotaPlanId, quotaKeyId, 2, 0);
|
||||
}
|
||||
|
||||
@Test @Order(3)
|
||||
void callWithoutAKeyOfThePlanIsNotMetered() {
|
||||
call("prod", "open", null).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test @Order(4)
|
||||
void throttleRefusesTheCallOverTheBurst() {
|
||||
call("throttled", "open", throttleKeyValue).then().statusCode(200);
|
||||
call("throttled", "open", throttleKeyValue).then().statusCode(429)
|
||||
.header("x-amzn-ErrorType", "TooManyRequestsException")
|
||||
.body("message", equalTo("Too Many Requests"));
|
||||
// Measured: a plan without a quota reports [0, 0].
|
||||
assertUsage(throttlePlanId, throttleKeyId, 0, 0);
|
||||
}
|
||||
|
||||
// Measured: the key is metered before request validation, so a call that fails it counts and an
|
||||
// exhausted key is refused with 429 rather than 400.
|
||||
@Test @Order(5)
|
||||
void callThatFailsValidationCountsAndAnExhaustedKeyIsRefusedBeforeValidation() {
|
||||
call("validated", "checked", validatedKeyValue).then().statusCode(400);
|
||||
assertUsage(validatedPlanId, validatedKeyId, 1, 0);
|
||||
|
||||
call("validated", "checked", validatedKeyValue).then().statusCode(429)
|
||||
.body("message", equalTo("Limit Exceeded"));
|
||||
assertUsage(validatedPlanId, validatedKeyId, 1, 0);
|
||||
}
|
||||
|
||||
// The refusals are gateway responses, so the API's own QUOTA_EXCEEDED, or its DEFAULT_4XX for a
|
||||
// type it did not customise, shapes the 429.
|
||||
@Test @Order(6)
|
||||
void refusalsAnswerWithTheApisCustomisedGatewayResponses() {
|
||||
customiseGatewayResponse("QUOTA_EXCEEDED", "quota spent");
|
||||
customiseGatewayResponse("DEFAULT_4XX", "slow down");
|
||||
|
||||
call("prod", "secret", quotaKeyValue).then().statusCode(429)
|
||||
.header("Access-Control-Allow-Origin", "*")
|
||||
.body("message", equalTo("quota spent"));
|
||||
call("throttled", "open", throttleKeyValue).then().statusCode(429)
|
||||
.header("Access-Control-Allow-Origin", "*")
|
||||
.body("message", equalTo("slow down"));
|
||||
}
|
||||
|
||||
private void customiseGatewayResponse(String type, String message) {
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"responseParameters\":{\"gatewayresponse.header.Access-Control-Allow-Origin\":\"'*'\"},"
|
||||
+ "\"responseTemplates\":{\"application/json\":\"{\\\"message\\\":\\\"" + message + "\\\"}\"}}")
|
||||
.when().put("/restapis/" + apiId + "/gatewayresponses/" + type)
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
private void mockMethod(String parentId, String pathPart, String methodFields) {
|
||||
String resourceId = given().contentType(ContentType.JSON)
|
||||
.body("{\"pathPart\":\"" + pathPart + "\"}")
|
||||
.when().post("/restapis/" + apiId + "/resources/" + parentId)
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"authorizationType\":\"NONE\"," + methodFields + "}")
|
||||
.when().put(method)
|
||||
.then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{}")
|
||||
.when().put(method + "/responses/200")
|
||||
.then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
|
||||
.when().put(method + "/integration")
|
||||
.then().statusCode(201);
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{}\"}}")
|
||||
.when().put(method + "/integration/responses/200")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
private String plan(String stage, String limits) {
|
||||
return given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"metering-" + stage + "\",\"apiStages\":[{\"apiId\":\"" + apiId
|
||||
+ "\",\"stage\":\"" + stage + "\"}]," + limits + "}")
|
||||
.when().post("/usageplans")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
}
|
||||
|
||||
private static String keyOn(String planId) {
|
||||
String keyId = given().contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"metering-key-" + planId + "\",\"enabled\":true}")
|
||||
.when().post("/apikeys")
|
||||
.then().statusCode(201)
|
||||
.extract().path("id");
|
||||
given().contentType(ContentType.JSON)
|
||||
.body("{\"keyId\":\"" + keyId + "\",\"keyType\":\"API_KEY\"}")
|
||||
.when().post("/usageplans/" + planId + "/keys")
|
||||
.then().statusCode(201);
|
||||
return keyId;
|
||||
}
|
||||
|
||||
private static String keyValue(String keyId) {
|
||||
return given().when().get("/apikeys/" + keyId + "?includeValue=true")
|
||||
.then().statusCode(200)
|
||||
.extract().path("value");
|
||||
}
|
||||
|
||||
private static Response call(String stage, String path, String keyValue) {
|
||||
RequestSpecification request = given();
|
||||
if (keyValue != null) {
|
||||
request.header("x-api-key", keyValue);
|
||||
}
|
||||
return request.when().get("/execute-api/" + apiId + "/" + stage + "/" + path);
|
||||
}
|
||||
|
||||
// API key ids can start with a digit, which a dotted GPath parses as a number.
|
||||
private void assertUsage(String planId, String keyId, int used, int remaining) {
|
||||
String today = LocalDate.now(clock).toString();
|
||||
given().when().get("/usageplans/" + planId + "/usage?startDate=" + today + "&endDate=" + today)
|
||||
.then().statusCode(200)
|
||||
.body("values['" + keyId + "'][0][0]", equalTo(used))
|
||||
.body("values['" + keyId + "'][0][1]", equalTo(remaining));
|
||||
}
|
||||
}
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
package io.floci.aws.services.apigateway;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.TlsCertificateManager;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.apigateway.model.GatewayResponseType;
|
||||
import io.floci.aws.services.apigateway.model.UsagePlan;
|
||||
import io.floci.aws.services.apigateway.model.UsagePlanKey;
|
||||
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import io.floci.aws.testing.ManualClock;
|
||||
import io.floci.aws.testing.StorageFactories;
|
||||
import io.floci.aws.testing.ThreadStates;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
|
||||
class ApiGatewayUsageMeteringServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
// A Friday.
|
||||
private final ManualClock clock = new ManualClock(Instant.parse("2026-11-06T10:00:00Z"));
|
||||
private final RegionResolver regionResolver = spy(new RegionResolver(REGION, ACCOUNT));
|
||||
private ApiGatewayService service = service(new InMemoryStorageFactory(ACCOUNT));
|
||||
|
||||
private ApiGatewayService service(StorageFactory storageFactory) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
return new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class), regionResolver,
|
||||
new ApiGatewayV2Service(storageFactory, config, regionResolver), clock);
|
||||
}
|
||||
|
||||
private String plan(Map<String, Object> limits) {
|
||||
Map<String, Object> request = new HashMap<>(limits);
|
||||
request.put("name", "metered");
|
||||
return service.createUsagePlan(REGION, request).getId();
|
||||
}
|
||||
|
||||
private String keyOn(String planId) {
|
||||
String keyId = service.createApiKey(REGION, Map.of("name", "metered-key", "enabled", true)).getId();
|
||||
service.createUsagePlanKey(REGION, planId, Map.of("keyId", keyId, "keyType", "API_KEY"));
|
||||
return keyId;
|
||||
}
|
||||
|
||||
private List<List<Long>> usage(String planId, String keyId, String from, String to) {
|
||||
return service.getUsage(REGION, planId, from, to, keyId, null, null).items().get(keyId).stream()
|
||||
.map(pair -> List.of(pair[0], pair[1]))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void dailyQuotaAdmitsTheLimitRefusesTheRestAndResetsAtUtcMidnight() {
|
||||
String planId = plan(Map.of("quota", Map.of("limit", 2, "period", "DAY")));
|
||||
String keyId = keyOn(planId);
|
||||
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(List.of(List.of(1L, 1L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(GatewayResponseType.QUOTA_EXCEEDED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
// Measured: a refused call is not counted.
|
||||
assertEquals(List.of(List.of(2L, 0L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
|
||||
clock.advance(Duration.ofHours(14));
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(List.of(List.of(2L, 0L), List.of(1L, 1L)), usage(planId, keyId, "2026-11-06", "2026-11-07"));
|
||||
}
|
||||
|
||||
// Measured: remaining is the limit minus the use from the start of the period through that day,
|
||||
// and a day of the previous period reports the full limit.
|
||||
@Test
|
||||
void weeklyRemainingIsCumulativeOverThePeriod() {
|
||||
String planId = plan(Map.of("quota", Map.of("limit", 5, "period", "WEEK")));
|
||||
String keyId = keyOn(planId);
|
||||
|
||||
clock.advance(Duration.ofDays(-1));
|
||||
service.meterApiKeyCall(REGION, planId, keyId);
|
||||
service.meterApiKeyCall(REGION, planId, keyId);
|
||||
clock.advance(Duration.ofDays(1));
|
||||
service.meterApiKeyCall(REGION, planId, keyId);
|
||||
|
||||
assertEquals(List.of(List.of(0L, 5L), List.of(0L, 5L), List.of(0L, 5L), List.of(0L, 5L),
|
||||
List.of(0L, 5L), List.of(2L, 3L), List.of(1L, 2L)),
|
||||
usage(planId, keyId, "2026-10-31", "2026-11-06"));
|
||||
assertEquals(List.of(List.of(1L, 2L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
}
|
||||
|
||||
// Measured: a plan without a quota reports [0, 0] for a key it admitted.
|
||||
@Test
|
||||
void planWithoutQuotaNeverRefusesAndReportsZero() {
|
||||
String planId = plan(Map.of());
|
||||
String keyId = keyOn(planId);
|
||||
|
||||
for (int call = 0; call < 3; call++) {
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
}
|
||||
assertEquals(List.of(List.of(0L, 0L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttleIsATokenBucketOfBurstSizeRefilledAtTheRate() {
|
||||
String planId = plan(Map.of("throttle", Map.of("burstLimit", 2, "rateLimit", 1.0)));
|
||||
String keyId = keyOn(planId);
|
||||
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(GatewayResponseType.THROTTLED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(GatewayResponseType.THROTTLED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttledCallIsNotCountedAgainstTheQuota() {
|
||||
String planId = plan(Map.of("throttle", Map.of("burstLimit", 1, "rateLimit", 0.0),
|
||||
"quota", Map.of("limit", 5, "period", "DAY")));
|
||||
String keyId = keyOn(planId);
|
||||
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(GatewayResponseType.THROTTLED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(List.of(List.of(1L, 4L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttleBucketsAreSeparatePerAccount() {
|
||||
String planId = plan(Map.of("throttle", Map.of("burstLimit", 1, "rateLimit", 0.0)));
|
||||
String keyId = keyOn(planId);
|
||||
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
doReturn("111111111111").when(regionResolver).getAccountId();
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
}
|
||||
|
||||
// An emulator reset wipes the stores and then calls clear(), which takes the in-memory buckets with them.
|
||||
@Test
|
||||
void resetRefillsTheThrottleBuckets() {
|
||||
String planId = plan(Map.of("throttle", Map.of("burstLimit", 1, "rateLimit", 0.0)));
|
||||
String keyId = keyOn(planId);
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(GatewayResponseType.THROTTLED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
|
||||
service.clear();
|
||||
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void quotaUseSurvivesARestart(String mode, @TempDir Path directory) {
|
||||
StorageFactory first = StorageFactories.open(directory, mode, ACCOUNT);
|
||||
String planId;
|
||||
String keyId;
|
||||
try {
|
||||
service = service(first);
|
||||
planId = plan(Map.of("quota", Map.of("limit", 1, "period", "DAY")));
|
||||
keyId = keyOn(planId);
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
} finally {
|
||||
first.shutdownAll();
|
||||
}
|
||||
|
||||
StorageFactory second = StorageFactories.open(directory, mode, ACCOUNT);
|
||||
try {
|
||||
service = service(second);
|
||||
assertEquals(List.of(List.of(1L, 0L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
assertEquals(GatewayResponseType.QUOTA_EXCEEDED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
} finally {
|
||||
second.shutdownAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttleRefillKeepsTimeBelowAMillisecond() {
|
||||
String planId = plan(Map.of("throttle", Map.of("burstLimit", 1, "rateLimit", 1.0)));
|
||||
String keyId = keyOn(planId);
|
||||
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
int admitted = 0;
|
||||
for (int attempt = 0; attempt < 2_100; attempt++) {
|
||||
clock.advance(Duration.ofNanos(500_000));
|
||||
if (service.meterApiKeyCall(REGION, planId, keyId) == null) {
|
||||
admitted++;
|
||||
}
|
||||
}
|
||||
assertEquals(1, admitted);
|
||||
}
|
||||
|
||||
@Test
|
||||
void clockSteppingBackDoesNotRefillTheThrottle() {
|
||||
String planId = plan(Map.of("throttle", Map.of("burstLimit", 1, "rateLimit", 1.0)));
|
||||
String keyId = keyOn(planId);
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
|
||||
clock.advance(Duration.ofSeconds(-1));
|
||||
assertEquals(GatewayResponseType.THROTTLED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
|
||||
assertEquals(GatewayResponseType.THROTTLED, service.meterApiKeyCall(REGION, planId, keyId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void planRecreatedWithTheIdOfADeletedOneStartsWithNoUse() {
|
||||
Map<String, Object> request = Map.of("name", "pinned", "quota", Map.of("limit", 1, "period", "DAY"),
|
||||
"tags", Map.of("floci:override-id", "pinned-plan"));
|
||||
String planId = service.createUsagePlan(REGION, request).getId();
|
||||
String keyId = keyOn(planId);
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
|
||||
service.deleteUsagePlan(REGION, planId);
|
||||
service.createUsagePlan(REGION, request);
|
||||
|
||||
assertEquals(List.of(), service.getUsagePlanKeys(REGION, planId));
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
service.createUsagePlanKey(REGION, planId, Map.of("keyId", keyId, "keyType", "API_KEY"));
|
||||
assertEquals(List.of(List.of(0L, 1L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void keyAddedWhileItsPlanOrItselfIsDeletedIsNotLeftBehind(boolean deleteKey) {
|
||||
String[] ids = new String[2];
|
||||
AtomicReference<Thread> deleter = new AtomicReference<>();
|
||||
CompletableFuture<?>[] deletion = new CompletableFuture<?>[1];
|
||||
InMemoryStorage<String, UsagePlanKey> keys = new InMemoryStorage<>() {
|
||||
@Override
|
||||
public void put(String key, UsagePlanKey value) {
|
||||
deletion[0] = CompletableFuture.runAsync(() -> {
|
||||
deleter.set(Thread.currentThread());
|
||||
if (deleteKey) {
|
||||
service.deleteApiKey(REGION, ids[1]);
|
||||
} else {
|
||||
service.deleteUsagePlan(REGION, ids[0]);
|
||||
}
|
||||
});
|
||||
// The deletion blocks behind the plan lock this write holds; without it, it sweeps first.
|
||||
try {
|
||||
ThreadStates.awaitBlockedOrDone(deleter, deletion[0]);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
super.put(key, value);
|
||||
}
|
||||
};
|
||||
service = service(new InMemoryStorageFactory(ACCOUNT).withStore("apigateway-usageplankeys.json", keys));
|
||||
ids[0] = plan(Map.of());
|
||||
ids[1] = service.createApiKey(REGION, Map.of("name", "racing", "enabled", true)).getId();
|
||||
|
||||
service.createUsagePlanKey(REGION, ids[0], Map.of("keyId", ids[1], "keyType", "API_KEY"));
|
||||
deletion[0].join();
|
||||
|
||||
assertEquals(List.of(), service.getUsagePlanKeys(REGION, ids[0]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void callResolvedBeforeItsKeyWasDeletedLeavesNoUseBehind() {
|
||||
String planId = plan(Map.of("quota", Map.of("limit", 1, "period", "DAY")));
|
||||
Map<String, Object> keyRequest = Map.of("name", "fixed", "enabled", true,
|
||||
"value", "fixed-value-0123456789", "generateDistinctId", false);
|
||||
String keyId = service.createApiKey(REGION, keyRequest).getId();
|
||||
service.createUsagePlanKey(REGION, planId, Map.of("keyId", keyId, "keyType", "API_KEY"));
|
||||
|
||||
service.deleteApiKey(REGION, keyId);
|
||||
service.meterApiKeyCall(REGION, planId, keyId);
|
||||
service.createApiKey(REGION, keyRequest);
|
||||
service.createUsagePlanKey(REGION, planId, Map.of("keyId", keyId, "keyType", "API_KEY"));
|
||||
|
||||
assertEquals(List.of(List.of(0L, 1L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyRecreatedWithTheIdOfADeletedOneStartsWithNoUse() {
|
||||
String planId = plan(Map.of("quota", Map.of("limit", 1, "period", "DAY"),
|
||||
"throttle", Map.of("burstLimit", 1, "rateLimit", 0.0)));
|
||||
Map<String, Object> keyRequest = Map.of("name", "fixed", "enabled", true,
|
||||
"value", "fixed-value-0123456789", "generateDistinctId", false);
|
||||
String keyId = service.createApiKey(REGION, keyRequest).getId();
|
||||
service.createUsagePlanKey(REGION, planId, Map.of("keyId", keyId, "keyType", "API_KEY"));
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
String otherKeyId = keyOn(planId);
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, otherKeyId));
|
||||
|
||||
service.deleteApiKey(REGION, keyId);
|
||||
service.createApiKey(REGION, keyRequest);
|
||||
service.createUsagePlanKey(REGION, planId, Map.of("keyId", keyId, "keyType", "API_KEY"));
|
||||
|
||||
assertEquals(List.of(List.of(0L, 1L)), usage(planId, keyId, "2026-11-06", "2026-11-06"));
|
||||
assertNull(service.meterApiKeyCall(REGION, planId, keyId));
|
||||
assertEquals(List.of(List.of(1L, 0L)), usage(planId, otherKeyId, "2026-11-06", "2026-11-06"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotaPeriodStartsOnTheDaySundayOrFirstShiftedByTheOffset() {
|
||||
LocalDate friday = LocalDate.parse("2026-11-06");
|
||||
assertEquals(friday, ApiGatewayService.quotaPeriodStart(friday, new UsagePlan.Quota(1, 0, "DAY")));
|
||||
assertEquals(LocalDate.parse("2026-11-01"),
|
||||
ApiGatewayService.quotaPeriodStart(friday, new UsagePlan.Quota(1, 0, "WEEK")));
|
||||
assertEquals(friday, ApiGatewayService.quotaPeriodStart(friday, new UsagePlan.Quota(1, 5, "WEEK")));
|
||||
assertEquals(LocalDate.parse("2026-10-31"),
|
||||
ApiGatewayService.quotaPeriodStart(friday, new UsagePlan.Quota(1, 6, "WEEK")));
|
||||
assertEquals(LocalDate.parse("2026-11-01"),
|
||||
ApiGatewayService.quotaPeriodStart(friday, new UsagePlan.Quota(1, 0, "MONTH")));
|
||||
assertEquals(LocalDate.parse("2026-10-11"),
|
||||
ApiGatewayService.quotaPeriodStart(friday, new UsagePlan.Quota(1, 10, "MONTH")));
|
||||
assertEquals(LocalDate.parse("2026-11-11"), ApiGatewayService.quotaPeriodStart(
|
||||
LocalDate.parse("2026-11-11"), new UsagePlan.Quota(1, 10, "MONTH")));
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,11 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.TlsCertificateManager;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.apigateway.model.UsagePlan;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
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;
|
||||
@@ -28,11 +26,8 @@ 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.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 {
|
||||
|
||||
@@ -41,12 +36,8 @@ class ApiGatewayUsagePlanServiceTest {
|
||||
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),
|
||||
return new ApiGatewayService(new InMemoryStorageFactory(ACCOUNT),
|
||||
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
|
||||
mock(TlsCertificateManager.class), new RegionResolver(REGION, ACCOUNT));
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -12,6 +12,7 @@ import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -60,7 +61,7 @@ class ApiGatewayV2ApiMappingServiceTest {
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
v2Service = new ApiGatewayV2Service(storageFactory, config, regionResolver);
|
||||
service = new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class), regionResolver,
|
||||
v2Service);
|
||||
v2Service, Clock.systemUTC());
|
||||
}
|
||||
|
||||
private void v2Domain(String name) {
|
||||
|
||||
Reference in new issue
Block a user