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

* feat(cloudformation): provision AWS::ApiGateway::ApiKey

Per-service provisioner over ApiGatewayService. Ref and Fn::GetAtt APIKeyId
both yield the key id. Description, Enabled and Tags update in place. Name,
Value and GenerateDistinctId are createOnly, so a change to any of them is
refused as a replacement rather than applied to the existing key. A template
that omits Name keeps its generated name across updates instead of minting a
second key. Stack deletion deletes the key and tolerates one already gone.

ApiGatewayService gains replaceApiKeyTags so an update can drop a tag the
template no longer declares.

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

* fix(cloudformation): keep an API key's create-time reserved tags across updates

replaceApiKeyTags checked the whole desired map against the reserved list,
so a key created with a reserved floci tag could never change an ordinary tag
afterwards. Only a reserved tag that is new or changed is an update-time
override attempt and is refused now. Adds a test that dropping Description
from the template clears it on the key.
This commit is contained in:
lex00 authored and GitHub committed 2026-09-06 15:12:50 -05:00
1 parent ba3dd657b6
commit cbde58f238
7 files changed
+631 -1

No files matched your search

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