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>() {}, WriteProfile.APPEND_HEAVY); } // ──────────────────────────── Account ──────────────────────────── @@ -1454,14 +1471,18 @@ public class ApiGatewayService implements ResourceProvider { /** * Deleting a key detaches it from every usage plan, matching AWS. Usage plan keys hold their own * copy of the key value, so leaving the associations behind would keep a deleted key working as a - * credential on the data plane and keep it listed by GetUsagePlanKeys. + * credential on the data plane and keep it listed by GetUsagePlanKeys. Under the plan lock, so + * CreateUsagePlanKey cannot attach the key after the sweep. */ public void deleteApiKey(String region, String apiKeyId) { - getApiKey(region, apiKeyId); - for (UsagePlan plan : getUsagePlans(region)) { - usagePlanKeyStore.delete(usagePlanKeyPathKey(region, plan.getId(), apiKeyId)); + synchronized (usagePlanLock) { + getApiKey(region, apiKeyId); + for (UsagePlan plan : getUsagePlans(region)) { + usagePlanKeyStore.delete(usagePlanKeyPathKey(region, plan.getId(), apiKeyId)); + } + forgetUsage(meterKey -> meterKey.startsWith(region + "::") && meterKey.endsWith("::" + apiKeyId)); + apiKeyStore.delete(apiKeyGlobalKey(region, apiKeyId)); } - apiKeyStore.delete(apiKeyGlobalKey(region, apiKeyId)); } public ApiKey updateApiKey(String region, String apiKeyId, List> patchOperations) { @@ -1654,10 +1675,14 @@ public class ApiGatewayService implements ResourceProvider { .toList(); } + /** Its key associations go with it, or a plan recreated with its id would inherit the old keys. */ public void deleteUsagePlan(String region, String usagePlanId) { synchronized (usagePlanLock) { getUsagePlan(region, usagePlanId); usagePlanStore.delete(usagePlanKey(region, usagePlanId)); + String prefix = region + "::" + usagePlanId + "::"; + usagePlanKeyStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(usagePlanKeyStore::delete); + forgetUsage(meterKey -> meterKey.startsWith(prefix)); } } @@ -1722,22 +1747,25 @@ public class ApiGatewayService implements ResourceProvider { // ──────────────────────────── Usage Plan Keys ──────────────────────────── + /** Under the plan lock, so a key cannot be written after DeleteUsagePlan or DeleteApiKey swept it. */ public UsagePlanKey createUsagePlanKey(String region, String usagePlanId, Map request) { - getUsagePlan(region, usagePlanId); - String keyId = (String) request.get("keyId"); - String keyType = (String) request.get("keyType"); + synchronized (usagePlanLock) { + getUsagePlan(region, usagePlanId); + String keyId = (String) request.get("keyId"); + String keyType = (String) request.get("keyType"); - ApiKey apiKey = getApiKey(region, keyId); + ApiKey apiKey = getApiKey(region, keyId); - UsagePlanKey usagePlanKey = new UsagePlanKey(); - usagePlanKey.setId(apiKey.getId()); - usagePlanKey.setName(apiKey.getName()); - usagePlanKey.setType(keyType); - usagePlanKey.setValue(apiKey.getValue()); + UsagePlanKey usagePlanKey = new UsagePlanKey(); + usagePlanKey.setId(apiKey.getId()); + usagePlanKey.setName(apiKey.getName()); + usagePlanKey.setType(keyType); + usagePlanKey.setValue(apiKey.getValue()); - usagePlanKeyStore.put(usagePlanKeyPathKey(region, usagePlanId, keyId), usagePlanKey); - LOG.infov("Created Usage Plan Key {0} for Usage Plan {1}", keyId, usagePlanId); - return usagePlanKey; + usagePlanKeyStore.put(usagePlanKeyPathKey(region, usagePlanId, keyId), usagePlanKey); + LOG.infov("Created Usage Plan Key {0} for Usage Plan {1}", keyId, usagePlanId); + return usagePlanKey; + } } public UsagePlanKey getUsagePlanKey(String region, String usagePlanId, String keyId) { @@ -1753,21 +1781,21 @@ public class ApiGatewayService implements ResourceProvider { * {@code [used, remaining]} pair per day of the inclusive range. {@code position} is absent * when there is no further page, which is what stops a caller's pagination loop. * - *

Both numbers are zero. Nothing counts requests per API key, so there is no - * use to report or to subtract from a plan's quota. Counting on the execute path is the piece - * still missing; this method is where it would surface. + *

