From f2debe4ce0280c25e00a7fc6b16c65a611eeb936 Mon Sep 17 00:00:00 2001 From: Jimmy Liu Jia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:30:24 +0800 Subject: [PATCH] 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 --- .../provisioners/KmsCfnProvisioner.java | 4 +- .../floci/services/kms/KmsService.java | 2 +- ...mationKmsKeyPropertiesIntegrationTest.java | 111 ++++++++++++++++++ .../provisioners/LeafCfnProvisionerTest.java | 54 ++++++++- .../floci/services/kms/KmsServiceTest.java | 42 +++++++ .../cloudformation/writable-property-gaps.tsv | 2 - 6 files changed, 209 insertions(+), 6 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationKmsKeyPropertiesIntegrationTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java index 813b8605d3..a53f9ede72 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/KmsCfnProvisioner.java @@ -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 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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index 1def677876..f69df91f2a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationKmsKeyPropertiesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationKmsKeyPropertiesIntegrationTest.java new file mode 100644 index 0000000000..f2611625af --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationKmsKeyPropertiesIntegrationTest.java @@ -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(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java index d79191c107..a5ac5295b6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LeafCfnProvisionerTest.java @@ -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> 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"); diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java index b0c3e5c7ee..a875f424b2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java @@ -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 diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 6f53127a92..dd424f8ee7 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -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