feat(apigateway): API key management — UpdateApiKey, DeleteApiKey, UsagePlan custom-id, generateDistinctId (#1883)

* feat(apigateway): implement UpdateApiKey and DeleteApiKey

Adds the two missing API key lifecycle operations for API Gateway v1:

- UpdateApiKey (PATCH /apikeys/{apiKeyId}): applies replace patch
  operations for /name, /description and /enabled, 404 when absent
- DeleteApiKey (DELETE /apikeys/{apiKeyId}): 202 on success, 404 when
  absent

Also adds a description field to the ApiKey model so it can be set on
create, returned in responses and patched via UpdateApiKey.

Integration tests cover each patch path, the 404 cases and a repeated
delete. Service docs updated to move both operations out of the Not
Implemented list.

* feat(apigateway): persist and return UsagePlan tags

CreateUsagePlan accepted a tags map but discarded it, so tags never
appeared in CreateUsagePlan, GetUsagePlan or GetUsagePlans responses.
Tags are now stored on the UsagePlan model and emitted by the
controller.

A _custom_id_ tag sets a deterministic plan ID, mirroring the existing
createRestApi behaviour. Tag values are coerced through String.valueOf
rather than an unchecked cast so a non-string value in the request body
cannot produce a ClassCastException on later reads.

The tags field defaults to an empty map, so usage plans already
persisted without it deserialize unchanged.

* fix(apigateway): treat an absent generateDistinctId as id == value

CreateApiKey generated a distinct short-token id whenever
generateDistinctId was absent, so the emulator's default disagreed with
AWS. Only an explicit generateDistinctId: true produces an id that
differs from the key value; absent and false both yield id == value.

A blank supplied value now falls back to a generated UUID on the
distinct-id path too, matching the guard the shared-value path already
had.

Integration tests cover all three states — absent, explicit false and
explicit true — and the service docs gain a table for the behaviour.

* refactor(apigateway): route UsagePlan custom IDs through ReservedTags

The usage plan override read the raw _custom_id_ key directly, which
diverged from createRestApi after #2045 made floci:override-id the
reserved key. It now calls ReservedTags.extractOverrideApiId, so the
plan gets the same validation (non-blank, no whitespace, no control
characters, no /?#) and the same precedence when both keys are present.

Persisted tags go through stripApiGatewayReservedTags, so neither
override key survives into CreateUsagePlan, GetUsagePlan or
GetUsagePlans responses.

Tests assert the reserved keys are absent from the returned tags and
cover the deprecated key, the precedence rule and both rejection paths.

* fix(apigateway): stop deleted and disabled API keys authenticating

A UsagePlanKey stores its own copy of the API key value, and the data
plane resolves requestContext.identity.apiKey by matching the x-api-key
header against those copies. Neither revocation path reached them:

- DeleteApiKey removed the key from apiKeyStore but left every usage
  plan association behind, so a deleted key stayed listed by
  GetUsagePlanKeys and kept being recognised on the data plane. It now
  detaches the key from every plan in the region first, matching AWS.
- resolveApiKeyForRequest never read enabled, despite its javadoc
  saying it matched enabled keys, so patching /enabled to false changed
  nothing about request handling. It now requires the key to still exist
  and be enabled, via a new non-throwing findApiKey lookup.

Floci has no apiKeyRequired gate, so a revoked key yields a null
identity.apiKey rather than a 403; the docs now say so explicitly. The
new integration test pins both paths and fails on all three assertions
without these changes.
This commit is contained in:
Dennis O'Connor authored and GitHub committed 2026-08-12 00:02:32 -04:00
1 parent f17dd1ed81
commit b6765b3056
9 files changed
+683 -8

No files matched your search

+54 -2
View File
@@ -52,7 +52,7 @@ duplicate override IDs.
| **Deployments** | CreateDeployment, GetDeployments |
| **Stages** | CreateStage, GetStage, GetStages, UpdateStage, DeleteStage |
| **Authorizers** | CreateAuthorizer, GetAuthorizer, GetAuthorizers |
| **API Keys** | CreateApiKey, GetApiKeys |
| **API Keys** | CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey |
| **Usage Plans** | CreateUsagePlan, GetUsagePlans, DeleteUsagePlan |
| **Usage Plan Keys** | CreateUsagePlanKey, GetUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey |
| **Request Validators** | CreateRequestValidator, GetRequestValidator, GetRequestValidators, DeleteRequestValidator |
@@ -62,13 +62,44 @@ duplicate override IDs.
| **Account** | GetAccount, UpdateAccount |
| **Tags** | TagResource, UntagResource, GetTags (ListTagsForResource) |
### API Key Behaviour Notes
#### `generateDistinctId`
Controls whether the key's `id` and `value` fields are distinct. AWS's undocumented default behaviour is that they are **the same string** unless `generateDistinctId=true` is explicitly requested.
| `generateDistinctId` | `id` | `value` |
|---|---|---|
| absent (default) | same as `value` | caller-supplied `value`, or a generated UUID-derived string |
| `false` | same as `value` | caller-supplied `value`, or a generated UUID-derived string |
| `true` | opaque short token (`shortId`) | caller-supplied `value`, or a generated UUID-derived string |
When `generateDistinctId` is absent or `false`, a single shared string is used for both `id` and `value`. If the caller supplies a `value` in the request body, that string is used for both; otherwise a UUID-derived string is generated and assigned to both.
When `generateDistinctId=true`, `id` is set to an opaque short token independent of `value`.
#### Revocation
`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.
`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
immediately.
> [!NOTE]
> Floci does not implement the `apiKeyRequired` gate on methods, so a request carrying an unknown,
> disabled, or deleted key is still executed — it simply arrives with a null `identity.apiKey` rather
> than being rejected with `403`.
### Not Implemented
These management-plane operations have no handler in v1. Calls will return `404` or an error:
- Deployment detail and lifecycle: `GetDeployment`, `UpdateDeployment`, `DeleteDeployment`
- Authorizer lifecycle: `UpdateAuthorizer`, `DeleteAuthorizer`, `TestInvokeAuthorizer`
- API key detail: `GetApiKey`, `UpdateApiKey`, `DeleteApiKey`, `ImportApiKeys`
- API key detail: `ImportApiKeys`
- Usage plan detail: `GetUsagePlan`, `UpdateUsagePlan`
- Model updates and templates: `UpdateModel`, `GetModelTemplate`
- Gateway Responses (the entire family: `PutGatewayResponse`, `GetGatewayResponse`, etc.)
@@ -132,6 +163,27 @@ aws apigateway create-deployment \
curl http://localhost:4566/restapis/$API_ID/dev/_user_request_/users
```
### Usage Plan Tags and Custom IDs
Usage plans accept arbitrary tags, and the same reserved `floci:override-id` tag used for
[custom API IDs](#custom-api-ids) pins the plan's `id`:
```bash
# Create a usage plan with a custom ID and additional tags
aws apigateway create-usage-plan \
--name "my-plan" \
--tags '{"floci:override-id":"my-plan-id","env":"staging"}' \
--endpoint-url $AWS_ENDPOINT_URL
# The plan is now accessible at its custom ID
aws apigateway get-usage-plans --endpoint-url $AWS_ENDPOINT_URL
```
The override key is validated and consumed exactly as it is for `CreateRestApi`, so it never appears in
the tags a usage plan returns. The deprecated `_custom_id_` key is still honored on create for existing
setups, and `floci:override-id` wins when both are present. Every other tag is persisted and returned in
`CreateUsagePlan` and `GetUsagePlans` responses.
---
## Configuration
@@ -642,6 +642,32 @@ public class ApiGatewayController {
return Response.ok(node.toString()).type(MediaType.APPLICATION_JSON).build();
}
@PATCH
@Path("/apikeys/{apiKeyId}")
public Response updateApiKey(@Context HttpHeaders headers,
@PathParam("apiKeyId") String apiKeyId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
@SuppressWarnings("unchecked")
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
ApiKey key = service.updateApiKey(region, apiKeyId, patchOperations);
return Response.ok(toApiKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build();
} catch (IOException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@DELETE
@Path("/apikeys/{apiKeyId}")
public Response deleteApiKey(@Context HttpHeaders headers,
@PathParam("apiKeyId") String apiKeyId) {
String region = regionResolver.resolveRegion(headers);
service.deleteApiKey(region, apiKeyId);
return Response.accepted().build();
}
@POST
@Path("/usageplans")
public Response createUsagePlan(@Context HttpHeaders headers, String body) {
@@ -1666,6 +1692,9 @@ public class ApiGatewayController {
node.put("name", k.getName());
node.put("value", k.getValue());
node.put("enabled", k.isEnabled());
if (k.getDescription() != null) {
node.put("description", k.getDescription());
}
if (k.getTags() != null && !k.getTags().isEmpty()) {
ObjectNode tags = node.putObject("tags");
k.getTags().forEach(tags::put);
@@ -1677,6 +1706,10 @@ public class ApiGatewayController {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", p.getId());
node.put("name", p.getName());
if (p.getTags() != null && !p.getTags().isEmpty()) {
ObjectNode tags = node.putObject("tags");
p.getTags().forEach(tags::put);
}
return node;
}
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
import io.github.hectorvent.floci.services.apigateway.model.Integration;
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
@@ -602,9 +603,15 @@ public class ApiGatewayExecuteController {
boolean planCoversStage = plan.getApiStages().stream()
.anyMatch(s -> apiId.equals(s.apiId()) && stageName.equals(s.stage()));
if (!planCoversStage) continue;
// Check if any key in this plan matches the header value
// Check if any key in this plan matches the header value. The usage plan key holds a copy
// of the value, so the key itself must still exist and be enabled for the match to count.
for (UsagePlanKey planKey : apiGatewayService.getUsagePlanKeys(region, plan.getId())) {
if (keyHeader.equals(planKey.getValue())) {
if (!keyHeader.equals(planKey.getValue())) {
continue;
}
if (apiGatewayService.findApiKey(region, planKey.getId())
.filter(ApiKey::isEnabled)
.isPresent()) {
return planKey.getValue();
}
}
@@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
@@ -706,12 +707,27 @@ public class ApiGatewayService {
public ApiKey createApiKey(String region, Map<String, Object> request) {
ApiKey apiKey = new ApiKey();
apiKey.setId(shortId(10));
apiKey.setName((String) request.get("name"));
apiKey.setValue((String) request.getOrDefault("value", UUID.randomUUID().toString().replace("-", "")));
apiKey.setEnabled(!Boolean.FALSE.equals(request.get("enabled")));
apiKey.setCreatedDate(System.currentTimeMillis() / 1000L);
apiKey.setLastUpdatedDate(apiKey.getCreatedDate());
apiKey.setDescription((String) request.get("description"));
boolean generateDistinctId = Boolean.TRUE.equals(request.get("generateDistinctId"));
String suppliedValue = (String) request.get("value");
if (!generateDistinctId) {
String sharedValue = (suppliedValue != null && !suppliedValue.isBlank())
? suppliedValue
: UUID.randomUUID().toString().replace("-", "");
apiKey.setId(sharedValue);
apiKey.setValue(sharedValue);
} else {
apiKey.setId(shortId(10));
apiKey.setValue((suppliedValue != null && !suppliedValue.isBlank())
? suppliedValue
: UUID.randomUUID().toString().replace("-", ""));
}
Map<String, String> tags = new HashMap<>();
if (request.get("tags") instanceof Map<?, ?> rawTags) {
@@ -725,27 +741,69 @@ public class ApiGatewayService {
}
public ApiKey getApiKey(String region, String apiKeyId) {
return apiKeyStore.get(apiKeyGlobalKey(region, apiKeyId))
return findApiKey(region, apiKeyId)
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API Key identifier specified", 404));
}
/**
* Non-throwing key lookup for callers on the data plane, which must treat a missing key as
* "not authenticated" rather than surface a management-plane 404.
*/
public Optional<ApiKey> findApiKey(String region, String apiKeyId) {
return apiKeyStore.get(apiKeyGlobalKey(region, apiKeyId));
}
public List<ApiKey> getApiKeys(String region) {
String prefix = region + "::";
return apiKeyStore.scan(k -> k.startsWith(prefix));
}
/**
* 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.
*/
public void deleteApiKey(String region, String apiKeyId) {
getApiKey(region, apiKeyId);
for (UsagePlan plan : getUsagePlans(region)) {
usagePlanKeyStore.delete(usagePlanKeyPathKey(region, plan.getId(), apiKeyId));
}
apiKeyStore.delete(apiKeyGlobalKey(region, apiKeyId));
}
public ApiKey updateApiKey(String region, String apiKeyId, List<Map<String, String>> patchOperations) {
ApiKey key = getApiKey(region, apiKeyId);
if (patchOperations != null) {
for (Map<String, String> op : patchOperations) {
if (!"replace".equals(op.get("op"))) { continue; }
switch (op.getOrDefault("path", "")) {
case "/name" -> key.setName(op.get("value"));
case "/description" -> key.setDescription(op.get("value"));
case "/enabled" -> key.setEnabled(Boolean.parseBoolean(op.get("value")));
}
}
}
key.setLastUpdatedDate(System.currentTimeMillis() / 1000L);
apiKeyStore.put(apiKeyGlobalKey(region, apiKeyId), key);
return key;
}
// ──────────────────────────── Usage Plans ────────────────────────────
public UsagePlan createUsagePlan(String region, Map<String, Object> request) {
Map<String, String> tags = new HashMap<>();
if (request.get("tags") instanceof Map<?, ?> rawTags) {
rawTags.forEach((key, value) -> tags.put(String.valueOf(key), String.valueOf(value)));
}
String customId = ReservedTags.extractOverrideApiId(tags);
String planId = customId != null ? customId : shortId(10);
UsagePlan plan = new UsagePlan();
plan.setId(shortId(10));
plan.setId(planId);
plan.setName((String) request.get("name"));
plan.setDescription((String) request.get("description"));
plan.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
@SuppressWarnings("unchecked")
List<Map<String, Object>> apiStages = (List<Map<String, Object>>) request.get("apiStages");
@@ -15,6 +15,7 @@ public class ApiKey {
private boolean enabled;
private long createdDate;
private long lastUpdatedDate;
private String description;
private Map<String, String> tags = new HashMap<>();
public ApiKey() {}
@@ -37,6 +38,9 @@ public class ApiKey {
public long getLastUpdatedDate() { return lastUpdatedDate; }
public void setLastUpdatedDate(long lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new HashMap<>(); }
}
@@ -4,7 +4,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -13,6 +15,7 @@ public class UsagePlan {
private String name;
private String description;
private List<ApiStage> apiStages = new ArrayList<>();
private Map<String, String> tags = new HashMap<>();
public UsagePlan() {}
@@ -28,6 +31,9 @@ public class UsagePlan {
public List<ApiStage> getApiStages() { return apiStages; }
public void setApiStages(List<ApiStage> apiStages) { this.apiStages = apiStages; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? tags : new HashMap<>(); }
@RegisterForReflection
public record ApiStage(String apiId, String stage) {}
}
@@ -90,4 +90,148 @@ class ApiGatewayApiKeyIntegrationTest {
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("Invalid API Key identifier specified"));
}
@Test @Order(6)
void updateApiKeyName() {
String body = """
{"patchOperations":[{"op":"replace","path":"/name","value":"updated-name"}]}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().patch("/apikeys/" + apiKeyId)
.then()
.statusCode(200)
.body("id", equalTo(apiKeyId))
.body("name", equalTo("updated-name"));
}
@Test @Order(7)
void updateApiKeyDescription() {
String body = """
{"patchOperations":[{"op":"replace","path":"/description","value":"a test key"}]}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().patch("/apikeys/" + apiKeyId)
.then()
.statusCode(200)
.body("description", equalTo("a test key"));
}
@Test @Order(8)
void updateApiKeyEnabled() {
String body = """
{"patchOperations":[{"op":"replace","path":"/enabled","value":"false"}]}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().patch("/apikeys/" + apiKeyId)
.then()
.statusCode(200)
.body("enabled", equalTo(false));
}
@Test @Order(9)
void updateApiKeyNotFound() {
String body = """
{"patchOperations":[{"op":"replace","path":"/name","value":"x"}]}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().patch("/apikeys/doesnotexist")
.then()
.statusCode(404)
.contentType(ContentType.JSON)
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("Invalid API Key identifier specified"));
}
@Test @Order(10)
void deleteApiKey() {
given()
.when().delete("/apikeys/" + apiKeyId)
.then()
.statusCode(202);
}
@Test @Order(11)
void deleteApiKeyAlreadyGone() {
given()
.when().delete("/apikeys/" + apiKeyId)
.then()
.statusCode(404)
.contentType(ContentType.JSON)
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("Invalid API Key identifier specified"));
}
@Test @Order(12)
void createApiKey_generateDistinctIdFalse_idEqualsValue() {
String body = """
{"name":"shared-id-key","enabled":true,"generateDistinctId":false}
""";
String sharedId = given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/apikeys")
.then()
.statusCode(201)
.body("id", notNullValue())
.extract().path("id");
given()
.when().get("/apikeys/" + sharedId + "?includeValue=true")
.then()
.statusCode(200)
.body("id", equalTo(sharedId))
.body("value", equalTo(sharedId));
}
@Test @Order(13)
void createApiKey_generateDistinctIdAbsent_idEqualsValue() {
String body = """
{"name":"default-id-key","enabled":true}
""";
String sharedId = given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/apikeys")
.then()
.statusCode(201)
.body("id", notNullValue())
.extract().path("id");
given()
.when().get("/apikeys/" + sharedId + "?includeValue=true")
.then()
.statusCode(200)
.body("id", equalTo(sharedId))
.body("value", equalTo(sharedId));
}
@Test @Order(14)
void createApiKey_generateDistinctIdTrue_idDistinctFromValue() {
String body = """
{"name":"distinct-id-key","enabled":true,"generateDistinctId":true}
""";
String keyId = given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/apikeys")
.then()
.statusCode(201)
.body("id", notNullValue())
.extract().path("id");
given()
.when().get("/apikeys/" + keyId + "?includeValue=true")
.then()
.statusCode(200)
.body("id", equalTo(keyId))
.body("value", not(equalTo(keyId)));
}
}
@@ -0,0 +1,253 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
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.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.*;
/**
* Integration tests for API key revocation on the data plane.
*
* <p>A {@code UsagePlanKey} stores its own copy of the API key value, and
* {@code requestContext.identity.apiKey} is resolved by matching the {@code x-api-key} header against
* those copies. Disabling a key through {@code UpdateApiKey} or removing it through
* {@code DeleteApiKey} must therefore stop the value being recognised, otherwise a revoked credential
* keeps identifying requests.
*
* <p>Floci does not implement the {@code apiKeyRequired} gate, so a revoked key produces a request
* whose {@code identity.apiKey} is null rather than a 403. These tests assert the resolution
* behaviour that exists today.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayApiKeyRevocationIntegrationTest {
private static final String LAMBDA_BASE_PATH = "/2015-03-31/functions";
private static final String ECHO_FUNCTION = "apigw-apikey-revocation-echo";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/lambda-role";
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
// State shared across ordered tests
private static String apiId;
private static String resourceId;
private static String planId;
private static String keyId;
private static String keyValue;
@Test @Order(1)
void createEchoLambda() throws Exception {
String zipBase64 = Base64.getEncoder().encodeToString(zipEntries(Map.of("index.js", """
exports.handler = async (event) => ({
statusCode: 200,
body: JSON.stringify({
apiKey: event.requestContext && event.requestContext.identity
? event.requestContext.identity.apiKey
: null
})
});
""")));
given()
.contentType(ContentType.JSON)
.body("""
{
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Role": "%s",
"Handler": "index.handler",
"Timeout": 30,
"Code": {"ZipFile": "%s"}
}
""".formatted(ECHO_FUNCTION, ROLE_ARN, zipBase64))
.when().post(LAMBDA_BASE_PATH)
.then()
.statusCode(201);
}
@Test @Order(2)
void setupApiWithDeployedStage() {
apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"apikey-revocation-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");
resourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"echo\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET")
.then().statusCode(201);
String uri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/"
+ "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + ECHO_FUNCTION + "/invocations";
given()
.contentType(ContentType.JSON)
.body("""
{"type":"AWS_PROXY","httpMethod":"POST","uri":"%s"}
""".formatted(uri))
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
.then().statusCode(201);
String depId = given()
.contentType(ContentType.JSON)
.body("{\"description\":\"apikey-revocation\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("""
{"stageName":"prod","deploymentId":"%s"}
""".formatted(depId))
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
}
@Test @Order(3)
void createKeyAndAttachToUsagePlan() {
keyId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"revocation-key\",\"enabled\":true,\"generateDistinctId\":true}")
.when().post("/apikeys")
.then().statusCode(201)
.extract().path("id");
keyValue = given()
.when().get("/apikeys/" + keyId + "?includeValue=true")
.then().statusCode(200)
.extract().path("value");
assertNotNull(keyValue);
assertNotEquals(keyId, keyValue, "generateDistinctId=true should give the key a value distinct from its id");
planId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"revocation-plan","apiStages":[{"apiId":"%s","stage":"prod"}]}
""".formatted(apiId))
.when().post("/usageplans")
.then().statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("""
{"keyId":"%s","keyType":"API_KEY"}
""".formatted(keyId))
.when().post("/usageplans/" + planId + "/keys")
.then().statusCode(201);
}
@Test @Order(4)
void enabledKeyIsResolvedOnTheDataPlane() throws Exception {
assertEquals(keyValue, invokeAndReadApiKey(keyValue),
"an enabled key attached to a plan covering the stage must populate identity.apiKey");
}
@Test @Order(5)
void disabledKeyIsNotResolvedOnTheDataPlane() throws Exception {
given()
.contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/enabled\",\"value\":\"false\"}]}")
.when().patch("/apikeys/" + keyId)
.then().statusCode(200)
.body("enabled", org.hamcrest.Matchers.is(false));
assertNull(invokeAndReadApiKey(keyValue),
"a key disabled through UpdateApiKey must no longer populate identity.apiKey");
}
@Test @Order(6)
void reEnabledKeyIsResolvedAgain() throws Exception {
given()
.contentType(ContentType.JSON)
.body("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/enabled\",\"value\":\"true\"}]}")
.when().patch("/apikeys/" + keyId)
.then().statusCode(200)
.body("enabled", org.hamcrest.Matchers.is(true));
assertEquals(keyValue, invokeAndReadApiKey(keyValue),
"re-enabling the key must restore data-plane resolution");
}
@Test @Order(7)
void deleteApiKeyDetachesItFromEveryUsagePlan() {
given()
.when().get("/usageplans/" + planId + "/keys")
.then().statusCode(200)
.body("item.find { it.id == '" + keyId + "' }", org.hamcrest.Matchers.notNullValue());
given()
.when().delete("/apikeys/" + keyId)
.then().statusCode(202);
given()
.when().get("/usageplans/" + planId + "/keys")
.then().statusCode(200)
.body("item.find { it.id == '" + keyId + "' }", org.hamcrest.Matchers.nullValue());
given()
.when().get("/usageplans/" + planId + "/keys/" + keyId)
.then().statusCode(404);
}
@Test @Order(8)
void deletedKeyIsNotResolvedOnTheDataPlane() throws Exception {
assertNull(invokeAndReadApiKey(keyValue),
"a deleted key must no longer populate identity.apiKey");
}
// ──────────────────────────── Helpers ────────────────────────────
private static String invokeAndReadApiKey(String apiKeyHeader) throws Exception {
String response = given()
.header("x-api-key", apiKeyHeader)
.when().get("/execute-api/" + apiId + "/prod/echo")
.then().statusCode(200)
.extract().asString();
JsonNode body = OBJECT_MAPPER.readTree(response);
JsonNode apiKey = body.path("apiKey");
return apiKey.isNull() || apiKey.isMissingNode() ? null : apiKey.asText();
}
private static byte[] zipEntries(Map<String, String> entries) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Map.Entry<String, String> entry : entries.entrySet()) {
zos.putNextEntry(new ZipEntry(entry.getKey()));
zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
}
return baos.toByteArray();
}
}
@@ -0,0 +1,118 @@
package io.github.hectorvent.floci.services.apigateway;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
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 static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayUsagePlanIntegrationTest {
@Test @Order(1)
void createUsagePlan_flociOverrideIdTag_usesTagValueAsPlanId() {
String body = """
{"name":"my-plan","tags":{"floci:override-id":"my-plan-id","env":"test"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/usageplans")
.then()
.statusCode(201)
.body("id", equalTo("my-plan-id"))
.body("name", equalTo("my-plan"))
.body("tags.'floci:override-id'", nullValue())
.body("tags._custom_id_", nullValue())
.body("tags.env", equalTo("test"));
}
@Test @Order(2)
void getUsagePlans_returnsTagsWithoutReservedKeys() {
given()
.when().get("/usageplans")
.then()
.statusCode(200)
.body("item.find { it.id == 'my-plan-id' }.tags.env", equalTo("test"))
.body("item.find { it.id == 'my-plan-id' }.tags.'floci:override-id'", nullValue())
.body("item.find { it.id == 'my-plan-id' }.tags._custom_id_", nullValue());
}
@Test @Order(4)
void createUsagePlan_deprecatedCustomIdTag_stillHonoredButNotPersisted() {
String body = """
{"name":"legacy-plan","tags":{"_custom_id_":"legacy-plan-id","env":"legacy"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/usageplans")
.then()
.statusCode(201)
.body("id", equalTo("legacy-plan-id"))
.body("tags._custom_id_", nullValue())
.body("tags.env", equalTo("legacy"));
}
@Test @Order(5)
void createUsagePlan_bothOverrideKeys_prefersFlociOverrideId() {
String body = """
{"name":"both-keys-plan","tags":{"floci:override-id":"WINNERPLAN","_custom_id_":"LOSERPLAN"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/usageplans")
.then()
.statusCode(201)
.body("id", equalTo("WINNERPLAN"));
}
@Test @Order(6)
void createUsagePlan_blankOverrideId_isRejected() {
String body = """
{"name":"blank-override-plan","tags":{"floci:override-id":" "}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/usageplans")
.then()
.statusCode(400)
.body("message", containsString("must not be blank"));
}
@Test @Order(7)
void createUsagePlan_overrideIdWithPathSeparator_isRejected() {
String body = """
{"name":"bad-override-plan","tags":{"floci:override-id":"has/slash"}}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/usageplans")
.then()
.statusCode(400)
.body("message", containsString("unsupported characters"));
}
@Test @Order(8)
void createUsagePlan_noOverrideId_generatesRandomId() {
String body = """
{"name":"random-plan"}
""";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/usageplans")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("id", not(emptyString()));
}
}