Light, fluffy, and always free - The AWS Local Emulator alternative
fix(kms): match the AWS error codes, messages and check order (#3968)
TATSUNO “Taz” Yasuhiro68425d942a0d
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.javaindex 49db712655..d62c04cf81 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java@@ -407,17 +407,13 @@ class KmsFeaturesTest {void encryptWithPendingDeletionKeyRaisesKmsInvalidStateException() {String keyId = kms.createKey(b -> b.description("pending-encrypt")).keyMetadata().keyId();- try {- kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));- assertThatThrownBy(- () -> kms.encrypt(b -> b- .keyId(keyId)- .plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))- ).isInstanceOf(KmsInvalidStateException.class);- } finally {- kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));- }+ assertThatThrownBy(+ () -> kms.encrypt(b -> b+ .keyId(keyId)+ .plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))+ ).isInstanceOf(KmsInvalidStateException.class);}@Test@@ -425,22 +421,18 @@ class KmsFeaturesTest {void decryptWithPendingDeletionKeyRaisesKmsInvalidStateException() {String keyId = kms.createKey(b -> b.description("pending-decrypt")).keyMetadata().keyId();- try {- SdkBytes ciphertext = kms.encrypt(b -> b- .keyId(keyId)- .plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))- .ciphertextBlob();+ SdkBytes ciphertext = kms.encrypt(b -> b+ .keyId(keyId)+ .plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))+ .ciphertextBlob();- kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));- assertThatThrownBy(- () -> kms.decrypt(b -> b- .ciphertextBlob(ciphertext)- .keyId(keyId))- ).isInstanceOf(KmsInvalidStateException.class);- } finally {- kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));- }+ assertThatThrownBy(+ () -> kms.decrypt(b -> b+ .ciphertextBlob(ciphertext)+ .keyId(keyId))+ ).isInstanceOf(KmsInvalidStateException.class);}// ── Issue #3024: Encrypt/Decrypt apply real RSAES-OAEP for RSA keys ──────diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.javaindex 354a9c514f..7ccd6ecd44 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java@@ -36,7 +36,33 @@ public class KmsJsonHandler {this.regionResolver = regionResolver;}+ private static final Set<String> KEY_ID_OPERATIONS = Set.of(+ "GetPublicKey", "DescribeKey", "CreateGrant", "ListGrants", "RevokeGrant", "Encrypt", "GenerateDataKey",+ "GenerateDataKeyWithoutPlaintext", "Sign", "Verify", "GenerateMac", "VerifyMac", "ScheduleKeyDeletion",+ "CancelKeyDeletion", "TagResource", "UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy",+ "ListKeyPolicies", "UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation",+ "DisableKeyRotation", "EnableKey", "DisableKey", "RotateKeyOnDemand", "GetParametersForImport",+ "ImportKeyMaterial", "DeleteImportedKeyMaterial");++ private static final Set<String> KEY_ONLY_OPERATIONS = Set.of(+ "CreateGrant", "ListGrants", "RevokeGrant", "ScheduleKeyDeletion", "CancelKeyDeletion", "TagResource",+ "UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy", "ListKeyPolicies",+ "UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation", "DisableKeyRotation", "EnableKey",+ "DisableKey", "RotateKeyOnDemand", "GetParametersForImport", "ImportKeyMaterial",+ "DeleteImportedKeyMaterial");+public Response handle(String action, JsonNode request, String region) {+ if (KEY_ID_OPERATIONS.contains(action)) {+ validateKeyIdMember(request, "KeyId");+ String keyId = request.path("KeyId").asText();+ if (KEY_ONLY_OPERATIONS.contains(action) && (keyId.startsWith("alias/") || keyId.contains(":alias/"))) {+ throw new AwsException("InvalidArnException", "Key Aliases are not supported for this operation.", 400);+ }+ } else if ("ReEncrypt".equals(action)) {+ validateKeyIdMember(request, "DestinationKeyId");+ } else if ("CreateAlias".equals(action) || "UpdateAlias".equals(action)) {+ validateKeyIdMember(request, "TargetKeyId");+ }return switch (action) {case "CreateKey" -> handleCreateKey(request, region);case "GenerateRandom" -> handleGenerateRandom(request, region);@@ -251,7 +277,7 @@ public class KmsJsonHandler {private Response handleEncrypt(JsonNode request, String region) {String keyId = request.path("KeyId").asText();- byte[] plaintext = decodeBlob(request, "Plaintext");+ byte[] plaintext = requireSizedBlob(request, "Plaintext", true, KmsService.MAX_PLAINTEXT_BYTES);Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));String algorithm = request.path("EncryptionAlgorithm").asText(null);@@ -265,7 +291,7 @@ public class KmsJsonHandler {}private Response handleDecrypt(JsonNode request, String region) {- byte[] ciphertext = decodeBlob(request, "CiphertextBlob");+ byte[] ciphertext = requireSizedBlob(request, "CiphertextBlob", false, KmsService.MAX_CIPHERTEXT_BYTES);Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));String requestKeyId = request.path("KeyId").asText(null);String algorithm = request.path("EncryptionAlgorithm").asText(null);@@ -283,8 +309,8 @@ public class KmsJsonHandler {private Response handleGenerateDataKey(JsonNode request, String region) {String keyId = request.path("KeyId").asText();- String spec = request.path("KeySpec").asText(null);- int numberOfBytes = request.path("NumberOfBytes").asInt(0);+ String spec = readDataKeySpec(request);+ Integer numberOfBytes = readNumberOfBytes(request);Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);@@ -298,11 +324,11 @@ public class KmsJsonHandler {private Response handleGenerateDataKeyWithoutPlaintext(JsonNode request, String region) {String keyId = request.path("KeyId").asText();- String spec = request.path("KeySpec").asText(null);- int numberOfBytes = request.path("NumberOfBytes").asInt(0);+ String spec = readDataKeySpec(request);+ Integer numberOfBytes = readNumberOfBytes(request);Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));- Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);+ Map<String, Object> result = service.generateDataKeyWithoutPlaintext(keyId, spec, numberOfBytes, context, region);ObjectNode response = objectMapper.createObjectNode();response.put("CiphertextBlob", Base64.getEncoder().encodeToString((byte[]) result.get("CiphertextBlob")));@@ -311,7 +337,7 @@ public class KmsJsonHandler {}private Response handleReEncrypt(JsonNode request, String region) {- byte[] ciphertext = decodeBlob(request, "CiphertextBlob");+ byte[] ciphertext = requireSizedBlob(request, "CiphertextBlob", false, KmsService.MAX_CIPHERTEXT_BYTES);String destKeyId = request.path("DestinationKeyId").asText();Map<String, String> sourceContext = readEncryptionContext(request.path("SourceEncryptionContext"));Map<String, String> destContext = readEncryptionContext(request.path("DestinationEncryptionContext"));@@ -344,8 +370,8 @@ public class KmsJsonHandler {private Response handleSign(JsonNode request, String region) {String keyId = request.path("KeyId").asText();- byte[] message = decodeBlob(request, "Message");- String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");+ byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);+ String algorithm = request.path("SigningAlgorithm").asText(null);KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW"));byte[] signature = service.sign(keyId, message, algorithm, messageType, region);@@ -359,24 +385,24 @@ public class KmsJsonHandler {private Response handleVerify(JsonNode request, String region) {String keyId = request.path("KeyId").asText();- byte[] message = decodeBlob(request, "Message");- byte[] signature = decodeBlob(request, "Signature");- String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");+ byte[] signature = requireSizedBlob(request, "Signature", false, KmsService.MAX_CIPHERTEXT_BYTES);+ byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);+ String algorithm = request.path("SigningAlgorithm").asText(null);KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW"));- boolean valid = service.verify(keyId, message, signature, algorithm, messageType, region);+ service.verify(keyId, message, signature, algorithm, messageType, region);ObjectNode response = objectMapper.createObjectNode();response.put("KeyId", service.describeKey(keyId, region).getArn());- response.put("SignatureValid", valid);+ response.put("SignatureValid", true);response.put("SigningAlgorithm", algorithm);return Response.ok(response).build();}private Response handleGenerateMac(JsonNode request, String region) {String keyId = request.path("KeyId").asText();- byte[] message = decodeBlob(request, "Message");- String algorithm = request.path("MacAlgorithm").asText();+ byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);+ String algorithm = request.path("MacAlgorithm").asText(null);KmsService.GenerateMacResult result = service.generateMacAndResolveKey(keyId, message, algorithm, region);@@ -389,9 +415,9 @@ public class KmsJsonHandler {private Response handleVerifyMac(JsonNode request, String region) {String keyId = request.path("KeyId").asText();- byte[] message = decodeBlob(request, "Message");- byte[] mac = decodeBlob(request, "Mac");- String algorithm = request.path("MacAlgorithm").asText();+ byte[] mac = requireSizedBlob(request, "Mac", false, KmsService.MAX_CIPHERTEXT_BYTES);+ byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);+ String algorithm = request.path("MacAlgorithm").asText(null);KmsService.VerifyMacResult result = service.verifyMacAndResolveKey(keyId, message, mac, algorithm, region);@@ -530,6 +556,10 @@ public class KmsJsonHandler {}private Response handleEnableKeyRotation(JsonNode request, String region) {+ JsonNode rotationPeriod = request.path("RotationPeriodInDays");+ if (rotationPeriod.isNumber()) {+ validateRange("rotationPeriodInDays", rotationPeriod.asInt(), 90, 2560);+ }service.enableKeyRotation(request.path("KeyId").asText(), region);return Response.ok(objectMapper.createObjectNode()).build();}@@ -567,7 +597,10 @@ public class KmsJsonHandler {"Custom key stores are not supported.",400);}- int numberOfBytes = request.path("NumberOfBytes").asInt(0);+ if (!request.path("NumberOfBytes").isNumber()) {+ throw new AwsException("ValidationException", "NumberOfBytes is required.", 400);+ }+ int numberOfBytes = request.path("NumberOfBytes").asInt();byte[] randomBytes = service.generateRandom(numberOfBytes);ObjectNode response = objectMapper.createObjectNode();response.put("Plaintext", Base64.getEncoder().encodeToString(randomBytes));@@ -616,6 +649,71 @@ public class KmsJsonHandler {return Response.ok(response).build();}+ // The model check lists every KMS key spec, yet only the data key specs pass.+ private static String readDataKeySpec(JsonNode request) {+ String spec = request.path("KeySpec").asText(null);+ if (spec != null && !"AES_256".equals(spec) && !"AES_128".equals(spec)) {+ throw new AwsException("ValidationException", "1 validation error detected: Value '" + spec+ + "' at 'keySpec' failed to satisfy constraint: Member must satisfy enum value set: [RSA_2048, "+ + "RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384, ECC_NIST_P521, ECC_SECG_P256K1, "+ + "ECC_NIST_EDWARDS25519, SYMMETRIC_DEFAULT, HMAC_224, HMAC_256, HMAC_384, HMAC_512, SM2, "+ + "ML_DSA_44, ML_DSA_65, ML_DSA_87]", 400);+ }+ return spec;+ }++ private static Integer readNumberOfBytes(JsonNode request) {+ JsonNode numberOfBytes = request.path("NumberOfBytes");+ if (!numberOfBytes.isNumber()) {+ return null;+ }+ validateRange("numberOfBytes", numberOfBytes.asInt(), 1, 1024);+ return numberOfBytes.asInt();+ }++ private static void validateRange(String member, int value, int min, int max) {+ if (value < min) {+ throw new AwsException("ValidationException", "1 validation error detected: Value '" + value + "' at '"+ + member + "' failed to satisfy constraint: Member must have value greater than or equal to " + min, 400);+ }+ if (max < value) {+ throw new AwsException("ValidationException", "1 validation error detected: Value '" + value + "' at '"+ + member + "' failed to satisfy constraint: Member must have value less than or equal to " + max, 400);+ }+ }++ private static void validateKeyIdMember(JsonNode request, String member) {+ String name = Character.toLowerCase(member.charAt(0)) + member.substring(1);+ JsonNode value = request.path(member);+ if (value.isMissingNode() || value.isNull()) {+ throw new AwsException("ValidationException", "1 validation error detected: Value null at '" + name+ + "' failed to satisfy constraint: Member must not be null", 400);+ }+ String keyId = value.asText();+ String pattern = "Value '" + keyId + "' at '" + name+ + "' failed to satisfy constraint: Member must satisfy regular expression pattern: ^\\p{ASCII}+$";+ if (keyId.isEmpty()) {+ throw new AwsException("ValidationException", "2 validation errors detected: Value '' at '" + name+ + "' failed to satisfy constraint: Member must have length greater than or equal to 1; " + pattern, 400);+ }+ if (!keyId.chars().allMatch(c -> c < 128)) {+ throw new AwsException("ValidationException", "1 validation error detected: " + pattern, 400);+ }+ }++ // KMS hides the value of a sensitive member, even when it is null.+ private static byte[] requireSizedBlob(JsonNode request, String member, boolean sensitive, int max) {+ String name = Character.toLowerCase(member.charAt(0)) + member.substring(1);+ JsonNode value = request.path(member);+ if (value.isMissingNode() || value.isNull()) {+ throw new AwsException("ValidationException", "1 validation error detected: Value " + (sensitive ? "" : "null ")+ + "at '" + name + "' failed to satisfy constraint: Member must not be null", 400);+ }+ byte[] blob = decodeBlob(request, member);+ KmsService.validateBlobLength(name, blob, max);+ return blob;+ }+private static String requireKeyId(JsonNode request) {String keyId = request.path("KeyId").asText(null);if (keyId == null || keyId.isBlank()) {diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.javaindex bcd9936251..197c297c8f 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.java@@ -112,7 +112,7 @@ final class KmsKeyImport {return cipher.doFinal(encryptedKeyMaterial);} catch (Exception e) {LOG.debugv(e, "Unwrapping imported key material failed for wrapping algorithm {0}", wrappingAlgorithm);- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}}}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.javaindex 0b640dc3a9..987e651093 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@@ -32,6 +32,7 @@ import java.time.Duration;import java.time.Instant;import java.util.*;import java.util.concurrent.ThreadLocalRandom;+import java.util.regex.Pattern;import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;@@ -92,10 +93,13 @@ public class KmsService implements ResourceProvider {}public byte[] generateRandom(int numberOfBytes) {- if (numberOfBytes < 1 || numberOfBytes > 1024) {- throw new AwsException("ValidationException",- "1 validation error detected: Value '" + numberOfBytes + "' at 'numberOfBytes' failed to satisfy constraint: Member must have value greater than or equal to 1 and less than or equal to 1024",- 400);+ if (numberOfBytes < 1) {+ throw new AwsException("ValidationException", "1 validation error detected: Value '" + numberOfBytes+ + "' at 'numberOfBytes' failed to satisfy constraint: Member must have value greater than or equal to 1", 400);+ }+ if (1024 < numberOfBytes) {+ throw new AwsException("ValidationException", "1 validation error detected: Value '" + numberOfBytes+ + "' at 'numberOfBytes' failed to satisfy constraint: Member must have value less than or equal to 1024", 400);}byte[] bytes = new byte[numberOfBytes];secureRandom.nextBytes(bytes);@@ -250,9 +254,11 @@ public class KmsService implements ResourceProvider {public KmsKey getPublicKey(String keyId, String region) {KmsKey key = resolveKey(keyId, region);+ requireNotPendingDeletion(key);+ requireImportedKeyMaterial(key);KmsKeySpec spec = key.getKeySpec();if (KmsKeySpec.SYMMETRIC_DEFAULT == spec || isHmac(spec)) {- throw new AwsException("UnsupportedOperationException", "GetPublicKey is not supported for symmetric keys.", 400);+ throw new AwsException("UnsupportedOperationException", null, 400);}return key;}@@ -395,6 +401,7 @@ public class KmsService implements ResourceProvider {validateGrantConstraints(constraints);KmsKey key = resolveKey(keyId, region);+ requireNotPendingDeletion(key);String grantId = UUID.randomUUID().toString();byte[] tokenBytes = new byte[32];ThreadLocalRandom.current().nextBytes(tokenBytes);@@ -587,6 +594,7 @@ public class KmsService implements ResourceProvider {public void scheduleKeyDeletion(String keyId, int pendingWindowInDays, String region) {KmsKey key = resolveKey(keyId, region);+ requireNotPendingDeletion(key);key.setKeyState("PendingDeletion");key.setDeletionDate(Instant.now().plusSeconds((long) pendingWindowInDays * 86400).getEpochSecond());keyStore.put(region + "::" + key.getKeyId(), key);@@ -651,6 +659,7 @@ public class KmsService implements ResourceProvider {public void updateKeyDescription(String keyId, String description, String region) {KmsKey key = resolveKey(keyId, region);+ requireNotPendingDeletion(key);key.setDescription(description);keyStore.put(region + "::" + key.getKeyId(), key);LOG.infov("Updated description for KMS key: {0} in {1}", key.getKeyId(), region);@@ -669,7 +678,9 @@ public class KmsService implements ResourceProvider {public void enableKeyRotation(String keyId, String region) {KmsKey key = resolveKey(keyId, region);- validateRotationSupported(key);+ validateRotationOrigin(key);+ validateKeyIsUsableForCryptoOperations(key);+ validateRotationKeySpec(key);key.setKeyRotationEnabled(true);keyStore.put(region + "::" + key.getKeyId(), key);LOG.infov("Enabled key rotation for KMS key: {0} in {1}", key.getKeyId(), region);@@ -677,7 +688,8 @@ public class KmsService implements ResourceProvider {public void disableKeyRotation(String keyId, String region) {KmsKey key = resolveKey(keyId, region);- validateRotationSupported(key);+ validateRotationOrigin(key);+ validateKeyIsUsableForCryptoOperations(key);key.setKeyRotationEnabled(false);keyStore.put(region + "::" + key.getKeyId(), key);LOG.infov("Disabled key rotation for KMS key: {0} in {1}", key.getKeyId(), region);@@ -685,11 +697,8 @@ public class KmsService implements ResourceProvider {public void enableKey(String keyId, String region) {KmsKey key = resolveKey(keyId, region);- if (PENDING_DELETION.equals(key.getKeyState())) {- throw new AwsException("KMSInvalidStateException",- "KMS key " + key.getKeyId() + " is pending deletion.", 400);- }- requireImportedKeyMaterial(key, "EnableKey");+ requireNotPendingDeletion(key);+ requireImportedKeyMaterial(key);key.setEnabled(true);key.setKeyState("Enabled");keyStore.put(region + "::" + key.getKeyId(), key);@@ -698,7 +707,8 @@ public class KmsService implements ResourceProvider {public void disableKey(String keyId, String region) {KmsKey key = resolveKey(keyId, region);- requireImportedKeyMaterial(key, "DisableKey");+ requireNotPendingDeletion(key);+ requireImportedKeyMaterial(key);key.setEnabled(false);key.setKeyState("Disabled");keyStore.put(region + "::" + key.getKeyId(), key);@@ -709,11 +719,12 @@ public class KmsService implements ResourceProvider {public String rotateKeyOnDemand(String keyId, String region) {synchronized (backingKeyMaterialLock) {KmsKey key = resolveKey(keyId, region);- if (!key.isEnabled()) {- throw new AwsException("DisabledException",- "KMS key " + key.getKeyId() + " is disabled.", 400);+ validateKeyIsUsableForCryptoOperations(key);+ validateRotationKeySpec(key);+ if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {+ throw new AwsException("KMSInvalidStateException",+ "No available key material pending rotation for the key: " + key.getArn() + ".", 400);}- validateRotationSupported(key);if (key.getOnDemandRotationCount() >= ON_DEMAND_ROTATION_LIMIT) {throw new AwsException("LimitExceededException","On-demand rotation quota for KMS key " + key.getKeyId() + " is exceeded.", 400);@@ -727,19 +738,16 @@ public class KmsService implements ResourceProvider {}}- private void validateRotationSupported(KmsKey key) {+ private static void validateRotationOrigin(KmsKey key) {if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {- throw new AwsException(- "UnsupportedOperationException",- "You cannot enable automatic rotation of imported key material.",- 400);+ throw invalidOrigin(key);}+ }++ private static void validateRotationKeySpec(KmsKey key) {if (KmsKeyUsage.ENCRYPT_DECRYPT != key.getKeyUsage()|| KmsKeySpec.SYMMETRIC_DEFAULT != key.getKeySpec()) {- throw new AwsException(- "UnsupportedOperationException",- "You cannot perform this operation on a non-symmetric key or a key with non-ENCRYPT_DECRYPT key usage.",- 400);+ throw new AwsException("UnsupportedOperationException", null, 400);}}@@ -751,7 +759,7 @@ public class KmsService implements ResourceProvider {public ImportParameters getParametersForImport(String keyId, String wrappingAlgorithm,String wrappingKeySpec, String region) {KmsKey key = resolveKey(keyId, region);- requireExternalOrigin(key, "GetParametersForImport");+ requireExternalOrigin(key);requireNotPendingDeletion(key);KmsKeyImport.validateWrappingAlgorithm(wrappingAlgorithm);@@ -777,7 +785,7 @@ public class KmsService implements ResourceProvider {public KmsKey importKeyMaterial(String keyId, String importToken, byte[] encryptedKeyMaterial,String expirationModel, Long validTo, String importType, String region) {KmsKey key = resolveKey(keyId, region);- requireExternalOrigin(key, "ImportKeyMaterial");+ requireExternalOrigin(key);requireNotPendingDeletion(key);validateImportType(importType, key);@@ -831,7 +839,7 @@ public class KmsService implements ResourceProvider {*/public KmsKey deleteImportedKeyMaterial(String keyId, String region) {KmsKey key = resolveKey(keyId, region);- requireExternalOrigin(key, "DeleteImportedKeyMaterial");+ requireExternalOrigin(key);clearImportedKeyMaterial(key);keyStore.put(region + "::" + key.getKeyId(), key);LOG.infov("Deleted imported key material for KMS key {0} in {1}", key.getKeyId(), region);@@ -1029,26 +1037,26 @@ public class KmsService implements ResourceProvider {return EXTERNAL_ORIGIN;}- private static void requireExternalOrigin(KmsKey key, String operation) {+ private static void requireExternalOrigin(KmsKey key) {if (!EXTERNAL_ORIGIN.equals(key.getOrigin())) {- throw new AwsException("UnsupportedOperationException",- operation + " is only supported for KMS keys with Origin EXTERNAL; key "- + key.getKeyId() + " has origin " + key.getOrigin() + ".", 400);+ throw invalidOrigin(key);}}+ private static AwsException invalidOrigin(KmsKey key) {+ return new AwsException("UnsupportedOperationException",+ key.getArn() + " origin is " + key.getOrigin() + " which is not valid for this operation.", 400);+ }+private static void requireNotPendingDeletion(KmsKey key) {if (PENDING_DELETION.equals(key.getKeyState())) {- throw new AwsException("KMSInvalidStateException",- "KMS key " + key.getKeyId() + " is pending deletion.", 400);+ throw new AwsException("KMSInvalidStateException", key.getArn() + " is pending deletion.", 400);}}- private static void requireImportedKeyMaterial(KmsKey key, String operation) {+ private static void requireImportedKeyMaterial(KmsKey key) {if (PENDING_IMPORT.equals(key.getKeyState())) {- throw new AwsException("KMSInvalidStateException",- operation + " is not valid for KMS key " + key.getKeyId()- + " because it has no key material. Its state is PendingImport.", 400);+ throw new AwsException("KMSInvalidStateException", key.getArn() + " is pending import.", 400);}}@@ -1059,6 +1067,7 @@ public class KmsService implements ResourceProvider {throw new AwsException("InvalidAliasNameException", "Alias name must begin with 'alias/'", 400);}KmsKey key = resolveKey(targetKeyId, region); // Validate key exists and normalize to plain key ID+ requireNotPendingDeletion(key);String aliasArn = regionResolver.buildArn("kms", region, aliasName);KmsAlias alias = new KmsAlias(aliasName, aliasArn, key.getKeyId());@@ -1069,15 +1078,12 @@ public class KmsService implements ResourceProvider {public void updateAlias(String aliasName, String targetKeyId, String region) {String storageKey = region + "::" + aliasName;KmsAlias existing = aliasStore.get(storageKey)- .orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + aliasName, 404));+ .orElseThrow(() -> aliasNotFound(aliasName, region));KmsKey currentKey = resolveKey(existing.getTargetKeyId(), region);KmsKey newKey = resolveKey(targetKeyId, region); // Validate key exists and normalize to plain key ID- if ("PendingDeletion".equals(newKey.getKeyState())) {- throw new AwsException("KMSInvalidStateException",- "KMS key " + newKey.getKeyId() + " is pending deletion.", 400);- }+ requireNotPendingDeletion(newKey);if (currentKey.getKeyUsage() != newKey.getKeyUsage() || !sameKeyFamily(currentKey.getKeySpec(), newKey.getKeySpec())) {throw new AwsException("ValidationException","The replacement KMS key must have the same key usage and key type "@@ -1093,7 +1099,7 @@ public class KmsService implements ResourceProvider {public void deleteAlias(String aliasName, String region) {String key = region + "::" + aliasName;if (aliasStore.get(key).isEmpty()) {- throw new AwsException("NotFoundException", "Alias not found", 404);+ throw aliasNotFound(aliasName, region);}aliasStore.delete(key);}@@ -1138,12 +1144,8 @@ public class KmsService implements ResourceProvider {private static final int AES_KEY_BYTES = KmsKeySpec.SYMMETRIC_DEFAULT.materialByteLength();private static final String BLOB_PREFIX_V2 = "kms:v2:";private static final String BLOB_PREFIX_V1 = "kms:";- private static final int MIN_MAC_MESSAGE_BYTES = 1;- private static final int MAX_MAC_MESSAGE_BYTES = 4096;- private static final int MIN_ENCRYPT_PLAINTEXT_BYTES = 1;- private static final int MAX_ENCRYPT_PLAINTEXT_BYTES = 4096;- private static final int MIN_MAC_BYTES = 1;- private static final int MAX_MAC_BYTES = 6144;+ static final int MAX_PLAINTEXT_BYTES = 4096;+ static final int MAX_CIPHERTEXT_BYTES = 6144;private static final SecureRandom SECURE_RANDOM = new SecureRandom();public byte[] encrypt(String keyId, byte[] plaintext, String region) {@@ -1162,11 +1164,11 @@ public class KmsService implements ResourceProvider {private EncryptResult encrypt(String keyId, byte[] plaintext, Map<String, String> encryptionContext,String encryptionAlgorithm, String region, String operation) {KmsKeySpec.Algorithm algorithm = resolveEncryptionAlgorithm(encryptionAlgorithm);- validatePlaintextLength(plaintext, operation);+ validateBlobLength("plaintext", plaintext, MAX_PLAINTEXT_BYTES);KmsKey kmsKey = resolveKey(keyId, region);+ validateKeyUsage(kmsKey, KmsKeyUsage.ENCRYPT_DECRYPT, operation);validateKeyIsUsableForCryptoOperations(kmsKey);- validateKeyUsageForEncryptionOperation(kmsKey, operation);- validateEncryptionAlgorithmForSpec(algorithm, kmsKey.getKeySpec());+ validateAlgorithmForSpec(algorithm, kmsKey.getKeySpec());if (algorithm != KmsKeySpec.Algorithm.SYMMETRIC_DEFAULT) {rejectEncryptionContextForAsymmetricKey(encryptionContext);@@ -1190,7 +1192,7 @@ public class KmsService implements ResourceProvider {}ParsedBlob parsed = parseBlob(ciphertext);if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}return decodePayload(parsed);}@@ -1231,9 +1233,9 @@ public class KmsService implements ResourceProvider {throw new AwsException("ValidationException", "KeyId must not be null", 400);}KmsKey requestKey = resolveKey(requestKeyId, region);+ validateKeyUsage(requestKey, KmsKeyUsage.ENCRYPT_DECRYPT, "Decrypt");validateKeyIsUsableForCryptoOperations(requestKey);- validateKeyUsageForEncryptionOperation(requestKey, "Decrypt");- validateEncryptionAlgorithmForSpec(algorithm, requestKey.getKeySpec());+ validateAlgorithmForSpec(algorithm, requestKey.getKeySpec());rejectEncryptionContextForAsymmetricKey(encryptionContext);byte[] plaintext = keyTypes.of(requestKey.getKeySpec()).decrypt(requestKey, algorithm, ciphertext);return new DecryptResult(plaintext, requestKey.getArn(), algorithm.getAlgName());@@ -1244,7 +1246,7 @@ public class KmsService implements ResourceProvider {KmsKey key = resolveEnvelopeKey(envelope.keyId(), region);// A key whose imported material was deleted or expired no longer holds the backing// key this blob names; answer with the key's state, as AWS does, not "invalid ciphertext".- requireImportedKeyMaterial(key, "Decrypt");+ requireImportedKeyMaterial(key);byte[] plaintext = decryptEnvelopeV3(envelope, key, encryptionContext);if (requestKeyId != null && !requestKeyId.isBlank()) {@@ -1252,7 +1254,7 @@ public class KmsService implements ResourceProvider {if (!requestKey.getKeyId().equals(key.getKeyId())) {throw new AwsException("IncorrectKeyException",- "The request was rejected because the specified KMS key cannot decrypt the data.",+ "The key ID in the request does not identify a CMK that can perform this operation.",400);}@@ -1270,7 +1272,7 @@ public class KmsService implements ResourceProvider {// InvalidCiphertextException, not InvalidKeyUsageException (measured in us-east-1).ParsedBlob parsed = parseBlob(ciphertext);if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}byte[] plaintext = decodePayload(parsed);@@ -1279,7 +1281,7 @@ public class KmsService implements ResourceProvider {if (!requestKey.getKeyId().equals(parsed.keyId)) {throw new AwsException("IncorrectKeyException",- "The request was rejected because the specified KMS key cannot decrypt the data.",+ "The key ID in the request does not identify a CMK that can perform this operation.",400);}@@ -1337,7 +1339,7 @@ public class KmsService implements ResourceProvider {buffer.get(magic);byte version = buffer.get();if (version != ENVELOPE_VERSION_V3) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}byte[] keyIdBytes = new byte[buffer.getShort() & 0xFFFF];buffer.get(keyIdBytes);@@ -1349,7 +1351,7 @@ public class KmsService implements ResourceProvider {byte[] ciphertextAndTag = new byte[buffer.remaining()];buffer.get(ciphertextAndTag);if (ciphertextAndTag.length == 0) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}byte[] aadHeader = Arrays.copyOfRange(blob, 0, headerLength + GCM_IV_BYTES);return new EnvelopeV3(new String(keyIdBytes, StandardCharsets.UTF_8),@@ -1357,7 +1359,7 @@ public class KmsService implements ResourceProvider {} catch (AwsException e) {throw e;} catch (RuntimeException e) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}}@@ -1418,7 +1420,7 @@ public class KmsService implements ResourceProvider {try {return resolveKey(keyId, region);} catch (AwsException e) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}}@@ -1434,7 +1436,7 @@ public class KmsService implements ResourceProvider {materialB64 = key.getBackingKeys() == null ? null : key.getBackingKeys().get(envelope.backingKeyId());}if (materialB64 == null) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}byte[] dek = decodeBackingMaterial(materialB64);try {@@ -1442,7 +1444,7 @@ public class KmsService implements ResourceProvider {envelope.aadHeader(), contextFingerprint(encryptionContext).getBytes(StandardCharsets.UTF_8));return cipher.doFinal(envelope.ciphertextAndTag());} catch (GeneralSecurityException e) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}}@@ -1464,7 +1466,7 @@ public class KmsService implements ResourceProvider {}return material;} catch (IllegalArgumentException e) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}}@@ -1476,7 +1478,7 @@ public class KmsService implements ResourceProvider {// v2: keyId, nonce, contextFingerprint, payloadString[] parts = data.substring(BLOB_PREFIX_V2.length()).split(":", 4);if (parts.length < 4) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}return new ParsedBlob(parts[0], parts[1], parts[2], parts[3]);}@@ -1488,7 +1490,7 @@ public class KmsService implements ResourceProvider {return new ParsedBlob(parts[0], "", "", parts[1]);}}- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}/** A blob whose payload is not valid base64 is a bad ciphertext, not a server fault. */@@ -1496,7 +1498,7 @@ public class KmsService implements ResourceProvider {try {return Base64.getDecoder().decode(parsed.payload);} catch (IllegalArgumentException e) {- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}}@@ -1528,7 +1530,7 @@ public class KmsService implements ResourceProvider {/*** Resolves the wire EncryptionAlgorithm value. Real KMS models the enum as- * [RSAES_OAEP_SHA_256, RSAES_OAEP_SHA_1, SYMMETRIC_DEFAULT, SM2PKE]. A null or blank+ * [RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256, SM2PKE, SYMMETRIC_DEFAULT]. A null or blank* value falls back to the SYMMETRIC_DEFAULT default.*/private static KmsKeySpec.Algorithm resolveEncryptionAlgorithm(String encryptionAlgorithm) {@@ -1543,30 +1545,34 @@ public class KmsService implements ResourceProvider {default -> throw new AwsException("ValidationException","1 validation error detected: Value '" + name + "' at 'encryptionAlgorithm' failed to satisfy "+ "constraint: Member must satisfy enum value set: "- + "[RSAES_OAEP_SHA_256, RSAES_OAEP_SHA_1, SYMMETRIC_DEFAULT, SM2PKE]", 400);+ + "[RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256, SM2PKE, SYMMETRIC_DEFAULT]", 400);};}- private static void validateKeyUsageForEncryptionOperation(KmsKey key, String operation) {- if (KmsKeyUsage.ENCRYPT_DECRYPT != key.getKeyUsage()) {+ private static void validateKeyUsage(KmsKey key, KmsKeyUsage keyUsage, String operation) {+ if (keyUsage != key.getKeyUsage()) {throw new AwsException("InvalidKeyUsageException",key.getArn() + " key usage is " + key.getKeyUsage() + " which is not valid for "+ operation + ".", 400);}}- private static void validateEncryptionAlgorithmForSpec(KmsKeySpec.Algorithm algorithm, KmsKeySpec spec) {+ private static void validateAlgorithmForSpec(KmsKeySpec.Algorithm algorithm, KmsKeySpec spec) {if (!spec.getAlgorithm().contains(algorithm)) {throw new AwsException("InvalidKeyUsageException","Algorithm " + algorithm.getAlgName() + " is incompatible with key spec " + spec.name() + ".", 400);}}- private static void validatePlaintextLength(byte[] plaintext, String operation) {- int length = plaintext == null ? 0 : plaintext.length;- if (length < MIN_ENCRYPT_PLAINTEXT_BYTES || length > MAX_ENCRYPT_PLAINTEXT_BYTES) {- throw new AwsException("ValidationException",- "Plaintext must be between 1 and 4096 bytes for " + operation + ".", 400);+ static void validateBlobLength(String member, byte[] value, int max) {+ int length = value == null ? 0 : value.length;+ if (length < 1) {+ throw new AwsException("ValidationException", "1 validation error detected: Value at '" + member+ + "' failed to satisfy constraint: Member must have length greater than or equal to 1", 400);+ }+ if (max < length) {+ throw new AwsException("ValidationException", "1 validation error detected: Value at '" + member+ + "' failed to satisfy constraint: Member must have length less than or equal to " + max, 400);}}@@ -1577,14 +1583,40 @@ public class KmsService implements ResourceProvider {}}+ private static final List<String> SIGNING_ALGORITHMS = List.of(+ "RSASSA_PSS_SHA_256", "RSASSA_PSS_SHA_384", "RSASSA_PSS_SHA_512",+ "RSASSA_PKCS1_V1_5_SHA_256", "RSASSA_PKCS1_V1_5_SHA_384", "RSASSA_PKCS1_V1_5_SHA_512",+ "ECDSA_SHA_256", "ECDSA_SHA_384", "ECDSA_SHA_512", "ED25519_SHA_512", "ED25519_PH_SHA_512",+ "SM2DSA", "ML_DSA_SHAKE_256");++ private static final List<String> MAC_ALGORITHMS =+ List.of("HMAC_SHA_384", "HMAC_SHA_256", "HMAC_SHA_224", "HMAC_SHA_512");++ private static final Map<KmsKeySpec.Algorithm, Integer> DIGEST_BYTES = Map.of(+ KmsKeySpec.Algorithm.RSASSA_PSS_SHA_256, 32,+ KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_256, 32,+ KmsKeySpec.Algorithm.ECDSA_SHA_256, 32,+ KmsKeySpec.Algorithm.RSASSA_PSS_SHA_384, 48,+ KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_384, 48,+ KmsKeySpec.Algorithm.ECDSA_SHA_384, 48,+ KmsKeySpec.Algorithm.RSASSA_PSS_SHA_512, 64,+ KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_512, 64,+ KmsKeySpec.Algorithm.ECDSA_SHA_512, 64,+ KmsKeySpec.Algorithm.ED25519_PH_SHA_512, 64);+public byte[] sign(String keyId, byte[] message, String algorithm, String region) {return sign(keyId, message, algorithm, RAW, region);}public byte[] sign(String keyId, byte[] message, String algorithm, KmsMessageType messageType, String region) {+ KmsKeySpec.Algorithm signingAlgorithm = resolveSigningAlgorithm(algorithm);KmsKey kmsKey = resolveKey(keyId, region);+ validateKeyUsage(kmsKey, KmsKeyUsage.SIGN_VERIFY, "Sign");+ validateKeyIsUsableForCryptoOperations(kmsKey);+ validateAlgorithmForSpec(signingAlgorithm, kmsKey.getKeySpec());+ validateDigestLength(signingAlgorithm, messageType, message);try {- return keyTypes.of(kmsKey.getKeySpec()).sign(kmsKey, message, algorithm, messageType);+ return keyTypes.of(kmsKey.getKeySpec()).sign(kmsKey, message, signingAlgorithm, messageType);} catch (AwsException e) {throw e;} catch (Exception e) {@@ -1592,34 +1624,72 @@ public class KmsService implements ResourceProvider {}}- public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, String region) {- return verify(keyId, message, signature, algorithm, RAW, region);+ private static void validateDigestLength(KmsKeySpec.Algorithm algorithm, KmsMessageType messageType,+ byte[] message) {+ Integer expected = DIGEST_BYTES.get(algorithm);+ if (messageType == KmsMessageType.DIGEST && expected != null && expected != message.length) {+ throw new AwsException("ValidationException",+ "Digest is invalid length for algorithm " + algorithm.getAlgName() + ".", 400);+ }+ }++ private static KmsKeySpec.Algorithm resolveSigningAlgorithm(String algorithm) {+ if (!"SYMMETRIC_DEFAULT".equals(algorithm)) {+ validateEnumMember("signingAlgorithm", algorithm, SIGNING_ALGORITHMS);+ }+ return KmsKeySpec.Algorithm.valueOf(algorithm);+ }++ private static void validateEnumMember(String member, String value, List<String> allowed) {+ if (value == null) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value null at '" + member + "' failed to satisfy "+ + "constraint: Member must not be null", 400);+ }+ if (!allowed.contains(value)) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + value + "' at '" + member + "' failed to "+ + "satisfy constraint: Member must satisfy enum value set: ["+ + String.join(", ", allowed) + "]", 400);+ }+ }++ public void verify(String keyId, byte[] message, byte[] signature, String algorithm, String region) {+ verify(keyId, message, signature, algorithm, RAW, region);}- public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, KmsMessageType messageType, String region) {+ public void verify(String keyId, byte[] message, byte[] signature, String algorithm, KmsMessageType messageType, String region) {+ KmsKeySpec.Algorithm signingAlgorithm = resolveSigningAlgorithm(algorithm);KmsKey kmsKey = resolveKey(keyId, region);+ validateKeyUsage(kmsKey, KmsKeyUsage.SIGN_VERIFY, "Verify");+ validateKeyIsUsableForCryptoOperations(kmsKey);+ validateAlgorithmForSpec(signingAlgorithm, kmsKey.getKeySpec());+ validateDigestLength(signingAlgorithm, messageType, message);+ boolean valid;try {- return keyTypes.of(kmsKey.getKeySpec()).verify(kmsKey, message, signature, algorithm, messageType);+ valid = keyTypes.of(kmsKey.getKeySpec()).verify(kmsKey, message, signature, signingAlgorithm, messageType);} catch (AwsException e) {throw e;} catch (Exception e) {- LOG.warnv("Verification failed for key {0}: {1}", keyId, e.getMessage());- return false;+ throw new AwsException("InternalFailure", "Failed to verify signature: " + e.getMessage(), 500);+ }+ if (!valid) {+ throw new AwsException("KMSInvalidSignatureException", null, 400);}}public byte[] generateMac(String keyId, byte[] message, String algorithm, String region) {- KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);+ KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "GenerateMac", region);return generateMac(kmsKey, message, algorithm);}public GenerateMacResult generateMacAndResolveKey(String keyId, byte[] message, String algorithm, String region) {- KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);+ KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "GenerateMac", region);return new GenerateMacResult(generateMac(kmsKey, message, algorithm), kmsKey.getArn());}private byte[] generateMac(KmsKey kmsKey, byte[] message, String algorithm) {- validateMacMessageLength(message);+ validateBlobLength("message", message, MAX_PLAINTEXT_BYTES);try {return keyTypes.of(kmsKey.getKeySpec()).generateMac(kmsKey, message, algorithm);@@ -1631,14 +1701,14 @@ public class KmsService implements ResourceProvider {}public void verifyMac(String keyId, byte[] message, byte[] mac, String algorithm, String region) {- validateMacLength(mac);- KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);+ validateBlobLength("mac", mac, MAX_CIPHERTEXT_BYTES);+ KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "VerifyMac", region);verifyMac(kmsKey, message, mac, algorithm);}public VerifyMacResult verifyMacAndResolveKey(String keyId, byte[] message, byte[] mac, String algorithm, String region) {- validateMacLength(mac);- KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);+ validateBlobLength("mac", mac, MAX_CIPHERTEXT_BYTES);+ KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "VerifyMac", region);verifyMac(kmsKey, message, mac, algorithm);return new VerifyMacResult(kmsKey.getArn());}@@ -1646,56 +1716,55 @@ public class KmsService implements ResourceProvider {private void verifyMac(KmsKey kmsKey, byte[] message, byte[] mac, String algorithm) {byte[] expected = generateMac(kmsKey, message, algorithm);if (!MessageDigest.isEqual(expected, mac)) {- throw new AwsException("KMSInvalidMacException", "The MAC is not valid.", 400);+ throw new AwsException("KMSInvalidMacException", null, 400);}}- private KmsKey validateMacOperationKey(String keyId, String algorithm, String region) {+ private KmsKey validateMacOperationKey(String keyId, String algorithm, String operation, String region) {+ validateEnumMember("macAlgorithm", algorithm, MAC_ALGORITHMS);KmsKey kmsKey = resolveKey(keyId, region);- requireImportedKeyMaterial(kmsKey, "MAC operations");- KmsKeySpec spec = kmsKey.getKeySpec();- if (!isHmac(spec) || !KmsKeyUsage.GENERATE_VERIFY_MAC.equals(kmsKey.getKeyUsage())) {- throw new AwsException("InvalidKeyUsageException",- "MAC operations require an HMAC key with KeyUsage GENERATE_VERIFY_MAC.", 400);- }-- String expectedAlgorithm = kmsKey.getKeySpec().getAlgorithm().getFirst().getAlgName();- if (!Objects.equals(expectedAlgorithm, algorithm)) {- throw new AwsException("InvalidKeyUsageException",- "MacAlgorithm " + algorithm + " is not valid for KeySpec " + spec + ".", 400);- }+ validateKeyUsage(kmsKey, KmsKeyUsage.GENERATE_VERIFY_MAC, operation);+ validateKeyIsUsableForCryptoOperations(kmsKey);+ validateAlgorithmForSpec(KmsKeySpec.Algorithm.valueOf(algorithm), kmsKey.getKeySpec());return kmsKey;}- private static void validateMacMessageLength(byte[] message) {- int length = message == null ? 0 : message.length;- if (length < MIN_MAC_MESSAGE_BYTES || length > MAX_MAC_MESSAGE_BYTES) {- throw new AwsException("ValidationException",- "Message must be between 1 and 4096 bytes for MAC operations.", 400);- }++ public Map<String, Object> generateDataKey(String keyId, String keySpec, Integer numberOfBytes, String region) {+ return generateDataKey(keyId, keySpec, numberOfBytes, Map.of(), region);}- private static void validateMacLength(byte[] mac) {- int length = mac == null ? 0 : mac.length;- if (length < MIN_MAC_BYTES || length > MAX_MAC_BYTES) {- throw new AwsException("ValidationException",- "Mac must be between 1 and 6144 bytes for VerifyMac.", 400);- }+ public Map<String, Object> generateDataKey(String keyId, String keySpec, Integer numberOfBytes,+ Map<String, String> encryptionContext, String region) {+ return generateDataKey(keyId, keySpec, numberOfBytes, encryptionContext, region, "GenerateDataKey");}- public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes, String region) {- return generateDataKey(keyId, keySpec, numberOfBytes, Map.of(), region);+ Map<String, Object> generateDataKeyWithoutPlaintext(String keyId, String keySpec, Integer numberOfBytes,+ Map<String, String> encryptionContext, String region) {+ Map<String, Object> dataKey = generateDataKey(keyId, keySpec, numberOfBytes, encryptionContext, region,+ "GenerateDataKeyWithoutPlaintext");+ dataKey.remove("Plaintext");+ return dataKey;}- public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes,- Map<String, String> encryptionContext, String region) {- resolveKey(keyId, region);- int len = (keySpec != null && keySpec.contains("256")) ? 32 : (numberOfBytes > 0 ? numberOfBytes : 32);+ private Map<String, Object> generateDataKey(String keyId, String keySpec, Integer numberOfBytes,+ Map<String, String> encryptionContext, String region,+ String operation) {+ KmsKey key = resolveKey(keyId, region);+ if ((keySpec == null) == (numberOfBytes == null)) {+ throw new AwsException("ValidationException", "Please specify either number of bytes or key spec.", 400);+ }+ validateKeyUsage(key, KmsKeyUsage.ENCRYPT_DECRYPT, operation);+ validateKeyIsUsableForCryptoOperations(key);+ if (KmsKeySpec.SYMMETRIC_DEFAULT != key.getKeySpec()) {+ throw new AwsException("InvalidKeyUsageException", "You cannot generate a data key with an asymmetric CMK", 400);+ }+ int len = keySpec == null ? numberOfBytes : "AES_128".equals(keySpec) ? 16 : 32;byte[] plaintext = new byte[len];ThreadLocalRandom.current().nextBytes(plaintext);- EncryptResult encrypted = encrypt(keyId, plaintext, encryptionContext, null, region, "GenerateDataKey");+ EncryptResult encrypted = encrypt(keyId, plaintext, encryptionContext, null, region, operation);Map<String, Object> result = new HashMap<>();result.put("Plaintext", plaintext);@@ -1708,6 +1777,7 @@ public class KmsService implements ResourceProvider {public void tagResource(String keyId, Map<String, String> tags, String region) {KmsKey key = resolveKey(keyId, region);+ requireNotPendingDeletion(key);ReservedTags.rejectReservedTagsOnUpdate(tags);key.getTags().putAll(tags);keyStore.put(region + "::" + key.getKeyId(), key);@@ -1715,6 +1785,7 @@ public class KmsService implements ResourceProvider {public void untagResource(String keyId, List<String> tagKeys, String region) {KmsKey key = resolveKey(keyId, region);+ requireNotPendingDeletion(key);tagKeys.forEach(key.getTags()::remove);keyStore.put(region + "::" + key.getKeyId(), key);}@@ -1722,6 +1793,12 @@ public class KmsService implements ResourceProvider {// ──────────────────────────── Helpers ────────────────────────────private KmsKey resolveKey(String keyIdOrArn, String region) {+ if (AwsArnUtils.isArnFor(keyIdOrArn, "kms")) {+ String arnRegion = AwsArnUtils.parse(keyIdOrArn).region();+ if (!region.equals(arnRegion)) {+ throw new AwsException("NotFoundException", "Invalid arn " + arnRegion, 400);+ }+ }String id = keyIdOrArn;// Alias arnif (id.contains(":alias/")) {@@ -1729,7 +1806,7 @@ public class KmsService implements ResourceProvider {String aliasKey = region + "::" + aliasName;id = aliasStore.get(aliasKey).map(KmsAlias::getTargetKeyId)- .orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + keyIdOrArn, 404));+ .orElseThrow(() -> aliasNotFound(aliasName, region));} else if (AwsArnUtils.isArnFor(id, "kms")) {// Key arnid = id.substring(id.lastIndexOf("/") + 1);@@ -1738,30 +1815,48 @@ public class KmsService implements ResourceProvider {String aliasKey = region + "::" + id;id = aliasStore.get(aliasKey).map(KmsAlias::getTargetKeyId)- .orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + keyIdOrArn, 404));+ .orElseThrow(() -> aliasNotFound(keyIdOrArn, region));}// Key id+ String keyId = id;KmsKey key = keyStore.get(region + "::" + id)- .orElseThrow(() -> new AwsException("NotFoundException", "Key not found: " + keyIdOrArn, 404));+ .orElseThrow(() -> keyNotFound(keyIdOrArn, keyId, region));key = expireImportedKeyMaterialIfDue(key, region);key = ensureBackingKeyMaterial(key, region);return key;}+ private AwsException aliasNotFound(String aliasName, String region) {+ return new AwsException("NotFoundException",+ "Alias " + regionResolver.buildArn("kms", region, aliasName) + " is not found.", 400);+ }++ private static final Pattern KEY_ID_PATTERN = Pattern.compile(+ "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|mrk-[0-9a-fA-F]{32}");++ private AwsException keyNotFound(String keyIdOrArn, String keyId, String region) {+ if (!KEY_ID_PATTERN.matcher(keyId).matches()) {+ String shown = AwsArnUtils.isArnFor(keyIdOrArn, "kms") ? keyId : "'" + keyId + "'";+ return new AwsException("NotFoundException", "Invalid keyId " + shown, 400);+ }+ return new AwsException("NotFoundException",+ "Key '" + regionResolver.buildArn("kms", region, "key/" + keyId) + "' does not exist", 400);+ }+private static void validateKeyIsUsableForCryptoOperations(KmsKey key) {if (PENDING_DELETION.equals(key.getKeyState())) {throw new AwsException("KMSInvalidStateException",- "KMS key " + key.getKeyId() + " is pending deletion.",+ key.getArn() + " is pending deletion.",400);}- requireImportedKeyMaterial(key, "This operation");+ requireImportedKeyMaterial(key);if (!key.isEnabled()) {throw new AwsException("DisabledException",- "The request was rejected because the specified KMS key is not enabled.",+ key.getArn() + " is disabled.",400);}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/AsymmetricKeys.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/AsymmetricKeys.javaindex ebbfb16aff..e828df3b6d 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/AsymmetricKeys.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/AsymmetricKeys.java@@ -13,6 +13,7 @@ import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;import java.security.PublicKey;import java.security.Signature;+import java.security.SignatureException;import java.security.spec.MGF1ParameterSpec;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.PSSParameterSpec;@@ -24,15 +25,6 @@ final class AsymmetricKeys {private AsymmetricKeys() {}- static KmsKeySpec.Algorithm requireSpecAlgorithm(KmsKeySpec spec, String algorithm) {- KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);- if (!spec.getAlgorithm().contains(signingAlgorithm)) {- throw new AwsException("InvalidKeyUsageException",- "Algorithm " + algorithm + " is incompatible with key spec " + spec.name() + ".", 400);- }- return signingAlgorithm;- }-static void requireRawMessage(KmsKeySpec spec, KmsMessageType messageType) {if (messageType != KmsMessageType.RAW) {throw new AwsException("ValidationException",@@ -67,7 +59,11 @@ final class AsymmetricKeys {Signature verifier = signatureFor(jcaAlgorithm);verifier.initVerify(publicKey);verifier.update(message);- return verifier.verify(signature);+ try {+ return verifier.verify(signature);+ } catch (SignatureException e) {+ return false;+ }}// KMS RSASSA_PSS uses MGF1 over the same digest, with a salt as long as the digest.diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccNistKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccNistKeyType.javaindex 5f96689cac..6fe9907ac2 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccNistKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccNistKeyType.java@@ -20,26 +20,23 @@ final class EccNistKeyType implements KmsKeyType {}@Override- public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)+ public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)throws GeneralSecurityException {PrivateKey privateKey = AsymmetricKeys.privateKey(key, "EC");- String jcaAlgorithm = switch (messageType) {- case DIGEST -> "NONEwithECDSA";- case RAW -> KmsKeySpec.getSignVerifyAlgorithm(algorithm).getJavaName();- };- return AsymmetricKeys.sign(privateKey, jcaAlgorithm, message);+ return AsymmetricKeys.sign(privateKey, jcaAlgorithm(algorithm, messageType), message);}@Override- public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,+ public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,KmsMessageType messageType) throws GeneralSecurityException {PublicKey publicKey = AsymmetricKeys.publicKey(key, "EC");- // An unknown algorithm name fails even for DIGEST.- KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);- String jcaAlgorithm = switch (messageType) {+ return AsymmetricKeys.verify(publicKey, jcaAlgorithm(algorithm, messageType), message, signature);+ }++ private static String jcaAlgorithm(KmsKeySpec.Algorithm algorithm, KmsMessageType messageType) {+ return switch (messageType) {case DIGEST -> "NONEwithECDSA";- case RAW -> signingAlgorithm.getJavaName();+ case RAW -> algorithm.getJavaName();};- return AsymmetricKeys.verify(publicKey, jcaAlgorithm, message, signature);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccSecgP256k1KeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccSecgP256k1KeyType.javaindex 212c192b3b..d42fbaa1c8 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccSecgP256k1KeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/EccSecgP256k1KeyType.java@@ -1,11 +1,9 @@package io.github.hectorvent.floci.services.kms.keytype;-import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.kms.model.KmsKey;import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;import io.github.hectorvent.floci.services.kms.model.KmsMessageType;import org.bouncycastle.asn1.ASN1Integer;-import org.bouncycastle.asn1.ASN1Primitive;import org.bouncycastle.asn1.ASN1Sequence;import org.bouncycastle.asn1.DERSequenceGenerator;import org.bouncycastle.crypto.params.ECPrivateKeyParameters;@@ -36,13 +34,10 @@ final class EccSecgP256k1KeyType implements KmsKeyType {}@Override- public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)+ public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)throws GeneralSecurityException, IOException {ECPrivateKeyParameters privateKey = BcEcKeys.privateKeyParameters(key, CURVE);- byte[] hash = switch (messageType) {- case DIGEST -> message;- case RAW -> hashForEcdsa(message, KmsKeySpec.getSignVerifyAlgorithm(algorithm));- };+ byte[] hash = hash(message, algorithm, messageType);ECDSASigner signer = new ECDSASigner();signer.init(true, new ParametersWithRandom(privateKey, random));@@ -57,33 +52,39 @@ final class EccSecgP256k1KeyType implements KmsKeyType {}@Override- public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,+ public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,KmsMessageType messageType) throws GeneralSecurityException, IOException {ECPublicKeyParameters publicKey = BcEcKeys.publicKeyParameters(key, CURVE);- // An unknown algorithm name fails even for DIGEST.- KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);- byte[] hash = switch (messageType) {- case DIGEST -> message;- case RAW -> hashForEcdsa(message, signingAlgorithm);- };+ byte[] hash = hash(message, algorithm, messageType);- ASN1Sequence asn1 = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(signature));- BigInteger r = ASN1Integer.getInstance(asn1.getObjectAt(0)).getValue();- BigInteger s = ASN1Integer.getInstance(asn1.getObjectAt(1)).getValue();+ BigInteger r;+ BigInteger s;+ try {+ ASN1Sequence asn1 = ASN1Sequence.getInstance(signature);+ if (asn1.size() != 2) {+ return false;+ }+ r = ASN1Integer.getInstance(asn1.getObjectAt(0)).getValue();+ s = ASN1Integer.getInstance(asn1.getObjectAt(1)).getValue();+ } catch (IllegalArgumentException e) {+ return false;+ }ECDSASigner verifier = new ECDSASigner();verifier.init(false, publicKey);return verifier.verifySignature(hash, r, s);}- private static byte[] hashForEcdsa(byte[] message, KmsKeySpec.Algorithm algorithm)+ private static byte[] hash(byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)throws GeneralSecurityException {+ if (messageType == KmsMessageType.DIGEST) {+ return message;+ }String digest = switch (algorithm) {case ECDSA_SHA_256 -> "SHA-256";case ECDSA_SHA_384 -> "SHA-384";case ECDSA_SHA_512 -> "SHA-512";- default -> throw new AwsException("InvalidSigningAlgorithmException",- "Unsupported EC algorithm: " + algorithm.getJavaName(), 400);+ default -> throw new IllegalStateException("Not an ECDSA algorithm: " + algorithm);};return MessageDigest.getInstance(digest).digest(message);}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Ed25519KeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Ed25519KeyType.javaindex 19678d28bf..0a126705bb 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Ed25519KeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Ed25519KeyType.java@@ -19,8 +19,6 @@ import java.security.interfaces.EdECPrivateKey;final class Ed25519KeyType implements KmsKeyType {- private static final int SHA_512_DIGEST_BYTES = 64;-@Overridepublic void generateKeyMaterial(KmsKey key, String region) throws GeneralSecurityException {AsymmetricKeys.store(key, KeyPairGenerator.getInstance("Ed25519").generateKeyPair());@@ -28,11 +26,11 @@ final class Ed25519KeyType implements KmsKeyType {// KMS runs Ed25519ph over the digest the caller sends, so the digest is hashed again.@Override- public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)+ public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)throws GeneralSecurityException, CryptoException {- KmsKeySpec.Algorithm signingAlgorithm = validateRequest(key.getKeySpec(), algorithm, messageType, message);+ validateMessageType(algorithm, messageType);PrivateKey privateKey = AsymmetricKeys.privateKey(key, "Ed25519");- if (signingAlgorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {+ if (algorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {return AsymmetricKeys.sign(privateKey, "Ed25519", message);}Ed25519phSigner signer = new Ed25519phSigner(new byte[0]);@@ -42,11 +40,11 @@ final class Ed25519KeyType implements KmsKeyType {}@Override- public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,+ public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,KmsMessageType messageType) throws GeneralSecurityException {- KmsKeySpec.Algorithm signingAlgorithm = validateRequest(key.getKeySpec(), algorithm, messageType, message);+ validateMessageType(algorithm, messageType);PublicKey publicKey = AsymmetricKeys.publicKey(key, "Ed25519");- if (signingAlgorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {+ if (algorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {return AsymmetricKeys.verify(publicKey, "Ed25519", message, signature);}Ed25519phSigner verifier = new Ed25519phSigner(new byte[0]);@@ -55,19 +53,13 @@ final class Ed25519KeyType implements KmsKeyType {return verifier.verifySignature(signature);}- private static KmsKeySpec.Algorithm validateRequest(KmsKeySpec spec, String algorithm,- KmsMessageType messageType, byte[] message) {- KmsKeySpec.Algorithm algo = AsymmetricKeys.requireSpecAlgorithm(spec, algorithm);- KmsMessageType required = algo == KmsKeySpec.Algorithm.ED25519_SHA_512 ? KmsMessageType.RAW : KmsMessageType.DIGEST;+ private static void validateMessageType(KmsKeySpec.Algorithm algorithm, KmsMessageType messageType) {+ KmsMessageType required = algorithm == KmsKeySpec.Algorithm.ED25519_SHA_512+ ? KmsMessageType.RAW : KmsMessageType.DIGEST;if (messageType != required) {throw new AwsException("ValidationException",- "Message type " + messageType + " is incompatible with algorithm " + algorithm + ".", 400);- }- if (algo == KmsKeySpec.Algorithm.ED25519_PH_SHA_512 && message.length != SHA_512_DIGEST_BYTES) {- throw new AwsException("ValidationException",- "Digest is invalid length for algorithm " + algorithm + ".", 400);+ "Message type " + messageType + " is incompatible with algorithm " + algorithm.getAlgName() + ".", 400);}- return algo;}private static byte[] seed(PrivateKey privateKey) throws InvalidKeyException {diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.javaindex bab9c85c7e..77c321e069 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.java@@ -1,6 +1,5 @@package io.github.hectorvent.floci.services.kms.keytype;-import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.kms.model.KmsKey;import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;import io.github.hectorvent.floci.services.kms.model.KmsMessageType;@@ -11,14 +10,14 @@ public interface KmsKeyType {void generateKeyMaterial(KmsKey key, String region) throws GeneralSecurityException;- default byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)+ default byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)throws Exception {- throw new AwsException("UnsupportedOperationException", "Unsupported key spec for signing.", 400);+ throw new IllegalStateException(key.getKeySpec() + " does not sign");}- default boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,+ default boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,KmsMessageType messageType) throws Exception {- return false;+ throw new IllegalStateException(key.getKeySpec() + " does not verify");}default byte[] encrypt(KmsKey key, KmsKeySpec.Algorithm algorithm, byte[] plaintext) {diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/MlDsaKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/MlDsaKeyType.javaindex a5c3da45fa..9358b55ba6 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/MlDsaKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/MlDsaKeyType.java@@ -11,8 +11,6 @@ import java.security.PublicKey;final class MlDsaKeyType implements KmsKeyType {- private static final String JCA_ALGORITHM = KmsKeySpec.Algorithm.ML_DSA_SHAKE_256.getJavaName();-@Overridepublic void generateKeyMaterial(KmsKey key, String region) throws GeneralSecurityException {String algorithm = key.getKeySpec().name().replace('_', '-');@@ -20,20 +18,18 @@ final class MlDsaKeyType implements KmsKeyType {}@Override- public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)+ public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)throws GeneralSecurityException {- AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);PrivateKey privateKey = AsymmetricKeys.privateKey(key, "ML-DSA");- return AsymmetricKeys.sign(privateKey, JCA_ALGORITHM, message);+ return AsymmetricKeys.sign(privateKey, algorithm.getJavaName(), message);}@Override- public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,+ public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,KmsMessageType messageType) throws GeneralSecurityException {- AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);PublicKey publicKey = AsymmetricKeys.publicKey(key, "ML-DSA");- return AsymmetricKeys.verify(publicKey, JCA_ALGORITHM, message, signature);+ return AsymmetricKeys.verify(publicKey, algorithm.getJavaName(), message, signature);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.javaindex 938925ef6c..53e971880a 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.java@@ -31,7 +31,7 @@ import java.security.PublicKey;import java.security.SecureRandom;import java.security.spec.MGF1ParameterSpec;-import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.DIGEST;+import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;final class RsaKeyType implements KmsKeyType {@@ -51,34 +51,29 @@ final class RsaKeyType implements KmsKeyType {}@Override- public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType) throws Exception {+ public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)+ throws Exception {PrivateKey privateKey = AsymmetricKeys.privateKey(key, "RSA");- if (messageType == DIGEST) {- if (isPss(algorithm)) {- return signPssDigest(privateKey, message, algorithm);- }- // RFC 8017 9.2: PKCS#1 v1.5 signs DigestInfo{hashOID, digest}, not the- // bare digest, so the signature validates with external verifiers and- // real KMS (NONEwithRSA only pads the bytes it is given).- return AsymmetricKeys.sign(privateKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm));+ if (messageType == RAW) {+ return AsymmetricKeys.sign(privateKey, algorithm.getJavaName(), message);+ }+ if (isPss(algorithm)) {+ return signPssDigest(privateKey, message, algorithm);}- return AsymmetricKeys.sign(privateKey, KmsKeySpec.getSignVerifyAlgorithm(algorithm).getJavaName(), message);+ return AsymmetricKeys.sign(privateKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm));}@Override- public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,+ public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,KmsMessageType messageType) throws Exception {PublicKey publicKey = AsymmetricKeys.publicKey(key, "RSA");- // An unknown algorithm name fails even for DIGEST.- KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);- if (messageType == DIGEST) {- if (isPss(algorithm)) {- return verifyPssDigest(publicKey, message, signature, algorithm);- }- // Mirror sign(): verify against DigestInfo{hashOID, digest} (RFC 8017 9.2).- return AsymmetricKeys.verify(publicKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm), signature);+ if (messageType == RAW) {+ return AsymmetricKeys.verify(publicKey, algorithm.getJavaName(), message, signature);+ }+ if (isPss(algorithm)) {+ return verifyPssDigest(publicKey, message, signature, algorithm);}- return AsymmetricKeys.verify(publicKey, signingAlgorithm.getJavaName(), message, signature);+ return AsymmetricKeys.verify(publicKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm), signature);}@Override@@ -96,7 +91,6 @@ final class RsaKeyType implements KmsKeyType {return Integer.parseInt(spec.name().substring("RSA_".length()));}- /** RFC 8017 7.1.1: OAEP holds at most k - 2*hLen - 2 bytes, k being the modulus length. */private static void validatePlaintextLength(byte[] plaintext, KmsKeySpec.Algorithm algorithm, KmsKeySpec spec) {int modulusBytes = keySize(spec) / 8;int digestBytes = algorithm == KmsKeySpec.Algorithm.RSAES_OAEP_SHA_1 ? 20 : 32;@@ -124,29 +118,28 @@ final class RsaKeyType implements KmsKeyType {} catch (Exception e) {if (mode == Cipher.DECRYPT_MODE) {LOG.debugv(e, "RSA OAEP decrypt failed for key {0}", key.getKeyId());- throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ throw new AwsException("InvalidCiphertextException", null, 400);}LOG.warnv(e, "RSA OAEP encrypt failed for key {0}", key.getKeyId());throw new AwsException("InternalFailure", "Failed to encrypt: " + e.getMessage(), 500);}}- private static boolean isPss(String algorithm) {- return algorithm.startsWith("RSASSA_PSS");+ private static boolean isPss(KmsKeySpec.Algorithm algorithm) {+ return switch (algorithm) {+ case RSASSA_PSS_SHA_256, RSASSA_PSS_SHA_384, RSASSA_PSS_SHA_512 -> true;+ default -> false;+ };}// NONEwithRSA pads only the bytes it gets, so PKCS#1 v1.5 needs the DigestInfo wrapper (RFC 8017 9.2).- private static byte[] wrapInDigestInfo(byte[] digest, String algorithm) {- ASN1ObjectIdentifier hashOid;- if (algorithm.endsWith("SHA_256")) {- hashOid = NISTObjectIdentifiers.id_sha256;- } else if (algorithm.endsWith("SHA_384")) {- hashOid = NISTObjectIdentifiers.id_sha384;- } else if (algorithm.endsWith("SHA_512")) {- hashOid = NISTObjectIdentifiers.id_sha512;- } else {- throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + algorithm, 400);- }+ private static byte[] wrapInDigestInfo(byte[] digest, KmsKeySpec.Algorithm algorithm) {+ ASN1ObjectIdentifier hashOid = switch (algorithm) {+ case RSASSA_PKCS1_V1_5_SHA_256 -> NISTObjectIdentifiers.id_sha256;+ case RSASSA_PKCS1_V1_5_SHA_384 -> NISTObjectIdentifiers.id_sha384;+ case RSASSA_PKCS1_V1_5_SHA_512 -> NISTObjectIdentifiers.id_sha512;+ default -> throw new IllegalStateException("Not a PKCS#1 v1.5 algorithm: " + algorithm);+ };try {return new DigestInfo(new AlgorithmIdentifier(hashOid, DERNull.INSTANCE), digest).getEncoded();} catch (IOException e) {@@ -155,27 +148,28 @@ final class RsaKeyType implements KmsKeyType {}// The JDK RSASSA-PSS Signature always hashes its input, so a DIGEST request needs BC's raw PSS signer.- private byte[] signPssDigest(PrivateKey privateKey, byte[] digest, String algorithm) throws Exception {+ private byte[] signPssDigest(PrivateKey privateKey, byte[] digest, KmsKeySpec.Algorithm algorithm)+ throws Exception {PSSSigner signer = rawPssSigner(algorithm);signer.init(true, new ParametersWithRandom(PrivateKeyFactory.createKey(privateKey.getEncoded()), random));signer.update(digest, 0, digest.length);return signer.generateSignature();}- private static boolean verifyPssDigest(PublicKey publicKey, byte[] digest, byte[] signature, String algorithm)- throws IOException {+ private static boolean verifyPssDigest(PublicKey publicKey, byte[] digest, byte[] signature,+ KmsKeySpec.Algorithm algorithm) throws IOException {PSSSigner signer = rawPssSigner(algorithm);signer.init(false, PublicKeyFactory.createKey(publicKey.getEncoded()));signer.update(digest, 0, digest.length);return signer.verifySignature(signature);}- private static PSSSigner rawPssSigner(String algorithm) {+ private static PSSSigner rawPssSigner(KmsKeySpec.Algorithm algorithm) {Digest digest = switch (algorithm) {- case "RSASSA_PSS_SHA_256" -> new SHA256Digest();- case "RSASSA_PSS_SHA_384" -> new SHA384Digest();- case "RSASSA_PSS_SHA_512" -> new SHA512Digest();- default -> throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + algorithm, 400);+ case RSASSA_PSS_SHA_256 -> new SHA256Digest();+ case RSASSA_PSS_SHA_384 -> new SHA384Digest();+ case RSASSA_PSS_SHA_512 -> new SHA512Digest();+ default -> throw new IllegalStateException("Not a PSS algorithm: " + algorithm);};return PSSSigner.createRawSigner(new RSABlindedEngine(), digest);}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.javaindex e8185c33ef..70bf2aabdb 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/Sm2KeyType.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.kms.keytype;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.kms.model.KmsKey;+import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;import io.github.hectorvent.floci.services.kms.model.KmsMessageType;import org.bouncycastle.crypto.CryptoException;import org.bouncycastle.crypto.params.ParametersWithRandom;@@ -31,9 +32,8 @@ final class Sm2KeyType implements KmsKeyType {}@Override- public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)+ public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)throws IOException, CryptoException {- AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);SM2Signer signer = new SM2Signer();signer.init(true, new ParametersWithRandom(BcEcKeys.privateKeyParameters(key, CURVE), random));@@ -42,9 +42,8 @@ final class Sm2KeyType implements KmsKeyType {}@Override- public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,+ public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,KmsMessageType messageType) throws IOException {- AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);SM2Signer verifier = new SM2Signer();verifier.init(false, BcEcKeys.publicKeyParameters(key, CURVE));diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKeySpec.java b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKeySpec.javaindex f9d54b261b..0142cc898f 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKeySpec.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKeySpec.java@@ -129,14 +129,6 @@ public enum KmsKeySpec {Algorithm.RSAES_OAEP_SHA_1, Algorithm.RSAES_OAEP_SHA_256);}- public static Algorithm getSignVerifyAlgorithm(String signingAlgorithm) {- try {- return Algorithm.valueOf(signingAlgorithm);- } catch (IllegalArgumentException _) {- throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + signingAlgorithm, 400);- }- }-public enum Algorithm {SYMMETRIC_DEFAULT("SYMMETRIC_DEFAULT", "", KmsKeyUsage.ENCRYPT_DECRYPT),RSASSA_PSS_SHA_256("RSASSA_PSS_SHA_256","SHA256withRSA/PSS", KmsKeyUsage.SIGN_VERIFY),diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsMessageType.java b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsMessageType.javaindex daf4ab79e9..dd4fda383d 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsMessageType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsMessageType.java@@ -11,7 +11,9 @@ public enum KmsMessageType {try {return KmsMessageType.valueOf(messageType);} catch (IllegalArgumentException _) {- throw new AwsException("ValidationException", "1 validation error detected: Value '" + messageType + "' at 'MessageType' failed to satisfy constraint", 400);+ throw new AwsException("ValidationException", "1 validation error detected: Value '" + messageType+ + "' at 'messageType' failed to satisfy constraint: Member must satisfy enum value set: "+ + "[RAW, DIGEST, EXTERNAL_MU]", 400);}}}diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.javaindex bd25f9cdfe..175509e63b 100644--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.kms;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;@@ -25,6 +26,7 @@ import static org.hamcrest.Matchers.hasKey;import static org.hamcrest.Matchers.matchesPattern;import static org.hamcrest.Matchers.not;import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;import static org.hamcrest.Matchers.startsWith;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;@@ -173,7 +175,8 @@ class KmsIntegrationTest {.post("/").then().statusCode(400)- .body("__type", equalTo("KMSInvalidMacException"));+ .body("__type", equalTo("KMSInvalidMacException"))+ .body("message", nullValue());}@Test@@ -210,7 +213,8 @@ class KmsIntegrationTest {.post("/").then().statusCode(400)- .body("__type", equalTo("ValidationException"));+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("NumberOfBytes is required."));}@Test@@ -227,7 +231,9 @@ class KmsIntegrationTest {.post("/").then().statusCode(400)- .body("__type", equalTo("ValidationException"));+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value '0' at 'numberOfBytes' failed to satisfy "+ + "constraint: Member must have value greater than or equal to 1"));}@Test@@ -261,7 +267,9 @@ class KmsIntegrationTest {.post("/").then().statusCode(400)- .body("__type", equalTo("ValidationException"));+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value '1025' at 'numberOfBytes' failed to satisfy "+ + "constraint: Member must have value less than or equal to 1024"));}@Test@@ -548,7 +556,7 @@ class KmsIntegrationTest {.when().post("/").then()- .statusCode(404)+ .statusCode(400).body("__type", equalTo("NotFoundException"));}@@ -633,7 +641,7 @@ class KmsIntegrationTest {.when().post("/").then()- .statusCode(404)+ .statusCode(400).body("__type", equalTo("NotFoundException"));}@@ -855,7 +863,7 @@ class KmsIntegrationTest {.body("{\"KeyId\":\"non-existent-key\",\"GrantId\":\"some-grant-id\"}").when().post("/").then()- .statusCode(404)+ .statusCode(400).body("__type", equalTo("NotFoundException"));}@@ -1346,7 +1354,7 @@ class KmsIntegrationTest {.body("{\"AliasName\":\"alias/non-existent\",\"TargetKeyId\":\"" + keyId + "\"}").when().post("/").then()- .statusCode(404)+ .statusCode(400).body("__type", equalTo("NotFoundException"));}@@ -1375,7 +1383,7 @@ class KmsIntegrationTest {.body("{\"AliasName\":\"alias/update-alias-missing-target\",\"TargetKeyId\":\"non-existent-key\"}").when().post("/").then()- .statusCode(404)+ .statusCode(400).body("__type", equalTo("NotFoundException"));}@@ -1652,6 +1660,967 @@ class KmsIntegrationTest {.body("message", equalTo("Digest is invalid length for algorithm ED25519_PH_SHA_512."));}+ @ParameterizedTest+ @CsvSource({+ "HMAC_256, GENERATE_VERIFY_MAC, Sign",+ "HMAC_256, GENERATE_VERIFY_MAC, Verify",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, Sign",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, Verify",+ "RSA_2048, ENCRYPT_DECRYPT, Sign",+ "RSA_2048, ENCRYPT_DECRYPT, Verify",+ "ECC_NIST_P256, KEY_AGREEMENT, Sign",+ "ECC_NIST_P256, KEY_AGREEMENT, Verify",+ })+ void signAndVerifyRejectKeysWhoseUsageIsNotSignVerify(String keySpec, String keyUsage, String operation) {+ String keyArn = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyUsage\":\"%s\",\"KeySpec\":\"%s\"}".formatted(keyUsage, keySpec))+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.Arn");++ String signature = Base64.getEncoder().encodeToString(new byte[64]);+ given()+ .header("X-Amz-Target", "TrentService." + operation)+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Message\":\"bWVzc2FnZQ==\",\"MessageType\":\"RAW\",\"Signature\":\"%s\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"}"+ .formatted(keyArn, signature))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo(keyArn + " key usage is " + keyUsage + " which is not valid for " + operation + "."));+ }++ @Test+ void signRejectsAnUnknownSigningAlgorithmBeforeLookingUpTheKey() {+ given()+ .header("X-Amz-Target", "TrentService.Sign")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",\"Message\":\"bWVzc2FnZQ==\",\"SigningAlgorithm\":\"FOO\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value 'FOO' at 'signingAlgorithm' failed to "+ + "satisfy constraint: Member must satisfy enum value set: [RSASSA_PSS_SHA_256, "+ + "RSASSA_PSS_SHA_384, RSASSA_PSS_SHA_512, RSASSA_PKCS1_V1_5_SHA_256, RSASSA_PKCS1_V1_5_SHA_384, "+ + "RSASSA_PKCS1_V1_5_SHA_512, ECDSA_SHA_256, ECDSA_SHA_384, ECDSA_SHA_512, ED25519_SHA_512, "+ + "ED25519_PH_SHA_512, SM2DSA, ML_DSA_SHAKE_256]"));+ }++ @ParameterizedTest+ @CsvSource({"Sign", "Verify"})+ void signAndVerifyRequireASigningAlgorithm(String operation) {+ String keyArn = createKeyArn("RSA_2048", "SIGN_VERIFY");++ given()+ .header("X-Amz-Target", "TrentService." + operation)+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Message\":\"bWVzc2FnZQ==\",\"Signature\":\"%s\"}"+ .formatted(keyArn, Base64.getEncoder().encodeToString(new byte[64])))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value null at 'signingAlgorithm' failed to "+ + "satisfy constraint: Member must not be null"));+ }++ /** SYMMETRIC_DEFAULT is not in the modeled enum, yet KMS answers it with the key spec error. */+ @ParameterizedTest+ @CsvSource({+ "RSA_2048, ECDSA_SHA_256, Sign",+ "RSA_2048, ECDSA_SHA_256, Verify",+ "RSA_2048, SYMMETRIC_DEFAULT, Sign",+ "ECC_NIST_P256, ECDSA_SHA_384, Sign",+ "ECC_NIST_P256, ECDSA_SHA_384, Verify",+ "ECC_NIST_P256, RSASSA_PSS_SHA_256, Sign",+ "ECC_NIST_P256, ED25519_PH_SHA_512, Sign",+ })+ void signAndVerifyRejectAnAlgorithmTheKeySpecDoesNotSupport(String keySpec, String algorithm, String operation) {+ String keyArn = createKeyArn(keySpec, "SIGN_VERIFY");++ given()+ .header("X-Amz-Target", "TrentService." + operation)+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Message\":\"bWVzc2FnZQ==\",\"Signature\":\"%s\",\"SigningAlgorithm\":\"%s\"}"+ .formatted(keyArn, Base64.getEncoder().encodeToString(new byte[64]), algorithm))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo("Algorithm " + algorithm + " is incompatible with key spec " + keySpec + "."));+ }++ @Test+ void signRejectsAnEncryptionAlgorithmAsASigningAlgorithm() {+ String keyArn = createKeyArn("RSA_2048", "SIGN_VERIFY");++ given()+ .header("X-Amz-Target", "TrentService.Sign")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Message\":\"bWVzc2FnZQ==\",\"SigningAlgorithm\":\"RSAES_OAEP_SHA_256\"}"+ .formatted(keyArn))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", startsWith("1 validation error detected: Value 'RSAES_OAEP_SHA_256' at 'signingAlgorithm'"));+ }++ @ParameterizedTest+ @CsvSource({+ "ECC_NIST_P256, ECDSA_SHA_256, 20, Sign",+ "ECC_NIST_P256, ECDSA_SHA_256, 48, Sign",+ "ECC_NIST_P256, ECDSA_SHA_256, 20, Verify",+ "RSA_2048, RSASSA_PKCS1_V1_5_SHA_256, 20, Sign",+ "RSA_2048, RSASSA_PSS_SHA_256, 20, Sign",+ "RSA_2048, RSASSA_PSS_SHA_384, 32, Sign",+ "RSA_2048, RSASSA_PKCS1_V1_5_SHA_384, 64, Sign",+ "RSA_2048, RSASSA_PSS_SHA_256, 20, Verify",+ })+ void signAndVerifyRejectADigestOfTheWrongLength(String keySpec, String algorithm, int digestBytes,+ String operation) {+ String keyArn = createKeyArn(keySpec, "SIGN_VERIFY");++ given()+ .header("X-Amz-Target", "TrentService." + operation)+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Message\":\"%s\",\"MessageType\":\"DIGEST\",\"Signature\":\"%s\",\"SigningAlgorithm\":\"%s\"}"+ .formatted(keyArn, Base64.getEncoder().encodeToString(new byte[digestBytes]),+ Base64.getEncoder().encodeToString(new byte[64]), algorithm))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("Digest is invalid length for algorithm " + algorithm + "."));+ }++ @Test+ void signChecksTheKeySpecBeforeTheDigestLength() {+ String keyArn = createKeyArn("ECC_NIST_P256", "SIGN_VERIFY");++ given()+ .header("X-Amz-Target", "TrentService.Sign")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Message\":\"%s\",\"MessageType\":\"DIGEST\",\"SigningAlgorithm\":\"ECDSA_SHA_384\"}"+ .formatted(keyArn, Base64.getEncoder().encodeToString(new byte[20])))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo("Algorithm ECDSA_SHA_384 is incompatible with key spec ECC_NIST_P256."));+ }++ /** The key state is checked before the algorithm. */+ @ParameterizedTest+ @CsvSource({+ "RSA_2048, SIGN_VERIFY, Sign, RSASSA_PSS_SHA_256",+ "RSA_2048, SIGN_VERIFY, Verify, RSASSA_PSS_SHA_256",+ "RSA_2048, SIGN_VERIFY, Sign, ECDSA_SHA_256",+ "HMAC_256, GENERATE_VERIFY_MAC, GenerateMac, HMAC_SHA_256",+ "HMAC_256, GENERATE_VERIFY_MAC, VerifyMac, HMAC_SHA_256",+ "HMAC_256, GENERATE_VERIFY_MAC, GenerateMac, HMAC_SHA_512",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, Encrypt, SYMMETRIC_DEFAULT",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, GenerateDataKey, SYMMETRIC_DEFAULT",+ "RSA_2048, ENCRYPT_DECRYPT, Encrypt, RSAES_OAEP_SHA_256",+ "RSA_2048, ENCRYPT_DECRYPT, Decrypt, RSAES_OAEP_SHA_256",+ })+ void cryptoOperationsRejectADisabledKey(String keySpec, String keyUsage, String operation, String algorithm) {+ String keyArn = createKeyArn(keySpec, keyUsage);+ callKms("DisableKey", "{\"KeyId\":\"%s\"}".formatted(keyArn)).then().statusCode(200);++ callKms(operation, cryptoRequest(operation, keyArn, algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("DisabledException"))+ .body("message", equalTo(keyArn + " is disabled."));+ }++ /** The key state is checked before the algorithm. */+ @ParameterizedTest+ @CsvSource({+ "ECC_NIST_P256, SIGN_VERIFY, Sign, ECDSA_SHA_256",+ "ECC_NIST_P256, SIGN_VERIFY, Verify, ECDSA_SHA_256",+ "ECC_NIST_P256, SIGN_VERIFY, Sign, ECDSA_SHA_384",+ "HMAC_256, GENERATE_VERIFY_MAC, GenerateMac, HMAC_SHA_256",+ "HMAC_256, GENERATE_VERIFY_MAC, VerifyMac, HMAC_SHA_256",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, Encrypt, SYMMETRIC_DEFAULT",+ })+ void cryptoOperationsRejectAKeyPendingDeletion(String keySpec, String keyUsage, String operation,+ String algorithm) {+ String keyArn = createKeyArn(keySpec, keyUsage);+ callKms("ScheduleKeyDeletion", "{\"KeyId\":\"%s\",\"PendingWindowInDays\":7}".formatted(keyArn))+ .then().statusCode(200);++ callKms(operation, cryptoRequest(operation, keyArn, algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(keyArn + " is pending deletion."));+ }++ @ParameterizedTest+ @CsvSource({+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, Encrypt, SYMMETRIC_DEFAULT",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, GenerateDataKey, SYMMETRIC_DEFAULT",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, GenerateDataKeyWithoutPlaintext, SYMMETRIC_DEFAULT",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, EnableKey, SYMMETRIC_DEFAULT",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, DisableKey, SYMMETRIC_DEFAULT",+ "HMAC_256, GENERATE_VERIFY_MAC, GenerateMac, HMAC_SHA_256",+ "HMAC_256, GENERATE_VERIFY_MAC, VerifyMac, HMAC_SHA_256",+ "HMAC_256, GENERATE_VERIFY_MAC, GenerateMac, HMAC_SHA_512",+ })+ void operationsRejectAKeyPendingImport(String keySpec, String keyUsage, String operation, String algorithm) {+ String keyArn = callKms("CreateKey", "{\"Origin\":\"EXTERNAL\",\"KeySpec\":\"%s\",\"KeyUsage\":\"%s\"}"+ .formatted(keySpec, keyUsage)).then().statusCode(200).extract().path("KeyMetadata.Arn");++ callKms(operation, cryptoRequest(operation, keyArn, algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(keyArn + " is pending import."));+ }++ @ParameterizedTest+ @CsvSource({+ "RSA_2048, ENCRYPT_DECRYPT, AWS_KMS",+ "RSA_2048, SIGN_VERIFY, AWS_KMS",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, EXTERNAL",+ })+ void decryptRejectsAKeyIdThatDidNotEncryptTheCiphertext(String keySpec, String keyUsage, String origin) {+ String sourceArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ String otherArn = callKms("CreateKey", "{\"Origin\":\"%s\",\"KeySpec\":\"%s\",\"KeyUsage\":\"%s\"}"+ .formatted(origin, keySpec, keyUsage)).then().statusCode(200).extract().path("KeyMetadata.Arn");+ String ciphertext = callKms("Encrypt", "{\"KeyId\":\"%s\",\"Plaintext\":\"aGVsbG8=\"}".formatted(sourceArn))+ .then().statusCode(200).extract().path("CiphertextBlob");++ callKms("Decrypt", "{\"CiphertextBlob\":\"%s\",\"KeyId\":\"%s\"}".formatted(ciphertext, otherArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("IncorrectKeyException"))+ .body("message", equalTo("The key ID in the request does not identify a CMK that can perform this operation."));+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "GenerateDataKey|\"KeySpec\":\"FOO\"|Value 'FOO' at 'keySpec' failed to satisfy constraint: Member must satisfy enum value set: [RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384, ECC_NIST_P521, ECC_SECG_P256K1, ECC_NIST_EDWARDS25519, SYMMETRIC_DEFAULT, HMAC_224, HMAC_256, HMAC_384, HMAC_512, SM2, ML_DSA_44, ML_DSA_65, ML_DSA_87]",+ "GenerateDataKey|\"KeySpec\":\"RSA_2048\"|Value 'RSA_2048' at 'keySpec' failed to satisfy constraint: Member must satisfy enum value set: [RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384, ECC_NIST_P521, ECC_SECG_P256K1, ECC_NIST_EDWARDS25519, SYMMETRIC_DEFAULT, HMAC_224, HMAC_256, HMAC_384, HMAC_512, SM2, ML_DSA_44, ML_DSA_65, ML_DSA_87]",+ "GenerateDataKeyWithoutPlaintext|\"KeySpec\":\"FOO\"|Value 'FOO' at 'keySpec' failed to satisfy constraint: Member must satisfy enum value set: [RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384, ECC_NIST_P521, ECC_SECG_P256K1, ECC_NIST_EDWARDS25519, SYMMETRIC_DEFAULT, HMAC_224, HMAC_256, HMAC_384, HMAC_512, SM2, ML_DSA_44, ML_DSA_65, ML_DSA_87]",+ "GenerateDataKey|\"NumberOfBytes\":0|Value '0' at 'numberOfBytes' failed to satisfy constraint: Member must have value greater than or equal to 1",+ "GenerateDataKey|\"NumberOfBytes\":1025|Value '1025' at 'numberOfBytes' failed to satisfy constraint: Member must have value less than or equal to 1024",+ })+ void generateDataKeyValidatesItsInputBeforeLookingUpTheKey(String operation, String member, String error) {+ callKms(operation, "{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",%s}".formatted(member))+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: " + error));+ }++ @ParameterizedTest+ @CsvSource({+ "\"KeySpec\":\"AES_128\", 16",+ "\"KeySpec\":\"AES_256\", 32",+ "\"NumberOfBytes\":7, 7",+ })+ void generateDataKeyReturnsAPlaintextOfTheRequestedLength(String member, int length) {+ String plaintext = callKms("GenerateDataKey", "{\"KeyId\":\"%s\",%s}"+ .formatted(createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT"), member))+ .then().statusCode(200).extract().path("Plaintext");++ assertEquals(length, Base64.getDecoder().decode(plaintext).length);+ }++ @ParameterizedTest+ @CsvSource({"GenerateDataKey", "GenerateDataKeyWithoutPlaintext"})+ void generateDataKeyRejectsAnAsymmetricKey(String operation) {+ callKms(operation, "{\"KeyId\":\"%s\",\"KeySpec\":\"AES_256\"}".formatted(createKeyArn("RSA_2048", "ENCRYPT_DECRYPT")))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo("You cannot generate a data key with an asymmetric CMK"));+ }++ @ParameterizedTest+ @CsvSource({"GenerateDataKey", "GenerateDataKeyWithoutPlaintext"})+ void generateDataKeyNamesItsOperationInTheKeyUsageError(String operation) {+ String keyArn = createKeyArn("ECC_NIST_P256", "SIGN_VERIFY");++ callKms(operation, "{\"KeyId\":\"%s\",\"KeySpec\":\"AES_256\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo(keyArn + " key usage is SIGN_VERIFY which is not valid for " + operation + "."));+ }++ @Test+ void generateDataKeyChecksTheKeyStateBeforeTheKeySpec() {+ String keyArn = createKeyArn("RSA_2048", "ENCRYPT_DECRYPT");+ callKms("DisableKey", "{\"KeyId\":\"%s\"}".formatted(keyArn)).then().statusCode(200);++ callKms("GenerateDataKey", "{\"KeyId\":\"%s\",\"KeySpec\":\"AES_256\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("DisabledException"))+ .body("message", equalTo(keyArn + " is disabled."));+ }++ /** The key usage and the key state are checked after this. */+ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "GenerateDataKey|SYMMETRIC_DEFAULT|ENCRYPT_DECRYPT|",+ "GenerateDataKey|SYMMETRIC_DEFAULT|ENCRYPT_DECRYPT|,\"KeySpec\":\"AES_256\",\"NumberOfBytes\":32",+ "GenerateDataKeyWithoutPlaintext|SYMMETRIC_DEFAULT|ENCRYPT_DECRYPT|",+ "GenerateDataKey|RSA_2048|SIGN_VERIFY|",+ "GenerateDataKey|HMAC_256|GENERATE_VERIFY_MAC|",+ })+ void generateDataKeyNeedsEitherKeySpecOrNumberOfBytes(String operation, String keySpec, String keyUsage,+ String members) {+ String keyArn = createKeyArn(keySpec, keyUsage);+ callKms("DisableKey", "{\"KeyId\":\"%s\"}".formatted(keyArn)).then().statusCode(200);++ callKms(operation, "{\"KeyId\":\"%s\"%s}".formatted(keyArn, members == null ? "" : members))+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("Please specify either number of bytes or key spec."));+ }++ @ParameterizedTest+ @CsvSource({"Sign", "Verify"})+ void messageTypeValidationListsTheEnumBeforeLookingUpTheKey(String operation) {+ callKms(operation, ("{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",\"Message\":\"bWVzc2FnZQ==\","+ + "\"Signature\":\"AAAA\",\"SigningAlgorithm\":\"ECDSA_SHA_256\",\"MessageType\":\"FOO\"}"))+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value 'FOO' at 'messageType' failed to satisfy "+ + "constraint: Member must satisfy enum value set: [RAW, DIGEST, EXTERNAL_MU]"));+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "12345678-1234-1234-1234-123456789012|Key '{arn}12345678-1234-1234-1234-123456789012' does not exist",+ "786CA7CD-B74B-42B3-B887-902AD7AB6429|Key '{arn}786CA7CD-B74B-42B3-B887-902AD7AB6429' does not exist",+ "mrk-1234567812341234123412345678901a|Key '{arn}mrk-1234567812341234123412345678901a' does not exist",+ "{arn}12345678-1234-1234-1234-123456789012|Key '{arn}12345678-1234-1234-1234-123456789012' does not exist",+ "{arn}foo|Invalid keyId foo",+ "foo|Invalid keyId 'foo'",+ "12345678123412341234123456789012|Invalid keyId '12345678123412341234123456789012'",+ "mrk-1234|Invalid keyId 'mrk-1234'",+ })+ void describeKeyNamesAMissingKey(String keyId, String message) {+ String keyArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ String arnPrefix = keyArn.substring(0, keyArn.lastIndexOf('/') + 1);++ callKms("DescribeKey", "{\"KeyId\":\"%s\"}".formatted(keyId.replace("{arn}", arnPrefix)))+ .then()+ .statusCode(400)+ .body("__type", equalTo("NotFoundException"))+ .body("message", equalTo(message.replace("{arn}", arnPrefix)));+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "DescribeKey|{}|1 validation error detected: Value null at 'keyId' failed to satisfy constraint: Member must not be null",+ "Sign|{\"Message\":\"bWVzc2FnZQ==\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"}|1 validation error detected: Value null at 'keyId' failed to satisfy constraint: Member must not be null",+ "ScheduleKeyDeletion|{}|1 validation error detected: Value null at 'keyId' failed to satisfy constraint: Member must not be null",+ "ReEncrypt|{\"CiphertextBlob\":\"AAAA\"}|1 validation error detected: Value null at 'destinationKeyId' failed to satisfy constraint: Member must not be null",+ "CreateAlias|{\"AliasName\":\"alias/x\"}|1 validation error detected: Value null at 'targetKeyId' failed to satisfy constraint: Member must not be null",+ "GetPublicKey|{\"KeyId\":\"\"}|2 validation errors detected: Value '' at 'keyId' failed to satisfy constraint: Member must have length greater than or equal to 1; Value '' at 'keyId' failed to satisfy constraint: Member must satisfy regular expression pattern: ^\\p{ASCII}+$",+ "DescribeKey|{\"KeyId\":\"\\u30ad\\u30fc\"}|1 validation error detected: Value 'キー' at 'keyId' failed to satisfy constraint: Member must satisfy regular expression pattern: ^\\p{ASCII}+$",+ })+ void operationsValidateTheKeyIdMember(String operation, String body, String message) {+ callKms(operation, body)+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo(message));+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "Encrypt|\"Plaintext\":\"\"|Value at 'plaintext' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "Encrypt|\"Plaintext\":\"{4097}\"|Value at 'plaintext' failed to satisfy constraint: Member must have length less than or equal to 4096",+ "Encrypt||Value at 'plaintext' failed to satisfy constraint: Member must not be null",+ "Sign|\"Message\":\"\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "Sign|\"Message\":\"{4097}\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must have length less than or equal to 4096",+ "Sign|\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must not be null",+ "Verify|\"Message\":\"bWVzc2FnZQ==\",\"Signature\":\"\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value at 'signature' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "Verify|\"Message\":\"bWVzc2FnZQ==\",\"Signature\":\"{6145}\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value at 'signature' failed to satisfy constraint: Member must have length less than or equal to 6144",+ "Verify|\"Message\":\"bWVzc2FnZQ==\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value null at 'signature' failed to satisfy constraint: Member must not be null",+ "Verify|\"Message\":\"{4097}\",\"Signature\":\"AAAA\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must have length less than or equal to 4096",+ "Verify|\"Signature\":\"AAAA\",\"SigningAlgorithm\":\"ECDSA_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must not be null",+ "GenerateMac|\"Message\":\"\",\"MacAlgorithm\":\"HMAC_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "GenerateMac|\"Message\":\"{4097}\",\"MacAlgorithm\":\"HMAC_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must have length less than or equal to 4096",+ "GenerateMac|\"MacAlgorithm\":\"HMAC_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must not be null",+ "VerifyMac|\"Message\":\"bWVzc2FnZQ==\",\"Mac\":\"\",\"MacAlgorithm\":\"HMAC_SHA_256\"|Value at 'mac' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "VerifyMac|\"Message\":\"bWVzc2FnZQ==\",\"Mac\":\"{6145}\",\"MacAlgorithm\":\"HMAC_SHA_256\"|Value at 'mac' failed to satisfy constraint: Member must have length less than or equal to 6144",+ "VerifyMac|\"Message\":\"bWVzc2FnZQ==\",\"MacAlgorithm\":\"HMAC_SHA_256\"|Value null at 'mac' failed to satisfy constraint: Member must not be null",+ "VerifyMac|\"Message\":\"\",\"Mac\":\"AAAA\",\"MacAlgorithm\":\"HMAC_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "VerifyMac|\"Mac\":\"AAAA\",\"MacAlgorithm\":\"HMAC_SHA_256\"|Value at 'message' failed to satisfy constraint: Member must not be null",+ "Decrypt|\"CiphertextBlob\":\"\"|Value at 'ciphertextBlob' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "Decrypt|\"CiphertextBlob\":\"{6145}\"|Value at 'ciphertextBlob' failed to satisfy constraint: Member must have length less than or equal to 6144",+ "ReEncrypt|\"DestinationKeyId\":\"alias/floci-missing\",\"CiphertextBlob\":\"\"|Value at 'ciphertextBlob' failed to satisfy constraint: Member must have length greater than or equal to 1",+ "ReEncrypt|\"DestinationKeyId\":\"alias/floci-missing\"|Value null at 'ciphertextBlob' failed to satisfy constraint: Member must not be null",+ })+ void blobMembersAreValidatedBeforeTheKeyIsLookedUp(String operation, String members, String error) {+ String blobs = members == null ? "" : members+ .replace("{4097}", Base64.getEncoder().encodeToString(new byte[4097]))+ .replace("{6145}", Base64.getEncoder().encodeToString(new byte[6145]));+ String body = "{\"KeyId\":\"00000000-0000-0000-0000-000000000000\"" + (blobs.isEmpty() ? "" : "," + blobs) + "}";++ callKms(operation, body)+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: " + error));+ }++ @ParameterizedTest+ @CsvSource({+ "ScheduleKeyDeletion", "CancelKeyDeletion", "EnableKey", "DisableKey", "TagResource", "UntagResource",+ "ListResourceTags", "UpdateKeyDescription", "GetKeyPolicy", "PutKeyPolicy", "ListKeyPolicies",+ "GetKeyRotationStatus", "EnableKeyRotation", "DisableKeyRotation", "RotateKeyOnDemand", "CreateGrant",+ "ListGrants", "RevokeGrant", "GetParametersForImport", "ImportKeyMaterial", "DeleteImportedKeyMaterial",+ })+ void keyOnlyOperationsRejectAnAliasBeforeLookingItUp(String operation) {+ String keyArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ String aliasArn = keyArn.substring(0, keyArn.lastIndexOf(':') + 1) + "alias/floci-missing";++ for (String alias : List.of("alias/floci-missing", aliasArn)) {+ callKms(operation, "{\"KeyId\":\"%s\"}".formatted(alias))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidArnException"))+ .body("message", equalTo("Key Aliases are not supported for this operation."));+ }+ }++ @Test+ void decryptRequiresACiphertextBlob() {+ callKms("Decrypt", "{}")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value null at 'ciphertextBlob' failed to satisfy "+ + "constraint: Member must not be null"));+ }++ @ParameterizedTest+ @CsvSource({"key/", "alias/floci-missing"})+ void describeKeyRejectsAnArnFromAnotherRegion(String resource) {+ String keyArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ String otherRegion = keyArn.contains(":us-west-2:") ? "eu-west-1" : "us-west-2";+ String foreignArn = keyArn.replaceFirst(":kms:[^:]+:", ":kms:" + otherRegion + ":");+ String requested = "key/".equals(resource)+ ? foreignArn : foreignArn.substring(0, foreignArn.lastIndexOf(':') + 1) + resource;++ callKms("DescribeKey", "{\"KeyId\":\"%s\"}".formatted(requested))+ .then()+ .statusCode(400)+ .body("__type", equalTo("NotFoundException"))+ .body("message", equalTo("Invalid arn " + otherRegion));+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "DescribeKey|{\"KeyId\":\"alias/floci-missing\"}|alias/floci-missing",+ "DescribeKey|{\"KeyId\":\"{arn}alias/floci-missing\"}|alias/floci-missing",+ "DescribeKey|{\"KeyId\":\"alias/aws/floci-missing\"}|alias/aws/floci-missing",+ "Encrypt|{\"KeyId\":\"alias/floci-missing\",\"Plaintext\":\"AAAA\"}|alias/floci-missing",+ "UpdateAlias|{\"AliasName\":\"alias/floci-missing\",\"TargetKeyId\":\"{key}\"}|alias/floci-missing",+ "DeleteAlias|{\"AliasName\":\"alias/floci-missing\"}|alias/floci-missing",+ })+ void operationsNameAMissingAlias(String operation, String body, String aliasName) {+ String keyArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ String arnPrefix = keyArn.substring(0, keyArn.lastIndexOf(':') + 1);++ callKms(operation, body.replace("{arn}", arnPrefix).replace("{key}", keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("NotFoundException"))+ .body("message", equalTo("Alias " + arnPrefix + aliasName + " is not found."));+ }++ @ParameterizedTest+ @CsvSource({"Encrypt", "Decrypt"})+ void encryptionAlgorithmValidationListsTheEnumInAwsOrder(String operation) {+ callKms(operation, "{\"KeyId\":\"%s\",\"Plaintext\":\"aGVsbG8=\",\"CiphertextBlob\":\"AAAA\",\"EncryptionAlgorithm\":\"FOO\"}"+ .formatted(createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT")))+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value 'FOO' at 'encryptionAlgorithm' failed to "+ + "satisfy constraint: Member must satisfy enum value set: "+ + "[RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256, SM2PKE, SYMMETRIC_DEFAULT]"));+ }++ @ParameterizedTest+ @CsvSource({"garbage", "wrong context", "rsa garbage", "rsa short"})+ void decryptRejectsAnInvalidCiphertextWithoutAMessage(String kind) {+ String body = switch (kind) {+ case "garbage" -> "{\"CiphertextBlob\":\"AAAA\"}";+ case "wrong context" -> {+ String keyArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ String ciphertext = callKms("Encrypt", "{\"KeyId\":\"%s\",\"Plaintext\":\"aGVsbG8=\",\"EncryptionContext\":{\"a\":\"b\"}}"+ .formatted(keyArn)).then().statusCode(200).extract().path("CiphertextBlob");+ yield "{\"CiphertextBlob\":\"%s\",\"EncryptionContext\":{\"a\":\"c\"}}".formatted(ciphertext);+ }+ default -> {+ byte[] ciphertext = new byte["rsa garbage".equals(kind) ? 256 : 10];+ Arrays.fill(ciphertext, (byte) 1);+ yield "{\"CiphertextBlob\":\"%s\",\"KeyId\":\"%s\",\"EncryptionAlgorithm\":\"RSAES_OAEP_SHA_256\"}"+ .formatted(Base64.getEncoder().encodeToString(ciphertext), createKeyArn("RSA_2048", "ENCRYPT_DECRYPT"));+ }+ };++ callKms("Decrypt", body)+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidCiphertextException"))+ .body("message", nullValue());+ }++ @Test+ void reEncryptRejectsADestinationKeyPendingImport() {+ String sourceArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ String destinationArn = callKms("CreateKey", "{\"Origin\":\"EXTERNAL\"}")+ .then().statusCode(200).extract().path("KeyMetadata.Arn");+ String ciphertext = callKms("Encrypt", "{\"KeyId\":\"%s\",\"Plaintext\":\"aGVsbG8=\"}".formatted(sourceArn))+ .then().statusCode(200).extract().path("CiphertextBlob");++ callKms("ReEncrypt", "{\"CiphertextBlob\":\"%s\",\"DestinationKeyId\":\"%s\"}".formatted(ciphertext, destinationArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(destinationArn + " is pending import."));+ }++ @ParameterizedTest+ @CsvSource({"Decrypt, false", "Decrypt, true", "ReEncrypt, false"})+ void ciphertextOfDeletedKeyMaterialReportsPendingImport(String operation, boolean withKeyId) throws Exception {+ String keyId = createExternalSymmetricKey();+ importFreshMaterial(keyId);+ String keyArn = describeKey(keyId).extract().path("KeyMetadata.Arn");+ String ciphertext = callKms("Encrypt", "{\"KeyId\":\"%s\",\"Plaintext\":\"aGVsbG8=\"}".formatted(keyArn))+ .then().statusCode(200).extract().path("CiphertextBlob");+ callKms("DeleteImportedKeyMaterial", "{\"KeyId\":\"%s\"}".formatted(keyArn)).then().statusCode(200);+ String body = "ReEncrypt".equals(operation)+ ? "{\"CiphertextBlob\":\"%s\",\"DestinationKeyId\":\"%s\"}"+ .formatted(ciphertext, createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT"))+ : withKeyId+ ? "{\"CiphertextBlob\":\"%s\",\"KeyId\":\"%s\"}".formatted(ciphertext, keyArn)+ : "{\"CiphertextBlob\":\"%s\"}".formatted(ciphertext);++ callKms(operation, body)+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(keyArn + " is pending import."));+ }++ @ParameterizedTest+ @CsvSource({+ "EnableKey, AWS_KMS",+ "DisableKey, AWS_KMS",+ "UpdateKeyDescription, AWS_KMS",+ "TagResource, AWS_KMS",+ "UntagResource, AWS_KMS",+ "CreateGrant, AWS_KMS",+ "ScheduleKeyDeletion, AWS_KMS",+ "CreateAlias, AWS_KMS",+ "UpdateAlias, AWS_KMS",+ "GetParametersForImport, EXTERNAL",+ "ImportKeyMaterial, EXTERNAL",+ })+ void keyManagementRejectsAKeyPendingDeletion(String operation, String origin) {+ String keyArn = callKms("CreateKey", "{\"Origin\":\"%s\"}".formatted(origin))+ .then().statusCode(200).extract().path("KeyMetadata.Arn");+ String request = keyManagementRequest(operation, keyArn);+ callKms("ScheduleKeyDeletion", "{\"KeyId\":\"%s\",\"PendingWindowInDays\":7}".formatted(keyArn))+ .then().statusCode(200);++ callKms(operation, request)+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(keyArn + " is pending deletion."));+ }++ /** The key state is checked before the key spec. */+ @ParameterizedTest+ @CsvSource({+ "ECC_NIST_P256, SIGN_VERIFY, AWS_KMS, is pending deletion.",+ "HMAC_256, GENERATE_VERIFY_MAC, AWS_KMS, is pending deletion.",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, EXTERNAL, is pending import.",+ })+ void getPublicKeyRejectsAKeyPendingDeletionOrImport(String keySpec, String keyUsage, String origin,+ String state) {+ String keyArn = callKms("CreateKey", "{\"Origin\":\"%s\",\"KeySpec\":\"%s\",\"KeyUsage\":\"%s\"}"+ .formatted(origin, keySpec, keyUsage)).then().statusCode(200).extract().path("KeyMetadata.Arn");+ if ("AWS_KMS".equals(origin)) {+ callKms("ScheduleKeyDeletion", "{\"KeyId\":\"%s\",\"PendingWindowInDays\":7}".formatted(keyArn))+ .then().statusCode(200);+ }++ callKms("GetPublicKey", "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(keyArn + " " + state));+ }++ @Test+ void getPublicKeyRejectsASymmetricKeyWithoutAMessage() {+ String keyArn = createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");++ callKms("GetPublicKey", "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedOperationException"))+ .body("message", nullValue());+ }++ @Test+ void getPublicKeyWorksOnADisabledKey() {+ String keyArn = createKeyArn("RSA_2048", "SIGN_VERIFY");+ callKms("DisableKey", "{\"KeyId\":\"%s\"}".formatted(keyArn)).then().statusCode(200);++ callKms("GetPublicKey", "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(200)+ .body("KeyId", equalTo(keyArn));+ }++ /** The key state is checked before the key spec. */+ @ParameterizedTest+ @CsvSource({+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, EnableKeyRotation",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, DisableKeyRotation",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, RotateKeyOnDemand",+ "HMAC_256, GENERATE_VERIFY_MAC, EnableKeyRotation",+ "HMAC_256, GENERATE_VERIFY_MAC, DisableKeyRotation",+ "HMAC_256, GENERATE_VERIFY_MAC, RotateKeyOnDemand",+ })+ void rotationRejectsADisabledKey(String keySpec, String keyUsage, String operation) {+ String keyArn = createKeyArn(keySpec, keyUsage);+ callKms("DisableKey", "{\"KeyId\":\"%s\"}".formatted(keyArn)).then().statusCode(200);++ callKms(operation, "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("DisabledException"))+ .body("message", equalTo(keyArn + " is disabled."));+ }++ /** The key state is checked before the key spec. */+ @ParameterizedTest+ @CsvSource({"EnableKeyRotation", "DisableKeyRotation", "RotateKeyOnDemand"})+ void rotationRejectsAKeyPendingDeletion(String operation) {+ String keyArn = createKeyArn("HMAC_256", "GENERATE_VERIFY_MAC");+ callKms("ScheduleKeyDeletion", "{\"KeyId\":\"%s\",\"PendingWindowInDays\":7}".formatted(keyArn))+ .then().statusCode(200);++ callKms(operation, "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(keyArn + " is pending deletion."));+ }++ @ParameterizedTest+ @CsvSource({+ "HMAC_256, GENERATE_VERIFY_MAC, EnableKeyRotation",+ "HMAC_256, GENERATE_VERIFY_MAC, RotateKeyOnDemand",+ "RSA_2048, ENCRYPT_DECRYPT, EnableKeyRotation",+ "RSA_2048, ENCRYPT_DECRYPT, RotateKeyOnDemand",+ })+ void rotationRejectsAKeySpecThatDoesNotRotateWithoutAMessage(String keySpec, String keyUsage, String operation) {+ String keyArn = createKeyArn(keySpec, keyUsage);++ callKms(operation, "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedOperationException"))+ .body("message", nullValue());+ }++ @ParameterizedTest+ @CsvSource({+ "HMAC_256, GENERATE_VERIFY_MAC",+ "RSA_2048, ENCRYPT_DECRYPT",+ "RSA_2048, SIGN_VERIFY",+ "ECC_NIST_P256, SIGN_VERIFY",+ "ML_DSA_44, SIGN_VERIFY",+ })+ void disableKeyRotationAcceptsAKeySpecThatDoesNotRotate(String keySpec, String keyUsage) {+ String keyArn = createKeyArn(keySpec, keyUsage);++ callKms("DisableKeyRotation", "{\"KeyId\":\"%s\"}".formatted(keyArn)).then().statusCode(200);+ }++ @ParameterizedTest+ @CsvSource({+ "EnableKeyRotation, EXTERNAL",+ "DisableKeyRotation, EXTERNAL",+ "GetParametersForImport, AWS_KMS",+ "ImportKeyMaterial, AWS_KMS",+ "DeleteImportedKeyMaterial, AWS_KMS",+ })+ void operationsRejectAKeyWithTheWrongOrigin(String operation, String origin) {+ String keyArn = callKms("CreateKey", "{\"Origin\":\"%s\"}".formatted(origin))+ .then().statusCode(200).extract().path("KeyMetadata.Arn");++ callKms(operation, keyManagementRequest(operation, keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedOperationException"))+ .body("message", equalTo(keyArn + " origin is " + origin + " which is not valid for this operation."));+ }++ @Test+ void rotateKeyOnDemandNeedsNewKeyMaterialForAnExternalKey() throws Exception {+ String keyId = createExternalSymmetricKey();+ importFreshMaterial(keyId);+ String keyArn = describeKey(keyId).extract().path("KeyMetadata.Arn");++ callKms("RotateKeyOnDemand", "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo("No available key material pending rotation for the key: " + keyArn + "."));+ }++ /** The key spec is checked before the key material. */+ @Test+ void rotateKeyOnDemandRejectsAnExternalHmacKeyForItsKeySpec() throws Exception {+ String keyId = callKms("CreateKey", "{\"Origin\":\"EXTERNAL\",\"KeySpec\":\"HMAC_256\",\"KeyUsage\":\"GENERATE_VERIFY_MAC\"}")+ .then().statusCode(200).extract().path("KeyMetadata.KeyId");+ importFreshMaterial(keyId);++ callKms("RotateKeyOnDemand", "{\"KeyId\":\"%s\"}".formatted(keyId))+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedOperationException"))+ .body("message", nullValue());+ }++ @ParameterizedTest+ @CsvSource({+ "89, greater than or equal to 90",+ "2561, less than or equal to 2560",+ })+ void enableKeyRotationValidatesTheRotationPeriodBeforeLookingUpTheKey(int days, String constraint) {+ callKms("EnableKeyRotation", "{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",\"RotationPeriodInDays\":%d}"+ .formatted(days))+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value '" + days + "' at 'rotationPeriodInDays' "+ + "failed to satisfy constraint: Member must have value " + constraint));+ }++ @Test+ void rotateKeyOnDemandRejectsAKeyPendingImport() {+ String keyArn = callKms("CreateKey", "{\"Origin\":\"EXTERNAL\"}")+ .then().statusCode(200).extract().path("KeyMetadata.Arn");++ callKms("RotateKeyOnDemand", "{\"KeyId\":\"%s\"}".formatted(keyArn))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"))+ .body("message", equalTo(keyArn + " is pending import."));+ }++ private static String keyManagementRequest(String operation, String keyArn) {+ return switch (operation) {+ case "UpdateAlias" -> {+ String aliasName = "alias/pending-deletion-" + keyArn.substring(keyArn.lastIndexOf('/') + 1);+ callKms("CreateAlias", "{\"AliasName\":\"%s\",\"TargetKeyId\":\"%s\"}"+ .formatted(aliasName, createKeyArn("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT")))+ .then().statusCode(200);+ yield "{\"AliasName\":\"%s\",\"TargetKeyId\":\"%s\"}".formatted(aliasName, keyArn);+ }+ case "GetParametersForImport" ->+ "{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSAES_OAEP_SHA_256\",\"WrappingKeySpec\":\"RSA_2048\"}"+ .formatted(keyArn);+ case "ImportKeyMaterial" -> ("{\"KeyId\":\"%s\",\"ImportToken\":\"AAAA\",\"EncryptedKeyMaterial\":\"AAAA\","+ + "\"ExpirationModel\":\"KEY_MATERIAL_DOES_NOT_EXPIRE\"}").formatted(keyArn);+ case "UpdateKeyDescription" -> "{\"KeyId\":\"%s\",\"Description\":\"x\"}".formatted(keyArn);+ case "TagResource" -> "{\"KeyId\":\"%s\",\"Tags\":[{\"TagKey\":\"a\",\"TagValue\":\"b\"}]}".formatted(keyArn);+ case "UntagResource" -> "{\"KeyId\":\"%s\",\"TagKeys\":[\"a\"]}".formatted(keyArn);+ case "CreateGrant" -> ("{\"KeyId\":\"%s\",\"GranteePrincipal\":\"arn:aws:iam::000000000000:root\","+ + "\"Operations\":[\"Encrypt\"]}").formatted(keyArn);+ case "ScheduleKeyDeletion" -> "{\"KeyId\":\"%s\",\"PendingWindowInDays\":7}".formatted(keyArn);+ case "CreateAlias" -> "{\"AliasName\":\"alias/pending-deletion-%s\",\"TargetKeyId\":\"%s\"}"+ .formatted(keyArn.substring(keyArn.lastIndexOf('/') + 1), keyArn);+ default -> "{\"KeyId\":\"%s\"}".formatted(keyArn);+ };+ }++ @ParameterizedTest+ @CsvSource({+ "HMAC_256, GENERATE_VERIFY_MAC, DisableKey, Sign, RSASSA_PSS_SHA_256",+ "HMAC_256, GENERATE_VERIFY_MAC, ScheduleKeyDeletion, Sign, RSASSA_PSS_SHA_256",+ "RSA_2048, SIGN_VERIFY, DisableKey, Encrypt, RSAES_OAEP_SHA_256",+ })+ void keyUsageIsCheckedBeforeTheKeyState(String keySpec, String keyUsage, String stateChange, String operation,+ String algorithm) {+ String keyArn = createKeyArn(keySpec, keyUsage);+ callKms(stateChange, "{\"KeyId\":\"%s\",\"PendingWindowInDays\":7}".formatted(keyArn)).then().statusCode(200);++ callKms(operation, cryptoRequest(operation, keyArn, algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo(keyArn + " key usage is " + keyUsage + " which is not valid for " + operation + "."));+ }++ @ParameterizedTest+ @CsvSource({+ "ECC_NIST_P256, ECDSA_SHA_256, true",+ "ECC_NIST_P256, ECDSA_SHA_256, false",+ "RSA_2048, RSASSA_PSS_SHA_256, true",+ "RSA_2048, RSASSA_PSS_SHA_256, false",+ })+ void verifyRejectsASignatureThatDoesNotMatch(String keySpec, String algorithm, boolean realSignature) {+ String keyArn = createKeyArn(keySpec, "SIGN_VERIFY");+ String signature = realSignature+ ? callKms("Sign", "{\"KeyId\":\"%s\",\"Message\":\"b3RoZXI=\",\"SigningAlgorithm\":\"%s\"}"+ .formatted(keyArn, algorithm)).then().statusCode(200).extract().path("Signature")+ : "AAAAAAAAAAAAAA==";++ callKms("Verify", "{\"KeyId\":\"%s\",\"Message\":\"bWVzc2FnZQ==\",\"Signature\":\"%s\",\"SigningAlgorithm\":\"%s\"}"+ .formatted(keyArn, signature, algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidSignatureException"))+ .body("message", nullValue());+ }++ @ParameterizedTest+ @CsvSource({+ "RSA_2048, RSASSA_PSS_SHA_256, RAW, 1, 1",+ "RSA_2048, RSASSA_PKCS1_V1_5_SHA_256, RAW, 6144, 97",+ "RSA_2048, RSASSA_PKCS1_V1_5_SHA_256, DIGEST, 6144, 97",+ "ECC_NIST_P256, ECDSA_SHA_256, RAW, 1, 1",+ "ECC_SECG_P256K1, ECDSA_SHA_256, RAW, 1, 1",+ "ECC_SECG_P256K1, ECDSA_SHA_256, RAW, 6144, 97",+ "ECC_NIST_EDWARDS25519, ED25519_SHA_512, RAW, 1, 1",+ "ML_DSA_44, ML_DSA_SHAKE_256, RAW, 6144, 97",+ })+ void verifyRejectsAMalformedSignature(String keySpec, String algorithm, String messageType, int length,+ byte fill) {+ String keyArn = createKeyArn(keySpec, "SIGN_VERIFY");+ String message = "DIGEST".equals(messageType)+ ? Base64.getEncoder().encodeToString(new byte[32]) : "bWVzc2FnZQ==";+ byte[] signature = new byte[length];+ Arrays.fill(signature, fill);++ callKms("Verify", ("{\"KeyId\":\"%s\",\"Message\":\"%s\",\"MessageType\":\"%s\",\"Signature\":\"%s\","+ + "\"SigningAlgorithm\":\"%s\"}").formatted(keyArn, message, messageType,+ Base64.getEncoder().encodeToString(signature), algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidSignatureException"))+ .body("message", nullValue());+ }++ @ParameterizedTest+ @CsvSource({+ "RSA_2048, SIGN_VERIFY, GenerateMac",+ "RSA_2048, SIGN_VERIFY, VerifyMac",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, GenerateMac",+ "SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, VerifyMac",+ })+ void macOperationsRejectKeysWhoseUsageIsNotGenerateVerifyMac(String keySpec, String keyUsage, String operation) {+ String keyArn = createKeyArn(keySpec, keyUsage);++ callKms(operation, cryptoRequest(operation, keyArn, "HMAC_SHA_256"))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo(keyArn + " key usage is " + keyUsage + " which is not valid for " + operation + "."));+ }++ @ParameterizedTest+ @CsvSource({"GenerateMac, FOO", "VerifyMac, FOO", "GenerateMac, hmac_sha_256"})+ void macOperationsRejectAnUnknownMacAlgorithmBeforeLookingUpTheKey(String operation, String algorithm) {+ callKms(operation, cryptoRequest(operation, "00000000-0000-0000-0000-000000000000", algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value '" + algorithm + "' at 'macAlgorithm' "+ + "failed to satisfy constraint: Member must satisfy enum value set: "+ + "[HMAC_SHA_384, HMAC_SHA_256, HMAC_SHA_224, HMAC_SHA_512]"));+ }++ @ParameterizedTest+ @CsvSource({"GenerateMac", "VerifyMac"})+ void macOperationsRequireAMacAlgorithm(String operation) {+ callKms(operation, "{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",\"Message\":\"bWVzc2FnZQ==\",\"Mac\":\"%s\"}"+ .formatted(Base64.getEncoder().encodeToString(new byte[32])))+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Value null at 'macAlgorithm' failed to "+ + "satisfy constraint: Member must not be null"));+ }++ @ParameterizedTest+ @CsvSource({"GenerateMac, HMAC_SHA_512", "GenerateMac, HMAC_SHA_224", "VerifyMac, HMAC_SHA_384"})+ void macOperationsRejectAnAlgorithmTheKeySpecDoesNotSupport(String operation, String algorithm) {+ String keyArn = createKeyArn("HMAC_256", "GENERATE_VERIFY_MAC");++ callKms(operation, cryptoRequest(operation, keyArn, algorithm))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo("Algorithm " + algorithm + " is incompatible with key spec HMAC_256."));+ }++ private static String cryptoRequest(String operation, String keyArn, String algorithm) {+ String blob = Base64.getEncoder().encodeToString(new byte[64]);+ return switch (operation) {+ case "Sign", "Verify" ->+ "{\"KeyId\":\"%s\",\"Message\":\"bWVzc2FnZQ==\",\"Signature\":\"%s\",\"SigningAlgorithm\":\"%s\"}"+ .formatted(keyArn, blob, algorithm);+ case "GenerateMac", "VerifyMac" ->+ "{\"KeyId\":\"%s\",\"Message\":\"bWVzc2FnZQ==\",\"Mac\":\"%s\",\"MacAlgorithm\":\"%s\"}"+ .formatted(keyArn, blob, algorithm);+ case "Encrypt" -> "{\"KeyId\":\"%s\",\"Plaintext\":\"bWVzc2FnZQ==\",\"EncryptionAlgorithm\":\"%s\"}"+ .formatted(keyArn, algorithm);+ case "Decrypt" -> "{\"KeyId\":\"%s\",\"CiphertextBlob\":\"%s\",\"EncryptionAlgorithm\":\"%s\"}"+ .formatted(keyArn, blob, algorithm);+ case "GenerateDataKey", "GenerateDataKeyWithoutPlaintext" ->+ "{\"KeyId\":\"%s\",\"KeySpec\":\"AES_256\"}".formatted(keyArn);+ case "EnableKey", "DisableKey" -> "{\"KeyId\":\"%s\"}".formatted(keyArn);+ default -> throw new IllegalArgumentException(operation);+ };+ }++ private static Response callKms(String operation, String body) {+ return given()+ .header("X-Amz-Target", "TrentService." + operation)+ .contentType(KMS_CONTENT_TYPE)+ .body(body)+ .when().post("/");+ }++ private static String createKeyArn(String keySpec, String keyUsage) {+ return given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyUsage\":\"%s\",\"KeySpec\":\"%s\"}".formatted(keyUsage, keySpec))+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.Arn");+ }+private static byte[] sha512(byte[] value) {try {return java.security.MessageDigest.getInstance("SHA-512").digest(value);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.javaindex 017bea6e4e..e56f108bff 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@@ -46,6 +46,7 @@ import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.junit.jupiter.params.provider.ValueSource;import static org.junit.jupiter.api.Assertions.*;@@ -124,7 +125,7 @@ class KmsServiceTest {assertEquals(KmsKeyUsage.SIGN_VERIFY, key.getKeyUsage());assertNotNull(key.getPrivateKeyEncoded());assertNotNull(key.getPublicKeyEncoded());- assertTrue(kmsService.verify(key.getKeyId(), message, signature, "SM2DSA", region));+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, signature, "SM2DSA", region));}@Test@@ -1167,7 +1168,8 @@ class KmsServiceTest {kmsService.encrypt(key.getKeyId(), new byte[0], Map.of(), "RSAES_OAEP_SHA_256", REGION));assertEquals("ValidationException", ex.getErrorCode());- assertEquals("Plaintext must be between 1 and 4096 bytes for Encrypt.", ex.getMessage());+ assertEquals("1 validation error detected: Value at 'plaintext' failed to satisfy constraint: "+ + "Member must have length greater than or equal to 1", ex.getMessage());}@Test@@ -1203,10 +1205,10 @@ class KmsServiceTest {KmsKey key = createRsaKey();AwsException ex = assertThrows(AwsException.class, () ->- kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION));+ kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION));assertEquals("InvalidKeyUsageException", ex.getErrorCode());- assertEquals("Algorithm SYMMETRIC_DEFAULT is incompatible with key spec RSA_2048.", ex.getMessage());+ assertEquals("You cannot generate a data key with an asymmetric CMK", ex.getMessage());}@Test@@ -1214,7 +1216,7 @@ class KmsServiceTest {KmsKey key = kmsService.createKey("sign key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);AwsException ex = assertThrows(AwsException.class, () ->- kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION));+ kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION));assertEquals("InvalidKeyUsageException", ex.getErrorCode());assertEquals(key.getArn() + " key usage is SIGN_VERIFY which is not valid for GenerateDataKey.",@@ -1558,14 +1560,19 @@ class KmsServiceTest {}@ParameterizedTest- @ValueSource(strings = {"ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "ECC_SECG_P256K1"})- void signAndVerify(String keySpec) {+ @CsvSource({+ "ECC_NIST_P256, ECDSA_SHA_256",+ "ECC_NIST_P384, ECDSA_SHA_384",+ "ECC_NIST_P521, ECDSA_SHA_512",+ "ECC_SECG_P256K1, ECDSA_SHA_256",+ })+ void signAndVerify(String keySpec, String algorithm) {KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", keySpec, null, Map.of(), REGION);byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);- byte[] sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION);+ byte[] sig = kmsService.sign(key.getKeyId(), message, algorithm, REGION);assertNotNull(sig);- assertTrue(kmsService.verify(key.getKeyId(), message, sig, "ECDSA_SHA_256", REGION));+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig, algorithm, REGION));}@Test@@ -1575,7 +1582,7 @@ class KmsServiceTest {byte[] sig = kmsService.sign(key.getKeyId(), message, "RSASSA_PKCS1_V1_5_SHA_256", REGION);assertNotNull(sig);- assertTrue(kmsService.verify(key.getKeyId(), message, sig, "RSASSA_PKCS1_V1_5_SHA_256", REGION));+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig, "RSASSA_PKCS1_V1_5_SHA_256", REGION));}@Test@@ -1588,7 +1595,7 @@ class KmsServiceTest {"RSASSA_PKCS1_V1_5_SHA_512", KmsMessageType.DIGEST, REGION);// floci's own Verify round-trips.- assertTrue(kmsService.verify(key.getKeyId(), digest, sig,+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), digest, sig,"RSASSA_PKCS1_V1_5_SHA_512", KmsMessageType.DIGEST, REGION));// External verifier (standard JCA, standing in for openssl/python) reconstructs@@ -1631,9 +1638,9 @@ class KmsServiceTest {"RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION);// floci's own Verify round-trips, against the digest and against the raw message.- assertTrue(kmsService.verify(key.getKeyId(), digest, sig,+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), digest, sig,"RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION));- assertTrue(kmsService.verify(key.getKeyId(), message, sig,+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig,"RSASSA_PSS_SHA_256", KmsMessageType.RAW, REGION));// External verifier with the PSS parameters AWS documents for RSASSA_PSS_SHA_256.@@ -1647,34 +1654,52 @@ class KmsServiceTest {}@Test- void signWithInvalidAlgorithmThrowsInvalidSigningAlgorithm() {- var key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);+ void signWithInvalidAlgorithmFailsValidation() {+ KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);- var ex = assertThrows(AwsException.class, () ->+ AwsException ex = assertThrows(AwsException.class, () ->kmsService.sign(key.getKeyId(), "sign me".getBytes(StandardCharsets.UTF_8), "NOT_AN_ALGORITHM", REGION));- assertEquals("InvalidSigningAlgorithmException", ex.getErrorCode());+ assertEquals("ValidationException", ex.getErrorCode());+ assertTrue(ex.getMessage().startsWith(+ "1 validation error detected: Value 'NOT_AN_ALGORITHM' at 'signingAlgorithm' failed to satisfy constraint"));}@Test- void verifyWithInvalidAlgorithmThrowsInvalidSigningAlgorithm() {- var key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);- var message = "sign me".getBytes(StandardCharsets.UTF_8);- var sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION);+ void verifyWithInvalidAlgorithmFailsValidation() {+ KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);+ byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);+ byte[] sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION);- var ex = assertThrows(AwsException.class, () ->+ AwsException ex = assertThrows(AwsException.class, () ->kmsService.verify(key.getKeyId(), message, sig, "NOT_AN_ALGORITHM", REGION));- assertEquals("InvalidSigningAlgorithmException", ex.getErrorCode());+ assertEquals("ValidationException", ex.getErrorCode());}@Test- void verifyWithWrongSignatureReturnsFalse() {+ void verifyWithWrongSignatureThrowsInvalidSignature() {KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);- assertFalse(kmsService.verify(key.getKeyId(), message,+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.verify(key.getKeyId(), message,"not-a-valid-sig".getBytes(StandardCharsets.UTF_8), "ECDSA_SHA_256", REGION));++ assertEquals("KMSInvalidSignatureException", ex.getErrorCode());+ assertNull(ex.getMessage());+ }++ @Test+ void verifyWithCorruptKeyMaterialIsAnInternalFailure() {+ KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);+ KmsKey stored = keyStore.get(REGION + "::" + key.getKeyId()).orElseThrow();+ stored.setPublicKeyEncoded(Base64.getEncoder().encodeToString(new byte[16]));+ keyStore.put(REGION + "::" + key.getKeyId(), stored);++ AwsException ex = assertThrows(AwsException.class, () -> kmsService.verify(key.getKeyId(),+ "sign me".getBytes(StandardCharsets.UTF_8), new byte[64], "ECDSA_SHA_256", REGION));++ assertEquals("InternalFailure", ex.getErrorCode());}@Test@@ -1694,13 +1719,24 @@ class KmsServiceTest {@Testvoid generateDataKey() {KmsKey key = kmsService.createKey(null, REGION);- Map<String, Object> result = kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION);+ Map<String, Object> result = kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION);assertNotNull(result.get("Plaintext"));assertNotNull(result.get("CiphertextBlob"));assertEquals(32, ((byte[]) result.get("Plaintext")).length);}+ @Test+ void generateDataKeyWithoutPlaintextKeepsThePlaintextToItself() {+ KmsKey key = kmsService.createKey(null, REGION);++ Map<String, Object> result = kmsService.generateDataKeyWithoutPlaintext(key.getKeyId(), "AES_256", null,+ Map.of(), REGION);++ assertFalse(result.containsKey("Plaintext"));+ assertNotNull(result.get("CiphertextBlob"));+ }+@Testvoid tagResource() {KmsKey key = kmsService.createKey(null, REGION);@@ -2132,7 +2168,7 @@ class KmsServiceTest {String algo = "RSASSA_PKCS1_V1_5_SHA_256";byte[] sig = kmsService.sign(key.getKeyId(), message, algo, REGION);assertNotNull(sig);- assertTrue(kmsService.verify(key.getKeyId(), message, sig, algo, REGION));+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig, algo, REGION));}@ParameterizedTest@@ -2150,7 +2186,7 @@ class KmsServiceTest {byte[] sig = kmsService.sign(key.getKeyId(), digest, algorithm.getAlgName(), KmsMessageType.DIGEST, REGION);assertNotNull(sig);- assertTrue(kmsService.verify(key.getKeyId(), digest, sig, algorithm.getAlgName(), KmsMessageType.DIGEST, REGION));+ assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), digest, sig, algorithm.getAlgName(), KmsMessageType.DIGEST, REGION));}@Test@@ -2161,7 +2197,8 @@ class KmsServiceTest {String keyId = key.getKeyId();AwsException ex = assertThrows(AwsException.class, () ->kmsService.sign(keyId, message, "RSASSA_PKCS1_V1_5_SHA_256", REGION));- assertEquals("UnsupportedOperationException", ex.getErrorCode());+ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals(key.getArn() + " key usage is ENCRYPT_DECRYPT which is not valid for Sign.", ex.getMessage());}@Test@@ -2261,6 +2298,7 @@ class KmsServiceTest {AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(keyId, token, wrongly, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));assertEquals("InvalidCiphertextException", ex.getErrorCode());+ assertNull(ex.getMessage());assertEquals("PendingImport", kmsService.describeKey(keyId, REGION).getKeyState());}diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyTypesTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyTypesTest.javaindex 77af8a0ff7..e3d4ec7b57 100644--- a/src/test/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyTypesTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyTypesTest.java@@ -7,7 +7,6 @@ import io.github.hectorvent.floci.services.kms.model.KmsMessageType;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;-import org.junit.jupiter.params.provider.EnumSource;import org.junit.jupiter.params.provider.ValueSource;import javax.crypto.Mac;@@ -16,9 +15,11 @@ import java.nio.charset.StandardCharsets;import java.security.GeneralSecurityException;import java.security.MessageDigest;import java.security.SecureRandom;+import java.util.Arrays;import java.util.Base64;import java.util.EnumMap;import java.util.HashMap;+import java.util.List;import java.util.Map;import static org.junit.jupiter.api.Assertions.*;@@ -114,7 +115,8 @@ class KmsKeyTypesTest {"ECC_NIST_EDWARDS25519, ED25519_SHA_512","ML_DSA_44, ML_DSA_SHAKE_256",})- void rawSignatureVerifiesOnlyForTheSignedMessage(KmsKeySpec spec, String algorithm) throws Exception {+ void rawSignatureVerifiesOnlyForTheSignedMessage(KmsKeySpec spec, KmsKeySpec.Algorithm algorithm)+ throws Exception {KmsKey key = generatedKey(spec, REGION);KmsKeyType keyType = keyTypes.of(spec);@@ -125,6 +127,35 @@ class KmsKeyTypesTest {algorithm, KmsMessageType.RAW));}+ @ParameterizedTest+ @CsvSource({+ "RSA_2048, RSASSA_PKCS1_V1_5_SHA_256",+ "RSA_2048, RSASSA_PSS_SHA_256",+ "ECC_NIST_P256, ECDSA_SHA_256",+ "ECC_SECG_P256K1, ECDSA_SHA_256",+ "ECC_NIST_EDWARDS25519, ED25519_SHA_512",+ "ML_DSA_44, ML_DSA_SHAKE_256",+ })+ void malformedSignatureDoesNotVerify(KmsKeySpec spec, KmsKeySpec.Algorithm algorithm) throws Exception {+ KmsKey key = generatedKey(spec, REGION);+ KmsKeyType keyType = keyTypes.of(spec);+ byte[] oversized = new byte[6144];+ Arrays.fill(oversized, (byte) 'a');++ for (byte[] signature : List.of(new byte[]{1}, new byte[64], oversized)) {+ assertFalse(keyType.verify(key, MESSAGE, signature, algorithm, KmsMessageType.RAW));+ }+ }++ @Test+ void corruptPublicKeyThrowsInsteadOfFailingVerification() throws GeneralSecurityException {+ KmsKey key = generatedKey(KmsKeySpec.ECC_NIST_P256, REGION);+ key.setPublicKeyEncoded(Base64.getEncoder().encodeToString(new byte[16]));++ assertThrows(GeneralSecurityException.class, () -> keyTypes.of(KmsKeySpec.ECC_NIST_P256)+ .verify(key, MESSAGE, new byte[64], KmsKeySpec.Algorithm.ECDSA_SHA_256, KmsMessageType.RAW));+ }+@ParameterizedTest@CsvSource({"RSA_2048, RSASSA_PKCS1_V1_5_SHA_256, SHA-256",@@ -132,8 +163,8 @@ class KmsKeyTypesTest {"ECC_NIST_P256, ECDSA_SHA_256, SHA-256","ECC_SECG_P256K1, ECDSA_SHA_256, SHA-256",})- void digestSignatureVerifiesAsARawSignature(KmsKeySpec spec, String algorithm, String digestAlgorithm)- throws Exception {+ void digestSignatureVerifiesAsARawSignature(KmsKeySpec spec, KmsKeySpec.Algorithm algorithm,+ String digestAlgorithm) throws Exception {KmsKey key = generatedKey(spec, REGION);KmsKeyType keyType = keyTypes.of(spec);byte[] digest = MessageDigest.getInstance(digestAlgorithm).digest(MESSAGE);@@ -150,22 +181,10 @@ class KmsKeyTypesTest {KmsKeyType keyType = keyTypes.of(KmsKeySpec.ECC_NIST_EDWARDS25519);byte[] digest = MessageDigest.getInstance("SHA-512").digest(MESSAGE);- byte[] signature = keyType.sign(key, digest, "ED25519_PH_SHA_512", KmsMessageType.DIGEST);+ byte[] signature = keyType.sign(key, digest, KmsKeySpec.Algorithm.ED25519_PH_SHA_512, KmsMessageType.DIGEST);- assertTrue(keyType.verify(key, digest, signature, "ED25519_PH_SHA_512", KmsMessageType.DIGEST));- }-- @ParameterizedTest- @EnumSource(value = KmsKeySpec.class, names = {"ECC_NIST_EDWARDS25519", "ML_DSA_65", "SM2"})- void keyTypesWithOneSigningAlgorithmRejectAnyOther(KmsKeySpec spec) throws GeneralSecurityException {- KmsKey key = generatedKey(spec, "cn-north-1");-- AwsException exception = assertThrows(AwsException.class,- () -> keyTypes.of(spec).sign(key, MESSAGE, "ECDSA_SHA_256", KmsMessageType.RAW));-- assertEquals("InvalidKeyUsageException", exception.getErrorCode());- assertEquals("Algorithm ECDSA_SHA_256 is incompatible with key spec " + spec.name() + ".",- exception.getMessage());+ assertTrue(keyType.verify(key, digest, signature, KmsKeySpec.Algorithm.ED25519_PH_SHA_512,+ KmsMessageType.DIGEST));}@ParameterizedTest@@ -214,9 +233,9 @@ class KmsKeyTypesTest {KmsKey key = generatedKey(KmsKeySpec.SM2, region);KmsKeyType keyType = keyTypes.of(KmsKeySpec.SM2);- byte[] signature = keyType.sign(key, MESSAGE, "SM2DSA", KmsMessageType.RAW);+ byte[] signature = keyType.sign(key, MESSAGE, KmsKeySpec.Algorithm.SM2DSA, KmsMessageType.RAW);- assertTrue(keyType.verify(key, MESSAGE, signature, "SM2DSA", KmsMessageType.RAW));+ assertTrue(keyType.verify(key, MESSAGE, signature, KmsKeySpec.Algorithm.SM2DSA, KmsMessageType.RAW));}@Test@@ -230,19 +249,6 @@ class KmsKeyTypesTest {assertNull(key.getPrivateKeyEncoded());}- @ParameterizedTest- @EnumSource(value = KmsKeySpec.class, names = {"SYMMETRIC_DEFAULT", "HMAC_256"})- void keyTypesWithoutSigningRefuseToSignAndNeverVerify(KmsKeySpec spec) throws Exception {- KmsKey key = generatedKey(spec, REGION);- KmsKeyType keyType = keyTypes.of(spec);-- AwsException exception = assertThrows(AwsException.class,- () -> keyType.sign(key, MESSAGE, "RSASSA_PSS_SHA_256", KmsMessageType.RAW));-- assertEquals("UnsupportedOperationException", exception.getErrorCode());- assertFalse(keyType.verify(key, MESSAGE, new byte[64], "RSASSA_PSS_SHA_256", KmsMessageType.RAW));- }-private KmsKey generatedKey(KmsKeySpec spec, String region) throws GeneralSecurityException {KmsKey key = newKey(spec);keyTypes.of(spec).generateKeyMaterial(key, region);