{@code used} is what {@link #meterApiKeyCall} admitted that day and {@code remaining} the + * quota limit minus the use from the start of that day's quota period through the day, so a day + * nothing was called on still reports the limit left. A plan without a quota reports + * {@code [0, 0]}, as AWS does. */ public UsageReport getUsage(String region, String usagePlanId, String startDate, String endDate, String keyId, Integer limit, String position) { // Resolving the plan first gives the same NotFoundException an unknown id gets on AWS. - getUsagePlan(region, usagePlanId); + UsagePlan.Quota quota = getUsagePlan(region, usagePlanId).getQuota(); LocalDate start = parseUsageDate(startDate, "startDate"); LocalDate end = parseUsageDate(endDate, "endDate"); if (end.isBefore(start)) { throw new AwsException("BadRequestException", "Usage end date must be after start date", 400); } - int days = (int) ChronoUnit.DAYS.between(start, end) + 1; int pageSize = resolveUsageLimit(limit); List keys = getUsagePlanKeys(region, usagePlanId).stream() @@ -1798,19 +1826,33 @@ public class ApiGatewayService implements ResourceProvider { boolean more = from + pageSize < keys.size(); Map> items = new LinkedHashMap<>(); - for (UsagePlanKey key : page) { - List perDay = new ArrayList<>(); - for (int day = 0; day < days; day++) { - // [used, remaining]: nothing is metered, so there is no use to report or subtract from a quota. - perDay.add(new long[] {0L, 0L}); + // Under the metering lock, so a pair never mixes counts from before and after a call. + synchronized (usageLock) { + for (UsagePlanKey key : page) { + items.put(key.getId(), quota == null + ? start.datesUntil(end.plusDays(1)).map(day -> new long[] {0L, 0L}).toList() + : usagePerDay(usagePlanKeyPathKey(region, usagePlanId, key.getId()), start, end, quota)); } - items.put(key.getId(), perDay); } // A token only when another page exists; its absence is what ends a caller's loop. String next = more && !page.isEmpty() ? page.get(page.size() - 1).getId() : null; return new UsageReport(usagePlanId, start.toString(), end.toString(), items, next); } + /** One pass from the start of {@code start}'s quota period, carrying the period's use from day to day. */ + private List usagePerDay(String meterKey, LocalDate start, LocalDate end, UsagePlan.Quota quota) { + List perDay = new ArrayList<>(); + long periodUsed = 0L; + for (LocalDate day = quotaPeriodStart(start, quota); !day.isAfter(end); day = day.plusDays(1)) { + long used = usageStore.get(meterKey + "::" + day).orElse(0L); + periodUsed = (quotaPeriodStart(day, quota).equals(day) ? 0L : periodUsed) + used; + if (!day.isBefore(start)) { + perDay.add(new long[] {used, Math.max(0L, quota.limit() - periodUsed)}); + } + } + return perDay; + } + /** * Resolves the effective page size, which is not the same thing as accepting the request. * @@ -1853,6 +1895,109 @@ public class ApiGatewayService implements ResourceProvider { } } + /** + * Meters one execute-api call made with a key of a usage plan, as measured on a REST API in + * eu-west-1: the plan's throttle refuses it first, then its quota, and only an admitted call + * counts. Nothing is counted for a plan without a quota, which AWS reports as {@code [0, 0]}. + * + * @return the gateway response refusing the call, or null when it is admitted + */ + public GatewayResponseType meterApiKeyCall(String region, String usagePlanId, String keyId) { + synchronized (usageLock) { + UsagePlan plan = usagePlanStore.get(usagePlanKey(region, usagePlanId)).orElse(null); + String meterKey = usagePlanKeyPathKey(region, usagePlanId, keyId); + // Rechecked here because deletion detaches the key before forgetUsage takes this lock. + if (plan == null || usagePlanKeyStore.get(meterKey).isEmpty()) { + return null; + } + // One snapshot, as an update can replace the throttle and quota while this call runs. + UsagePlan.Limits limits = plan.limits(); + Instant now = clock.instant(); + if (limits.throttle() != null && !takeToken(meterKey, limits.throttle(), now)) { + return GatewayResponseType.THROTTLED; + } + UsagePlan.Quota quota = limits.quota(); + if (quota == null) { + return null; + } + LocalDate today = LocalDate.ofInstant(now, ZoneOffset.UTC); + if (usedBetween(meterKey, quotaPeriodStart(today, quota), today) >= quota.limit()) { + return GatewayResponseType.QUOTA_EXCEEDED; + } + usageStore.put(meterKey + "::" + today, usedBetween(meterKey, today, today) + 1); + return null; + } + } + + /** + * A token bucket holding up to {@code burstLimit} calls, starting full and refilled at + * {@code rateLimit} a second: measured, burst 0 throttles every call and rate 0 never refills. + * ponytail: per-method throttles of the plan's stages are not enforced. + */ + private boolean takeToken(String meterKey, UsagePlan.Throttle throttle, Instant now) { + // The usage store is account-scoped by its backend; the buckets are not, so the key carries it. + String bucketKey = regionResolver.getAccountId() + "::" + meterKey; + TokenBucket bucket = throttleBuckets.get(bucketKey); + double tokens = bucket == null ? throttle.burstLimit() : Math.min(throttle.burstLimit(), bucket.tokens() + + throttle.rateLimit() * Math.max(0L, Duration.between(bucket.refilledAt(), now).toNanos()) / 1e9); + boolean admitted = tokens >= 1; + // Never rewound, so a clock stepping back and forth cannot refill the bucket twice. + Instant refilledAt = bucket == null || now.isAfter(bucket.refilledAt()) ? now : bucket.refilledAt(); + throttleBuckets.put(bucketKey, new TokenBucket(admitted ? tokens - 1 : tokens, refilledAt)); + return admitted; + } + + private record TokenBucket(double tokens, Instant refilledAt) {} + + /** + * Drops, in one pass, the counts and buckets of each meter key ({@code region::plan::key}) matched, + * so a plan or key recreated with its id starts unused. + */ + private void forgetUsage(Predicate meterKey) { + synchronized (usageLock) { + usageStore.keys().stream().filter(k -> meterKey.test(k.substring(0, k.lastIndexOf("::")))) + .forEach(usageStore::delete); + String accountPrefix = regionResolver.getAccountId() + "::"; + throttleBuckets.keySet().removeIf(k -> k.startsWith(accountPrefix) + && meterKey.test(k.substring(accountPrefix.length()))); + } + } + + /** Storage is wiped before this runs; the in-memory token buckets go with it. */ + @Override + public void clear() { + synchronized (usageLock) { + throttleBuckets.clear(); + } + } + + private long usedBetween(String meterKey, LocalDate from, LocalDate to) { + return from.datesUntil(to.plusDays(1)) + .mapToLong(day -> usageStore.get(meterKey + "::" + day).orElse(0L)) + .sum(); + } + + /** + * The first UTC day of the quota period holding {@code day}. Measured, the offset does not + * subtract requests as documented, and AWS bounds it below the days of the period (WEEK 0-6, + * MONTH 0-27), so it is read as the days the period starts after Sunday or the 1st. + * ponytail: that anchor is inferred, as a period boundary cannot be measured within a day. + */ + static LocalDate quotaPeriodStart(LocalDate day, UsagePlan.Quota quota) { + return switch (quota.period()) { + case "WEEK" -> { + LocalDate start = day.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)) + .plusDays(quota.offset()); + yield start.isAfter(day) ? start.minusWeeks(1) : start; + } + case "MONTH" -> { + LocalDate start = day.withDayOfMonth(1).plusDays(quota.offset()); + yield start.isAfter(day) ? day.minusMonths(1).withDayOfMonth(1).plusDays(quota.offset()) : start; + } + default -> day; + }; + } + public List getUsagePlanKeys(String region, String usagePlanId) { String prefix = region + "::" + usagePlanId + "::"; return usagePlanKeyStore.scan(k -> k.startsWith(prefix)); diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayDeploymentModelTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayDeploymentModelTest.java index db09d7a26b..09565c5cf6 100644 --- a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayDeploymentModelTest.java +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayDeploymentModelTest.java @@ -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"); diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayGetUsageIntegrationTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayGetUsageIntegrationTest.java index e0b11b75fb..0333fc1e4f 100644 --- a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayGetUsageIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayGetUsageIntegrationTest.java @@ -21,8 +21,9 @@ import static org.hamcrest.Matchers.nullValue; * no {@code position} when there is no further page. * *

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 { diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsageMeteringIntegrationTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsageMeteringIntegrationTest.java new file mode 100644 index 0000000000..f380e48686 --- /dev/null +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsageMeteringIntegrationTest.java @@ -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)); + } +} diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsageMeteringServiceTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsageMeteringServiceTest.java new file mode 100644 index 0000000000..1380e46107 --- /dev/null +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsageMeteringServiceTest.java @@ -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 limits) { + Map 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> 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 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 deleter = new AtomicReference<>(); + CompletableFuture[] deletion = new CompletableFuture[1]; + InMemoryStorage 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 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 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"))); + } +} diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsagePlanServiceTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsagePlanServiceTest.java index 75d1a918ec..72397baea7 100644 --- a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsagePlanServiceTest.java +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayUsagePlanServiceTest.java @@ -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> 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)); } diff --git a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java index 94437d1d55..308508e78c 100644 --- a/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java +++ b/src/test/java/io/floci/aws/services/apigateway/ApiGatewayV2ApiMappingServiceTest.java @@ -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) {