feat(cloudformation): provision AWS::ApiGateway::UsagePlan and UsagePlanKey (#3123)

* feat(cloudformation): provision AWS::ApiGateway::UsagePlan and UsagePlanKey

Per-service provisioner over ApiGatewayService. A plan's Ref and Fn::GetAtt
Id are the plan id. Every plan property is mutable, so an update patches name
and description in place and adds or removes API stages as the template moves
them. Tags are driven to the template's desired state through the new
replaceUsagePlanTags.

A key's Ref and Fn::GetAtt Id are <keyId>:<usagePlanId>, as on AWS. All three
of its properties are createOnly, so a change to any of them is refused as a
replacement rather than re-associating a different key under the old id. The
composite id is what lets delete find the association without scanning every
plan.

Stack deletion removes the plan and the association and tolerates either
being gone already.

Ported from lex00/floci#118. Tracked in lex00/floci#192.

* fix(cloudformation): validate usage plan key properties and survive a recreated plan

An association only counts as still there while its plan does. deleteUsagePlan
leaves associations behind, and a plan recreated after an out-of-band delete has
a new id, so the stale association no longer reads the new UsagePlanId as a
rename. KeyType must be API_KEY and both ids must be present, per the registry
schema, and a non-list ApiStages is refused instead of read as empty.
replaceUsagePlanTags strips the reserved id-override tags the way createUsagePlan
does rather than refusing them.

* fix(cloudformation): check a usage plan key's KeyId even while recovering drift

The createOnly checks sat behind the association lookup, so a template that
changed KeyId while its plan was missing created an association for the new key
instead of refusing the change. KeyId is checked against the prior composite id
either way now. UsagePlanId stays conditional, since a plan recreated after an
out-of-band delete legitimately has a new id.
This commit is contained in:
lex00 authored and GitHub committed 2026-09-06 22:09:54 -05:00
1 parent 2c6a92c07d
commit 3a4982c294
7 files changed
+910 -1

No files matched your search

+1 -1
View File
@@ -84,7 +84,7 @@ cross-resource references.
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
| Route 53 | `HostedZone`, `RecordSet` |
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `ApiKey` |
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` |
| Step Functions | `StateMachine` |
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
@@ -1122,6 +1122,21 @@ public class ApiGatewayService {
usagePlanStore.delete(usagePlanKey(region, usagePlanId));
}
/**
* Replaces a usage plan's tags wholesale. CloudFormation drives a resource's tags to the
* template's desired state on update, so a dropped key has to disappear, which the additive
* TagResource shape cannot express.
*/
public UsagePlan replaceUsagePlanTags(String region, String usagePlanId, Map<String, String> tags) {
UsagePlan plan = getUsagePlan(region, usagePlanId);
// createUsagePlan consumes the reserved id-override tags and strips them, so a template that
// pinned the id still carries them on every update. They are stripped here the same way
// rather than refused, or a pinned plan could never change an ordinary tag again.
plan.setTags(ReservedTags.stripApiGatewayReservedTags(tags));
usagePlanStore.put(usagePlanKey(region, usagePlanId), plan);
return plan;
}
// ──────────────────────────── Usage Plan Keys ────────────────────────────
public UsagePlanKey createUsagePlanKey(String region, String usagePlanId, Map<String, Object> request) {
@@ -0,0 +1,301 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::ApiGateway::UsagePlan} and
* {@code AWS::ApiGateway::UsagePlanKey}, backed by {@link ApiGatewayService}.
*
* <p>A usage plan's {@code Ref} and {@code Fn::GetAtt Id} are the plan id. Every plan property is
* mutable, so an update patches the plan in place, adding and removing API stages as the template
* moves them. Throttle and Quota, on the plan and per stage, have no counterpart in
* {@link UsagePlan} and are accepted without effect.
*
* <p>A usage plan key's {@code Ref} and {@code Fn::GetAtt Id} are {@code <keyId>:<usagePlanId>},
* as on AWS. All three of its properties are createOnly, so a change to any of them is refused as a
* replacement rather than re-associating a different key or plan under the old id.
*/
@ApplicationScoped
public class ApiGatewayUsagePlanCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(ApiGatewayUsagePlanCfnProvisioner.class);
private static final String USAGE_PLAN = "AWS::ApiGateway::UsagePlan";
private static final String USAGE_PLAN_KEY = "AWS::ApiGateway::UsagePlanKey";
private static final String NOT_FOUND = "NotFoundException";
private static final String KEY_ID_SEPARATOR = ":";
/** The registry schema's only allowed KeyType. */
private static final String API_KEY_TYPE = "API_KEY";
/** Well under AWS's 1024-character name limit, and in line with the other generated names. */
private static final int GENERATED_NAME_MAX = 128;
private final ApiGatewayService apiGatewayService;
@Inject
public ApiGatewayUsagePlanCfnProvisioner(ApiGatewayService apiGatewayService) {
this.apiGatewayService = apiGatewayService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(USAGE_PLAN, USAGE_PLAN_KEY);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
case USAGE_PLAN -> provisionUsagePlan(r, props, ctx);
case USAGE_PLAN_KEY -> provisionUsagePlanKey(r, props, ctx);
default -> throw new IllegalStateException(
"ApiGatewayUsagePlanCfnProvisioner cannot handle " + r.getResourceType());
}
}
// ──────────────────────────── UsagePlan ────────────────────────────
private void provisionUsagePlan(StackResource r, JsonNode props, ProvisionContext ctx) {
if (ctx.isUpdate()) {
// An update re-invokes provision with the prior physical id. Creating unconditionally
// would mint a second plan on every update and orphan the first, which then outlives
// the stack since delete only knows the id recorded last.
UsagePlan existing = findUsagePlan(ctx.region(), ctx.priorPhysicalId());
if (existing != null) {
updateUsagePlan(r, existing, props, ctx);
return;
}
}
String name = ctx.resolveOptional(props, "UsagePlanName");
if (name == null || name.isBlank()) {
name = ctx.generatePhysicalName(r.getLogicalId(), GENERATED_NAME_MAX, false);
}
Map<String, Object> request = new HashMap<>();
request.put("name", name);
request.put("description", ctx.resolveOptional(props, "Description"));
List<Map<String, Object>> apiStages = new ArrayList<>();
for (UsagePlan.ApiStage stage : apiStages(props, ctx)) {
Map<String, Object> entry = new HashMap<>();
entry.put("apiId", stage.apiId());
entry.put("stage", stage.stage());
apiStages.add(entry);
}
request.put("apiStages", apiStages);
request.put("tags", ctx.resolveTags(props, "Tags"));
recordPlan(r, apiGatewayService.createUsagePlan(ctx.region(), request));
}
private void updateUsagePlan(StackResource r, UsagePlan existing, JsonNode props, ProvisionContext ctx) {
List<Map<String, String>> patches = new ArrayList<>();
// A template that omits UsagePlanName keeps whatever name the plan was created with.
String name = ctx.resolveOptional(props, "UsagePlanName");
if (name != null && !name.isBlank() && !name.equals(existing.getName())) {
patches.add(patch("replace", "/name", name));
}
String description = ctx.resolveOptional(props, "Description");
if (!Objects.equals(blankToNull(description), blankToNull(existing.getDescription()))) {
// The service rejects a null patch value, so a dropped Description clears to "".
patches.add(patch("replace", "/description", description == null ? "" : description));
}
// ApiStages is a set the template owns outright: stages it no longer lists come off the
// plan, stages it adds go on. The service models that as add/remove of "apiId:stage".
List<UsagePlan.ApiStage> desired = apiStages(props, ctx);
List<UsagePlan.ApiStage> current = List.copyOf(existing.getApiStages());
for (UsagePlan.ApiStage stage : current) {
if (!desired.contains(stage)) {
patches.add(patch("remove", "/apiStages", stage.apiId() + KEY_ID_SEPARATOR + stage.stage()));
}
}
for (UsagePlan.ApiStage stage : desired) {
if (!current.contains(stage)) {
patches.add(patch("add", "/apiStages", stage.apiId() + KEY_ID_SEPARATOR + stage.stage()));
}
}
UsagePlan plan = patches.isEmpty()
? existing
: apiGatewayService.updateUsagePlan(ctx.region(), existing.getId(), patches);
// The stored tags never include the reserved id-override keys (createUsagePlan strips them),
// so the comparison ignores them too; the service strips them again on the way in.
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
if (!ReservedTags.stripApiGatewayReservedTags(desiredTags).equals(plan.getTags())) {
plan = apiGatewayService.replaceUsagePlanTags(ctx.region(), plan.getId(), desiredTags);
}
recordPlan(r, plan);
}
/** The template's ApiStages as (apiId, stage) pairs, in template order. */
private static List<UsagePlan.ApiStage> apiStages(JsonNode props, ProvisionContext ctx) {
List<UsagePlan.ApiStage> stages = new ArrayList<>();
if (props == null || !props.has("ApiStages")) {
return stages;
}
JsonNode resolved = ctx.engine().resolveNode(props.get("ApiStages"));
if (resolved == null || resolved.isNull()) {
return stages;
}
if (!resolved.isArray()) {
throw new AwsException("ValidationError", "ApiStages of a usage plan must be a list.", 400);
}
for (JsonNode entry : resolved) {
String apiId = blankToNull(ctx.engine().resolve(entry.path("ApiId")));
String stage = blankToNull(ctx.engine().resolve(entry.path("Stage")));
if (apiId == null || stage == null) {
throw new AwsException("ValidationError",
"Every ApiStages entry of a usage plan needs both ApiId and Stage.", 400);
}
UsagePlan.ApiStage apiStage = new UsagePlan.ApiStage(apiId, stage);
if (!stages.contains(apiStage)) {
stages.add(apiStage);
}
}
return stages;
}
private UsagePlan findUsagePlan(String region, String usagePlanId) {
try {
return apiGatewayService.getUsagePlan(region, usagePlanId);
} catch (AwsException e) {
if (!NOT_FOUND.equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Usage plan {0} from the previous provision is gone, creating a new one", usagePlanId);
return null;
}
}
private static void recordPlan(StackResource r, UsagePlan plan) {
r.setPhysicalId(plan.getId());
r.getAttributes().put("Id", plan.getId());
}
// ──────────────────────────── UsagePlanKey ────────────────────────────
private void provisionUsagePlanKey(StackResource r, JsonNode props, ProvisionContext ctx) {
String usagePlanId = blankToNull(ctx.resolveOptional(props, "UsagePlanId"));
String keyId = blankToNull(ctx.resolveOptional(props, "KeyId"));
String keyType = blankToNull(ctx.resolveOptional(props, "KeyType"));
if (usagePlanId == null || keyId == null) {
throw new AwsException("ValidationError",
"AWS::ApiGateway::UsagePlanKey requires both UsagePlanId and KeyId.", 400);
}
if (!API_KEY_TYPE.equals(keyType)) {
throw new AwsException("ValidationError",
"KeyType of a usage plan key must be " + API_KEY_TYPE + ".", 400);
}
String[] prior = ctx.isUpdate() ? splitKeyId(ctx.priorPhysicalId()) : null;
if (prior != null) {
// KeyId is createOnly and nothing legitimate changes it, so it is checked whether or not
// the plan is still there. UsagePlanId is different: deleteUsagePlan leaves associations
// behind and a plan recreated after an out-of-band delete has a new id, so a changed
// plan id is a move only while the plan it moved off still exists.
rejectIfChanged("KeyId", prior[0], keyId);
UsagePlanKey existing = findUsagePlan(ctx.region(), prior[1]) == null
? null
: findUsagePlanKey(ctx.region(), prior[1], prior[0]);
if (existing != null) {
rejectIfChanged("UsagePlanId", prior[1], usagePlanId);
rejectIfChanged("KeyType", existing.getType(), keyType);
recordKey(r, prior[0], prior[1]);
return;
}
}
Map<String, Object> request = new HashMap<>();
request.put("keyId", keyId);
request.put("keyType", keyType);
apiGatewayService.createUsagePlanKey(ctx.region(), usagePlanId, request);
recordKey(r, keyId, usagePlanId);
}
private UsagePlanKey findUsagePlanKey(String region, String usagePlanId, String keyId) {
try {
return apiGatewayService.getUsagePlanKey(region, usagePlanId, keyId);
} catch (AwsException e) {
if (!NOT_FOUND.equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Usage plan key {0} on plan {1} from the previous provision is gone, creating it again",
keyId, usagePlanId);
return null;
}
}
/** AWS reports a usage plan key as {@code <keyId>:<usagePlanId>}; that is also what delete needs. */
private static void recordKey(StackResource r, String keyId, String usagePlanId) {
String id = keyId + KEY_ID_SEPARATOR + usagePlanId;
r.setPhysicalId(id);
r.getAttributes().put("Id", id);
}
/** {@code [keyId, usagePlanId]}, or null when the id is not in that shape. */
private static String[] splitKeyId(String physicalId) {
if (physicalId == null) {
return null;
}
int separator = physicalId.indexOf(KEY_ID_SEPARATOR);
if (separator <= 0 || separator == physicalId.length() - 1) {
return null;
}
return new String[] {physicalId.substring(0, separator), physicalId.substring(separator + 1)};
}
// ──────────────────────────── shared ────────────────────────────
private static void rejectIfChanged(String property, String existing, String requested) {
if (!Objects.equals(blankToNull(existing), blankToNull(requested))) {
throw new AwsException("ValidationError",
"Updating " + property + " requires resource replacement, which is not supported.", 400);
}
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
private static Map<String, String> patch(String op, String path, String value) {
Map<String, String> patch = new HashMap<>();
patch.put("op", op);
patch.put("path", path);
patch.put("value", value);
return patch;
}
/** Without this the plan, or the key's membership in it, outlives the stack. */
@Override
public void delete(String resourceType, String physicalId, String region) {
if (physicalId == null || physicalId.isBlank()) {
return;
}
switch (resourceType) {
case USAGE_PLAN -> CfnDeletes.safeDelete("usage plan", physicalId,
() -> apiGatewayService.deleteUsagePlan(region, physicalId), NOT_FOUND);
case USAGE_PLAN_KEY -> {
String[] parts = splitKeyId(physicalId);
if (parts == null) {
LOG.warnv("Usage plan key {0} has no <keyId>:<usagePlanId> physical id, leaving it in place",
physicalId);
return;
}
CfnDeletes.safeDelete("usage plan key", physicalId,
() -> apiGatewayService.deleteUsagePlanKey(region, parts[1], parts[0]), NOT_FOUND);
}
default -> { }
}
}
}
@@ -0,0 +1,242 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Provisions an {@code AWS::ApiGateway::UsagePlan} over a deployed REST API stage and an
* {@code AWS::ApiGateway::UsagePlanKey} attaching an API key to it, the way a template guards an
* API behind a key. The API and the key are created outside the stack, since the stack only owns
* the plan and the association. Asserts that {@code Ref} and {@code Fn::GetAtt Id} resolve to the
* plan id and to {@code <keyId>:<usagePlanId>}, that an update renames the plan and moves its stage
* in place, and that deleting the stack removes the plan and the association but not the key.
*/
@QuarkusTest
class ApiGatewayUsagePlanCfnIntegrationTest {
private static final String REGION = "us-east-1";
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
private static final String STACK = "apigw-usageplan-cfn-it";
private static final String TEMPLATE = """
{
"Parameters": {
"ApiId": {"Type": "String"},
"StageName": {"Type": "String"},
"KeyId": {"Type": "String"},
"PlanName": {"Type": "String"},
"Description": {"Type": "String"},
"TagValue": {"Type": "String"}
},
"Resources": {
"Plan": {
"Type": "AWS::ApiGateway::UsagePlan",
"Properties": {
"UsagePlanName": {"Ref": "PlanName"},
"Description": {"Ref": "Description"},
"ApiStages": [{"ApiId": {"Ref": "ApiId"}, "Stage": {"Ref": "StageName"}}],
"Throttle": {"BurstLimit": 10, "RateLimit": 5},
"Quota": {"Limit": 1000, "Period": "MONTH"},
"Tags": [{"Key": "stack", "Value": {"Ref": "TagValue"}}]
}
},
"PlanKey": {
"Type": "AWS::ApiGateway::UsagePlanKey",
"Properties": {
"UsagePlanId": {"Ref": "Plan"},
"KeyId": {"Ref": "KeyId"},
"KeyType": "API_KEY"
}
}
},
"Outputs": {
"PlanRef": {"Value": {"Ref": "Plan"}},
"PlanId": {"Value": {"Fn::GetAtt": ["Plan", "Id"]}},
"KeyRef": {"Value": {"Ref": "PlanKey"}},
"KeyAttId": {"Value": {"Fn::GetAtt": ["PlanKey", "Id"]}}
}
}
""";
@Inject
ApiGatewayService apiGatewayService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createUpdateAndDeleteAUsagePlanWithAKey() throws InterruptedException {
String apiId = createMockApi(STACK);
String deploymentId = createDeployment(apiId);
createStage(apiId, "dev", deploymentId);
createStage(apiId, "prod", deploymentId);
String keyId = given().contentType(ContentType.JSON).body("{\"name\":\"" + STACK + "-key\"}")
.when().post("/apikeys").then().statusCode(201).extract().path("id");
try {
cloudFormation("CreateStack", parameters(apiId, "dev", keyId, "gold", "first", "v1"));
String created = describeStacks("CREATE_COMPLETE");
String planId = outputValue(created, "PlanRef");
// Fn::GetAtt Id is the plan id, and the key resource reports <keyId>:<usagePlanId> as on AWS.
assertEquals(planId, outputValue(created, "PlanId"));
assertEquals(keyId + ":" + planId, outputValue(created, "KeyRef"));
assertEquals(keyId + ":" + planId, outputValue(created, "KeyAttId"));
getUsagePlan(planId)
.statusCode(200)
.body("name", equalTo("gold"))
.body("description", equalTo("first"))
.body("tags.stack", equalTo("v1"));
assertEquals(List.of(new UsagePlan.ApiStage(apiId, "dev")),
apiGatewayService.getUsagePlan(REGION, planId).getApiStages());
getUsagePlanKey(planId, keyId).statusCode(200).body("type", equalTo("API_KEY"));
cloudFormation("UpdateStack", parameters(apiId, "prod", keyId, "platinum", "second", "v2"));
String updated = describeStacks("UPDATE_COMPLETE");
// The plan is renamed and moved to the other stage in place; the association survives.
assertEquals(planId, outputValue(updated, "PlanRef"));
assertEquals(keyId + ":" + planId, outputValue(updated, "KeyRef"));
getUsagePlan(planId)
.statusCode(200)
.body("name", equalTo("platinum"))
.body("description", equalTo("second"))
.body("tags.stack", equalTo("v2"));
assertEquals(List.of(new UsagePlan.ApiStage(apiId, "prod")),
apiGatewayService.getUsagePlan(REGION, planId).getApiStages());
getUsagePlanKey(planId, keyId).statusCode(200);
cloudFormation("DeleteStack", Map.of());
awaitStackDeleted();
// The stack owned the plan and the association, not the key.
getUsagePlan(planId).statusCode(404);
getUsagePlanKey(planId, keyId).statusCode(404);
given().when().get("/apikeys/" + keyId).then().statusCode(200);
} finally {
given().when().delete("/apikeys/" + keyId);
given().when().delete("/restapis/" + apiId);
}
}
private static Map<String, String> parameters(String apiId, String stage, String keyId, String planName,
String description, String tagValue) {
return Map.of("ApiId", apiId, "StageName", stage, "KeyId", keyId, "PlanName", planName,
"Description", description, "TagValue", tagValue);
}
private static void cloudFormation(String action, Map<String, String> parameters) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", STACK);
if (!"DeleteStack".equals(action)) {
request.formParam("TemplateBody", TEMPLATE);
}
int index = 1;
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
index++;
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
/** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
private static void awaitStackDeleted() throws InterruptedException {
for (int i = 0; i < 100; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().extract().asString();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("stack delete failed: " + body);
}
Thread.sleep(50);
}
fail("stack " + STACK + " was not deleted within the timeout");
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
private static ValidatableResponse getUsagePlan(String planId) {
return given().when().get("/usageplans/" + planId).then();
}
private static ValidatableResponse getUsagePlanKey(String planId, String keyId) {
return given().when().get("/usageplans/" + planId + "/keys/" + keyId).then();
}
/** A REST API whose GET /items is a MOCK integration, enough for a deployment and two stages. */
private static String createMockApi(String name) {
String apiId = given().contentType(ContentType.JSON).body("{\"name\":\"" + name + "\"}")
.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");
String resourceId = given().contentType(ContentType.JSON).body("{\"pathPart\":\"items\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId).then().statusCode(201).extract().path("id");
String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
.when().put(method).then().statusCode(201);
given().contentType(ContentType.JSON).body("{\"responseParameters\":{}}")
.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);
return apiId;
}
private static String createDeployment(String apiId) {
return given().contentType(ContentType.JSON).body("{\"description\":\"v1\"}")
.when().post("/restapis/" + apiId + "/deployments").then().statusCode(201).extract().path("id");
}
private static void createStage(String apiId, String stage, String deploymentId) {
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"" + stage + "\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages").then().statusCode(201);
}
}
@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.wafv2.WafV2Service;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AcmCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayAccountCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayApiKeyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
@@ -245,6 +246,7 @@ final class CfnProvisionerFixture {
if (apiGatewayService != null) {
discovered.add(new ApiGatewayAccountCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayApiKeyCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayUsagePlanCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService));
}
if (autoScalingService != null) {
@@ -0,0 +1,347 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlan;
import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** The API Gateway usage plan CFN provisioner in isolation, against a mocked {@link ApiGatewayService}. */
class ApiGatewayUsagePlanCfnProvisionerTest {
private static final String REGION = "us-east-1";
private static final String PLAN = "AWS::ApiGateway::UsagePlan";
private static final String PLAN_KEY = "AWS::ApiGateway::UsagePlanKey";
private static final AwsException NOT_FOUND =
new AwsException("NotFoundException", "Usage Plan not found", 404);
private final ApiGatewayService apiGateway = mock(ApiGatewayService.class);
private final ApiGatewayUsagePlanCfnProvisioner provisioner = new ApiGatewayUsagePlanCfnProvisioner(apiGateway);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
return ctx(null);
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
}
private static StackResource resource(String type, String logicalId, String priorPhysicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
r.setResourceType(type);
r.setPhysicalId(priorPhysicalId);
r.setAttributes(new HashMap<>());
return r;
}
private static UsagePlan plan(String id, String name, String description, Map<String, String> tags,
UsagePlan.ApiStage... stages) {
UsagePlan plan = new UsagePlan();
plan.setId(id);
plan.setName(name);
plan.setDescription(description);
plan.setTags(new HashMap<>(tags));
plan.getApiStages().addAll(List.of(stages));
return plan;
}
private ObjectNode planProps(String name, String description, String tagValue, String... apiIdStagePairs) {
ObjectNode props = mapper.createObjectNode();
if (name != null) {
props.put("UsagePlanName", name);
}
if (description != null) {
props.put("Description", description);
}
if (tagValue != null) {
props.putArray("Tags").addObject().put("Key", "stack").put("Value", tagValue);
}
ArrayNode stages = props.putArray("ApiStages");
for (String pair : apiIdStagePairs) {
String[] parts = pair.split(":");
stages.addObject().put("ApiId", parts[0]).put("Stage", parts[1]);
}
return props;
}
private ObjectNode keyProps(String planId, String keyId, String keyType) {
return mapper.createObjectNode().put("UsagePlanId", planId).put("KeyId", keyId).put("KeyType", keyType);
}
// ──────────────────────────── UsagePlan ────────────────────────────
@Test
void usagePlanCreateSendsNameDescriptionStagesAndTags() {
when(apiGateway.createUsagePlan(eq(REGION), anyMap()))
.thenReturn(plan("plan-1", "gold", "a plan", Map.of("stack", "v1")));
StackResource r = resource(PLAN, "Plan", null);
provisioner.provision(r, planProps("gold", "a plan", "v1", "api1:dev", "api2:prod"), ctx());
assertEquals("plan-1", r.getPhysicalId());
assertEquals("plan-1", r.getAttributes().get("Id"));
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
verify(apiGateway).createUsagePlan(eq(REGION), request.capture());
assertEquals("gold", request.getValue().get("name"));
assertEquals("a plan", request.getValue().get("description"));
assertEquals(Map.of("stack", "v1"), request.getValue().get("tags"));
assertEquals(List.of(Map.of("apiId", "api1", "stage", "dev"), Map.of("apiId", "api2", "stage", "prod")),
request.getValue().get("apiStages"));
}
@Test
void usagePlanWithoutANameGetsAGeneratedOne() {
when(apiGateway.createUsagePlan(eq(REGION), anyMap())).thenReturn(plan("plan-1", "x", null, Map.of()));
provisioner.provision(resource(PLAN, "Plan", null), mapper.createObjectNode(), ctx());
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
verify(apiGateway).createUsagePlan(eq(REGION), request.capture());
String name = (String) request.getValue().get("name");
assertTrue(name.startsWith("my-stack-Plan-"), name);
assertEquals(List.of(), request.getValue().get("apiStages"));
}
@Test
void aStageWithoutAnApiIdIsRejected() {
ObjectNode props = mapper.createObjectNode();
props.putArray("ApiStages").addObject().put("Stage", "dev");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(PLAN, "Plan", null), props, ctx()));
assertEquals("ValidationError", e.getErrorCode());
verify(apiGateway, never()).createUsagePlan(any(), anyMap());
}
@Test
void usagePlanUpdatePatchesNameDescriptionAndStagesInPlace() {
UsagePlan existing = plan("plan-1", "gold", "old", Map.of(),
new UsagePlan.ApiStage("api1", "dev"), new UsagePlan.ApiStage("api1", "test"));
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
when(apiGateway.updateUsagePlan(eq(REGION), eq("plan-1"), anyList())).thenReturn(existing);
StackResource r = resource(PLAN, "Plan", "plan-1");
provisioner.provision(r, planProps("platinum", "new", null, "api1:dev", "api1:prod"), ctx("plan-1"));
verify(apiGateway, never()).createUsagePlan(any(), anyMap());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Map<String, String>>> patches = ArgumentCaptor.forClass(List.class);
verify(apiGateway).updateUsagePlan(eq(REGION), eq("plan-1"), patches.capture());
List<Map<String, String>> ops = patches.getValue();
assertTrue(ops.contains(Map.of("op", "replace", "path", "/name", "value", "platinum")), ops.toString());
assertTrue(ops.contains(Map.of("op", "replace", "path", "/description", "value", "new")), ops.toString());
assertTrue(ops.contains(Map.of("op", "remove", "path", "/apiStages", "value", "api1:test")), ops.toString());
assertTrue(ops.contains(Map.of("op", "add", "path", "/apiStages", "value", "api1:prod")), ops.toString());
assertEquals(4, ops.size(), ops.toString());
assertEquals("plan-1", r.getPhysicalId());
assertEquals("plan-1", r.getAttributes().get("Id"));
}
@Test
void anUnchangedUsagePlanUpdateTouchesNothing() {
UsagePlan existing = plan("plan-1", "gold", "same", Map.of("stack", "v1"), new UsagePlan.ApiStage("api1", "dev"));
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
provisioner.provision(resource(PLAN, "Plan", "plan-1"), planProps("gold", "same", "v1", "api1:dev"), ctx("plan-1"));
verify(apiGateway, never()).createUsagePlan(any(), anyMap());
verify(apiGateway, never()).updateUsagePlan(any(), any(), anyList());
verify(apiGateway, never()).replaceUsagePlanTags(any(), any(), anyMap());
}
@Test
void changedUsagePlanTagsAreReplacedWholesale() {
UsagePlan existing = plan("plan-1", "gold", null, Map.of("stack", "v1", "stale", "x"));
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(existing);
when(apiGateway.replaceUsagePlanTags(eq(REGION), eq("plan-1"), anyMap())).thenReturn(existing);
provisioner.provision(resource(PLAN, "Plan", "plan-1"), planProps("gold", null, "v2"), ctx("plan-1"));
verify(apiGateway).replaceUsagePlanTags(REGION, "plan-1", Map.of("stack", "v2"));
verify(apiGateway, never()).updateUsagePlan(any(), any(), anyList());
}
@Test
void aUsagePlanDeletedOutOfBandIsCreatedAgain() {
when(apiGateway.getUsagePlan(REGION, "gone")).thenThrow(NOT_FOUND);
when(apiGateway.createUsagePlan(eq(REGION), anyMap())).thenReturn(plan("plan-2", "gold", null, Map.of()));
StackResource r = resource(PLAN, "Plan", "gone");
provisioner.provision(r, planProps("gold", null, null), ctx("gone"));
assertEquals("plan-2", r.getPhysicalId());
assertEquals("plan-2", r.getAttributes().get("Id"));
}
@Test
void deleteUsagePlanDelegatesAndToleratesAMissingPlan() {
provisioner.delete(PLAN, "plan-1", REGION);
verify(apiGateway).deleteUsagePlan(REGION, "plan-1");
doThrow(NOT_FOUND).when(apiGateway).deleteUsagePlan(REGION, "gone");
assertDoesNotThrow(() -> provisioner.delete(PLAN, "gone", REGION));
}
// ──────────────────────────── UsagePlanKey ────────────────────────────
@Test
void usagePlanKeyCreateRecordsTheCompositeId() {
when(apiGateway.createUsagePlanKey(eq(REGION), eq("plan-1"), anyMap()))
.thenReturn(new UsagePlanKey("key-1", "my-key", "API_KEY", "value"));
StackResource r = resource(PLAN_KEY, "PlanKey", null);
provisioner.provision(r, keyProps("plan-1", "key-1", "API_KEY"), ctx());
assertEquals("key-1:plan-1", r.getPhysicalId());
assertEquals("key-1:plan-1", r.getAttributes().get("Id"));
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
verify(apiGateway).createUsagePlanKey(eq(REGION), eq("plan-1"), request.capture());
assertEquals("key-1", request.getValue().get("keyId"));
assertEquals("API_KEY", request.getValue().get("keyType"));
}
@Test
void anUnchangedUsagePlanKeyUpdateIsANoOp() {
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(plan("plan-1", "gold", null, Map.of()));
when(apiGateway.getUsagePlanKey(REGION, "plan-1", "key-1"))
.thenReturn(new UsagePlanKey("key-1", "my-key", "API_KEY", "value"));
StackResource r = resource(PLAN_KEY, "PlanKey", "key-1:plan-1");
provisioner.provision(r, keyProps("plan-1", "key-1", "API_KEY"), ctx("key-1:plan-1"));
verify(apiGateway, never()).createUsagePlanKey(any(), any(), anyMap());
assertEquals("key-1:plan-1", r.getPhysicalId());
assertEquals("key-1:plan-1", r.getAttributes().get("Id"));
}
@Test
void aChangedKeyOrPlanIsRefusedAsReplacementWorthy() {
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(plan("plan-1", "gold", null, Map.of()));
when(apiGateway.getUsagePlanKey(REGION, "plan-1", "key-1"))
.thenReturn(new UsagePlanKey("key-1", "my-key", "API_KEY", "value"));
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
resource(PLAN_KEY, "PlanKey", "key-1:plan-1"), keyProps("plan-1", "key-2", "API_KEY"), ctx("key-1:plan-1")));
assertEquals("ValidationError", e.getErrorCode());
assertTrue(e.getMessage().contains("KeyId"), e.getMessage());
verify(apiGateway, never()).createUsagePlanKey(any(), any(), anyMap());
}
@Test
void aUsagePlanKeyGoneFromThePlanIsAssociatedAgain() {
when(apiGateway.getUsagePlan(REGION, "plan-1")).thenReturn(plan("plan-1", "gold", null, Map.of()));
when(apiGateway.getUsagePlanKey(REGION, "plan-1", "key-1"))
.thenThrow(new AwsException("NotFoundException", "Usage Plan Key not found", 404));
when(apiGateway.createUsagePlanKey(eq(REGION), eq("plan-1"), anyMap()))
.thenReturn(new UsagePlanKey("key-1", "my-key", "API_KEY", "value"));
StackResource r = resource(PLAN_KEY, "PlanKey", "key-1:plan-1");
provisioner.provision(r, keyProps("plan-1", "key-1", "API_KEY"), ctx("key-1:plan-1"));
verify(apiGateway).createUsagePlanKey(eq(REGION), eq("plan-1"), anyMap());
assertEquals("key-1:plan-1", r.getPhysicalId());
}
@Test
void anAssociationWhosePlanIsGoneIsRecreatedOnTheNewPlan() {
when(apiGateway.getUsagePlan(REGION, "plan-old")).thenThrow(NOT_FOUND);
when(apiGateway.createUsagePlanKey(eq(REGION), eq("plan-new"), anyMap()))
.thenReturn(new UsagePlanKey("key-1", "my-key", "API_KEY", "value"));
StackResource r = resource(PLAN_KEY, "PlanKey", "key-1:plan-old");
provisioner.provision(r, keyProps("plan-new", "key-1", "API_KEY"), ctx("key-1:plan-old"));
// The stale association under the deleted plan is not consulted, so the new plan id is not a rename.
verify(apiGateway, never()).getUsagePlanKey(any(), any(), any());
verify(apiGateway).createUsagePlanKey(eq(REGION), eq("plan-new"), anyMap());
assertEquals("key-1:plan-new", r.getPhysicalId());
}
@Test
void aChangedKeyIsRefusedEvenWhileRecoveringADeletedPlan() {
when(apiGateway.getUsagePlan(REGION, "plan-old")).thenThrow(NOT_FOUND);
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
resource(PLAN_KEY, "PlanKey", "key-1:plan-old"), keyProps("plan-new", "key-2", "API_KEY"),
ctx("key-1:plan-old")));
assertTrue(e.getMessage().contains("KeyId"), e.getMessage());
verify(apiGateway, never()).createUsagePlanKey(any(), any(), anyMap());
}
@Test
void aKeyTypeOtherThanApiKeyIsRejected() {
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
resource(PLAN_KEY, "PlanKey", null), keyProps("plan-1", "key-1", "BEARER"), ctx()));
assertEquals("ValidationError", e.getErrorCode());
verify(apiGateway, never()).createUsagePlanKey(any(), any(), anyMap());
}
@Test
void aMissingKeyIdIsRejected() {
ObjectNode props = mapper.createObjectNode().put("UsagePlanId", "plan-1").put("KeyType", "API_KEY");
assertThrows(AwsException.class, () -> provisioner.provision(resource(PLAN_KEY, "PlanKey", null), props, ctx()));
verify(apiGateway, never()).createUsagePlanKey(any(), any(), anyMap());
}
@Test
void apiStagesThatIsNotAListIsRejected() {
ObjectNode props = mapper.createObjectNode().put("UsagePlanName", "gold").put("ApiStages", "api1:dev");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(PLAN, "Plan", null), props, ctx()));
assertEquals("ValidationError", e.getErrorCode());
verify(apiGateway, never()).createUsagePlan(any(), anyMap());
}
@Test
void deleteUsagePlanKeySplitsTheIdAndToleratesAMissingAssociation() {
provisioner.delete(PLAN_KEY, "key-1:plan-1", REGION);
verify(apiGateway).deleteUsagePlanKey(REGION, "plan-1", "key-1");
doThrow(new AwsException("NotFoundException", "Usage Plan Key not found", 404))
.when(apiGateway).deleteUsagePlanKey(REGION, "plan-1", "gone");
assertDoesNotThrow(() -> provisioner.delete(PLAN_KEY, "gone:plan-1", REGION));
}
}
@@ -8,6 +8,8 @@ AWS::ApiGateway::Method LEGACY_SWITCH
AWS::ApiGateway::Resource LEGACY_SWITCH
AWS::ApiGateway::RestApi LEGACY_SWITCH
AWS::ApiGateway::Stage LEGACY_SWITCH
AWS::ApiGateway::UsagePlan ApiGatewayUsagePlanCfnProvisioner
AWS::ApiGateway::UsagePlanKey ApiGatewayUsagePlanCfnProvisioner
AWS::ApiGatewayV2::Api LEGACY_SWITCH
AWS::ApiGatewayV2::Authorizer LEGACY_SWITCH
AWS::ApiGatewayV2::Deployment LEGACY_SWITCH
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
8 AWS::ApiGateway::Resource LEGACY_SWITCH
9 AWS::ApiGateway::RestApi LEGACY_SWITCH
10 AWS::ApiGateway::Stage LEGACY_SWITCH
11 AWS::ApiGateway::UsagePlan ApiGatewayUsagePlanCfnProvisioner
12 AWS::ApiGateway::UsagePlanKey ApiGatewayUsagePlanCfnProvisioner
13 AWS::ApiGatewayV2::Api LEGACY_SWITCH
14 AWS::ApiGatewayV2::Authorizer LEGACY_SWITCH
15 AWS::ApiGatewayV2::Deployment LEGACY_SWITCH