diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 80b62fb209..09d837706f 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -172,7 +172,8 @@ explicitly request values.
`DeleteApiKey` detaches the key from every usage plan before removing it, matching AWS. A usage plan key
stores its own copy of the key value, so without that sweep a deleted key would stay listed by
-`GetUsagePlanKeys` and keep being recognised on the data plane.
+`GetUsagePlanKeys` and keep being recognised on the data plane. `DeleteUsagePlan` drops the plan's keys
+the same way, so a plan recreated with the same pinned id starts with none.
`requestContext.identity.apiKey` is only populated when the `x-api-key` header matches a key that still
exists and has `enabled` set to `true`, so disabling a key through `UpdateApiKey` takes effect
@@ -183,6 +184,11 @@ deleted, or not bound to the stage by a usage plan, with `403` `{"message":"Forb
`x-amzn-ErrorType: ForbiddenException`, as AWS does. The header stays when the API customises its
`INVALID_API_KEY` gateway response.
+A request whose key is attached to the stage's usage plan is metered on every method of that stage,
+including methods without `apiKeyRequired`, and before request validation, as measured against AWS.
+An unknown key, or one outside the stage's plans, is not metered on a method that does not require a
+key. See [Usage plan enforcement](#usage-plan-enforcement).
+
#### API key source
A REST API's `apiKeySource` is set with `CreateRestApi`, a `replace /apiKeySource` patch on
@@ -379,6 +385,8 @@ This is what lets a browser read a `401`/`403`/`400` as such instead of as a COR
| Lambda authorizer fails or throws | `AUTHORIZER_FAILURE` | `AuthorizerConfigurationException` |
| Cognito authorizer gets no token, an invalid one, one from another pool, or one claiming none of the method's authorization scopes (`401 Unauthorized`) | `UNAUTHORIZED` | `UnauthorizedException` |
| Method with `apiKeyRequired` and no usable `x-api-key` (`403 Forbidden`) | `INVALID_API_KEY` | `ForbiddenException` |
+| Usage plan throttle refuses the key (`429 Too Many Requests`) | `THROTTLED` | `TooManyRequestsException` |
+| Usage plan quota for the period is used up (`429 Limit Exceeded`) | `QUOTA_EXCEEDED` | `LimitExceededException` |
| Request validator rejects a parameter / the body | `BAD_REQUEST_PARAMETERS` / `BAD_REQUEST_BODY` | `BadRequestException` |
| `passthroughBehavior` rejects the request `Content-Type` (`415`) | `UNSUPPORTED_MEDIA_TYPE` | `BadRequestException` |
| Missing or unresolvable integration or URI, MOCK template that does not render | `API_CONFIGURATION_ERROR` | `InternalServerErrorException` |
@@ -387,11 +395,10 @@ This is what lets a browser read a `401`/`403`/`400` as such instead of as a COR
A customised `statusCode` overrides the status Floci would otherwise send; the `x-amzn-ErrorType` stays, as on AWS.
A gateway response that maps its own `gatewayresponse.header.x-amzn-ErrorType` (that exact key) replaces it for
`BAD_REQUEST_PARAMETERS`, `BAD_REQUEST_BODY`, `UNSUPPORTED_MEDIA_TYPE`, `API_CONFIGURATION_ERROR` and
-`INTEGRATION_FAILURE`, and is sent ahead of it for the other types, as AWS does. Throttling, quota, request
-size and WAF answers are not produced on the execute plane, so
-`THROTTLED`, `QUOTA_EXCEEDED`, `REQUEST_TOO_LARGE` and `WAF_FILTERED` can be configured but never
-fire, and an `HTTP`/`HTTP_PROXY` backend's own status is relayed rather than treated as a gateway
-response.
+`INTEGRATION_FAILURE`, and is sent ahead of it for the other types, as AWS does. Request size and WAF
+answers are not produced on the execute plane, so `REQUEST_TOO_LARGE` and `WAF_FILTERED` can be
+configured but never fire, and an `HTTP`/`HTTP_PROXY` backend's own status is relayed rather than
+treated as a gateway response.
### Not Implemented
@@ -637,8 +644,8 @@ lists is a `ConflictException`. `AWS::ApiGateway::UsagePlan` maps its `ApiStages
in no plan or an unknown key. A blank `keyId` lists every plan, as on AWS. Every matching plan comes
back in one page.
-Floci does not check that a stage's API, stage or method exists, and does not enforce throttles or
-quotas.
+Floci does not check that a stage's API, stage or method exists. The plan's throttle and quota are
+enforced on the execute plane, see [Usage plan enforcement](#usage-plan-enforcement).
A `CreateUsagePlan` body member of the wrong JSON type is a `SerializationException` with API
Gateway's deserializer message, before anything else is validated. The message names the Java class
@@ -681,9 +688,32 @@ The lower bound is a deliberate divergence: real API Gateway answers `limit=0` a
an `InternalFailure`, which is a fault rather than a contract, so a page size below one is rejected
as a `BadRequestException` instead of reproducing a 500.
-**Both numbers are always zero.** Nothing meters requests per API key, so there is no use to report
-or to subtract from a plan's quota. Throttle settings and quotas are stored and returned but never
-enforced.
+`used` is the number of calls the key made through the plan's stages on that UTC day, and `remaining`
+is the quota limit minus the key's use from the start of the quota period through that day. A plan
+without a quota reports `[0, 0]` for every day, as AWS does. Floci lists every key attached to the
+plan, while AWS lists only the keys with usage in the range.
+
+### Usage plan enforcement
+
+A call with a key attached to the stage's usage plan is counted against that key, per plan and UTC
+day, across all stages of the plan. Counts are kept in the `apigateway-usage.json` store, so they
+follow the configured storage mode. Deleting the plan or the key drops its counts, so a plan or key
+recreated with the same id starts unused.
+
+- **Quota.** Once the key's use in the current period reaches `quota.limit`, the call is refused with
+ `429` `{"message":"Limit Exceeded"}` and `x-amzn-ErrorType: LimitExceededException`. A `DAY` period
+ starts at UTC midnight, a `WEEK` period on Sunday and a `MONTH` period on the 1st, each shifted by
+ `quota.offset` days. AWS bounds the offset to the period's length but does not document the anchor,
+ so the anchor is inferred.
+- **Throttle.** The plan's `throttle` is a token bucket per key that starts full at `burstLimit` and
+ refills at `rateLimit` requests per second. Buckets are held in memory, so a restart or an emulator
+ reset refills them. An empty bucket refuses the call with `429`
+ `{"message":"Too Many Requests"}` and `x-amzn-ErrorType: TooManyRequestsException`. AWS throttles on
+ a best-effort basis, so the exact moment a burst is cut off can differ. Per-method stage throttles
+ and stage or account level throttles are stored but not enforced.
+
+A refused call is not counted, and a call without a key, or with a key outside the stage's plans, is
+not metered.
### Usage Plan Tags and Custom IDs
diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java
index 6843d92480..b188d5050d 100644
--- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayController.java
@@ -977,11 +977,8 @@ public class ApiGatewayController {
*
*
Each pair is {@code [used, remaining]}, not {@code [used, quota]}: measured against real
* API Gateway, the second element is the quota limit minus the cumulative use so far in the
- * period. Both elements are {@code 0} here because the emulator does not meter requests per API
- * key, so there is no use to report or to subtract from a plan's quota. Once the execute path
- * counts per key, this method is where the count feeds in; until then a caller that sums the
- * used counts gets the same zero it already gets from an unsupported action, without having to
- * special-case a missing endpoint.
+ * period. The execute path counts each admitted call per key and UTC day, and a plan without a
+ * quota reports {@code [0, 0]}, as AWS does.
*/
@GET
@Path("/usageplans/{usagePlanId}/usage")
diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java
index 502843bdfb..bad9465fd1 100644
--- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java
+++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayExecuteController.java
@@ -510,6 +510,16 @@ public class ApiGatewayExecuteController {
if (method.isApiKeyRequired() && resolvedApiKey == null) {
return gatewayResponse(scope, GatewayResponseType.INVALID_API_KEY, 403, "Forbidden");
}
+ // Measured: a key of the stage's usage plan is metered on every method, whether or not it
+ // requires one, and before request validation, so a call that then fails it still counts.
+ if (resolvedApiKey != null) {
+ GatewayResponseType refusal = apiGatewayService.meterApiKeyCall(region, resolvedApiKey.usagePlanId(),
+ resolvedApiKey.id());
+ if (refusal != null) {
+ return gatewayResponse(scope, refusal, 429,
+ refusal == GatewayResponseType.THROTTLED ? "Too Many Requests" : "Limit Exceeded");
+ }
+ }
// 2. Request validation
Response validationResponse = validateRequest(scope, region, apiId, method, headers, uriInfo, body);
@@ -1426,7 +1436,7 @@ public class ApiGatewayExecuteController {
if (apiGatewayService.findApiKey(region, planKey.getId())
.filter(ApiKey::isEnabled)
.isPresent()) {
- return new ResolvedApiKey(planKey.getId(), planKey.getValue());
+ return new ResolvedApiKey(planKey.getId(), planKey.getValue(), plan.getId());
}
}
}
@@ -1436,9 +1446,9 @@ public class ApiGatewayExecuteController {
/**
* The id and value of an API key matched to a request via a usage plan. A REQUEST authorizer
* resolves {@code GetApiKey} by id (event.requestContext.identity.apiKeyId), while the key
- * value is carried separately under identity.apiKey.
+ * value is carried separately under identity.apiKey. The usage plan is the one metering the call.
*/
- private record ResolvedApiKey(String id, String value) {}
+ private record ResolvedApiKey(String id, String value, String usagePlanId) {}
private String buildMethodArn(String region, String apiId, String stageName, String httpMethod, String requestPath) {
String normalizedPath = requestPath == null ? "" : requestPath.replaceFirst("^/", "");
@@ -4141,6 +4151,8 @@ public class ApiGatewayExecuteController {
case AUTHORIZER_FAILURE, AUTHORIZER_CONFIGURATION_ERROR -> "AuthorizerConfigurationException";
case BAD_REQUEST_PARAMETERS, BAD_REQUEST_BODY, UNSUPPORTED_MEDIA_TYPE -> "BadRequestException";
case API_CONFIGURATION_ERROR, INTEGRATION_FAILURE -> "InternalServerErrorException";
+ case THROTTLED -> "TooManyRequestsException";
+ case QUOTA_EXCEEDED -> "LimitExceededException";
default -> null;
};
}
diff --git a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java
index cb367a0650..2bb95675ce 100644
--- a/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/floci/aws/services/apigateway/ApiGatewayService.java
@@ -17,6 +17,7 @@ import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.CloudFrontEdgeDomain;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.ReservedTags;
+import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.resource.ExplorerResource;
import io.floci.aws.core.resource.ResourceProvider;
@@ -24,6 +25,7 @@ import io.floci.aws.core.resource.SupportedResourceType;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
+import io.floci.aws.core.storage.WriteProfile;
import io.floci.aws.services.apigateway.model.Account;
import io.floci.aws.services.apigateway.model.ApiGatewayResource;
import io.floci.aws.services.apigateway.model.ApiKey;
@@ -67,10 +69,14 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.time.DayOfWeek;
+import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
+import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
-import java.time.temporal.ChronoUnit;
+import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
@@ -90,7 +96,7 @@ import java.util.function.Predicate;
import java.util.regex.Pattern;
@ApplicationScoped
-public class ApiGatewayService implements ResourceProvider {
+public class ApiGatewayService implements ResourceProvider, Resettable {
/** The only partition where API Gateway offers edge-optimized APIs and custom domain names. */
private static final Set EDGE_OPTIMIZED_PARTITIONS = Set.of("aws");
@@ -147,6 +153,13 @@ public class ApiGatewayService implements ResourceProvider {
* be undone.
*/
private final Object usagePlanLock = new Object();
+ /** Calls admitted per UTC day, keyed region::usagePlanId::keyId::yyyy-MM-dd. */
+ private final AccountAwareStorageBackend usageStore;
+ /** The usage plan throttles' token buckets, keyed account::region::usagePlanId::keyId; in memory only. */
+ private final Map throttleBuckets = new HashMap<>();
+ /** Guards the usage counts and the token buckets: metering a call is a read-modify-write of both. */
+ private final Object usageLock = new Object();
+ private final Clock clock;
private final TlsCertificateManager certificateManager;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@@ -186,17 +199,18 @@ public class ApiGatewayService implements ResourceProvider {
ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
TlsCertificateManager certificateManager, RegionResolver regionResolver) {
this(storageFactory, config, certificateManager, regionResolver,
- new ApiGatewayV2Service(storageFactory, config, regionResolver));
+ new ApiGatewayV2Service(storageFactory, config, regionResolver), Clock.systemUTC());
}
@Inject
public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,
TlsCertificateManager certificateManager, RegionResolver regionResolver,
- ApiGatewayV2Service apiGatewayV2Service) {
+ ApiGatewayV2Service apiGatewayV2Service, Clock clock) {
this.certificateManager = certificateManager;
this.config = config;
this.regionResolver = regionResolver;
this.apiGatewayV2Service = apiGatewayV2Service;
+ this.clock = clock;
this.apiStore = storageFactory.create("apigateway", "apigateway-apis.json",
new TypeReference<>() {
});
@@ -248,6 +262,9 @@ public class ApiGatewayService implements ResourceProvider {
this.basePathMappingStore = storageFactory.create("apigateway", "apigateway-mappings.json",
new TypeReference<>() {
});
+ // Every metered call writes a count, so under persistent mode the store is journaled.
+ this.usageStore = storageFactory.create("apigateway", "apigateway-usage.json",
+ new TypeReference