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

@@ -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()));
}
}