mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): update a KMS key in place unless the engine says it must be replaced (#8718)
An AWS::KMS::Key update created a new key every time and left the old one enabled. The key now keeps its id: Description, KeyPolicy, Enabled, EnableKeyRotation and Tags are updated in place, keeping tags added outside the stack, and a failed stack update puts them back. A changed KeySpec, KeyUsage, Origin or MultiRegion fails the update, as the AWS::KMS::Key reference says. Create now honors KeyPolicy, Enabled, EnableKeyRotation, Origin and MultiRegion, and a key that a failed create or update leaves behind is scheduled for deletion. Part of #6606
This commit is contained in:
1 parent
0e782b62f2
commit
790b93e739
8 files changed
+430
-20
No files matched your search
@@ -214,7 +214,7 @@ cross-resource references.
|
||||
| IAM | `Role`, `User` (template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete), `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
|
||||
| Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` |
|
||||
| SSM | `Parameter` |
|
||||
| KMS | `Key`, `Alias` |
|
||||
| KMS | `Key` (created with `Description`, `KeyPolicy`, `KeySpec`, `KeyUsage`, `Origin`, `MultiRegion`, `Enabled`, `EnableKeyRotation` and `Tags`; updated in place for `Description`, `KeyPolicy`, `Enabled`, `EnableKeyRotation` and `Tags`, keeping tags added outside the stack; a template that drops `Description`, `Enabled` or `EnableKeyRotation` clears the description, enables the key and turns rotation off, a dropped `KeyPolicy` keeps the current policy, and one the stack never declared keeps the value set outside it; a rotation change on a key that stays disabled fails, as AWS raises `DisabledException`; a change to `KeySpec`, `KeyUsage`, `Origin` or `MultiRegion` fails the update, as on AWS, and the stack rolls back), `Alias` |
|
||||
| Secrets Manager | `Secret`, `SecretTargetAttachment` |
|
||||
| ECR | `Repository` |
|
||||
| ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` |
|
||||
@@ -879,8 +879,8 @@ A property the previous template declared and the new template drops is cleared
|
||||
goes back to its create default, or is kept, on the AppSync resources, the EC2 networking types
|
||||
(`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`), an
|
||||
`AWS::ApiGatewayV2::Stage`, `Route` and `Authorizer`, an `AWS::EC2::Instance`, an `AWS::ECS::Service`, an
|
||||
`AWS::Lambda::Alias`, an `AWS::SecretsManager::Secret`, an `AWS::Cognito::UserPoolGroup` and an
|
||||
`AWS::CloudTrail::Trail`. Kept: required members (`AuthenticationType`, `Type`, a function's
|
||||
`AWS::Lambda::Alias`, an `AWS::SecretsManager::Secret`, an `AWS::Cognito::UserPoolGroup`, an
|
||||
`AWS::CloudTrail::Trail` and an `AWS::KMS::Key`. Kept: required members (`AuthenticationType`, `Type`, a function's
|
||||
`DataSourceName`, a `Route`'s `RouteKey`, an authorizer's `Name` and `AuthorizerType`), a data source's
|
||||
and a function's `Name`,
|
||||
an API key's `Expires`, a GraphQL API's `ApiType` and `Visibility`, a UNIT resolver's `DataSourceName`,
|
||||
@@ -900,8 +900,9 @@ dropped `Target` and `AuthorizerId`, and an `Authorizer`'s dropped `AuthorizerUr
|
||||
while the route's authorization type stays `JWT` or `CUSTOM`. An `Instance`'s dropped `UserData` is
|
||||
cleared: a running instance is stopped for the rewrite and started again, and a stopped one stays stopped.
|
||||
An `Alias`'s, a `Secret`'s and a `UserPoolGroup`'s dropped `Description` and a `Trail`'s dropped
|
||||
`S3KeyPrefix` are cleared. A dropped `RoutingConfig` removes the alias weights. The other members of
|
||||
those four types are kept or create-only when dropped, as the drop policy table lists them, except a
|
||||
`S3KeyPrefix` are cleared. A dropped `RoutingConfig` removes the alias weights. A key's dropped `Description` is cleared, its dropped `Enabled` enables it and its dropped
|
||||
`EnableKeyRotation` turns rotation off; a dropped `KeyPolicy` keeps the policy. The other members of
|
||||
those five types are kept or create-only when dropped, as the drop policy table lists them, except a
|
||||
`Secret`'s `Tags`, which every update drives to the template.
|
||||
An update that drops a `PrefixList`'s `AddressFamily` or `PrefixListName`, or a `Route`'s or
|
||||
`Authorizer`'s `ApiId`, fails. Create-only members are not cleared either.
|
||||
|
||||
@@ -183,6 +183,13 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String EKS_NODEGROUP_UPDATE_SNAPSHOT_ATTR = "__FlociEksNodegroupUpdateSnapshot";
|
||||
|
||||
/**
|
||||
* The description, key policy, enabled state, rotation and tags a KMS key carried before an
|
||||
* in-place update changed them, so a failed stack update can put them back. Written and spent
|
||||
* by {@code KmsCfnProvisioner}.
|
||||
*/
|
||||
public static final String KMS_KEY_UPDATE_SNAPSHOT_ATTR = "__FlociKmsKeyUpdateSnapshot";
|
||||
|
||||
public static final String STACK_SET_UPDATE_SNAPSHOT_ATTR = "__FlociStackSetUpdateSnapshot";
|
||||
|
||||
/**
|
||||
|
||||
+265
-6
@@ -1,14 +1,23 @@
|
||||
package io.floci.aws.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.ReservedTags;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import io.floci.aws.services.kms.model.KmsKey;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Provisions {@code AWS::KMS::Key} and {@code AWS::KMS::Alias}. */
|
||||
@@ -18,6 +27,19 @@ public class KmsCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final String KEY = "AWS::KMS::Key";
|
||||
private static final String ALIAS = "AWS::KMS::Alias";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SNAPSHOT_ATTR = CfnRollback.KMS_KEY_UPDATE_SNAPSHOT_ATTR;
|
||||
/** The tag keys the template that provisioned the key set, resolved then: the next update drops the ones it omits. */
|
||||
static final String TAG_KEYS_ATTR = "__FlociKmsTagKeys";
|
||||
/**
|
||||
* The properties AWS refuses to change on an existing key: the update request fails whatever
|
||||
* UpdateReplacePolicy says, so a changed one never replaces the key.
|
||||
*/
|
||||
private static final List<String> IMMUTABLE = List.of("KeySpec", "KeyUsage", "MultiRegion", "Origin");
|
||||
private static final String PENDING_IMPORT = "PendingImport";
|
||||
/** KMS's shortest deletion window, used to retire a key a failed create or update left behind. */
|
||||
private static final int MIN_DELETION_WINDOW_DAYS = 7;
|
||||
|
||||
private final KmsService kmsService;
|
||||
|
||||
public KmsCfnProvisioner(KmsService kmsService) {
|
||||
@@ -40,14 +62,251 @@ public class KmsCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
private void provisionKey(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
String requestedSpec = ctx.resolveOptional(props, "KeySpec");
|
||||
String requestedUsage = ctx.resolveOptional(props, "KeyUsage");
|
||||
// A snapshot describes the update in flight; one an earlier update left behind is stale.
|
||||
r.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
// A stack from before this type had a provisioner holds the dispatcher's stub, which names
|
||||
// no key, so the key is created as on a first deploy.
|
||||
boolean stub = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), r.getAttributes());
|
||||
KmsKey existing = ctx.isUpdate() && !stub ? liveKey(ctx.priorPhysicalId(), ctx.region()) : null;
|
||||
if (existing != null) {
|
||||
updateInPlace(r, props, ctx, existing);
|
||||
return;
|
||||
}
|
||||
createKey(r, props, ctx);
|
||||
if (ctx.isUpdate() && !stub) {
|
||||
// The key the update started from is gone, so this one is the update's to undo. A stub
|
||||
// never named a key, and LeafCfnProvisionerTest pins the attributes of that case.
|
||||
CfnRollback.recordCreatedByUpdate(r, ctx, SNAPSHOT_ATTR);
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates the key with the properties its create call takes, then applies Enabled and EnableKeyRotation. */
|
||||
private void createKey(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
// Unstripped: createKey reads the reserved override-id tag, then drops it.
|
||||
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, ctx);
|
||||
KmsKey key = kmsService.createKey(description, requestedUsage, requestedSpec, null, tags, ctx.region());
|
||||
r.setPhysicalId(key.getKeyId());
|
||||
boolean multiRegion = Boolean.TRUE.equals(ctx.resolveOptionalBoolean(props, "MultiRegion"));
|
||||
String origin = ctx.resolveOptional(props, "Origin");
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
String usage = ctx.resolveOptional(props, "KeyUsage");
|
||||
String spec = ctx.resolveOptional(props, "KeySpec");
|
||||
String policy = keyPolicy(props, ctx);
|
||||
Boolean rotation = ctx.resolveOptionalBoolean(props, "EnableKeyRotation");
|
||||
// Resolved with the rest, before the key is stored: an invalid value must not leave a key behind.
|
||||
Boolean enabled = ctx.resolveOptionalBoolean(props, "Enabled");
|
||||
// The shorter overload is the same call with the origin and multi-region defaults.
|
||||
KmsKey key = origin == null && !multiRegion
|
||||
? kmsService.createKey(description, usage, spec, policy, tags, ctx.region())
|
||||
: kmsService.createKey(description, usage, spec, policy, tags, origin, multiRegion, ctx.region());
|
||||
String keyId = key.getKeyId();
|
||||
r.setPhysicalId(keyId);
|
||||
r.getAttributes().put("Arn", key.getArn());
|
||||
r.getAttributes().put("KeyId", key.getKeyId());
|
||||
r.getAttributes().put("KeyId", keyId);
|
||||
Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, ReservedTags.stripReservedTags(tags));
|
||||
// A step that fails after the key is stored schedules it for deletion: a key cannot be removed outright.
|
||||
CfnRollback.guarded(r, ctx, true,
|
||||
() -> kmsService.scheduleKeyDeletion(keyId, MIN_DELETION_WINDOW_DAYS, ctx.region()),
|
||||
() -> { }, () -> {
|
||||
if (rotation != null && rotation) {
|
||||
kmsService.enableKeyRotation(keyId, ctx.region());
|
||||
}
|
||||
// A key imported later (Origin EXTERNAL) starts disabled, which is what Enabled false asks for.
|
||||
if (enabled != null && !enabled && key.isEnabled()) {
|
||||
kmsService.disableKey(keyId, ctx.region());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** The template's KeyPolicy as JSON, or null when it has none, which keeps the key's current policy. */
|
||||
private static String keyPolicy(JsonNode props, ProvisionContext ctx) {
|
||||
String policy = props == null ? null : ctx.engine().resolveJsonAttributeStrict(props.path("KeyPolicy"));
|
||||
return policy == null || policy.isBlank() ? null : policy;
|
||||
}
|
||||
|
||||
/** The key an update starts from, or null when it is gone and the update creates one. */
|
||||
private KmsKey liveKey(String keyId, String region) {
|
||||
try {
|
||||
return kmsService.describeKey(keyId, region);
|
||||
} catch (AwsException e) {
|
||||
if ("NotFoundException".equals(e.getErrorCode())) {
|
||||
return null;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The update AWS makes: the mutable properties go through the calls KMS offers for them and the
|
||||
* key keeps its id. KeySpec, KeyUsage, MultiRegion and Origin cannot change on an existing key,
|
||||
* so an update that changes one fails before anything is written.
|
||||
*/
|
||||
private void updateInPlace(StackResource r, JsonNode props, ProvisionContext ctx, KmsKey key) {
|
||||
PropertyChanges changes = ctx.changes(KEY, props);
|
||||
for (String name : IMMUTABLE) {
|
||||
PropertyChanges.Kind kind = changes.kindOf(name);
|
||||
if (kind == null || kind == PropertyChanges.Kind.UNCHANGED || sameAsLive(name, key, props, ctx)) {
|
||||
continue;
|
||||
}
|
||||
throw new AwsException("ValidationError", "Update of " + name + " on " + KEY + " "
|
||||
+ r.getLogicalId() + " is not allowed: a KMS key cannot change its " + name
|
||||
+ " after it is created.", 400);
|
||||
}
|
||||
String keyId = key.getKeyId();
|
||||
String region = ctx.region();
|
||||
// A property the template drops goes back to its create default; one it never declared keeps
|
||||
// the value set outside the stack (null: leave as is).
|
||||
Set<String> dropped = ctx.droppedProperties(props);
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
if (description == null && dropped.contains("Description")) {
|
||||
description = "";
|
||||
}
|
||||
Boolean enabled = ctx.resolveOptionalBoolean(props, "Enabled");
|
||||
if (enabled == null && dropped.contains("Enabled")) {
|
||||
// A key waiting for its key material keeps its state.
|
||||
enabled = PENDING_IMPORT.equals(key.getKeyState()) ? key.isEnabled() : Boolean.TRUE;
|
||||
}
|
||||
Boolean rotation = ctx.resolveOptionalBoolean(props, "EnableKeyRotation");
|
||||
if (rotation == null && dropped.contains("EnableKeyRotation")) {
|
||||
rotation = Boolean.FALSE;
|
||||
}
|
||||
Map<String, String> desiredTags = ReservedTags.stripReservedTags(
|
||||
parseCfnTags(props != null ? props.get("Tags") : null, ctx));
|
||||
// Only the keys the previous template or this one sets are the stack's to change or drop.
|
||||
Set<String> priorTagKeys = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx);
|
||||
Set<String> managedTagKeys = new TreeSet<>(priorTagKeys);
|
||||
managedTagKeys.addAll(desiredTags.keySet());
|
||||
// Resolved before the snapshot: a template that cannot be read changes nothing.
|
||||
String policy = keyPolicy(props, ctx);
|
||||
ObjectNode snapshot = MAPPER.createObjectNode();
|
||||
snapshot.put("keyId", keyId);
|
||||
snapshot.put("region", region);
|
||||
snapshot.put("description", key.getDescription());
|
||||
snapshot.put("policy", key.getPolicy());
|
||||
snapshot.put("enabled", key.isEnabled());
|
||||
snapshot.put("rotation", key.isKeyRotationEnabled());
|
||||
Ec2Tags.snapshotOwned(snapshot, priorTagKeys, desiredTags, key.getTags(), r.getAttributes().get(TAG_KEYS_ATTR));
|
||||
r.setPhysicalId(keyId);
|
||||
r.getAttributes().put("Arn", key.getArn());
|
||||
r.getAttributes().put("KeyId", keyId);
|
||||
r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString());
|
||||
String finalDescription = description;
|
||||
Boolean finalEnabled = enabled;
|
||||
Boolean finalRotation = rotation;
|
||||
// A dropped KeyPolicy keeps the current policy: no AWS documentation says it resets to the default.
|
||||
CfnRollback.guarded(r, ctx, false, () -> { }, () -> restore(snapshot), () ->
|
||||
converge(key, finalDescription, policy, finalEnabled, finalRotation, desiredTags,
|
||||
managedTagKeys, region));
|
||||
Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives {@code key} to the given state, calling only what differs: the one path both an update
|
||||
* and its rollback take. A null {@code description}, {@code policy}, {@code enabled} or
|
||||
* {@code rotation} leaves that setting as it is; only {@code managedTagKeys}
|
||||
* absent from {@code tags} are removed, so a tag added outside the stack stays.
|
||||
*/
|
||||
private void converge(KmsKey key, String description, String policy, Boolean wantEnabled, Boolean wantRotation,
|
||||
Map<String, String> tags, Collection<String> managedTagKeys, String region) {
|
||||
String keyId = key.getKeyId();
|
||||
// Read before the first call: the service may change the stored key object in place.
|
||||
boolean enabledNow = key.isEnabled();
|
||||
boolean rotationNow = key.isKeyRotationEnabled();
|
||||
String descriptionNow = key.getDescription();
|
||||
String policyNow = key.getPolicy();
|
||||
boolean enabled = wantEnabled == null ? enabledNow : wantEnabled;
|
||||
boolean rotation = wantRotation == null ? rotationNow : wantRotation;
|
||||
if (description != null && !Objects.equals(description, descriptionNow)) {
|
||||
kmsService.updateKeyDescription(keyId, description, region);
|
||||
}
|
||||
if (policy != null && !policy.equals(policyNow)) {
|
||||
kmsService.putKeyPolicy(keyId, policy, region);
|
||||
}
|
||||
// Rotation changes need an enabled key: enable first, and disable only after rotation is set.
|
||||
if (enabled && !enabledNow) {
|
||||
kmsService.enableKey(keyId, region);
|
||||
}
|
||||
if (rotation != rotationNow) {
|
||||
if (rotation) {
|
||||
kmsService.enableKeyRotation(keyId, region);
|
||||
} else {
|
||||
kmsService.disableKeyRotation(keyId, region);
|
||||
}
|
||||
}
|
||||
if (!enabled && enabledNow) {
|
||||
kmsService.disableKey(keyId, region);
|
||||
}
|
||||
CfnRollback.reconcileTags(managedTagKeys, tags, dropped -> kmsService.untagResource(keyId, dropped, region),
|
||||
added -> kmsService.tagResource(keyId, added, region));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the requested value of an immutable property is the one the key has. An absent value
|
||||
* names the property's default (KeySpec SYMMETRIC_DEFAULT, KeyUsage ENCRYPT_DECRYPT, MultiRegion
|
||||
* false, Origin AWS_KMS), so adding or dropping a default is not a change.
|
||||
*/
|
||||
private static boolean sameAsLive(String name, KmsKey key, JsonNode props, ProvisionContext ctx) {
|
||||
return switch (name) {
|
||||
// A key stored before these fields existed holds null, which means the default.
|
||||
case "KeySpec" -> orDefault(key.getKeySpec() == null ? null : key.getKeySpec().name(),
|
||||
"SYMMETRIC_DEFAULT").equalsIgnoreCase(
|
||||
orDefault(ctx.resolveOptional(props, "KeySpec"), "SYMMETRIC_DEFAULT"));
|
||||
case "KeyUsage" -> orDefault(key.getKeyUsage() == null ? null : key.getKeyUsage().name(),
|
||||
"ENCRYPT_DECRYPT").equalsIgnoreCase(
|
||||
orDefault(ctx.resolveOptional(props, "KeyUsage"), "ENCRYPT_DECRYPT"));
|
||||
case "MultiRegion" -> Boolean.TRUE.equals(ctx.resolveOptionalBoolean(props, "MultiRegion"))
|
||||
== key.isMultiRegion();
|
||||
case "Origin" -> orDefault(ctx.resolveOptional(props, "Origin"), "AWS_KMS").equals(orDefault(key.getOrigin(), "AWS_KMS"));
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static String orDefault(String value, String fallback) {
|
||||
return value == null || value.isBlank() ? fallback : value;
|
||||
}
|
||||
|
||||
private void restore(JsonNode snapshot) {
|
||||
String keyId = snapshot.path("keyId").asText();
|
||||
String region = snapshot.path("region").asText();
|
||||
String description = CfnRollback.snapshotText(snapshot, "description");
|
||||
converge(kmsService.describeKey(keyId, region), description == null ? "" : description,
|
||||
CfnRollback.snapshotText(snapshot, "policy"), snapshot.path("enabled").asBoolean(),
|
||||
snapshot.path("rotation").asBoolean(), CfnRollback.snapshotTags(snapshot),
|
||||
touchedKeys(snapshot), region);
|
||||
}
|
||||
|
||||
private static List<String> touchedKeys(JsonNode snapshot) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
snapshot.path("touched").forEach(key -> keys.add(key.asText()));
|
||||
return keys;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR);
|
||||
if (snapshot == null) {
|
||||
return false;
|
||||
}
|
||||
// A key the update created because the prior one was gone is scheduled for deletion instead.
|
||||
if (CfnRollback.undoCreatedByUpdate(resource, snapshot, SNAPSHOT_ATTR, "KeyId",
|
||||
(createdId, region) -> kmsService.scheduleKeyDeletion(createdId, MIN_DELETION_WINDOW_DAYS, region))) {
|
||||
resource.getAttributes().remove("Arn");
|
||||
return true;
|
||||
}
|
||||
// Spent only once the restore succeeded: one that throws leaves it for the next attempt.
|
||||
restore(snapshot);
|
||||
Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, snapshot);
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
return UpdateCleanupResult.notApplicable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
private void provisionAlias(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
|
||||
+138
-1
@@ -9,10 +9,17 @@ import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationKmsKeyPropertiesIntegrationTest {
|
||||
@@ -59,7 +66,137 @@ class CloudFormationKmsKeyPropertiesIntegrationTest {
|
||||
() -> assertEquals("ENCRYPT_DECRYPT", key.getString("KeyMetadata.KeyUsage")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackChangesDescriptionAndTagsInPlace() {
|
||||
String account = TestAccounts.randomId();
|
||||
String stack = "kms-cfn-update-" + account;
|
||||
String auth = EnforcementFixtures.auth(account, "cloudformation");
|
||||
CfnRequests.deploy("CreateStack", stack, template("v1", tags("one")), auth, "CREATE_COMPLETE");
|
||||
String keyId = CfnRequests.physicalId(stack, KEY_RESOURCE, auth);
|
||||
String arn = kms(account, "DescribeKey", "{\"KeyId\":\"%s\"}".formatted(keyId))
|
||||
.getString("KeyMetadata.Arn");
|
||||
int keysBefore = kms(account, "ListKeys", "{}").getList("Keys").size();
|
||||
|
||||
CfnRequests.deploy("UpdateStack", stack, template("v2", tags("two")), auth, "UPDATE_COMPLETE");
|
||||
|
||||
JsonPath key = kms(account, "DescribeKey", "{\"KeyId\":\"%s\"}".formatted(keyId));
|
||||
assertAll(
|
||||
() -> assertEquals(keyId, CfnRequests.physicalId(stack, KEY_RESOURCE, auth)),
|
||||
() -> assertEquals(arn, key.getString("KeyMetadata.Arn")),
|
||||
() -> assertEquals("v2", key.getString("KeyMetadata.Description")),
|
||||
() -> assertEquals(keysBefore, kms(account, "ListKeys", "{}").getList("Keys").size()),
|
||||
() -> assertEquals(List.of("two"), kms(account, "ListResourceTags",
|
||||
"{\"KeyId\":\"%s\"}".formatted(keyId)).getList("Tags.TagValue")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackRollsBackWhenKeyUsageChanges() {
|
||||
String account = TestAccounts.randomId();
|
||||
String stack = "kms-cfn-immutable-" + account;
|
||||
String auth = EnforcementFixtures.auth(account, "cloudformation");
|
||||
CfnRequests.deploy("CreateStack", stack, template(KEY_DESCRIPTION, ""), auth, "CREATE_COMPLETE");
|
||||
String keyId = CfnRequests.physicalId(stack, KEY_RESOURCE, auth);
|
||||
int keysBefore = kms(account, "ListKeys", "{}").getList("Keys").size();
|
||||
|
||||
CfnRequests.deploy("UpdateStack", stack, template("v2", "\"KeySpec\": \"ECC_NIST_P256\",\n\"KeyUsage\": \"SIGN_VERIFY\""),
|
||||
auth, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
JsonPath key = kms(account, "DescribeKey", "{\"KeyId\":\"%s\"}".formatted(keyId));
|
||||
assertAll(
|
||||
() -> assertEquals(keyId, CfnRequests.physicalId(stack, KEY_RESOURCE, auth)),
|
||||
() -> assertEquals(KEY_DESCRIPTION, key.getString("KeyMetadata.Description")),
|
||||
() -> assertEquals("ENCRYPT_DECRYPT", key.getString("KeyMetadata.KeyUsage")),
|
||||
() -> assertEquals(keysBefore, kms(account, "ListKeys", "{}").getList("Keys").size()));
|
||||
}
|
||||
|
||||
private static final String POLICY_ONE = policy("PolicyOne");
|
||||
private static final String POLICY_TWO = policy("PolicyTwo");
|
||||
|
||||
static Stream<Arguments> honoredCreateProperties() {
|
||||
return Stream.of(
|
||||
Arguments.of("\"KeyPolicy\": " + POLICY_ONE, "GetKeyPolicy", "Policy", "PolicyOne"),
|
||||
Arguments.of("\"Enabled\": false", "DescribeKey", "KeyMetadata.KeyState", "Disabled"),
|
||||
Arguments.of("\"Enabled\": false", "DescribeKey", "KeyMetadata.Enabled", "false"),
|
||||
Arguments.of("\"EnableKeyRotation\": true", "GetKeyRotationStatus", "KeyRotationEnabled", "true"),
|
||||
Arguments.of("\"Origin\": \"EXTERNAL\"", "DescribeKey", "KeyMetadata.Origin", "EXTERNAL"),
|
||||
Arguments.of("\"Origin\": \"EXTERNAL\"", "DescribeKey", "KeyMetadata.KeyState", "PendingImport"),
|
||||
Arguments.of("\"MultiRegion\": true", "DescribeKey", "KeyMetadata.MultiRegion", "true"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("honoredCreateProperties")
|
||||
void createStackHonorsKeyProperty(String property, String action, String path, String expected) {
|
||||
String account = TestAccounts.randomId();
|
||||
String stack = "kms-cfn-honor-" + account;
|
||||
String auth = EnforcementFixtures.auth(account, "cloudformation");
|
||||
CfnRequests.deploy("CreateStack", stack, template(property), auth, "CREATE_COMPLETE");
|
||||
String keyId = CfnRequests.physicalId(stack, KEY_RESOURCE, auth);
|
||||
|
||||
String actual = kms(account, action, "{\"KeyId\":\"%s\"}".formatted(keyId)).getString(path);
|
||||
|
||||
assertTrue(actual.contains(expected), path + " was " + actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateChangesKeyPropertiesInPlaceAndARolledBackUpdateRestoresThem() {
|
||||
String account = TestAccounts.randomId();
|
||||
String stack = "kms-cfn-lifecycle-" + account;
|
||||
String auth = EnforcementFixtures.auth(account, "cloudformation");
|
||||
String keyBody = "{\"KeyId\":\"%s\"}";
|
||||
CfnRequests.deploy("CreateStack", stack, template("v1",
|
||||
"\"Enabled\": false,\n\"EnableKeyRotation\": false,\n\"KeyPolicy\": " + POLICY_ONE + ",\n" + tags("one")),
|
||||
auth, "CREATE_COMPLETE");
|
||||
String keyId = CfnRequests.physicalId(stack, KEY_RESOURCE, auth);
|
||||
|
||||
CfnRequests.deploy("UpdateStack", stack, template("v2",
|
||||
"\"Enabled\": true,\n\"EnableKeyRotation\": true,\n\"KeyPolicy\": " + POLICY_TWO + ",\n" + tags("two")),
|
||||
auth, "UPDATE_COMPLETE");
|
||||
|
||||
JsonPath updated = kms(account, "DescribeKey", keyBody.formatted(keyId));
|
||||
assertAll(
|
||||
() -> assertEquals(keyId, CfnRequests.physicalId(stack, KEY_RESOURCE, auth)),
|
||||
() -> assertEquals("Enabled", updated.getString("KeyMetadata.KeyState")),
|
||||
() -> assertTrue(kms(account, "GetKeyRotationStatus", keyBody.formatted(keyId))
|
||||
.getBoolean("KeyRotationEnabled")),
|
||||
() -> assertTrue(kms(account, "GetKeyPolicy", keyBody.formatted(keyId))
|
||||
.getString("Policy").contains("PolicyTwo")));
|
||||
|
||||
String failing = template("v3", "\"Enabled\": false,\n\"EnableKeyRotation\": false,\n" + tags("three"))
|
||||
.replace("\n }\n}", ",\n"
|
||||
+ "\"BadSecret\": {\"Type\": \"AWS::SecretsManager::Secret\", \"Properties\": "
|
||||
+ "{\"SecretString\": \"x\", \"GenerateSecretString\": {\"PasswordLength\": 8}}}\n }\n}");
|
||||
CfnRequests.deploy("UpdateStack", stack, failing, auth, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
JsonPath restored = kms(account, "DescribeKey", keyBody.formatted(keyId));
|
||||
assertAll(
|
||||
() -> assertEquals(keyId, CfnRequests.physicalId(stack, KEY_RESOURCE, auth)),
|
||||
() -> assertEquals("v2", restored.getString("KeyMetadata.Description")),
|
||||
() -> assertEquals("Enabled", restored.getString("KeyMetadata.KeyState")),
|
||||
() -> assertTrue(kms(account, "GetKeyRotationStatus", keyBody.formatted(keyId))
|
||||
.getBoolean("KeyRotationEnabled")),
|
||||
() -> assertEquals(List.of("two"), kms(account, "ListResourceTags", keyBody.formatted(keyId))
|
||||
.getList("Tags.TagValue")));
|
||||
|
||||
CfnRequests.deploy("UpdateStack", stack, template("v4", ""), auth, "UPDATE_COMPLETE");
|
||||
|
||||
List<String> tagKeys = kms(account, "ListResourceTags", keyBody.formatted(keyId)).getList("Tags.TagKey");
|
||||
assertTrue(tagKeys == null || !tagKeys.contains("env"), "tags after the drop: " + tagKeys);
|
||||
}
|
||||
|
||||
private static String policy(String sid) {
|
||||
return "{\"Version\": \"2012-10-17\", \"Statement\": [{\"Sid\": \"%s\", \"Effect\": \"Allow\", "
|
||||
.formatted(sid) + "\"Principal\": {\"AWS\": \"*\"}, \"Action\": \"kms:*\", \"Resource\": \"*\"}]}";
|
||||
}
|
||||
|
||||
private static String tags(String value) {
|
||||
return "\"Tags\": [{\"Key\": \"env\", \"Value\": \"%s\"}]".formatted(value);
|
||||
}
|
||||
|
||||
private static String template(String additionalProperties) {
|
||||
return template(KEY_DESCRIPTION, additionalProperties);
|
||||
}
|
||||
|
||||
private static String template(String description, String additionalProperties) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
@@ -71,7 +208,7 @@ class CloudFormationKmsKeyPropertiesIntegrationTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(KEY_DESCRIPTION, additionalProperties.isEmpty() ? ""
|
||||
""".formatted(description, additionalProperties.isEmpty() ? ""
|
||||
: ",\n" + additionalProperties.strip());
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -100,8 +100,8 @@ class LeafCfnProvisionerTest {
|
||||
|
||||
assertEquals("k-123", r.getPhysicalId(), "Ref is the key id (schema primaryIdentifier)");
|
||||
// aws-kms-key.json readOnlyProperties
|
||||
assertEquals(Map.of("Arn", "arn:aws:kms:us-east-1:000000000000:key/k-123", "KeyId", "k-123"),
|
||||
r.getAttributes());
|
||||
assertEquals(Map.of("Arn", "arn:aws:kms:us-east-1:000000000000:key/k-123", "KeyId", "k-123",
|
||||
KmsCfnProvisioner.TAG_KEYS_ATTR, "[\"env\"]"), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -138,7 +138,8 @@ class LeafCfnProvisionerTest {
|
||||
|
||||
verify(kms, never()).describeKey(anyString(), anyString());
|
||||
assertEquals("k-real", r.getPhysicalId());
|
||||
assertEquals(Map.of("Arn", key.getArn(), "KeyId", "k-real"), r.getAttributes());
|
||||
assertEquals(Map.of("Arn", key.getArn(), "KeyId", "k-real", KmsCfnProvisioner.TAG_KEYS_ATTR, "[]"),
|
||||
r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -143,6 +143,15 @@ AWS::ECS::Service NetworkConfiguration keep:the update leaves a missing network
|
||||
AWS::ECS::Service ServiceName keep:the prior name is reused
|
||||
AWS::ECS::Service ServiceRegistries keep:AWS removes registries only through a declared empty list
|
||||
AWS::ECS::Service TaskDefinition keep:required for the ECS controller
|
||||
AWS::KMS::Key Description clear cleared to the empty description, KMS's own empty state; the CloudFormation page lists no default
|
||||
AWS::KMS::Key EnableKeyRotation default:false the CloudFormation page: EnableKeyRotation defaults to false
|
||||
AWS::KMS::Key Enabled default:true the CloudFormation page: Enabled defaults to true
|
||||
AWS::KMS::Key KeyPolicy keep:no AWS documentation says a dropped policy resets to the default, so the stored policy stays
|
||||
AWS::KMS::Key KeySpec keep:a drop names the create default, so a key holding another value fails the update, as a change does
|
||||
AWS::KMS::Key KeyUsage keep:a drop names the create default, so a key holding another value fails the update, as a change does
|
||||
AWS::KMS::Key MultiRegion keep:a drop names the create default, so a key holding another value fails the update, as a change does
|
||||
AWS::KMS::Key Origin keep:a drop names the create default, so a key holding another value fails the update, as a change does
|
||||
AWS::KMS::Key Tags clear every update drives the stack's own tag keys to the template; tags added outside the stack stay
|
||||
AWS::Lambda::Alias Description clear
|
||||
AWS::Lambda::Alias FunctionName create-only a drop fails: the provisioner requires it
|
||||
AWS::Lambda::Alias FunctionVersion keep:the update skips a null, so the stored version stays
|
||||
|
||||
|
@@ -374,11 +374,6 @@ AWS::IAM::Policy PolicyDocument accepted and ignored
|
||||
AWS::IAM::Role Tags accepted and ignored
|
||||
AWS::IAM::User LoginProfile documented as ignored (docs/services/cloudformation.md, IAM)
|
||||
AWS::KMS::Key BypassPolicyLockoutSafetyCheck accepted and ignored
|
||||
AWS::KMS::Key EnableKeyRotation accepted and ignored
|
||||
AWS::KMS::Key Enabled accepted and ignored
|
||||
AWS::KMS::Key KeyPolicy accepted and ignored
|
||||
AWS::KMS::Key MultiRegion accepted and ignored
|
||||
AWS::KMS::Key Origin accepted and ignored
|
||||
AWS::KMS::Key PendingWindowInDays accepted and ignored
|
||||
AWS::KMS::Key RotationPeriodInDays accepted and ignored
|
||||
AWS::Kinesis::Stream DesiredShardLevelMetrics accepted and ignored
|
||||
|
||||
|
@@ -225,6 +225,7 @@ notes:
|
||||
AWS::EKS::Cluster: 'created with `Name`, `Version`, `RoleArn` and `Tags`, a replacement included; `EncryptionConfig` and `KubernetesNetworkConfig` are accepted and ignored on create; updated in place for `Tags`, keeping tags added outside the stack; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator cannot upgrade a cluster in place'
|
||||
AWS::EKS::Nodegroup: 'created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place'
|
||||
AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete'
|
||||
AWS::KMS::Key: 'created with `Description`, `KeyPolicy`, `KeySpec`, `KeyUsage`, `Origin`, `MultiRegion`, `Enabled`, `EnableKeyRotation` and `Tags`; updated in place for `Description`, `KeyPolicy`, `Enabled`, `EnableKeyRotation` and `Tags`, keeping tags added outside the stack; a template that drops `Description`, `Enabled` or `EnableKeyRotation` clears the description, enables the key and turns rotation off, a dropped `KeyPolicy` keeps the current policy, and one the stack never declared keeps the value set outside it; a rotation change on a key that stays disabled fails, as AWS raises `DisabledException`; a change to `KeySpec`, `KeyUsage`, `Origin` or `MultiRegion` fails the update, as on AWS, and the stack rolls back'
|
||||
AWS::IoT::DomainConfiguration: '`ServerCertificates` resolves to a JSON string'
|
||||
AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached'
|
||||
AWS::Route53::RecordSetGroup: 'written in one change batch, so a record set that cannot be written leaves the zone unchanged; every record set must be in the group''s hosted zone'
|
||||
|
||||
Reference in new issue
Block a user