Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision AWS::ApiGateway::ApiKey (#3122)

lex00cbde58f238a7
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index aedece9667..8601eee9fb 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -84,7 +84,7 @@ cross-resource references.
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook` |
| Route 53 | `HostedZone`, `RecordSet` |
-| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping` |
+| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `ApiKey` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` |
| Step Functions | `StateMachine` |
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index 14f19fba9b..92d651f6b0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -6,6 +6,7 @@ import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -995,6 +996,29 @@ public class ApiGatewayService {
return key;
}
+ /**
+ * Replaces an API key'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 ApiKey replaceApiKeyTags(String region, String apiKeyId, Map<String, String> tags) {
+ ApiKey key = getApiKey(region, apiKeyId);
+ // A reserved tag is an id override and only means something at create time, so adding or
+ // changing one here is refused. One the key already carries from its creation may stay, or
+ // a template that pins an id could never change any other tag afterwards.
+ Map<String, String> changed = new HashMap<>();
+ tags.forEach((tagKey, value) -> {
+ if (!Objects.equals(value, key.getTags().get(tagKey))) {
+ changed.put(tagKey, value);
+ }
+ });
+ ReservedTags.rejectApiGatewayReservedTagsOnUpdate(changed);
+ key.setTags(new HashMap<>(tags));
+ key.setLastUpdatedDate(System.currentTimeMillis() / 1000L);
+ apiKeyStore.put(apiKeyGlobalKey(region, apiKeyId), key);
+ return key;
+ }
+
// ──────────────────────────── Usage Plans ────────────────────────────
public UsagePlan createUsagePlan(String region, Map<String, Object> request) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayApiKeyCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayApiKeyCfnProvisioner.java
new file mode 100644
index 0000000000..279966a754
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayApiKeyCfnProvisioner.java
@@ -0,0 +1,173 @@
+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.services.apigateway.ApiGatewayService;
+import io.github.hectorvent.floci.services.apigateway.model.ApiKey;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+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::ApiKey}, backed by
+ * {@link ApiGatewayService}. {@code Ref} and {@code Fn::GetAtt [Key, APIKeyId]} both yield the key
+ * id, matching AWS.
+ *
+ * <p>Description, Enabled and Tags update in place. Name, Value and GenerateDistinctId are
+ * createOnly in the registry schema: AWS replaces the key for a change to any of them, and this
+ * provisioner has no replacement path, so such a change is reported rather than applied to a key
+ * whose value callers already hold. CustomerId and the deprecated StageKeys have no counterpart in
+ * {@link ApiKey} and are accepted without effect.
+ */
+@ApplicationScoped
+public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String TYPE = "AWS::ApiGateway::ApiKey";
+ private static final String NOT_FOUND = "NotFoundException";
+ /** 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 ApiGatewayApiKeyCfnProvisioner(ApiGatewayService apiGatewayService) {
+ this.apiGatewayService = apiGatewayService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(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 key on every update and orphan the first, which then outlives the
+ // stack since delete only knows the id recorded last.
+ ApiKey existing = apiGatewayService.findApiKey(ctx.region(), ctx.priorPhysicalId()).orElse(null);
+ if (existing != null) {
+ update(r, existing, props, ctx);
+ return;
+ }
+ }
+ create(r, props, ctx);
+ }
+
+ private void create(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = ctx.resolveOptional(props, "Name");
+ 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"));
+ Boolean enabled = resolveBoolean(props, "Enabled", ctx);
+ if (enabled != null) {
+ request.put("enabled", enabled);
+ }
+ Boolean generateDistinctId = resolveBoolean(props, "GenerateDistinctId", ctx);
+ if (generateDistinctId != null) {
+ request.put("generateDistinctId", generateDistinctId);
+ }
+ String value = ctx.resolveOptional(props, "Value");
+ if (value != null && !value.isBlank()) {
+ request.put("value", value);
+ }
+ request.put("tags", ctx.resolveTags(props, "Tags"));
+
+ record(r, apiGatewayService.createApiKey(ctx.region(), request));
+ }
+
+ private void update(StackResource r, ApiKey existing, JsonNode props, ProvisionContext ctx) {
+ // A template that omits Name keeps whatever name the key was created with, generated or
+ // not; only an explicit, different Name is a rename.
+ String name = ctx.resolveOptional(props, "Name");
+ if (name != null && !name.isBlank()) {
+ rejectIfChanged("Name", existing.getName(), name);
+ }
+ String value = ctx.resolveOptional(props, "Value");
+ if (value != null && !value.isBlank()) {
+ rejectIfChanged("Value", existing.getValue(), value);
+ }
+ // createApiKey gives a key with GenerateDistinctId=false its value as its id, so whether the
+ // two differ records which mode the key was created in.
+ boolean requestedDistinct = Boolean.TRUE.equals(resolveBoolean(props, "GenerateDistinctId", ctx));
+ boolean existingDistinct = !Objects.equals(existing.getId(), existing.getValue());
+ if (requestedDistinct != existingDistinct) {
+ throw replacementNotSupported("GenerateDistinctId");
+ }
+
+ List<Map<String, String>> patches = new ArrayList<>();
+ String description = ctx.resolveOptional(props, "Description");
+ if (!Objects.equals(blankToNull(description), blankToNull(existing.getDescription()))) {
+ patches.add(patch("/description", description));
+ }
+ // Enabled defaults to true when the template omits it, as in AWS.
+ Boolean enabled = resolveBoolean(props, "Enabled", ctx);
+ boolean desiredEnabled = enabled == null || enabled;
+ if (desiredEnabled != existing.isEnabled()) {
+ patches.add(patch("/enabled", Boolean.toString(desiredEnabled)));
+ }
+ ApiKey key = patches.isEmpty()
+ ? existing
+ : apiGatewayService.updateApiKey(ctx.region(), existing.getId(), patches);
+
+ Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
+ if (!desiredTags.equals(key.getTags())) {
+ key = apiGatewayService.replaceApiKeyTags(ctx.region(), key.getId(), desiredTags);
+ }
+ record(r, key);
+ }
+
+ private static void record(StackResource r, ApiKey key) {
+ r.setPhysicalId(key.getId());
+ r.getAttributes().put("APIKeyId", key.getId());
+ }
+
+ private static Boolean resolveBoolean(JsonNode props, String name, ProvisionContext ctx) {
+ String resolved = ctx.resolveOptional(props, name);
+ return resolved == null || resolved.isBlank() ? null : Boolean.parseBoolean(resolved);
+ }
+
+ private static void rejectIfChanged(String property, String existing, String requested) {
+ if (!Objects.equals(blankToNull(existing), blankToNull(requested))) {
+ throw replacementNotSupported(property);
+ }
+ }
+
+ private static AwsException replacementNotSupported(String property) {
+ return 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;
+ }
+
+ /** A null value clears the field, the way a template that drops Description reads on AWS. */
+ private static Map<String, String> patch(String path, String value) {
+ Map<String, String> op = new HashMap<>();
+ op.put("op", "replace");
+ op.put("path", path);
+ op.put("value", value);
+ return op;
+ }
+
+ /** Without this the key outlives its stack and keeps authenticating requests. */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ CfnDeletes.safeDelete("API key", physicalId,
+ () -> apiGatewayService.deleteApiKey(region, physicalId), NOT_FOUND);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayApiKeyCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayApiKeyCfnIntegrationTest.java
new file mode 100644
index 0000000000..32b3b646df
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayApiKeyCfnIntegrationTest.java
@@ -0,0 +1,188 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+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.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Provisions {@code AWS::ApiGateway::ApiKey} resources through a CloudFormation stack: a named key
+ * with every mutable property set, a key with no properties at all, and a key with a caller-chosen
+ * value and a distinct id. Asserts that {@code Ref} and {@code Fn::GetAtt APIKeyId} both resolve to
+ * the id {@code GetApiKey} serves rather than the literal the stub arm would leave, that an update
+ * changes description, enabled flag and tags on the same key, and that deleting the stack removes
+ * every key.
+ */
+@QuarkusTest
+class ApiGatewayApiKeyCfnIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
+ private static final String STACK = "apigw-apikey-cfn-it";
+ private static final String NAMED = "apigw-apikey-cfn-it-named";
+ private static final String CHOSEN_VALUE = "apigw-apikey-cfn-it-value-0123456789";
+
+ /** Description, Enabled and the tag value are parameters so one template drives create and update. */
+ private static final String TEMPLATE = """
+ {
+ "Parameters": {
+ "Description": {"Type": "String"},
+ "Enabled": {"Type": "String"},
+ "TagValue": {"Type": "String"}
+ },
+ "Resources": {
+ "Named": {
+ "Type": "AWS::ApiGateway::ApiKey",
+ "Properties": {
+ "Name": "%s",
+ "Description": {"Ref": "Description"},
+ "Enabled": {"Ref": "Enabled"},
+ "Tags": [{"Key": "stack", "Value": {"Ref": "TagValue"}}]
+ }
+ },
+ "Unnamed": {"Type": "AWS::ApiGateway::ApiKey"},
+ "Distinct": {
+ "Type": "AWS::ApiGateway::ApiKey",
+ "Properties": {"GenerateDistinctId": "true", "Value": "%s"}
+ }
+ },
+ "Outputs": {
+ "NamedRef": {"Value": {"Ref": "Named"}},
+ "NamedId": {"Value": {"Fn::GetAtt": ["Named", "APIKeyId"]}},
+ "UnnamedRef": {"Value": {"Ref": "Unnamed"}},
+ "DistinctRef": {"Value": {"Ref": "Distinct"}}
+ }
+ }
+ """.formatted(NAMED, CHOSEN_VALUE);
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void createUpdateAndDeleteApiKeys() throws InterruptedException {
+ cloudFormation("CreateStack", parameters("first", "false", "v1"));
+ String created = describeStacks("CREATE_COMPLETE");
+ String namedId = outputValue(created, "NamedRef");
+ String unnamedId = outputValue(created, "UnnamedRef");
+ String distinctId = outputValue(created, "DistinctRef");
+
+ // Fn::GetAtt APIKeyId is the id itself, not the literal "Named.APIKeyId" the stub arm leaves.
+ assertEquals(namedId, outputValue(created, "NamedId"));
+
+ getApiKey(namedId)
+ .statusCode(200)
+ .body("name", equalTo(NAMED))
+ .body("description", equalTo("first"))
+ .body("enabled", equalTo(false))
+ .body("tags.stack", equalTo("v1"))
+ .body("value", equalTo(namedId));
+
+ // A key with no properties gets a CloudFormation-style generated name and AWS's defaults.
+ getApiKey(unnamedId)
+ .statusCode(200)
+ .body("name", startsWith(STACK + "-Unnamed-"))
+ .body("enabled", equalTo(true));
+
+ // A caller-chosen value with a distinct id keeps the value and mints a separate id.
+ assertNotEquals(CHOSEN_VALUE, distinctId);
+ getApiKey(distinctId)
+ .statusCode(200)
+ .body("value", equalTo(CHOSEN_VALUE))
+ .body("id", not(equalTo(CHOSEN_VALUE)));
+
+ cloudFormation("UpdateStack", parameters("second", "true", "v2"));
+ String updated = describeStacks("UPDATE_COMPLETE");
+
+ // The mutable properties change on the same key; nothing is replaced.
+ assertEquals(namedId, outputValue(updated, "NamedRef"));
+ getApiKey(namedId)
+ .statusCode(200)
+ .body("description", equalTo("second"))
+ .body("enabled", equalTo(true))
+ .body("tags.stack", equalTo("v2"));
+
+ cloudFormation("DeleteStack", Map.of());
+ awaitStackDeleted();
+
+ getApiKey(namedId).statusCode(404);
+ getApiKey(unnamedId).statusCode(404);
+ getApiKey(distinctId).statusCode(404);
+ }
+
+ private static Map<String, String> parameters(String description, String enabled, String tagValue) {
+ return Map.of("Description", description, "Enabled", enabled, "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 getApiKey(String id) {
+ return given().when().get("/apikeys/" + id + "?includeValue=true").then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 697f5570e8..b388b32f41 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.sqs.SqsService;
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.ApiGatewayDomainCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
@@ -242,6 +243,7 @@ final class CfnProvisionerFixture {
}
if (apiGatewayService != null) {
discovered.add(new ApiGatewayAccountCfnProvisioner(apiGatewayService));
+ discovered.add(new ApiGatewayApiKeyCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService));
}
if (autoScalingService != null) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayApiKeyCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayApiKeyCfnProvisionerTest.java
new file mode 100644
index 0000000000..c4b91bf08c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayApiKeyCfnProvisionerTest.java
@@ -0,0 +1,242 @@
+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.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.ApiKey;
+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 java.util.Optional;
+
+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 API key CFN provisioner in isolation, against a mocked {@link ApiGatewayService}. */
+class ApiGatewayApiKeyCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String TYPE = "AWS::ApiGateway::ApiKey";
+
+ private final ApiGatewayService apiGateway = mock(ApiGatewayService.class);
+ private final ApiGatewayApiKeyCfnProvisioner provisioner = new ApiGatewayApiKeyCfnProvisioner(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 priorPhysicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId("MyKey");
+ r.setResourceType(TYPE);
+ r.setPhysicalId(priorPhysicalId);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private static ApiKey key(String id, String name, String value, boolean enabled, String description,
+ Map<String, String> tags) {
+ ApiKey key = new ApiKey();
+ key.setId(id);
+ key.setName(name);
+ key.setValue(value);
+ key.setEnabled(enabled);
+ key.setDescription(description);
+ key.setTags(new HashMap<>(tags));
+ return key;
+ }
+
+ private ObjectNode tags(String k, String v) {
+ ObjectNode props = mapper.createObjectNode();
+ props.putArray("Tags").addObject().put("Key", k).put("Value", v);
+ return props;
+ }
+
+ @Test
+ void createSendsTheTemplatePropertiesAndRecordsTheId() {
+ when(apiGateway.createApiKey(eq(REGION), anyMap()))
+ .thenReturn(key("abc123", "my-key", "0123456789abcdef0123", false, "a key", Map.of("team", "core")));
+ ObjectNode props = tags("team", "core")
+ .put("Name", "my-key")
+ .put("Description", "a key")
+ .put("Enabled", "false")
+ .put("GenerateDistinctId", "true")
+ .put("Value", "0123456789abcdef0123");
+ StackResource r = resource(null);
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("abc123", r.getPhysicalId());
+ assertEquals("abc123", r.getAttributes().get("APIKeyId"));
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
+ verify(apiGateway).createApiKey(eq(REGION), request.capture());
+ assertEquals("my-key", request.getValue().get("name"));
+ assertEquals("a key", request.getValue().get("description"));
+ assertEquals(Boolean.FALSE, request.getValue().get("enabled"));
+ assertEquals(Boolean.TRUE, request.getValue().get("generateDistinctId"));
+ assertEquals("0123456789abcdef0123", request.getValue().get("value"));
+ assertEquals(Map.of("team", "core"), request.getValue().get("tags"));
+ }
+
+ @Test
+ void unnamedKeyGetsAGeneratedName() {
+ when(apiGateway.createApiKey(eq(REGION), anyMap()))
+ .thenReturn(key("abc123", "generated", "abc123", true, null, Map.of()));
+
+ provisioner.provision(resource(null), mapper.createObjectNode(), ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
+ verify(apiGateway).createApiKey(eq(REGION), request.capture());
+ String name = (String) request.getValue().get("name");
+ assertTrue(name.startsWith("my-stack-MyKey-"), name);
+ assertEquals(Map.of(), request.getValue().get("tags"));
+ }
+
+ @Test
+ void updatePatchesDescriptionAndEnabledInPlace() {
+ ApiKey existing = key("abc123", "my-key", "abc123", false, "old", Map.of());
+ when(apiGateway.findApiKey(REGION, "abc123")).thenReturn(Optional.of(existing));
+ when(apiGateway.updateApiKey(eq(REGION), eq("abc123"), anyList())).thenReturn(existing);
+ ObjectNode props = mapper.createObjectNode().put("Name", "my-key").put("Description", "new").put("Enabled", "true");
+ StackResource r = resource("abc123");
+
+ provisioner.provision(r, props, ctx("abc123"));
+
+ verify(apiGateway, never()).createApiKey(any(), anyMap());
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<Map<String, String>>> patches = ArgumentCaptor.forClass(List.class);
+ verify(apiGateway).updateApiKey(eq(REGION), eq("abc123"), patches.capture());
+ assertTrue(patches.getValue().stream().anyMatch(op ->
+ "/description".equals(op.get("path")) && "new".equals(op.get("value"))));
+ assertTrue(patches.getValue().stream().anyMatch(op ->
+ "/enabled".equals(op.get("path")) && "true".equals(op.get("value"))));
+ assertEquals("abc123", r.getPhysicalId());
+ assertEquals("abc123", r.getAttributes().get("APIKeyId"));
+ }
+
+ @Test
+ void droppingDescriptionClearsItOnTheKey() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of());
+ when(apiGateway.findApiKey(REGION, "abc123")).thenReturn(Optional.of(existing));
+ when(apiGateway.updateApiKey(eq(REGION), eq("abc123"), anyList())).thenReturn(existing);
+
+ provisioner.provision(resource("abc123"), mapper.createObjectNode().put("Name", "my-key"), ctx("abc123"));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<Map<String, String>>> patches = ArgumentCaptor.forClass(List.class);
+ verify(apiGateway).updateApiKey(eq(REGION), eq("abc123"), patches.capture());
+ assertTrue(patches.getValue().stream().anyMatch(op ->
+ "/description".equals(op.get("path")) && op.get("value") == null), patches.getValue().toString());
+ }
+
+ @Test
+ void anUnchangedUpdateTouchesNothing() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "same", Map.of("team", "core"));
+ when(apiGateway.findApiKey(REGION, "abc123")).thenReturn(Optional.of(existing));
+ ObjectNode props = tags("team", "core").put("Name", "my-key").put("Description", "same");
+ StackResource r = resource("abc123");
+
+ provisioner.provision(r, props, ctx("abc123"));
+
+ verify(apiGateway, never()).createApiKey(any(), anyMap());
+ verify(apiGateway, never()).updateApiKey(any(), any(), anyList());
+ verify(apiGateway, never()).replaceApiKeyTags(any(), any(), anyMap());
+ assertEquals("abc123", r.getAttributes().get("APIKeyId"));
+ }
+
+ @Test
+ void changedTagsAreReplacedWholesale() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, null, Map.of("team", "core", "stale", "x"));
+ when(apiGateway.findApiKey(REGION, "abc123")).thenReturn(Optional.of(existing));
+ when(apiGateway.replaceApiKeyTags(eq(REGION), eq("abc123"), anyMap())).thenReturn(existing);
+
+ provisioner.provision(resource("abc123"), tags("team", "platform").put("Name", "my-key"), ctx("abc123"));
+
+ verify(apiGateway).replaceApiKeyTags(REGION, "abc123", Map.of("team", "platform"));
+ verify(apiGateway, never()).updateApiKey(any(), any(), anyList());
+ }
+
+ @Test
+ void aRenameIsRefusedAsReplacementWorthy() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, null, Map.of());
+ when(apiGateway.findApiKey(REGION, "abc123")).thenReturn(Optional.of(existing));
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource("abc123"), mapper.createObjectNode().put("Name", "renamed"), ctx("abc123")));
+
+ assertEquals("ValidationError", e.getErrorCode());
+ assertTrue(e.getMessage().contains("Name"), e.getMessage());
+ verify(apiGateway, never()).createApiKey(any(), anyMap());
+ verify(apiGateway, never()).updateApiKey(any(), any(), anyList());
+ }
+
+ @Test
+ void aChangedValueIsRefusedAsReplacementWorthy() {
+ ApiKey existing = key("abc123", "my-key", "0123456789abcdef0123", true, null, Map.of());
+ when(apiGateway.findApiKey(REGION, "abc123")).thenReturn(Optional.of(existing));
+ ObjectNode props = mapper.createObjectNode().put("Name", "my-key").put("Value", "fedcba9876543210fedc");
+
+ AwsException e = assertThrows(AwsException.class,
+ () -> provisioner.provision(resource("abc123"), props, ctx("abc123")));
+
+ assertTrue(e.getMessage().contains("Value"), e.getMessage());
+ }
+
+ @Test
+ void aKeyDeletedOutOfBandIsCreatedAgain() {
+ when(apiGateway.findApiKey(REGION, "gone")).thenReturn(Optional.empty());
+ when(apiGateway.createApiKey(eq(REGION), anyMap()))
+ .thenReturn(key("new1", "my-key", "new1", true, null, Map.of()));
+ StackResource r = resource("gone");
+
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "my-key"), ctx("gone"));
+
+ assertEquals("new1", r.getPhysicalId());
+ assertEquals("new1", r.getAttributes().get("APIKeyId"));
+ }
+
+ @Test
+ void deleteDelegatesToTheService() {
+ provisioner.delete(TYPE, "abc123", REGION);
+ verify(apiGateway).deleteApiKey(REGION, "abc123");
+ }
+
+ @Test
+ void deleteToleratesAKeyThatIsAlreadyGone() {
+ doThrow(new AwsException("NotFoundException", "Invalid API Key identifier specified", 404))
+ .when(apiGateway).deleteApiKey(REGION, "gone");
+
+ assertDoesNotThrow(() -> provisioner.delete(TYPE, "gone", REGION));
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index bbd0d345a8..38e1d9f5aa 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -1,4 +1,5 @@
AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
+AWS::ApiGateway::ApiKey ApiGatewayApiKeyCfnProvisioner
AWS::ApiGateway::Authorizer LEGACY_SWITCH
AWS::ApiGateway::BasePathMapping ApiGatewayDomainCfnProvisioner
AWS::ApiGateway::Deployment LEGACY_SWITCH