fix(cloudformation): preserve KMS key spec and usage on create (#7612)

* fix(cloudformation): preserve KMS key spec and usage on create

* fix(cloudformation): delegate KMS key defaults to service
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-05 15:30:24 -04:00
1 parent de71d91d8c
commit f2debe4ce0
6 files changed
+209 -6

No files matched your search

@@ -41,8 +41,10 @@ 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");
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, ctx);
KmsKey key = kmsService.createKey(description, null, tags, ctx.region());
KmsKey key = kmsService.createKey(description, requestedUsage, requestedSpec, null, tags, ctx.region());
r.setPhysicalId(key.getKeyId());
r.getAttributes().put("Arn", key.getArn());
r.getAttributes().put("KeyId", key.getKeyId());
@@ -152,7 +152,7 @@ public class KmsService implements ResourceProvider {
KmsKeyUsage effectiveUsage = Optional.ofNullable(keyUsage)
.map(KmsKeyUsage::fromString)
.orElse(KmsKeyUsage.ENCRYPT_DECRYPT);
KmsKeySpec effectiveSpec = Optional.of(keySpec)
KmsKeySpec effectiveSpec = Optional.ofNullable(keySpec)
.map(KmsKeySpec::fromString)
.orElse(KmsKeySpec.SYMMETRIC_DEFAULT);
validateKeyUsageForSpec(effectiveUsage, effectiveSpec);
@@ -0,0 +1,111 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.CfnRequests;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.TestAccounts;
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 static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class CloudFormationKmsKeyPropertiesIntegrationTest {
private static final String KEY_RESOURCE = "Key";
private static final String KEY_DESCRIPTION = "CloudFormation key properties";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createStackPreservesKmsKeySpecAndUsage() {
String account = TestAccounts.randomId();
String stack = "kms-cfn-spec-" + account;
createStack(account, stack, template("""
"KeySpec": "ECC_NIST_P256",
"KeyUsage": "SIGN_VERIFY"
"""));
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", EnforcementFixtures.auth(account, "cloudformation"));
String keyId = physicalId(account, stack);
JsonPath key = kms(account, "DescribeKey", "{\"KeyId\":\"%s\"}".formatted(keyId));
assertAll(
() -> assertEquals(keyId, key.getString("KeyMetadata.KeyId")),
() -> assertEquals("ECC_NIST_P256", key.getString("KeyMetadata.KeySpec")),
() -> assertEquals("SIGN_VERIFY", key.getString("KeyMetadata.KeyUsage")));
}
@Test
void createStackUsesDefaultKeySpecAndUsageWhenOmitted() {
String account = TestAccounts.randomId();
String stack = "kms-cfn-default-" + account;
createStack(account, stack, template(""));
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", EnforcementFixtures.auth(account, "cloudformation"));
String keyId = physicalId(account, stack);
JsonPath key = kms(account, "DescribeKey", "{\"KeyId\":\"%s\"}".formatted(keyId));
assertAll(
() -> assertEquals(keyId, key.getString("KeyMetadata.KeyId")),
() -> assertEquals("SYMMETRIC_DEFAULT", key.getString("KeyMetadata.KeySpec")),
() -> assertEquals("ENCRYPT_DECRYPT", key.getString("KeyMetadata.KeyUsage")));
}
private static String template(String additionalProperties) {
return """
{
"Resources": {
"Key": {
"Type": "AWS::KMS::Key",
"Properties": {
"Description": "%s"%s
}
}
}
}
""".formatted(KEY_DESCRIPTION, additionalProperties.isEmpty() ? ""
: ",\n" + additionalProperties.strip());
}
private static void createStack(String account, String stack, String template) {
CfnRequests.cfn("CreateStack", stack)
.header("Authorization", EnforcementFixtures.auth(account, "cloudformation"))
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private static String physicalId(String account, String stack) {
return CfnRequests.cfn("DescribeStackResource", stack)
.header("Authorization", EnforcementFixtures.auth(account, "cloudformation"))
.formParam("LogicalResourceId", KEY_RESOURCE)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("**.find { it.name() == 'PhysicalResourceId' }");
}
private static JsonPath kms(String account, String action, String body) {
return given()
.header("Authorization", EnforcementFixtures.auth(account, "kms"))
.header("X-Amz-Target", "TrentService." + action)
.contentType("application/x-amz-json-1.1")
.body(body)
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath();
}
}
@@ -90,7 +90,8 @@ class LeafCfnProvisionerTest {
KmsKey key = new KmsKey();
key.setKeyId("k-123");
key.setArn("arn:aws:kms:us-east-1:000000000000:key/k-123");
when(kms.createKey(eq("a key"), eq(null), any(), eq(REGION))).thenReturn(key);
when(kms.createKey(eq("a key"), eq(null), eq(null),
eq(null), any(), eq(REGION))).thenReturn(key);
StackResource r = resource("Key", "AWS::KMS::Key");
provisioner.provision(r, props("""
@@ -108,7 +109,7 @@ class LeafCfnProvisionerTest {
KmsKey key = new KmsKey();
key.setKeyId("k-1");
ArgumentCaptor<Map<String, String>> tags = ArgumentCaptor.forClass(Map.class);
when(kms.createKey(any(), any(), tags.capture(), anyString())).thenReturn(key);
when(kms.createKey(any(), eq(null), eq(null), any(), tags.capture(), anyString())).thenReturn(key);
provisioner.provision(resource("Key", "AWS::KMS::Key"), props("""
{"Tags": [{"Key": "team", "Value": "core"}]}
@@ -117,6 +118,55 @@ class LeafCfnProvisionerTest {
assertEquals(Map.of("team", "core"), tags.getValue());
}
@Test
void stubbedKeyCanBecomeARealKeyOnUpdate() {
KmsKey key = new KmsKey();
key.setKeyId("k-real");
key.setArn("arn:aws:kms:us-east-1:000000000000:key/k-real");
when(kms.createKey(eq(null), eq("SIGN_VERIFY"), eq("ECC_NIST_P256"),
eq(null), any(), eq(REGION))).thenReturn(key);
StackResource r = resource("Key", "AWS::KMS::Key");
r.setPhysicalId("Key-1a2b3c4d");
r.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "Key");
ProvisionContext update = new ProvisionContext(engine, REGION, "000000000000",
"my-stack", "Key-1a2b3c4d");
provisioner.provision(r, props("""
{"KeySpec": "ECC_NIST_P256", "KeyUsage": "SIGN_VERIFY"}
"""), update);
verify(kms, never()).describeKey(anyString(), anyString());
assertEquals("k-real", r.getPhysicalId());
assertEquals(Map.of("Arn", key.getArn(), "KeyId", "k-real"), r.getAttributes());
}
@Test
void explicitBlankKeySpecReachesTheService() {
KmsKey key = new KmsKey();
key.setKeyId("k-blank-spec");
when(kms.createKey(eq(null), eq(null), eq(""), eq(null), any(), eq(REGION)))
.thenReturn(key);
provisioner.provision(resource("Key", "AWS::KMS::Key"),
props("{\"KeySpec\":\"\"}"), ctx);
verify(kms).createKey(eq(null), eq(null), eq(""), eq(null), any(), eq(REGION));
}
@Test
void explicitBlankKeyUsageReachesTheService() {
KmsKey key = new KmsKey();
key.setKeyId("k-blank-usage");
when(kms.createKey(eq(null), eq(""), eq(null), eq(null), any(), eq(REGION)))
.thenReturn(key);
provisioner.provision(resource("Key", "AWS::KMS::Key"),
props("{\"KeyUsage\":\"\"}"), ctx);
verify(kms).createKey(eq(null), eq(""), eq(null), eq(null), any(), eq(REGION));
}
@Test
void aliasRefIsTheAliasName() {
StackResource r = resource("Alias", "AWS::KMS::Alias");
@@ -134,6 +134,48 @@ class KmsServiceTest {
assertEquals("Enabled", key.getKeyState());
}
@Test
void createKeyDefaultsNullSpecAndUsage() {
KmsKey key = kmsService.createKey("defaults", null, null, null, Map.of(), REGION);
assertEquals(KmsKeySpec.SYMMETRIC_DEFAULT, key.getKeySpec());
assertEquals(KmsKeyUsage.ENCRYPT_DECRYPT, key.getKeyUsage());
}
@Test
void createKeyDefaultsSpecWhenOnlyUsageIsPresent() {
KmsKey key = kmsService.createKey("defaults", "ENCRYPT_DECRYPT", null, null, Map.of(), REGION);
assertEquals(KmsKeySpec.SYMMETRIC_DEFAULT, key.getKeySpec());
assertEquals(KmsKeyUsage.ENCRYPT_DECRYPT, key.getKeyUsage());
}
@Test
void createKeyDefaultsUsageWhenOnlySpecIsPresent() {
KmsKey key = kmsService.createKey("defaults", null, "SYMMETRIC_DEFAULT", null, Map.of(), REGION);
assertEquals(KmsKeySpec.SYMMETRIC_DEFAULT, key.getKeySpec());
assertEquals(KmsKeyUsage.ENCRYPT_DECRYPT, key.getKeyUsage());
}
@Test
void createKeyRejectsBlankSpec() {
AwsException failure = assertThrows(AwsException.class, () ->
kmsService.createKey("invalid", null, "", null, Map.of(), REGION));
assertTrue(failure.getMessage().contains("KeySpec"));
assertTrue(keyStore.scan(id -> true).isEmpty());
}
@Test
void createKeyRejectsBlankUsage() {
AwsException failure = assertThrows(AwsException.class, () ->
kmsService.createKey("invalid", "", null, null, Map.of(), REGION));
assertTrue(failure.getMessage().contains("KeyUsage"));
assertTrue(keyStore.scan(id -> true).isEmpty());
}
/**
* The enforcement filter resolves the key a request names through this lookup rather than
* through {@code describeKey}, which throws: an operation naming no key the account holds
@@ -370,8 +370,6 @@ 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 KeySpec accepted and ignored
AWS::KMS::Key KeyUsage accepted and ignored
AWS::KMS::Key MultiRegion accepted and ignored
AWS::KMS::Key Origin accepted and ignored
AWS::KMS::Key PendingWindowInDays accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
370 AWS::KMS::Key EnableKeyRotation accepted and ignored
371 AWS::KMS::Key Enabled accepted and ignored
372 AWS::KMS::Key KeyPolicy accepted and ignored
AWS::KMS::Key KeySpec accepted and ignored
AWS::KMS::Key KeyUsage accepted and ignored
373 AWS::KMS::Key MultiRegion accepted and ignored
374 AWS::KMS::Key Origin accepted and ignored
375 AWS::KMS::Key PendingWindowInDays accepted and ignored