Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(apigateway): create API keys disabled unless enabled is set (#4731)

Mario Toffiab5c428319fff
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 8cf851f2d1..e87c7b10cb 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -121,6 +121,14 @@ The CSV header row is addressed by name, not position. AWS's own column set is
column defaults to `true`. Duplicate key values are reported in the `warnings` array, and
`failonwarnings=true` turns those warnings into a `BadRequestException`.
+#### `enabled` defaults to `false`
+
+`CreateApiKey` creates the key disabled when the request body has no `enabled` field, matching
+AWS. AWS SDKs that model `enabled` as a plain boolean, such as the AWS SDK for Go v2, leave the field
+out of the request when it is `false`, so a client that wants a usable key must send
+`enabled: true`. An `AWS::ApiGateway::ApiKey` CloudFormation resource that omits `Enabled` is
+likewise created, or updated, as disabled.
+
#### `generateDistinctId`
API key identifiers are generated independently from their secret values when `generateDistinctId`
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 6fa2031045..2d7a5aec2c 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
@@ -1073,7 +1073,7 @@ public class ApiGatewayService implements ResourceProvider {
public ApiKey createApiKey(String region, Map<String, Object> request) {
ApiKey apiKey = new ApiKey();
apiKey.setName((String) request.get("name"));
- apiKey.setEnabled(!Boolean.FALSE.equals(request.get("enabled")));
+ apiKey.setEnabled(Boolean.TRUE.equals(request.get("enabled")));
apiKey.setCreatedDate(System.currentTimeMillis() / 1000L);
apiKey.setLastUpdatedDate(apiKey.getCreatedDate());
apiKey.setDescription((String) request.get("description"));
@@ -1253,9 +1253,22 @@ public class ApiGatewayService implements ResourceProvider {
}
});
ReservedTags.rejectApiGatewayReservedTagsOnUpdate(changed);
+ return storeApiKeyTags(region, key, tags);
+ }
+
+ /**
+ * Sets an API key's tags to exactly the given ones, reserved tags included. It is for putting
+ * back the tags a key had before a failed stack update, which may include a reserved tag the
+ * key was created with and the update removed, so it skips the reserved-tag check.
+ */
+ public ApiKey restoreApiKeyTags(String region, String apiKeyId, Map<String, String> tags) {
+ return storeApiKeyTags(region, getApiKey(region, apiKeyId), tags);
+ }
+
+ private ApiKey storeApiKeyTags(String region, ApiKey key, Map<String, String> tags) {
key.setTags(new HashMap<>(tags));
key.setLastUpdatedDate(System.currentTimeMillis() / 1000L);
- apiKeyStore.put(apiKeyGlobalKey(region, apiKeyId), key);
+ apiKeyStore.put(apiKeyGlobalKey(region, key.getId()), key);
return key;
}
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
index a9b4d57b25..08915a563b 100644
--- 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
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
+import com.fasterxml.jackson.core.JsonProcessingException;
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;
@@ -20,16 +23,19 @@ import java.util.Set;
* {@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. The deprecated StageKeys property is accepted without effect.
+ * <p>CustomerId, Description, Enabled and Tags update in place, and the values the key had are kept
+ * on the resource so a failed stack update can put all four back. 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. The deprecated StageKeys property is
+ * accepted without effect.
*/
@ApplicationScoped
public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::ApiGateway::ApiKey";
private static final String NOT_FOUND = "NotFoundException";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
/** Well under AWS's 1024-character name limit, and in line with the other generated names. */
private static final int GENERATED_NAME_MAX = 128;
@@ -47,6 +53,8 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ // A snapshot describes the update in flight; one an earlier update left behind is stale.
+ r.getAttributes().remove(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
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
@@ -58,6 +66,21 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
}
}
create(r, props, ctx);
+ if (ctx.isUpdate()) {
+ recordCreatedByUpdate(r, ctx);
+ }
+ }
+
+ /**
+ * Records that this update created the key because the one at the prior physical id was gone,
+ * so {@link #rollbackUpdate} can delete it and name the prior id again.
+ */
+ private static void recordCreatedByUpdate(StackResource r, ProvisionContext ctx) {
+ ObjectNode snapshot = MAPPER.createObjectNode();
+ snapshot.put("region", ctx.region());
+ snapshot.put("createdId", r.getPhysicalId());
+ snapshot.put("priorId", ctx.priorPhysicalId());
+ r.getAttributes().put(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
}
private void create(StackResource r, JsonNode props, ProvisionContext ctx) {
@@ -108,30 +131,77 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
}
}
+ // Enabled defaults to false when the template omits it, as in the AWS registry schema.
+ Boolean enabled = resolveBoolean(props, "Enabled", ctx);
+ List<Map<String, String>> patches = patchesTo(existing, ctx.resolveOptional(props, "CustomerId"),
+ ctx.resolveOptional(props, "Description"), enabled != null && enabled);
+ Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
+ boolean tagsChanged = !desiredTags.equals(existing.getTags());
+ if (!patches.isEmpty() || tagsChanged) {
+ snapshotBeforeUpdate(r, existing, ctx.region());
+ }
+
+ // Tags go first: the service refuses a tag change that adds a reserved tag key, and refusing
+ // it before the patch leaves the key exactly as the stack last committed it.
+ ApiKey key = existing;
+ try {
+ if (tagsChanged) {
+ key = apiGatewayService.replaceApiKeyTags(ctx.region(), existing.getId(), desiredTags);
+ }
+ if (!patches.isEmpty()) {
+ key = apiGatewayService.updateApiKey(ctx.region(), existing.getId(), patches);
+ }
+ } catch (RuntimeException failure) {
+ // The stack skips rollbackUpdate for a resource whose own update failed, so undo it here.
+ try {
+ rollbackUpdate(r);
+ } catch (RuntimeException restoreFailure) {
+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
+ "Could not roll back the update of API key " + existing.getId() + ": "
+ + restoreFailure.getMessage());
+ if (restoreFailure != failure) {
+ failure.addSuppressed(restoreFailure);
+ }
+ }
+ throw failure;
+ }
+ record(r, key);
+ }
+
+ /**
+ * The patches that set the key's customer id, description and enabled flag to the given values,
+ * one for each value that differs from the key's. A blank string and no value count as equal.
+ */
+ private static List<Map<String, String>> patchesTo(ApiKey key, String customerId, String description,
+ boolean enabled) {
List<Map<String, String>> patches = new ArrayList<>();
- String customerId = ctx.resolveOptional(props, "CustomerId");
- if (!Objects.equals(blankToNull(customerId), blankToNull(existing.getCustomerId()))) {
+ if (!Objects.equals(blankToNull(customerId), blankToNull(key.getCustomerId()))) {
patches.add(patch("/customerId", customerId));
}
- String description = ctx.resolveOptional(props, "Description");
- if (!Objects.equals(blankToNull(description), blankToNull(existing.getDescription()))) {
+ if (!Objects.equals(blankToNull(description), blankToNull(key.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)));
+ if (enabled != key.isEnabled()) {
+ patches.add(patch("/enabled", Boolean.toString(enabled)));
}
- ApiKey key = patches.isEmpty()
- ? existing
- : apiGatewayService.updateApiKey(ctx.region(), existing.getId(), patches);
+ return 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);
+ /**
+ * Keeps the customer id, description, enabled flag and tags the key has before an in-place
+ * update changes them, so {@link #rollbackUpdate} can put them back. Written as text before the
+ * first mutating call, because the service updates the stored key object in place.
+ */
+ private static void snapshotBeforeUpdate(StackResource r, ApiKey existing, String region) {
+ ObjectNode snapshot = MAPPER.createObjectNode();
+ snapshot.put("region", region);
+ snapshot.put("id", existing.getId());
+ snapshot.put("customerId", existing.getCustomerId());
+ snapshot.put("description", existing.getDescription());
+ snapshot.put("enabled", existing.isEnabled());
+ ObjectNode tags = snapshot.putObject("tags");
+ existing.getTags().forEach(tags::put);
+ r.getAttributes().put(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
}
private static void record(StackResource r, ApiKey key) {
@@ -177,4 +247,65 @@ public class ApiGatewayApiKeyCfnProvisioner implements CfnResourceProvisioner {
CfnDeletes.safeDelete("API key", physicalId,
() -> apiGatewayService.deleteApiKey(region, physicalId), NOT_FOUND);
}
+
+ /**
+ * Undoes the update from the snapshot on the resource, and is also called by {@code update} when
+ * one of its own mutating calls fails. When the update created the key because
+ * the one at the prior physical id was gone, the created key is deleted and the resource names
+ * the prior id again. Otherwise the customer id, description, enabled flag and tags are put
+ * back, writing only the values where the live key differs from the snapshot, so an update that
+ * failed before it changed anything writes nothing. With no snapshot on the resource the update
+ * changed nothing, since every mutating call is preceded by the snapshot or followed by the
+ * creation record, so there is nothing to undo.
+ * A key deleted since the update fails the rollback with NotFoundException, and the stack
+ * reports the rollback as failed.
+ */
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ // The snapshot is spent only once the restore succeeded: a restore that throws leaves it in
+ // place for the next attempt instead of reporting a rollback that never happened.
+ String raw = resource.getAttributes().get(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
+ if (raw == null) {
+ return true;
+ }
+ JsonNode snapshot;
+ try {
+ snapshot = MAPPER.readTree(raw);
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Could not read the API key update snapshot for "
+ + resource.getLogicalId(), e);
+ }
+ String region = snapshot.path("region").asText();
+ String createdId = snapshotText(snapshot, "createdId");
+ if (createdId != null) {
+ // Deleted before the resource names the prior id again, so a failed delete leaves the
+ // resource naming the created key and deleting the stack still removes it.
+ delete(TYPE, createdId, region);
+ String priorId = snapshot.path("priorId").asText();
+ resource.setPhysicalId(priorId);
+ resource.getAttributes().put("APIKeyId", priorId);
+ resource.getAttributes().remove(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
+ return true;
+ }
+ String id = snapshot.path("id").asText();
+ ApiKey live = apiGatewayService.getApiKey(region, id);
+ Map<String, String> tags = new HashMap<>();
+ snapshot.path("tags").fields().forEachRemaining(tag -> tags.put(tag.getKey(), tag.getValue().asText()));
+ if (!tags.equals(live.getTags())) {
+ apiGatewayService.restoreApiKeyTags(region, id, tags);
+ }
+ List<Map<String, String>> patches = patchesTo(live, snapshotText(snapshot, "customerId"),
+ snapshotText(snapshot, "description"), snapshot.path("enabled").asBoolean());
+ if (!patches.isEmpty()) {
+ apiGatewayService.updateApiKey(region, id, patches);
+ }
+ resource.getAttributes().remove(CfnRollback.API_KEY_UPDATE_SNAPSHOT_ATTR);
+ return true;
+ }
+
+ /** A snapshotted string, or null when the key carried none. */
+ private static String snapshotText(JsonNode snapshot, String field) {
+ JsonNode value = snapshot.get(field);
+ return value == null || value.isNull() ? null : value.asText();
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
index a123e0b544..1565b62a33 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
@@ -78,6 +78,15 @@ public final class CfnRollback {
*/
public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot";
+ /**
+ * Holds the customer id, description, enabled flag and tags an API key carried before an
+ * in-place update changed them, or the key an update created because the one the stack held
+ * was gone, so a failed stack update can put the key back or delete the created one. Written
+ * by {@code ApiGatewayApiKeyCfnProvisioner} before its first in-place mutating call or right
+ * after that creation, and spent by its {@code rollbackUpdate}.
+ */
+ public static final String API_KEY_UPDATE_SNAPSHOT_ATTR = "__FlociApiKeyUpdateSnapshot";
+
/**
* Holds the complete prior metric filter, identity, name mode and per-address mutation outcomes
* and ownership states.
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java
index 710dafd2c4..1d94d74b54 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyIntegrationTest.java
@@ -285,4 +285,30 @@ class ApiGatewayApiKeyIntegrationTest {
.statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
+
+ @Test @Order(17)
+ void createApiKey_enabledAbsent_keyIsDisabled() {
+ String body = """
+ {"name":"enabled-absent-key"}
+ """;
+ String keyId = given()
+ .contentType(ContentType.JSON)
+ .body(body)
+ .when().post("/apikeys")
+ .then()
+ .statusCode(201)
+ .body("enabled", equalTo(false))
+ .extract().path("id");
+
+ given()
+ .when().get("/apikeys/" + keyId)
+ .then()
+ .statusCode(200)
+ .body("enabled", equalTo(false));
+
+ given()
+ .when().delete("/apikeys/" + keyId)
+ .then()
+ .statusCode(202);
+ }
}
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
index 6b87f13c6a..9f99ef2bfc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayApiKeyCfnIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayApiKeyCfnIntegrationTest.java
@@ -13,6 +13,7 @@ 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.hasItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -23,8 +24,9 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
* 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.
+ * changes description, enabled flag and tags on the same key, that an update which fails on a later
+ * resource puts the key's customer id, description, enabled flag and tags back, and that deleting
+ * the stack removes every key.
*/
@QuarkusTest
class ApiGatewayApiKeyCfnIntegrationTest {
@@ -68,6 +70,34 @@ class ApiGatewayApiKeyCfnIntegrationTest {
}
""".formatted(NAMED, CHOSEN_VALUE);
+ private static final String ROLLBACK_STACK = "apigw-apikey-cfn-rollback-it";
+
+ /** One key with the given properties, optionally followed by more resources. */
+ private static final String ROLLBACK_TEMPLATE = """
+ {
+ "Resources": {
+ "Key": {
+ "Type": "AWS::ApiGateway::ApiKey",
+ "Properties": {%s}
+ }%s
+ },
+ "Outputs": {"KeyRef": {"Value": {"Ref": "Key"}}}
+ }
+ """;
+
+ /** A resource that fails after the key, so the update rolls back. */
+ private static final String FAILING_RESOURCE = """
+ ,
+ "BadSecret": {
+ "Type": "AWS::SecretsManager::Secret",
+ "DependsOn": "Key",
+ "Properties": {
+ "Name": "apigw-apikey-cfn-rollback-it",
+ "SecretString": "explicit",
+ "GenerateSecretString": {"PasswordLength": 32}
+ }
+ }""";
+
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -96,7 +126,7 @@ class ApiGatewayApiKeyCfnIntegrationTest {
getApiKey(unnamedId)
.statusCode(200)
.body("name", startsWith(STACK + "-Unnamed-"))
- .body("enabled", equalTo(true));
+ .body("enabled", equalTo(false));
// A caller-chosen value with a distinct id keeps the value and mints a separate id.
assertNotEquals(CHOSEN_VALUE, distinctId);
@@ -124,18 +154,90 @@ class ApiGatewayApiKeyCfnIntegrationTest {
getApiKey(distinctId).statusCode(404);
}
+ @Test
+ void aFailedUpdatePutsTheKeyBackAsItWas() {
+ String original = """
+ "CustomerId": "customer-1", "Description": "original", "Enabled": "true",
+ "Tags": [{"Key": "stack", "Value": "v1"}]""";
+ cloudFormation(ROLLBACK_STACK, "CreateStack", ROLLBACK_TEMPLATE.formatted(original, ""), Map.of());
+ String keyId = outputValue(describeStacks(ROLLBACK_STACK, "CREATE_COMPLETE"), "KeyRef");
+
+ // Enabled is omitted, which disables the key, before the secret fails the update.
+ String changed = """
+ "CustomerId": "customer-2", "Description": "changed",
+ "Tags": [{"Key": "stack", "Value": "v2"}]""";
+ cloudFormation(ROLLBACK_STACK, "UpdateStack", ROLLBACK_TEMPLATE.formatted(changed, FAILING_RESOURCE), Map.of());
+ assertEquals(keyId, outputValue(describeStacks(ROLLBACK_STACK, "UPDATE_ROLLBACK_COMPLETE"), "KeyRef"));
+
+ getApiKey(keyId)
+ .statusCode(200)
+ .body("customerId", equalTo("customer-1"))
+ .body("description", equalTo("original"))
+ .body("enabled", equalTo(true))
+ .body("tags", equalTo(Map.of("stack", "v1")));
+
+ cloudFormation(ROLLBACK_STACK, "DeleteStack", null, Map.of());
+ CfnStackWaits.awaitStackDeleted(ROLLBACK_STACK);
+ getApiKey(keyId).statusCode(404);
+ }
+
+ @Test
+ void aFailedUpdateDeletesTheKeyItCreatedInPlaceOfOneDeletedOutOfBand() {
+ String stack = "apigw-apikey-cfn-recreate-it";
+ String name = "apigw-apikey-cfn-recreate-it-key";
+ String properties = "\"Name\": \"" + name + "\"";
+ cloudFormation(stack, "CreateStack", ROLLBACK_TEMPLATE.formatted(properties, ""), Map.of());
+ String keyId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "KeyRef");
+ given().when().delete("/apikeys/" + keyId).then().statusCode(202);
+
+ // The update creates a key in place of the deleted one before the secret fails it.
+ cloudFormation(stack, "UpdateStack", ROLLBACK_TEMPLATE.formatted(properties, FAILING_RESOURCE), Map.of());
+ describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
+ given().when().get("/apikeys").then()
+ .statusCode(200)
+ .body("item.name", not(hasItem(name)));
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ CfnStackWaits.awaitStackDeleted(stack);
+ }
+
+ @Test
+ void aFailedUpdatePutsBackAReservedTagTheUpdateRemoved() {
+ String stack = "apigw-apikey-cfn-reserved-it";
+ String kept = "\"Name\": \"apigw-apikey-cfn-reserved-it-key\", \"Enabled\": \"true\", \"Tags\": [";
+ String withReserved = kept + "{\"Key\": \"_custom_id_\", \"Value\": \"pinned\"}, {\"Key\": \"stack\", \"Value\": \"v1\"}]";
+ cloudFormation(stack, "CreateStack", ROLLBACK_TEMPLATE.formatted(withReserved, ""), Map.of());
+ String keyId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "KeyRef");
+
+ // The update drops the reserved tag before the secret fails it.
+ String withoutReserved = kept + "{\"Key\": \"stack\", \"Value\": \"v1\"}]";
+ cloudFormation(stack, "UpdateStack", ROLLBACK_TEMPLATE.formatted(withoutReserved, FAILING_RESOURCE), Map.of());
+ describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
+ getApiKey(keyId)
+ .statusCode(200)
+ .body("tags", equalTo(Map.of("_custom_id_", "pinned", "stack", "v1")));
+
+ cloudFormation(stack, "DeleteStack", null, Map.of());
+ CfnStackWaits.awaitStackDeleted(stack);
+ }
+
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) {
+ cloudFormation(STACK, action, "DeleteStack".equals(action) ? null : TEMPLATE, parameters);
+ }
+
+ private static void cloudFormation(String stack, String action, String templateBody,
+ 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);
+ .formParam("StackName", stack);
+ if (templateBody != null) {
+ request.formParam("TemplateBody", templateBody);
}
int index = 1;
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
@@ -147,11 +249,17 @@ class ApiGatewayApiKeyCfnIntegrationTest {
}
private static String describeStacks(String expectedStatus) {
+ return describeStacks(STACK, expectedStatus);
+ }
+
+ private static String describeStacks(String stack, String expectedStatus) {
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
+ assertEquals(expectedStatus, state.status(), state.reason());
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
- .formParam("StackName", STACK)
+ .formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
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
index 5110ac1be5..94bb973dc9 100644
--- 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
@@ -10,23 +10,31 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.function.BiConsumer;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
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.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -81,6 +89,42 @@ class ApiGatewayApiKeyCfnProvisionerTest {
return props;
}
+ /**
+ * Stubs the key's lookups and writes the way the in-memory store behaves: every call sees the one
+ * stored key object, and a write changes that object in place.
+ */
+ private void storeHolds(ApiKey stored) {
+ when(apiGateway.findApiKey(REGION, stored.getId())).thenReturn(Optional.of(stored));
+ when(apiGateway.getApiKey(REGION, stored.getId())).thenReturn(stored);
+ when(apiGateway.replaceApiKeyTags(eq(REGION), eq(stored.getId()), anyMap())).thenAnswer(inv -> {
+ Map<String, String> replaced = inv.getArgument(2);
+ stored.setTags(new HashMap<>(replaced));
+ return stored;
+ });
+ when(apiGateway.restoreApiKeyTags(eq(REGION), eq(stored.getId()), anyMap())).thenAnswer(inv -> {
+ Map<String, String> restored = inv.getArgument(2);
+ stored.setTags(new HashMap<>(restored));
+ return stored;
+ });
+ when(apiGateway.updateApiKey(eq(REGION), eq(stored.getId()), anyList())).thenAnswer(inv -> {
+ applyPatches(stored, inv.getArgument(2));
+ return stored;
+ });
+ }
+
+ /** Applies patch operations to the key the way {@code ApiGatewayService.updateApiKey} does. */
+ private static void applyPatches(ApiKey key, List<Map<String, String>> ops) {
+ for (Map<String, String> op : ops) {
+ BiConsumer<ApiKey, String> setter = switch (op.get("path")) {
+ case "/customerId" -> ApiKey::setCustomerId;
+ case "/description" -> ApiKey::setDescription;
+ case "/enabled" -> (k, v) -> k.setEnabled(Boolean.parseBoolean(v));
+ default -> throw new IllegalArgumentException(op.toString());
+ };
+ setter.accept(key, op.get("value"));
+ }
+ }
+
@Test
void createSendsTheTemplatePropertiesAndRecordsTheId() {
when(apiGateway.createApiKey(eq(REGION), anyMap()))
@@ -125,6 +169,34 @@ class ApiGatewayApiKeyCfnProvisionerTest {
assertEquals(Map.of(), request.getValue().get("tags"));
}
+ @Test
+ void createWithEnabledOmittedLeavesTheServiceDefault() {
+ when(apiGateway.createApiKey(eq(REGION), anyMap()))
+ .thenReturn(key("abc123", "my-key", "abc123", false, null, Map.of()));
+
+ provisioner.provision(resource(null), mapper.createObjectNode().put("Name", "my-key"), ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
+ verify(apiGateway).createApiKey(eq(REGION), request.capture());
+ assertFalse(request.getValue().containsKey("enabled"), request.getValue().toString());
+ }
+
+ @Test
+ void updateWithEnabledOmittedDisablesAnEnabledKey() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, null, 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 ->
+ "/enabled".equals(op.get("path")) && "false".equals(op.get("value"))), patches.getValue().toString());
+ }
+
@Test
void updatePatchesDescriptionAndEnabledInPlace() {
ApiKey existing = key("abc123", "my-key", "abc123", false, "old", Map.of());
@@ -171,7 +243,7 @@ class ApiGatewayApiKeyCfnProvisionerTest {
@Test
void anUnchangedUpdateTouchesNothing() {
- ApiKey existing = key("abc123", "my-key", "abc123", true, "same", Map.of("team", "core"));
+ ApiKey existing = key("abc123", "my-key", "abc123", false, "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");
@@ -186,7 +258,7 @@ class ApiGatewayApiKeyCfnProvisionerTest {
@Test
void changedTagsAreReplacedWholesale() {
- ApiKey existing = key("abc123", "my-key", "abc123", true, null, Map.of("team", "core", "stale", "x"));
+ ApiKey existing = key("abc123", "my-key", "abc123", false, 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);
@@ -235,6 +307,217 @@ class ApiGatewayApiKeyCfnProvisionerTest {
assertEquals("new1", r.getAttributes().get("APIKeyId"));
}
+ @Test
+ void aFailedStackUpdatePutsBackEveryValueTheUpdateChanged() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of("team", "core"));
+ existing.setCustomerId("customer-1");
+ storeHolds(existing);
+ ObjectNode props = tags("team", "platform")
+ .put("Name", "my-key")
+ .put("CustomerId", "customer-2")
+ .put("Description", "new");
+ StackResource r = resource("abc123");
+ provisioner.provision(r, props, ctx("abc123"));
+ clearInvocations(apiGateway);
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(apiGateway).restoreApiKeyTags(REGION, "abc123", Map.of("team", "core"));
+ @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 ->
+ "/customerId".equals(op.get("path")) && "customer-1".equals(op.get("value"))), patches.getValue().toString());
+ assertTrue(patches.getValue().stream().anyMatch(op ->
+ "/description".equals(op.get("path")) && "old".equals(op.get("value"))), patches.getValue().toString());
+ assertTrue(patches.getValue().stream().anyMatch(op ->
+ "/enabled".equals(op.get("path")) && "true".equals(op.get("value"))), patches.getValue().toString());
+ }
+
+ @Test
+ void anUnchangedUpdateLeavesNothingForARollbackToUndo() {
+ 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);
+ StackResource r = resource("abc123");
+ // An earlier update that changed the key and committed, then one that changes nothing.
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "my-key"), ctx("abc123"));
+ ObjectNode unchanged = mapper.createObjectNode()
+ .put("Name", "my-key")
+ .put("Description", "old")
+ .put("Enabled", "true");
+ provisioner.provision(r, unchanged, ctx("abc123"));
+ clearInvocations(apiGateway);
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(apiGateway, never()).updateApiKey(any(), any(), anyList());
+ verify(apiGateway, never()).restoreApiKeyTags(any(), any(), anyMap());
+ }
+
+ @Test
+ void aRollbackWritesOnlyTheValuesThatDiffer() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of("team", "core"));
+ storeHolds(existing);
+ ObjectNode props = tags("team", "core").put("Name", "my-key").put("Description", "new").put("Enabled", "true");
+ StackResource r = resource("abc123");
+ provisioner.provision(r, props, ctx("abc123"));
+ clearInvocations(apiGateway);
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(apiGateway, never()).restoreApiKeyTags(any(), any(), anyMap());
+ verify(apiGateway).updateApiKey(REGION, "abc123",
+ List.of(Map.of("op", "replace", "path", "/description", "value", "old")));
+ assertEquals("old", existing.getDescription());
+ }
+
+ @Test
+ void aRollbackPutsBackAReservedTagTheUpdateRemoved() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of("_custom_id_", "pinned", "team", "core"));
+ storeHolds(existing);
+ ObjectNode props = tags("team", "core").put("Name", "my-key").put("Description", "old").put("Enabled", "true");
+ StackResource r = resource("abc123");
+ provisioner.provision(r, props, ctx("abc123"));
+ clearInvocations(apiGateway);
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(apiGateway).restoreApiKeyTags(REGION, "abc123", Map.of("_custom_id_", "pinned", "team", "core"));
+ verify(apiGateway, never()).replaceApiKeyTags(any(), any(), anyMap());
+ }
+
+ @Test
+ void aRefusedTagChangeLeavesTheOtherValuesUnpatched() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of());
+ storeHolds(existing);
+ doThrow(new AwsException("BadRequestException",
+ "Reserved tag key _custom_id_ can only be supplied during resource creation.", 400))
+ .when(apiGateway).replaceApiKeyTags(REGION, "abc123", Map.of("_custom_id_", "other"));
+ ObjectNode props = tags("_custom_id_", "other").put("Name", "my-key").put("Description", "new");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(resource("abc123"), props, ctx("abc123")));
+
+ verify(apiGateway, never()).updateApiKey(any(), any(), anyList());
+ verify(apiGateway, times(1)).replaceApiKeyTags(any(), any(), anyMap());
+ verify(apiGateway, never()).restoreApiKeyTags(any(), any(), anyMap());
+ }
+
+ @Test
+ void aFailedPatchPutsTheWholeKeyBack() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of("team", "core"));
+ existing.setCustomerId("customer-1");
+ storeHolds(existing);
+ RuntimeException failure = new IllegalStateException("store write failed");
+ // The first patch changes the stored key and then fails to save it, as a failing store write does.
+ doAnswer(inv -> {
+ applyPatches(existing, inv.getArgument(2));
+ throw failure;
+ }).doAnswer(inv -> {
+ applyPatches(existing, inv.getArgument(2));
+ return existing;
+ }).when(apiGateway).updateApiKey(eq(REGION), eq("abc123"), anyList());
+ ObjectNode props = tags("team", "platform")
+ .put("Name", "my-key")
+ .put("CustomerId", "customer-2")
+ .put("Description", "new");
+ StackResource r = resource("abc123");
+
+ RuntimeException thrown = assertThrows(RuntimeException.class,
+ () -> provisioner.provision(r, props, ctx("abc123")));
+
+ assertSame(failure, thrown);
+ InOrder order = inOrder(apiGateway);
+ order.verify(apiGateway).replaceApiKeyTags(REGION, "abc123", Map.of("team", "platform"));
+ order.verify(apiGateway).restoreApiKeyTags(REGION, "abc123", Map.of("team", "core"));
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<Map<String, String>>> patches = ArgumentCaptor.forClass(List.class);
+ verify(apiGateway, times(2)).updateApiKey(eq(REGION), eq("abc123"), patches.capture());
+ List<Map<String, String>> restore = patches.getAllValues().get(1);
+ assertTrue(restore.stream().anyMatch(op ->
+ "/customerId".equals(op.get("path")) && "customer-1".equals(op.get("value"))), restore.toString());
+ assertTrue(restore.stream().anyMatch(op ->
+ "/description".equals(op.get("path")) && "old".equals(op.get("value"))), restore.toString());
+ assertTrue(restore.stream().anyMatch(op ->
+ "/enabled".equals(op.get("path")) && "true".equals(op.get("value"))), restore.toString());
+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
+ }
+
+ @Test
+ void aFailedUndoOfAFailedUpdateMarksTheRollbackFailed() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of("team", "core"));
+ storeHolds(existing);
+ RuntimeException restoreFailure = new IllegalStateException("store write failed again");
+ doThrow(restoreFailure).when(apiGateway).restoreApiKeyTags(REGION, "abc123", Map.of("team", "core"));
+ RuntimeException failure = new IllegalStateException("store write failed");
+ doThrow(failure).when(apiGateway).updateApiKey(eq(REGION), eq("abc123"), anyList());
+ ObjectNode props = tags("team", "platform").put("Name", "my-key").put("Description", "new");
+ StackResource r = resource("abc123");
+
+ RuntimeException thrown = assertThrows(RuntimeException.class,
+ () -> provisioner.provision(r, props, ctx("abc123")));
+
+ assertSame(failure, thrown);
+ assertTrue(List.of(thrown.getSuppressed()).contains(restoreFailure));
+ String reason = r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
+ assertTrue(reason != null && reason.contains("abc123") && reason.contains("store write failed again"),
+ String.valueOf(reason));
+ }
+
+ @Test
+ void aRestoreRethrowingTheUpdateFailureIsNotSuppressedInItself() {
+ ApiKey existing = key("abc123", "my-key", "abc123", true, "old", Map.of());
+ storeHolds(existing);
+ RuntimeException failure = new IllegalStateException("store write failed");
+ // Every patch changes the stored key and then fails to save it with the same exception object.
+ doAnswer(inv -> {
+ applyPatches(existing, inv.getArgument(2));
+ throw failure;
+ }).when(apiGateway).updateApiKey(eq(REGION), eq("abc123"), anyList());
+ ObjectNode props = mapper.createObjectNode().put("Name", "my-key").put("Description", "new").put("Enabled", "true");
+ StackResource r = resource("abc123");
+
+ RuntimeException thrown = assertThrows(RuntimeException.class,
+ () -> provisioner.provision(r, props, ctx("abc123")));
+
+ assertSame(failure, thrown);
+ assertEquals(0, thrown.getSuppressed().length);
+ assertTrue(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
+ }
+
+ @Test
+ void aRollbackOfAKeyDeletedSinceTheUpdateFails() {
+ 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);
+ StackResource r = resource("abc123");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "my-key"), ctx("abc123"));
+ AwsException gone = new AwsException("NotFoundException", "Invalid API Key identifier specified", 404);
+ doThrow(gone).when(apiGateway).getApiKey(REGION, "abc123");
+ doThrow(gone).when(apiGateway).updateApiKey(eq(REGION), eq("abc123"), anyList());
+ doThrow(gone).when(apiGateway).restoreApiKeyTags(eq(REGION), eq("abc123"), anyMap());
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+
+ assertEquals("NotFoundException", e.getErrorCode());
+ }
+
+ @Test
+ void aFailedStackUpdateDeletesTheKeyItCreatedInPlaceOfOneDeletedOutOfBand() {
+ 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");
+ r.getAttributes().put("APIKeyId", "gone");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "my-key"), ctx("gone"));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(apiGateway).deleteApiKey(REGION, "new1");
+ assertEquals("gone", r.getPhysicalId());
+ assertEquals("gone", r.getAttributes().get("APIKeyId"));
+ }
+
@Test
void deleteDelegatesToTheService() {
provisioner.delete(TYPE, "abc123", REGION);