mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
2c6a92c07d
commit
3a4982c294
7 files changed
+910
-1
No files matched your search
+242
@@ -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);
|
||||
}
|
||||
}
|
||||
+2
@@ -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) {
|
||||
|
||||
+347
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user