Light, fluffy, and always free - The AWS Local Emulator alternative
feat(kms): support ImportKeyMaterial for Origin=EXTERNAL keys (#3068)
Matheus Oliveira37faaa8abe0d
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 0fcef928e7..6f5ade1777 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@@ -3,6 +3,7 @@ package com.floci.test;import org.junit.jupiter.api.*;import software.amazon.awssdk.core.SdkBytes;import software.amazon.awssdk.services.kms.KmsClient;+import software.amazon.awssdk.services.kms.model.AlgorithmSpec;import software.amazon.awssdk.services.kms.model.CreateKeyResponse;import software.amazon.awssdk.services.kms.model.DisabledException;import software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec;@@ -12,9 +13,21 @@ import software.amazon.awssdk.services.kms.model.InvalidKeyUsageException;import software.amazon.awssdk.services.kms.model.KeySpec;import software.amazon.awssdk.services.kms.model.KeyUsageType;import software.amazon.awssdk.services.kms.model.KmsInvalidStateException;+import software.amazon.awssdk.services.kms.model.ExpirationModelType;+import software.amazon.awssdk.services.kms.model.KeyState;import software.amazon.awssdk.services.kms.model.ListResourceTagsResponse;+import software.amazon.awssdk.services.kms.model.OriginType;+import software.amazon.awssdk.services.kms.model.WrappingKeySpec;+import javax.crypto.Cipher;+import javax.crypto.spec.OAEPParameterSpec;+import javax.crypto.spec.PSource;import java.nio.charset.StandardCharsets;+import java.security.KeyFactory;+import java.security.PublicKey;+import java.security.spec.MGF1ParameterSpec;+import java.security.spec.X509EncodedKeySpec;+import java.util.Arrays;import java.util.Map;import static org.assertj.core.api.Assertions.*;@@ -28,8 +41,9 @@ import static org.assertj.core.api.Assertions.*;* #1844 — Decrypt enforces KeyId against the wrapping CMK (IncorrectKeyException)* #1844 — ReEncrypt enforces SourceKeyId against the wrapping CMK (IncorrectKeyException)* #3024: Encrypt/Decrypt apply real RSAES-OAEP for RSA keys+ * #1916: ImportKeyMaterial round trip on an Origin=EXTERNAL key*/-@DisplayName("KMS features (#258 #259 #269 #1844 #3024)")+@DisplayName("KMS features (#258 #259 #269 #1844 #1916 #3024)")@TestMethodOrder(MethodOrderer.OrderAnnotation.class)class KmsFeaturesTest {@@ -467,4 +481,70 @@ class KmsFeaturesTest {kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));}}++ @Test+ @Order(80)+ void importedKeyMaterialMakesAnExternalKeyUsable() throws Exception {+ var keyId = kms.createKey(b -> b.origin(OriginType.EXTERNAL)).keyMetadata().keyId();++ try {+ assertThat(kms.describeKey(b -> b.keyId(keyId)).keyMetadata())+ .satisfies(metadata -> {+ assertThat(metadata.origin()).isEqualTo(OriginType.EXTERNAL);+ assertThat(metadata.keyState()).isEqualTo(KeyState.PENDING_IMPORT);+ assertThat(metadata.enabled()).isFalse();+ });++ assertThatThrownBy(() -> kms.encrypt(b -> b+ .keyId(keyId)+ .plaintext(SdkBytes.fromString("secret payload", StandardCharsets.UTF_8))))+ .isInstanceOf(KmsInvalidStateException.class);++ var parameters = kms.getParametersForImport(b -> b+ .keyId(keyId)+ .wrappingAlgorithm(AlgorithmSpec.RSAES_OAEP_SHA_256)+ .wrappingKeySpec(WrappingKeySpec.RSA_2048));++ byte[] material = new byte[32];+ Arrays.fill(material, (byte) 17);+ SdkBytes wrapped = SdkBytes.fromByteArray(+ wrapWithRsaOaepSha256(parameters.publicKey().asByteArray(), material));++ kms.importKeyMaterial(b -> b+ .keyId(keyId)+ .importToken(parameters.importToken())+ .encryptedKeyMaterial(wrapped)+ .expirationModel(ExpirationModelType.KEY_MATERIAL_DOES_NOT_EXPIRE));++ assertThat(kms.describeKey(b -> b.keyId(keyId)).keyMetadata())+ .satisfies(metadata -> {+ assertThat(metadata.keyState()).isEqualTo(KeyState.ENABLED);+ assertThat(metadata.enabled()).isTrue();+ assertThat(metadata.expirationModel())+ .isEqualTo(ExpirationModelType.KEY_MATERIAL_DOES_NOT_EXPIRE);+ });++ var ciphertext = kms.encrypt(b -> b+ .keyId(keyId)+ .plaintext(SdkBytes.fromString("secret payload", StandardCharsets.UTF_8)));+ assertThat(kms.decrypt(b -> b.keyId(keyId).ciphertextBlob(ciphertext.ciphertextBlob()))+ .plaintext().asUtf8String()).isEqualTo("secret payload");++ kms.deleteImportedKeyMaterial(b -> b.keyId(keyId));+ assertThat(kms.describeKey(b -> b.keyId(keyId)).keyMetadata().keyState())+ .isEqualTo(KeyState.PENDING_IMPORT);+ } finally {+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));+ }+ }++ /** Wraps material the way any KMS client does, so the round trip proves wire compatibility. */+ private static byte[] wrapWithRsaOaepSha256(byte[] publicKeyDer, byte[] material) throws Exception {+ PublicKey wrappingKey = KeyFactory.getInstance("RSA")+ .generatePublic(new X509EncodedKeySpec(publicKeyDer));+ Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");+ cipher.init(Cipher.ENCRYPT_MODE, wrappingKey, new OAEPParameterSpec("SHA-256", "MGF1",+ new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT));+ return cipher.doFinal(material);+ }}diff --git a/docs/services/kms.md b/docs/services/kms.mdindex 50030ffab1..0a735b4f99 100644--- a/docs/services/kms.md+++ b/docs/services/kms.md@@ -46,6 +46,9 @@| `EnableKey` | Enable a key || `DisableKey` | Disable a key || `RotateKeyOnDemand` | Rotate key material on demand (symmetric keys only) |+| `GetParametersForImport` | Get the wrapping key and import token for an `EXTERNAL` key |+| `ImportKeyMaterial` | Import key material into an `EXTERNAL` key |+| `DeleteImportedKeyMaterial` | Delete imported key material, returning the key to `PendingImport` |<!-- floci:actions:end -->## Asymmetric Encryption@@ -54,6 +57,54 @@Symmetric keys keep the emulator's internal ciphertext format, which is not compatible with ciphertexts from real AWS KMS.+## Imported Key Material++`CreateKey` accepts `Origin=EXTERNAL`, which creates a key with no key material in state+`PendingImport`. `GetParametersForImport` returns a real RSA public key and an import token;+material wrapped with that public key by a standard client is unwrapped by `ImportKeyMaterial`,+which puts the key in state `Enabled`. Wrapping material against the wrong key, or with a+different algorithm than the one requested, fails with `InvalidCiphertextException` the same way+it does on AWS.++Supported `WrappingAlgorithm` values are `RSAES_OAEP_SHA_256` and `RSAES_OAEP_SHA_1`, over+`WrappingKeySpec` `RSA_2048`, `RSA_3072` or `RSA_4096`. `RSAES_PKCS1_V1_5` is rejected, matching+AWS, which stopped supporting it on October 10, 2023. The `RSA_AES_KEY_WRAP_*` variants exist for+material longer than an RSA modulus can hold and are also rejected: no importable key spec here+carries more than 64 bytes.++An import token is scoped to one key and spent by the import that uses it, and a second+`GetParametersForImport` call invalidates the token the previous one returned. Tokens expire 24+hours after they are issued.++`ExpirationModel=KEY_MATERIAL_EXPIRES` (the default) requires `ValidTo`, which must be in the+future and no more than 365 days out. Once `ValidTo` passes, the material is dropped and the key+returns to `PendingImport`, as does `DeleteImportedKeyMaterial`. Expiry is evaluated when the key+is next read rather than on a timer, which is not observable through the API. Deleting the+material of a key that is already in `PendingDeletion` leaves that state in place.++A key in `PendingImport` rejects cryptographic operations, `EnableKey` and `DisableKey` with+`KMSInvalidStateException`. `CancelKeyDeletion` on a key whose material was never imported, or was+deleted or expired while it was pending deletion, returns it to `PendingImport` rather than to a+usable state it could not serve. `DeleteImportedKeyMaterial` on a key that holds no material+succeeds, as it does on AWS. `ImportKeyMaterial` and `DeleteImportedKeyMaterial` return a+`KeyMaterialId`, derived from the key id and the material as AWS derives it. Re-importing+requires the same material the key was first given; different material is rejected with+`IncorrectKeyMaterialException`.++Automatic key rotation is rejected for keys with imported material, matching AWS: KMS does not+own the material and cannot rotate it.++**Deviations:**++- `Origin=EXTERNAL` is supported only for `SYMMETRIC_DEFAULT` and the `HMAC_*` key specs, whose+ material is a raw byte string. Real AWS KMS also imports asymmetric material as a DER-encoded+ key pair; here an asymmetric spec with `Origin=EXTERNAL` is rejected at `CreateKey` with+ `UnsupportedOperationException` rather than creating a key that could never sign or decrypt.+- Holding several imported key materials on one symmetric key, which real KMS uses for on-demand+ rotation of imported material, is not emulated. `ImportType=NEW_KEY_MATERIAL` on a key that+ already has key material is rejected with `UnsupportedOperationException`, and+ `ListKeyRotations` is not implemented.+## Grant Support ScopeGrant lifecycle operations (`CreateGrant`, `ListGrants`, `ListRetirableGrants`, `RevokeGrant`, `RetireGrant`) are supported. However, grant lifecycle support **does not** imply grant-based authorization enforcement on cryptographic operations (`Encrypt`, `Decrypt`, `Sign`, `Verify`, `GenerateDataKey`, etc.). Grants are stored and queryable but are not evaluated during crypto operations.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 4a9ee1348a..2945ea75ea 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@@ -76,6 +76,9 @@ public class KmsJsonHandler {case "EnableKey" -> handleEnableKey(request, region);case "DisableKey" -> handleDisableKey(request, region);case "RotateKeyOnDemand" -> handleRotateKeyOnDemand(request, region);+ case "GetParametersForImport" -> handleGetParametersForImport(request, region);+ case "ImportKeyMaterial" -> handleImportKeyMaterial(request, region);+ case "DeleteImportedKeyMaterial" -> handleDeleteImportedKeyMaterial(request, region);default -> Response.status(400).entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported.")).build();@@ -92,7 +95,8 @@ public class KmsJsonHandler {Map<String, String> tags = new HashMap<>();request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText()));rejectUnknownReservedTags(tags,"TagException");- KmsKey key = service.createKey(description, keyUsage, keySpec, policy, tags, region);+ String origin = request.path("Origin").asText(null);+ KmsKey key = service.createKey(description, keyUsage, keySpec, policy, tags, origin, region);ObjectNode response = objectMapper.createObjectNode();response.set("KeyMetadata", addKeyMetadata(key));return Response.ok(response).build();@@ -101,16 +105,16 @@ public class KmsJsonHandler {private Response handleGetPublicKey(JsonNode request, String region) {String keyId = request.path("KeyId").asText();KmsKey key = service.getPublicKey(keyId, region);-+ObjectNode response = objectMapper.createObjectNode();response.put("KeyId", key.getArn());response.put("PublicKey", key.getPublicKeyEncoded());response.put("CustomerMasterKeySpec", key.getKeySpec().name());response.put("KeySpec", key.getKeySpec().name());response.put("KeyUsage", key.getKeyUsage().name());-+addAlgorithms(key, response);-+return Response.ok(response).build();}@@ -595,6 +599,68 @@ public class KmsJsonHandler {return Response.ok(response).build();}+ private Response handleGetParametersForImport(JsonNode request, String region) {+ String keyId = requireKeyId(request);+ KmsService.ImportParameters parameters = service.getParametersForImport(+ keyId,+ request.path("WrappingAlgorithm").asText(null),+ request.path("WrappingKeySpec").asText(null),+ region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("KeyId", parameters.keyArn());+ response.put("PublicKey", parameters.publicKeyEncoded());+ response.put("ImportToken", parameters.importToken());+ response.put("ParametersValidTo", parameters.parametersValidTo());+ return Response.ok(response).build();+ }++ private Response handleImportKeyMaterial(JsonNode request, String region) {+ String keyId = requireKeyId(request);+ String importToken = request.path("ImportToken").asText(null);+ byte[] encryptedKeyMaterial = requireBlob(request, "EncryptedKeyMaterial");+ Long validTo = request.hasNonNull("ValidTo") ? request.path("ValidTo").asLong() : null;++ KmsKey key = service.importKeyMaterial(keyId, importToken, encryptedKeyMaterial,+ request.path("ExpirationModel").asText(null), validTo,+ request.path("ImportType").asText(null), region);++ ObjectNode response = objectMapper.createObjectNode();+ response.put("KeyId", key.getArn());+ response.put("KeyMaterialId", key.getKeyMaterialId());+ return Response.ok(response).build();+ }++ private Response handleDeleteImportedKeyMaterial(JsonNode request, String region) {+ KmsKey key = service.deleteImportedKeyMaterial(requireKeyId(request), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.put("KeyId", key.getArn());+ if (key.getKeyMaterialId() != null) {+ response.put("KeyMaterialId", key.getKeyMaterialId());+ }+ return Response.ok(response).build();+ }++ private static String requireKeyId(JsonNode request) {+ String keyId = request.path("KeyId").asText(null);+ if (keyId == null || keyId.isBlank()) {+ throw new AwsException("ValidationException", "KeyId is required.", 400);+ }+ return keyId;+ }++ /**+ * A required blob member. {@link #decodeBlob} reads a missing member as an empty blob, which+ * would reach the operation as key material of the wrong length instead of the absent member+ * it actually is.+ */+ private static byte[] requireBlob(JsonNode request, String member) {+ if (!request.path(member).isTextual()) {+ throw new AwsException("ValidationException", member + " is required.", 400);+ }+ return decodeBlob(request, member);+ }+private ObjectNode addKeyMetadata(KmsKey k) {ObjectNode keyMetadata = objectMapper.createObjectNode();keyMetadata.put("AWSAccountId", regionResolver.getAccountId());@@ -605,7 +671,13 @@ public class KmsJsonHandler {keyMetadata.put("Description", k.getDescription());keyMetadata.put("KeyUsage", k.getKeyUsage().name());keyMetadata.put("KeyState", k.getKeyState());- keyMetadata.put("Origin", "AWS_KMS");+ keyMetadata.put("Origin", k.getOrigin());+ if (k.getExpirationModel() != null) {+ keyMetadata.put("ExpirationModel", k.getExpirationModel());+ }+ if (k.getValidTo() > 0) {+ keyMetadata.put("ValidTo", k.getValidTo());+ }keyMetadata.put("KeyManager", "CUSTOMER");keyMetadata.put("CustomerMasterKeySpec", k.getKeySpec().name());keyMetadata.put("KeySpec", k.getKeySpec().name());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.javanew file mode 100644index 0000000000..bcd9936251--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.java@@ -0,0 +1,118 @@+package io.github.hectorvent.floci.services.kms;++import io.github.hectorvent.floci.core.common.AwsException;+import org.jboss.logging.Logger;++import javax.crypto.Cipher;+import javax.crypto.spec.OAEPParameterSpec;+import javax.crypto.spec.PSource;+import java.security.KeyFactory;+import java.security.KeyPair;+import java.security.KeyPairGenerator;+import java.security.NoSuchAlgorithmException;+import java.security.PrivateKey;+import java.security.spec.MGF1ParameterSpec;+import java.security.spec.PKCS8EncodedKeySpec;+import java.util.Base64;++/**+ * The cryptography behind the KMS import-key-material flow: the RSA wrapping key pair+ * GetParametersForImport hands out, and the unwrap ImportKeyMaterial performs on what comes+ * back.+ *+ * <p>Stateless on purpose. {@link KmsService} owns the import state machine, the token and the+ * store; this class only knows how to mint a wrapping key and how to open material wrapped+ * with one.+ */+final class KmsKeyImport {++ private static final Logger LOG = Logger.getLogger(KmsKeyImport.class);++ private static final String RSAES_PKCS1_V1_5 = "RSAES_PKCS1_V1_5";+ private static final String RSAES_OAEP_SHA_1 = "RSAES_OAEP_SHA_1";+ private static final String RSAES_OAEP_SHA_256 = "RSAES_OAEP_SHA_256";++ private KmsKeyImport() {+ }++ /**+ * An RSA wrapping key pair, both halves Base64-encoded. The public half goes to the caller+ * so it can wrap its key material; the private half stays on the KMS key so a later+ * ImportKeyMaterial can unwrap what the caller sends back.+ */+ record WrappingKeyPair(String publicKeyEncoded, String privateKeyEncoded) {+ }++ static WrappingKeyPair generateWrappingKeyPair(String wrappingKeySpec) {+ int keySize = switch (wrappingKeySpec == null ? "" : wrappingKeySpec) {+ case "RSA_2048" -> 2048;+ case "RSA_3072" -> 3072;+ case "RSA_4096" -> 4096;+ case "SM2" -> throw new AwsException("UnsupportedOperationException",+ "WrappingKeySpec SM2 is not supported.", 400);+ default -> throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + wrappingKeySpec + "' at 'wrappingKeySpec' failed to "+ + "satisfy constraint: Member must satisfy enum value set: "+ + "[RSA_2048, RSA_3072, RSA_4096, SM2]", 400);+ };+ try {+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");+ generator.initialize(keySize);+ KeyPair pair = generator.generateKeyPair();+ return new WrappingKeyPair(+ Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()),+ Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));+ } catch (NoSuchAlgorithmException e) {+ throw new AwsException("InternalFailure", "Failed to generate wrapping key: " + e.getMessage(), 500);+ }+ }++ /**+ * Rejects a WrappingAlgorithm this emulator cannot honour before a key pair is generated for+ * it, so a caller never wraps material against parameters that ImportKeyMaterial would then+ * refuse.+ *+ * <p>RSAES_PKCS1_V1_5 stays in the modelled enum but AWS KMS stopped honouring it on+ * October 10, 2023. The RSA_AES variants exist for material longer than an RSA modulus can+ * hold; every spec that can be imported here carries at most 64 bytes.+ */+ static void validateWrappingAlgorithm(String wrappingAlgorithm) {+ switch (wrappingAlgorithm == null ? "" : wrappingAlgorithm) {+ case RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256 -> { }+ case RSAES_PKCS1_V1_5 -> throw new AwsException("UnsupportedOperationException",+ "AWS KMS stopped supporting the RSAES_PKCS1_V1_5 wrapping algorithm on October 10, 2023. "+ + "Use RSAES_OAEP_SHA_256 or RSAES_OAEP_SHA_1.", 400);+ case "RSA_AES_KEY_WRAP_SHA_1", "RSA_AES_KEY_WRAP_SHA_256", "SM2PKE" ->+ throw new AwsException("UnsupportedOperationException",+ "WrappingAlgorithm " + wrappingAlgorithm + " is not supported. Supported values are "+ + "RSAES_OAEP_SHA_256 and RSAES_OAEP_SHA_1.", 400);+ default -> throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + wrappingAlgorithm + "' at 'wrappingAlgorithm' failed "+ + "to satisfy constraint: Member must satisfy enum value set: "+ + "[RSAES_OAEP_SHA_256, RSAES_OAEP_SHA_1, RSA_AES_KEY_WRAP_SHA_256, "+ + "RSA_AES_KEY_WRAP_SHA_1, SM2PKE, RSAES_PKCS1_V1_5]", 400);+ }+ }++ /**+ * Unwraps key material with the private half of the pair issued for this import.+ *+ * <p>Every failure answers InvalidCiphertextException, matching real KMS: whether the bytes+ * were garbage, wrapped for a different key, or wrapped with a different algorithm than the+ * one requested is not something the caller gets to distinguish.+ */+ static byte[] unwrap(String wrappingPrivateKeyEncoded, String wrappingAlgorithm, byte[] encryptedKeyMaterial) {+ try {+ PrivateKey wrappingKey = KeyFactory.getInstance("RSA").generatePrivate(+ new PKCS8EncodedKeySpec(Base64.getDecoder().decode(wrappingPrivateKeyEncoded)));+ String digest = RSAES_OAEP_SHA_1.equals(wrappingAlgorithm) ? "SHA-1" : "SHA-256";+ Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");+ cipher.init(Cipher.DECRYPT_MODE, wrappingKey, new OAEPParameterSpec(digest, "MGF1",+ new MGF1ParameterSpec(digest), PSource.PSpecified.DEFAULT));+ 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);+ }+ }+}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 e4cb68f20c..5118bbb1c4 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@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.kms.model.KmsAlias;import io.github.hectorvent.floci.services.kms.model.KmsGrant;+import io.github.hectorvent.floci.services.kms.model.KmsImportParameters;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.KmsKeyUsage;@@ -71,6 +72,7 @@ import java.security.spec.MGF1ParameterSpec;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.PSSParameterSpec;import java.security.spec.X509EncodedKeySpec;+import java.time.Duration;import java.time.Instant;import java.util.*;import java.util.concurrent.ThreadLocalRandom;@@ -83,6 +85,16 @@ public class KmsService implements ResourceProvider {private static final Logger LOG = Logger.getLogger(KmsService.class);+ private static final String AWS_KMS_ORIGIN = "AWS_KMS";+ private static final String EXTERNAL_ORIGIN = "EXTERNAL";+ private static final String PENDING_IMPORT = "PendingImport";+ private static final String PENDING_DELETION = "PendingDeletion";+ private static final String KEY_MATERIAL_EXPIRES = "KEY_MATERIAL_EXPIRES";+ private static final String KEY_MATERIAL_DOES_NOT_EXPIRE = "KEY_MATERIAL_DOES_NOT_EXPIRE";+ private static final Duration IMPORT_PARAMETERS_VALIDITY = Duration.ofHours(24);+ private static final Duration MAX_KEY_MATERIAL_VALIDITY = Duration.ofDays(365);+ private static final int IMPORT_TOKEN_BYTES = 32;+private final StorageBackend<String, KmsKey> keyStore;private final StorageBackend<String, KmsAlias> aliasStore;private final StorageBackend<String, KmsGrant> grantStore;@@ -146,6 +158,11 @@ public class KmsService implements ResourceProvider {}public KmsKey createKey(String description, String keyUsage, String keySpec, String policy, Map<String, String> tags, String region) {+ return createKey(description, keyUsage, keySpec, policy, tags, null, region);+ }++ public KmsKey createKey(String description, String keyUsage, String keySpec, String policy,+ Map<String, String> tags, String origin, String region) {String keyId = resolveKeyId(tags);if (keyStore.get(region + "::" + keyId).isPresent()) {throw new AwsException("AlreadyExistsException", "Key already exists", 400);@@ -168,11 +185,18 @@ public class KmsService implements ResourceProvider {key.setKeySpec(effectiveSpec);key.setPolicy(policy != null ? policy : buildDefaultKeyPolicy());key.getTags().putAll(ReservedTags.stripReservedTags(tags));+ key.setOrigin(resolveOrigin(origin, effectiveSpec));- generateKeyMaterial(key);+ if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {+ key.setKeyState(PENDING_IMPORT);+ key.setEnabled(false);+ } else {+ generateKeyMaterial(key);+ }keyStore.put(region + "::" + keyId, key);- LOG.infov("Created KMS key: {0} ({1}/{2}) in {3}", keyId, key.getKeyUsage(), key.getKeySpec(), region);+ LOG.infov("Created KMS key: {0} ({1}/{2}, origin {3}) in {4}",+ keyId, key.getKeyUsage(), key.getKeySpec(), key.getOrigin(), region);return key;}@@ -268,14 +292,11 @@ public class KmsService implements ResourceProvider {}private static int hmacKeyByteLength(KmsKeySpec spec) {- return switch (spec) {- case HMAC_224 -> 28;- case HMAC_256 -> 32;- case HMAC_384 -> 48;- case HMAC_512 -> 64;- default -> throw new AwsException("InvalidCustomerMasterKeySpecException",+ if (!isHmac(spec)) {+ throw new AwsException("InvalidCustomerMasterKeySpecException","Unsupported HMAC key spec: " + spec, 400);- };+ }+ return spec.materialByteLength();}public KmsKey describeKey(String keyId, String region) {@@ -595,13 +616,27 @@ public class KmsService implements ResourceProvider {keyStore.put(region + "::" + key.getKeyId(), key);}+ /**+ * A key whose material was never imported, or was deleted or expired while it sat pending+ * deletion, has nothing to come back to: it returns to PendingImport rather than to a usable+ * state that no cryptographic operation could actually serve.+ */public void cancelKeyDeletion(String keyId, String region) {KmsKey key = resolveKey(keyId, region);- key.setKeyState("Enabled");+ if (lacksImportedKeyMaterial(key)) {+ key.setKeyState(PENDING_IMPORT);+ key.setEnabled(false);+ } else {+ key.setKeyState("Enabled");+ }key.setDeletionDate(0);keyStore.put(region + "::" + key.getKeyId(), key);}+ private static boolean lacksImportedKeyMaterial(KmsKey key) {+ return EXTERNAL_ORIGIN.equals(key.getOrigin()) && key.getPrivateKeyEncoded() == null;+ }+public Map<String, Object> getKeyPolicy(String keyId, String region) {KmsKey key = resolveKey(keyId, region);Map<String, Object> result = new HashMap<>();@@ -674,10 +709,11 @@ public class KmsService implements ResourceProvider {public void enableKey(String keyId, String region) {KmsKey key = resolveKey(keyId, region);- if ("PendingDeletion".equals(key.getKeyState())) {+ if (PENDING_DELETION.equals(key.getKeyState())) {throw new AwsException("KMSInvalidStateException","KMS key " + key.getKeyId() + " is pending deletion.", 400);}+ requireImportedKeyMaterial(key, "EnableKey");key.setEnabled(true);key.setKeyState("Enabled");keyStore.put(region + "::" + key.getKeyId(), key);@@ -686,6 +722,7 @@ public class KmsService implements ResourceProvider {public void disableKey(String keyId, String region) {KmsKey key = resolveKey(keyId, region);+ requireImportedKeyMaterial(key, "DisableKey");key.setEnabled(false);key.setKeyState("Disabled");keyStore.put(region + "::" + key.getKeyId(), key);@@ -710,6 +747,12 @@ public class KmsService implements ResourceProvider {}private void validateRotationSupported(KmsKey key) {+ if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {+ throw new AwsException(+ "UnsupportedOperationException",+ "You cannot enable automatic rotation of imported key material.",+ 400);+ }if (KmsKeyUsage.ENCRYPT_DECRYPT != key.getKeyUsage()|| KmsKeySpec.SYMMETRIC_DEFAULT != key.getKeySpec()) {throw new AwsException(@@ -719,6 +762,294 @@ public class KmsService implements ResourceProvider {}}+ /** The wrapping parameters GetParametersForImport hands back to the caller. */+ public record ImportParameters(String keyArn, String publicKeyEncoded, String importToken,+ long parametersValidTo) {+ }++ public ImportParameters getParametersForImport(String keyId, String wrappingAlgorithm,+ String wrappingKeySpec, String region) {+ KmsKey key = resolveKey(keyId, region);+ requireExternalOrigin(key, "GetParametersForImport");+ requireNotPendingDeletion(key);+ KmsKeyImport.validateWrappingAlgorithm(wrappingAlgorithm);++ KmsKeyImport.WrappingKeyPair wrappingKeyPair = KmsKeyImport.generateWrappingKeyPair(wrappingKeySpec);+ KmsImportParameters parameters = new KmsImportParameters();+ parameters.setWrappingPrivateKeyEncoded(wrappingKeyPair.privateKeyEncoded());+ parameters.setWrappingAlgorithm(wrappingAlgorithm);+ parameters.setImportToken(newImportToken());+ parameters.setParametersValidTo(Instant.now().plus(IMPORT_PARAMETERS_VALIDITY).getEpochSecond());+ key.setImportParameters(parameters);+ keyStore.put(region + "::" + key.getKeyId(), key);++ LOG.infov("Issued import parameters for KMS key {0} in {1} ({2}/{3})",+ key.getKeyId(), region, wrappingAlgorithm, wrappingKeySpec);+ return new ImportParameters(key.getArn(), wrappingKeyPair.publicKeyEncoded(),+ parameters.getImportToken(), parameters.getParametersValidTo());+ }++ /**+ * Unwraps and installs key material, which takes the key from PendingImport to Enabled. The+ * import token is spent by the call that uses it, as it is on real KMS.+ */+ 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");+ requireNotPendingDeletion(key);+ validateImportType(importType, key);++ KmsImportParameters parameters = requireCurrentImportToken(key);+ if (!parameters.getImportToken().equals(importToken)) {+ throw new AwsException("InvalidImportTokenException",+ "The import token is invalid or was not issued for this KMS key.", 400);+ }+ String effectiveExpirationModel = resolveExpirationModel(expirationModel, validTo);++ byte[] material = KmsKeyImport.unwrap(parameters.getWrappingPrivateKeyEncoded(),+ parameters.getWrappingAlgorithm(), encryptedKeyMaterial);+ validateMaterialLength(key, material);+ String keyMaterialId = keyMaterialId(key.getKeyId(), material);+ requireSameMaterialAsFirstImport(key, keyMaterialId);++ key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(material));+ key.setKeyMaterialId(keyMaterialId);+ key.setExpirationModel(effectiveExpirationModel);+ key.setValidTo(KEY_MATERIAL_EXPIRES.equals(effectiveExpirationModel) ? validTo : 0L);+ key.setKeyState("Enabled");+ key.setEnabled(true);+ key.setImportParameters(null);+ keyStore.put(region + "::" + key.getKeyId(), key);++ LOG.infov("Imported key material into KMS key {0} in {1} ({2})",+ key.getKeyId(), region, effectiveExpirationModel);+ return key;+ }++ /**+ * Deleting material from a key that is already pending deletion leaves the key state alone,+ * as it does on AWS: PendingDeletion outranks the PendingImport this would otherwise set.+ */+ public KmsKey deleteImportedKeyMaterial(String keyId, String region) {+ KmsKey key = resolveKey(keyId, region);+ requireExternalOrigin(key, "DeleteImportedKeyMaterial");+ clearImportedKeyMaterial(key);+ keyStore.put(region + "::" + key.getKeyId(), key);+ LOG.infov("Deleted imported key material for KMS key {0} in {1}", key.getKeyId(), region);+ return key;+ }++ /**+ * Real KMS deletes expired imported key material on its own schedule. With no scheduler here+ * the check runs on the next read of the key instead, which is not observable from outside:+ * nothing can reach a key without going through this path first.+ */+ private KmsKey expireImportedKeyMaterialIfDue(KmsKey key, String region) {+ boolean expires = EXTERNAL_ORIGIN.equals(key.getOrigin())+ && KEY_MATERIAL_EXPIRES.equals(key.getExpirationModel())+ && key.getValidTo() > 0;+ boolean holdsMaterial = !PENDING_IMPORT.equals(key.getKeyState())+ && !PENDING_DELETION.equals(key.getKeyState());+ if (!expires || !holdsMaterial || key.getValidTo() > Instant.now().getEpochSecond()) {+ return key;+ }+ clearImportedKeyMaterial(key);+ keyStore.put(region + "::" + key.getKeyId(), key);+ LOG.infov("Imported key material for KMS key {0} in {1} expired; key is back in PendingImport",+ key.getKeyId(), region);+ return key;+ }++ /**+ * Drops the material but keeps {@code keyMaterialId}: KMS still refuses different material on+ * a later re-import, so what the key was originally given has to outlive the material itself.+ */+ private static void clearImportedKeyMaterial(KmsKey key) {+ key.setPrivateKeyEncoded(null);+ key.setExpirationModel(null);+ key.setValidTo(0);+ key.setImportParameters(null);+ if (PENDING_DELETION.equals(key.getKeyState())) {+ return;+ }+ key.setEnabled(false);+ key.setKeyState(PENDING_IMPORT);+ }++ private String newImportToken() {+ byte[] token = new byte[IMPORT_TOKEN_BYTES];+ SECURE_RANDOM.nextBytes(token);+ return Base64.getEncoder().encodeToString(token);+ }++ private static KmsImportParameters requireCurrentImportToken(KmsKey key) {+ KmsImportParameters parameters = key.getImportParameters();+ if (parameters == null) {+ throw new AwsException("InvalidImportTokenException",+ "No import parameters are outstanding for this KMS key. "+ + "Call GetParametersForImport first.", 400);+ }+ if (parameters.getParametersValidTo() < Instant.now().getEpochSecond()) {+ throw new AwsException("ExpiredImportTokenException",+ "The import token has expired. Call GetParametersForImport for new parameters.", 400);+ }+ return parameters;+ }++ private static String resolveExpirationModel(String expirationModel, Long validTo) {+ String effective = (expirationModel == null || expirationModel.isBlank())+ ? KEY_MATERIAL_EXPIRES : expirationModel;+ switch (effective) {+ case KEY_MATERIAL_EXPIRES -> {+ if (validTo == null) {+ throw new AwsException("ValidationException",+ "ValidTo is required when ExpirationModel is KEY_MATERIAL_EXPIRES.", 400);+ }+ validateValidTo(validTo);+ }+ case KEY_MATERIAL_DOES_NOT_EXPIRE -> {+ if (validTo != null) {+ throw new AwsException("ValidationException",+ "ValidTo must not be set when ExpirationModel is "+ + "KEY_MATERIAL_DOES_NOT_EXPIRE.", 400);+ }+ }+ default -> throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + expirationModel + "' at 'expirationModel' failed to "+ + "satisfy constraint: Member must satisfy enum value set: "+ + "[KEY_MATERIAL_EXPIRES, KEY_MATERIAL_DOES_NOT_EXPIRE]", 400);+ }+ return effective;+ }++ private static void validateValidTo(long validTo) {+ long now = Instant.now().getEpochSecond();+ if (validTo <= now) {+ throw new AwsException("ValidationException",+ "ValidTo must be a future date and time.", 400);+ }+ if (validTo > now + MAX_KEY_MATERIAL_VALIDITY.toSeconds()) {+ throw new AwsException("ValidationException",+ "ValidTo must be no more than 365 days from the request date.", 400);+ }+ }++ /**+ * Multi-material rotation, where a symmetric key holds several imported materials at once, is+ * not emulated. NEW_KEY_MATERIAL on a key that already has material is refused outright rather+ * than reported as material that fails to match.+ */+ private static void validateImportType(String importType, KmsKey key) {+ if (importType == null || importType.isBlank()) {+ return;+ }+ switch (importType) {+ case "NEW_KEY_MATERIAL" -> {+ if (key.getKeyMaterialId() != null) {+ throw new AwsException("UnsupportedOperationException",+ "Importing additional key material into a KMS key that already has key material "+ + "is not supported. Reimport the existing key material instead.", 400);+ }+ }+ case "EXISTING_KEY_MATERIAL" -> {+ if (key.getKeyMaterialId() == null) {+ throw new AwsException("IncorrectKeyMaterialException",+ "No key material has ever been imported into this KMS key, so there is no "+ + "existing key material to reimport.", 400);+ }+ }+ default -> throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + importType + "' at 'importType' failed to "+ + "satisfy constraint: Member must satisfy enum value set: "+ + "[NEW_KEY_MATERIAL, EXISTING_KEY_MATERIAL]", 400);+ }+ }++ private static void validateMaterialLength(KmsKey key, byte[] material) {+ int expected = key.getKeySpec().materialByteLength();+ if (material.length != expected) {+ throw new AwsException("IncorrectKeyMaterialException",+ "Key material for key spec " + key.getKeySpec() + " must be " + expected+ + " bytes but was " + material.length + " bytes.", 400);+ }+ }++ private static void requireSameMaterialAsFirstImport(KmsKey key, String keyMaterialId) {+ if (key.getKeyMaterialId() != null && !key.getKeyMaterialId().equals(keyMaterialId)) {+ throw new AwsException("IncorrectKeyMaterialException",+ "The key material does not match the key material that was previously imported "+ + "into this KMS key.", 400);+ }+ }++ /**+ * KMS derives a key material id from the KMS key id and the material itself. Deriving it the+ * same way identifies imported material without keeping a second copy of it: a re-import only+ * has to prove it carries the same bytes, never to have them read back.+ */+ private static String keyMaterialId(String keyId, byte[] material) {+ try {+ MessageDigest digest = MessageDigest.getInstance("SHA-256");+ digest.update(keyId.getBytes(StandardCharsets.UTF_8));+ digest.update(material);+ return HexFormat.of().formatHex(digest.digest());+ } catch (NoSuchAlgorithmException e) {+ throw new AwsException("InternalFailure", "SHA-256 unavailable", 500);+ }+ }++ private static String resolveOrigin(String origin, KmsKeySpec spec) {+ String effective = (origin == null || origin.isBlank()) ? AWS_KMS_ORIGIN : origin;+ return switch (effective) {+ case AWS_KMS_ORIGIN -> effective;+ case EXTERNAL_ORIGIN -> requireImportableSpec(spec);+ case "AWS_CLOUDHSM", "EXTERNAL_KEY_STORE" -> throw new AwsException("UnsupportedOperationException",+ "Origin " + effective + " is not supported.", 400);+ default -> throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + origin + "' at 'origin' failed to satisfy "+ + "constraint: Member must satisfy enum value set: "+ + "[AWS_KMS, EXTERNAL, AWS_CLOUDHSM, EXTERNAL_KEY_STORE]", 400);+ };+ }++ /**+ * Imported material here is a raw byte string, which covers SYMMETRIC_DEFAULT and the HMAC+ * specs. Real KMS also imports asymmetric material as a DER key pair; refusing it outright+ * beats accepting a key that could never sign or decrypt anything.+ */+ private static String requireImportableSpec(KmsKeySpec spec) {+ if (spec != KmsKeySpec.SYMMETRIC_DEFAULT && spec.getKeyType() != KmsKeySpec.KeyType.HMAC) {+ throw new AwsException("UnsupportedOperationException",+ "Origin EXTERNAL is only supported for SYMMETRIC_DEFAULT and HMAC key specs, not "+ + spec + ".", 400);+ }+ return EXTERNAL_ORIGIN;+ }++ private static void requireExternalOrigin(KmsKey key, String operation) {+ 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);+ }+ }++ private static void requireNotPendingDeletion(KmsKey key) {+ if (PENDING_DELETION.equals(key.getKeyState())) {+ throw new AwsException("KMSInvalidStateException",+ "KMS key " + key.getKeyId() + " is pending deletion.", 400);+ }+ }++ private static void requireImportedKeyMaterial(KmsKey key, String operation) {+ 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);+ }+ }+// ──────────────────────────── Aliases ────────────────────────────public void createAlias(String aliasName, String targetKeyId, String region) {@@ -1240,6 +1571,7 @@ public class KmsService implements ResourceProvider {private KmsKey validateMacOperationKey(String keyId, String algorithm, String region) {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",@@ -1600,18 +1932,20 @@ public class KmsService implements ResourceProvider {}// Key id- return keyStore.get(region + "::" + id)+ KmsKey key = keyStore.get(region + "::" + id).orElseThrow(() -> new AwsException("NotFoundException", "Key not found: " + keyIdOrArn, 404));+ return expireImportedKeyMaterialIfDue(key, region);}private static void validateKeyIsUsableForCryptoOperations(KmsKey key) {- if ("PendingDeletion".equals(key.getKeyState())) {+ if (PENDING_DELETION.equals(key.getKeyState())) {throw new AwsException("KMSInvalidStateException","KMS key " + key.getKeyId() + " is pending deletion.",400);}+ requireImportedKeyMaterial(key, "This operation");if (!key.isEnabled()) {throw new AwsException("DisabledException",diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsImportParameters.java b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsImportParameters.javanew file mode 100644index 0000000000..d0e2a55c64--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsImportParameters.java@@ -0,0 +1,37 @@+package io.github.hectorvent.floci.services.kms.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * The wrapping material GetParametersForImport issued for one KMS key, held until+ * ImportKeyMaterial consumes it.+ *+ * <p>It lives on the key rather than in a store of its own because KMS scopes an import+ * token to a single key and lets only the most recent one work: a second+ * GetParametersForImport call replaces these parameters, which invalidates the token the+ * first call handed out.+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class KmsImportParameters {++ private String wrappingPrivateKeyEncoded;+ private String wrappingAlgorithm;+ private String importToken;+ private long parametersValidTo;++ public String getWrappingPrivateKeyEncoded() { return wrappingPrivateKeyEncoded; }+ public void setWrappingPrivateKeyEncoded(String wrappingPrivateKeyEncoded) {+ this.wrappingPrivateKeyEncoded = wrappingPrivateKeyEncoded;+ }++ public String getWrappingAlgorithm() { return wrappingAlgorithm; }+ public void setWrappingAlgorithm(String wrappingAlgorithm) { this.wrappingAlgorithm = wrappingAlgorithm; }++ public String getImportToken() { return importToken; }+ public void setImportToken(String importToken) { this.importToken = importToken; }++ public long getParametersValidTo() { return parametersValidTo; }+ public void setParametersValidTo(long parametersValidTo) { this.parametersValidTo = parametersValidTo; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.javaindex 5ae062c80e..9e5a626586 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java@@ -14,7 +14,12 @@ public class KmsKey {private String arn;private String description;private boolean enabled = true;- private String keyState = "Enabled"; // Enabled, Disabled, PendingDeletion+ private String keyState = "Enabled"; // Enabled, Disabled, PendingDeletion, PendingImport+ private String origin = "AWS_KMS";+ private String expirationModel;+ private long validTo;+ private KmsImportParameters importParameters;+ private String keyMaterialId;private KmsKeyUsage keyUsage = KmsKeyUsage.ENCRYPT_DECRYPT;private KmsKeySpec keySpec = KmsKeySpec.SYMMETRIC_DEFAULT;private long creationDate;@@ -45,6 +50,23 @@ public class KmsKey {public String getKeyState() { return keyState; }public void setKeyState(String keyState) { this.keyState = keyState; }+ public String getOrigin() { return origin; }+ public void setOrigin(String origin) { this.origin = origin; }++ public String getExpirationModel() { return expirationModel; }+ public void setExpirationModel(String expirationModel) { this.expirationModel = expirationModel; }++ public long getValidTo() { return validTo; }+ public void setValidTo(long validTo) { this.validTo = validTo; }++ public KmsImportParameters getImportParameters() { return importParameters; }+ public void setImportParameters(KmsImportParameters importParameters) {+ this.importParameters = importParameters;+ }++ public String getKeyMaterialId() { return keyMaterialId; }+ public void setKeyMaterialId(String keyMaterialId) { this.keyMaterialId = keyMaterialId; }+public KmsKeyUsage getKeyUsage() { return keyUsage; }public void setKeyUsage(KmsKeyUsage keyUsage) { this.keyUsage = keyUsage; }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 c293de0c7a..050d3301cd 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@@ -102,6 +102,23 @@ public enum KmsKeySpec {};}+ /**+ * Length in bytes of the raw key material for the specs whose material is a byte string:+ * SYMMETRIC_DEFAULT and the HMAC family. Asymmetric specs carry a DER-encoded key pair with+ * no single length, so they have none.+ */+ public int materialByteLength() {+ return switch (this) {+ case SYMMETRIC_DEFAULT -> 32;+ case HMAC_224 -> 28;+ case HMAC_256 -> 32;+ case HMAC_384 -> 48;+ case HMAC_512 -> 64;+ default -> throw new AwsException("InvalidCustomerMasterKeySpecException",+ "Key spec " + this + " has no fixed key material length.", 400);+ };+ }+public enum KeyType {RSA, ECC, ED25519, SYMMETRIC, HMAC, ML_DSA, SM2}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 6a646aacfd..9379d6abae 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@@ -7,13 +7,22 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;+import javax.crypto.Cipher;+import javax.crypto.spec.OAEPParameterSpec;+import javax.crypto.spec.PSource;import java.nio.charset.StandardCharsets;+import java.security.KeyFactory;+import java.security.PublicKey;+import java.security.spec.MGF1ParameterSpec;+import java.security.spec.X509EncodedKeySpec;+import java.util.Arrays;import java.util.Base64;import java.util.List;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.equalTo;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.startsWith;@@ -1754,4 +1763,191 @@ class KmsIntegrationTest {.then().statusCode(200).extract().path("KeyMetadata.KeyId");}++ @Test+ void importKeyMaterialRoundTripEnablesAnExternalKey() throws Exception {+ String keyId = createExternalSymmetricKey();++ describeKey(keyId)+ .body("KeyMetadata.Origin", equalTo("EXTERNAL"))+ .body("KeyMetadata.KeyState", equalTo("PendingImport"))+ .body("KeyMetadata.Enabled", equalTo(false));++ given()+ .header("X-Amz-Target", "TrentService.Encrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\"}"+ .formatted(keyId, Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8))))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("KMSInvalidStateException"));++ var parameters = given()+ .header("X-Amz-Target", "TrentService.GetParametersForImport")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSAES_OAEP_SHA_256\",\"WrappingKeySpec\":\"RSA_2048\"}"+ .formatted(keyId))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("KeyId", startsWith("arn:aws:kms:"))+ .body("PublicKey", notNullValue())+ .body("ImportToken", notNullValue())+ .body("ParametersValidTo", notNullValue())+ .extract().jsonPath();++ byte[] material = new byte[32];+ Arrays.fill(material, (byte) 11);+ String wrapped = Base64.getEncoder().encodeToString(+ wrapWithRsaOaepSha256(parameters.getString("PublicKey"), material));++ given()+ .header("X-Amz-Target", "TrentService.ImportKeyMaterial")+ .contentType(KMS_CONTENT_TYPE)+ .body(("{\"KeyId\":\"%s\",\"ImportToken\":\"%s\",\"EncryptedKeyMaterial\":\"%s\","+ + "\"ExpirationModel\":\"KEY_MATERIAL_DOES_NOT_EXPIRE\"}")+ .formatted(keyId, parameters.getString("ImportToken"), wrapped))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("KeyId", startsWith("arn:aws:kms:"))+ .body("KeyMaterialId", matchesPattern("[a-f0-9]{64}"));++ describeKey(keyId)+ .body("KeyMetadata.KeyState", equalTo("Enabled"))+ .body("KeyMetadata.Enabled", equalTo(true))+ .body("KeyMetadata.Origin", equalTo("EXTERNAL"))+ .body("KeyMetadata.ExpirationModel", equalTo("KEY_MATERIAL_DOES_NOT_EXPIRE"))+ .body("KeyMetadata", not(hasKey("ValidTo")));++ given()+ .header("X-Amz-Target", "TrentService.Encrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\"}"+ .formatted(keyId, Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8))))+ .when().post("/")+ .then().statusCode(200);+ }++ @Test+ void deleteImportedKeyMaterialReturnsTheKeyToPendingImport() throws Exception {+ String keyId = createExternalSymmetricKey();+ importFreshMaterial(keyId);++ given()+ .header("X-Amz-Target", "TrentService.DeleteImportedKeyMaterial")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\"}".formatted(keyId))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("KeyId", startsWith("arn:aws:kms:"))+ .body("KeyMaterialId", matchesPattern("[a-f0-9]{64}"));++ describeKey(keyId)+ .body("KeyMetadata.KeyState", equalTo("PendingImport"))+ .body("KeyMetadata.Enabled", equalTo(false))+ .body("KeyMetadata", not(hasKey("ExpirationModel")));+ }++ @Test+ void describeKeyReportsAwsKmsOriginForAnOrdinaryKey() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ describeKey(keyId)+ .body("KeyMetadata.Origin", equalTo("AWS_KMS"))+ .body("KeyMetadata", not(hasKey("ExpirationModel")))+ .body("KeyMetadata", not(hasKey("ValidTo")));+ }++ @Test+ void importIsRejectedForAnAsymmetricKeySpec() {+ given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Origin\":\"EXTERNAL\",\"KeyUsage\":\"ENCRYPT_DECRYPT\",\"KeySpec\":\"RSA_2048\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedOperationException"));+ }++ @Test+ void aDeprecatedWrappingAlgorithmIsRejected() {+ String keyId = createExternalSymmetricKey();++ given()+ .header("X-Amz-Target", "TrentService.GetParametersForImport")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSAES_PKCS1_V1_5\",\"WrappingKeySpec\":\"RSA_2048\"}"+ .formatted(keyId))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("UnsupportedOperationException"));+ }++ private String createExternalSymmetricKey() {+ return given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Origin\":\"EXTERNAL\",\"Description\":\"external key\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");+ }++ private io.restassured.response.ValidatableResponse describeKey(String keyId) {+ return given()+ .header("X-Amz-Target", "TrentService.DescribeKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\"}".formatted(keyId))+ .when().post("/")+ .then().statusCode(200);+ }++ private void importFreshMaterial(String keyId) throws Exception {+ var parameters = given()+ .header("X-Amz-Target", "TrentService.GetParametersForImport")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSAES_OAEP_SHA_256\",\"WrappingKeySpec\":\"RSA_2048\"}"+ .formatted(keyId))+ .when().post("/")+ .then().statusCode(200)+ .extract().jsonPath();++ byte[] material = new byte[32];+ Arrays.fill(material, (byte) 3);+ String wrapped = Base64.getEncoder().encodeToString(+ wrapWithRsaOaepSha256(parameters.getString("PublicKey"), material));++ given()+ .header("X-Amz-Target", "TrentService.ImportKeyMaterial")+ .contentType(KMS_CONTENT_TYPE)+ .body(("{\"KeyId\":\"%s\",\"ImportToken\":\"%s\",\"EncryptedKeyMaterial\":\"%s\","+ + "\"ExpirationModel\":\"KEY_MATERIAL_DOES_NOT_EXPIRE\"}")+ .formatted(keyId, parameters.getString("ImportToken"), wrapped))+ .when().post("/")+ .then().statusCode(200);+ }++ /**+ * Wraps key material exactly as a caller would: the point of the round trip is that the+ * emulator unwraps what a standard RSAES-OAEP-SHA-256 client produces, not a shape of its own.+ */+ private static byte[] wrapWithRsaOaepSha256(String publicKeyEncoded, byte[] material) throws Exception {+ PublicKey wrappingKey = KeyFactory.getInstance("RSA")+ .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyEncoded)));+ Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");+ cipher.init(Cipher.ENCRYPT_MODE, wrappingKey, new OAEPParameterSpec("SHA-256", "MGF1",+ new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT));+ return cipher.doFinal(material);+ }}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 446c9cc4af..527af380d4 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@@ -16,6 +16,11 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;+import javax.crypto.Cipher;+import javax.crypto.Mac;+import javax.crypto.spec.OAEPParameterSpec;+import javax.crypto.spec.PSource;+import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;import java.security.Security;import java.security.KeyFactory;@@ -25,6 +30,8 @@ import java.security.Signature;import java.security.spec.MGF1ParameterSpec;import java.security.spec.PSSParameterSpec;import java.security.spec.X509EncodedKeySpec;+import java.time.Duration;+import java.time.Instant;import java.util.Arrays;import java.util.Base64;import java.util.LinkedHashMap;@@ -40,6 +47,7 @@ class KmsServiceTest {private static final String REGION = "us-east-1";private KmsService kmsService;+ private InMemoryStorage<String, KmsKey> keyStore;@BeforeAllstatic void registerBouncyCastle() {@@ -50,8 +58,9 @@ class KmsServiceTest {@BeforeEachvoid setUp() {+ keyStore = new InMemoryStorage<>();kmsService = new KmsService(- new InMemoryStorage<>(),+ keyStore,new InMemoryStorage<>(),new InMemoryStorage<>(),new RegionResolver("us-east-1", "000000000000")@@ -1626,7 +1635,7 @@ class KmsServiceTest {assertNotNull(publicKeyInfo.getPublicKeyEncoded());byte[] derBytes = Base64.getDecoder().decode(publicKeyInfo.getPublicKeyEncoded());-+// Verify it can be parsed as a standard Java PublicKeyKeyFactory factory = KeyFactory.getInstance("EC");PublicKey pub = factory.generatePublic(new X509EncodedKeySpec(derBytes));@@ -2116,4 +2125,461 @@ class KmsServiceTest {kmsService.generateMac(keyId, message, "HMAC_SHA_256", REGION));assertEquals("InvalidKeyUsageException", ex.getErrorCode());}++ @Nested+ class ImportedKeyMaterial {++ private static final String OAEP_SHA_256 = "RSAES_OAEP_SHA_256";++ private KmsKey externalKey(String keySpec, String keyUsage) {+ return kmsService.createKey("external", keyUsage, keySpec, null, Map.of(), "EXTERNAL", REGION);+ }++ private KmsKey externalSymmetricKey() {+ return externalKey("SYMMETRIC_DEFAULT", "ENCRYPT_DECRYPT");+ }++ private byte[] material(int length, byte seed) {+ byte[] material = new byte[length];+ Arrays.fill(material, seed);+ return material;+ }++ /** Wraps material the way a caller would, with the public key GetParametersForImport returned. */+ private byte[] wrap(String publicKeyEncoded, String wrappingAlgorithm, byte[] material) throws Exception {+ PublicKey wrappingKey = KeyFactory.getInstance("RSA")+ .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyEncoded)));+ String digest = "RSAES_OAEP_SHA_1".equals(wrappingAlgorithm) ? "SHA-1" : "SHA-256";+ Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");+ cipher.init(Cipher.ENCRYPT_MODE, wrappingKey, new OAEPParameterSpec(digest, "MGF1",+ new MGF1ParameterSpec(digest), PSource.PSpecified.DEFAULT));+ return cipher.doFinal(material);+ }++ private KmsKey importInto(KmsKey key, byte[] rawMaterial, String wrappingAlgorithm) throws Exception {+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), wrappingAlgorithm, "RSA_2048", REGION);+ return kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(),+ wrap(parameters.publicKeyEncoded(), wrappingAlgorithm, rawMaterial),+ "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION);+ }++ @Test+ void externalOriginCreatesAKeyWithoutMaterial() {+ KmsKey key = externalSymmetricKey();++ assertEquals("EXTERNAL", key.getOrigin());+ assertEquals("PendingImport", key.getKeyState());+ assertFalse(key.isEnabled());+ assertNull(key.getPrivateKeyEncoded());+ }++ @Test+ void encryptIsRejectedWhileTheKeyHasNoMaterial() {+ String keyId = externalSymmetricKey().getKeyId();+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(keyId, plaintext, REGION));+ assertEquals("KMSInvalidStateException", ex.getErrorCode());+ }++ @ParameterizedTest+ @ValueSource(strings = {"RSAES_OAEP_SHA_256", "RSAES_OAEP_SHA_1"})+ void everySupportedWrappingAlgorithmCompletesAnImport(String wrappingAlgorithm) throws Exception {+ KmsKey key = externalSymmetricKey();++ KmsKey imported = importInto(key, material(32, (byte) 7), wrappingAlgorithm);++ assertEquals("Enabled", imported.getKeyState());+ assertTrue(imported.isEnabled());+ assertNull(imported.getImportParameters());+ assertNotNull(kmsService.encrypt(key.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION));+ }++ @Test+ void materialWrappedForAnotherKeyIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsKey otherKey = externalSymmetricKey();+ KmsService.ImportParameters foreign =+ kmsService.getParametersForImport(otherKey.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ KmsService.ImportParameters own =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrongly = wrap(foreign.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));++ String keyId = key.getKeyId();+ String token = own.importToken();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrongly, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));+ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ assertEquals("PendingImport", kmsService.describeKey(keyId, REGION).getKeyState());+ }++ @Test+ void materialOfTheWrongLengthIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();++ AwsException ex = assertThrows(AwsException.class, () ->+ importInto(key, material(16, (byte) 1), OAEP_SHA_256));+ assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());+ }++ @Test+ void aSupersededImportTokenIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters first =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(first.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));++ String keyId = key.getKeyId();+ String staleToken = first.importToken();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, staleToken, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));+ assertEquals("InvalidImportTokenException", ex.getErrorCode());+ }++ @Test+ void importWithoutOutstandingParametersIsRejected() {+ String keyId = externalSymmetricKey().getKeyId();+ byte[] anything = material(32, (byte) 1);++ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, "some-token", anything, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));+ assertEquals("InvalidImportTokenException", ex.getErrorCode());+ }++ @Test+ void anImportTokenIsSpentByTheImportThatUsedIt() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 3));+ kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(), wrapped,+ "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION);++ String keyId = key.getKeyId();+ String spentToken = parameters.importToken();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, spentToken, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));+ assertEquals("InvalidImportTokenException", ex.getErrorCode());+ }++ /**+ * AWS requires ValidTo to be in the future, so the only honest way to reach an expired key+ * is to let the clock pass it. Rewinding the stored ValidTo stands in for that wait.+ */+ @Test+ void expiringMaterialReturnsTheKeyToPendingImport() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 9));+ kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(), wrapped,+ "KEY_MATERIAL_EXPIRES", Instant.now().getEpochSecond() + 3600, null, REGION);++ KmsKey stored = keyStore.get(REGION + "::" + key.getKeyId()).orElseThrow();+ stored.setValidTo(Instant.now().getEpochSecond() - 60);+ keyStore.put(REGION + "::" + key.getKeyId(), stored);++ KmsKey expired = kmsService.describeKey(key.getKeyId(), REGION);+ assertEquals("PendingImport", expired.getKeyState());+ assertFalse(expired.isEnabled());+ assertNull(expired.getPrivateKeyEncoded());+ assertEquals(0, expired.getValidTo());+ assertNull(expired.getExpirationModel());+ }++ @Test+ void validToInThePastIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));++ String keyId = key.getKeyId();+ String token = parameters.importToken();+ long past = Instant.now().getEpochSecond() - 60;+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrapped, "KEY_MATERIAL_EXPIRES", past, null, REGION));+ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void validToBeyondThreeHundredSixtyFiveDaysIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));++ String keyId = key.getKeyId();+ String token = parameters.importToken();+ long tooFar = Instant.now().plus(Duration.ofDays(366)).getEpochSecond();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrapped, "KEY_MATERIAL_EXPIRES", tooFar, null, REGION));+ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void theKeyMaterialIdIsDerivedFromTheKeyAndTheMaterial() throws Exception {+ byte[] sharedMaterial = material(32, (byte) 21);+ KmsKey first = externalSymmetricKey();+ KmsKey second = externalSymmetricKey();++ String firstId = importInto(first, sharedMaterial, OAEP_SHA_256).getKeyMaterialId();+ String secondId = importInto(second, sharedMaterial, OAEP_SHA_256).getKeyMaterialId();++ assertTrue(firstId.matches("[a-f0-9]{64}"));+ assertNotEquals(firstId, secondId);++ kmsService.deleteImportedKeyMaterial(first.getKeyId(), REGION);+ assertEquals(firstId, importInto(first, sharedMaterial, OAEP_SHA_256).getKeyMaterialId());+ }++ @Test+ void deprecatedPkcs1WrappingIsRejected() {+ String keyId = externalSymmetricKey().getKeyId();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.getParametersForImport(keyId, "RSAES_PKCS1_V1_5", "RSA_2048", REGION));+ assertEquals("UnsupportedOperationException", ex.getErrorCode());+ }++ @Test+ void importingNewMaterialIntoAKeyThatAlreadyHasSomeIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ importInto(key, material(32, (byte) 5), OAEP_SHA_256);+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));++ String keyId = key.getKeyId();+ String token = parameters.importToken();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, "NEW_KEY_MATERIAL", REGION));+ assertEquals("UnsupportedOperationException", ex.getErrorCode());+ }++ @Test+ void reimportingExistingMaterialIntoAFreshKeyIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));++ String keyId = key.getKeyId();+ String token = parameters.importToken();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, "EXISTING_KEY_MATERIAL", REGION));+ assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());+ }++ @Test+ void anUnmodelledImportTypeIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));++ String keyId = key.getKeyId();+ String token = parameters.importToken();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, "ROTATE", REGION));+ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void deletingMaterialFromAKeyPendingDeletionLeavesItPendingDeletion() throws Exception {+ KmsKey key = externalSymmetricKey();+ importInto(key, material(32, (byte) 5), OAEP_SHA_256);+ kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);++ KmsKey deleted = kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);++ assertEquals("PendingDeletion", deleted.getKeyState());+ assertNull(deleted.getPrivateKeyEncoded());+ }++ @Test+ void keyMaterialExpiresRequiresValidTo() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));++ String keyId = key.getKeyId();+ String token = parameters.importToken();+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrapped, "KEY_MATERIAL_EXPIRES", null, null, REGION));+ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void keyMaterialDoesNotExpireRejectsValidTo() throws Exception {+ KmsKey key = externalSymmetricKey();+ KmsService.ImportParameters parameters =+ kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);+ byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));++ String keyId = key.getKeyId();+ String token = parameters.importToken();+ long validTo = Instant.now().getEpochSecond() + 3600;+ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ keyId, token, wrapped, "KEY_MATERIAL_DOES_NOT_EXPIRE", validTo, null, REGION));+ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void deletingImportedMaterialReturnsTheKeyToPendingImport() throws Exception {+ KmsKey key = externalSymmetricKey();+ importInto(key, material(32, (byte) 5), OAEP_SHA_256);++ KmsKey deleted = kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);++ assertEquals("PendingImport", deleted.getKeyState());+ assertFalse(deleted.isEnabled());+ assertNull(deleted.getPrivateKeyEncoded());+ }++ @Test+ void reimportingTheSameMaterialRestoresTheKey() throws Exception {+ KmsKey key = externalSymmetricKey();+ byte[] rawMaterial = material(32, (byte) 5);+ importInto(key, rawMaterial, OAEP_SHA_256);+ kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);++ KmsKey reimported = importInto(key, rawMaterial, OAEP_SHA_256);++ assertEquals("Enabled", reimported.getKeyState());+ assertTrue(reimported.isEnabled());+ }++ @Test+ void reimportingDifferentMaterialIsRejected() throws Exception {+ KmsKey key = externalSymmetricKey();+ importInto(key, material(32, (byte) 5), OAEP_SHA_256);+ kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ importInto(key, material(32, (byte) 6), OAEP_SHA_256));+ assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());+ }++ @Test+ void anHmacKeyMacsWithTheMaterialThatWasImported() throws Exception {+ KmsKey key = externalKey("HMAC_256", "GENERATE_VERIFY_MAC");+ byte[] rawMaterial = material(32, (byte) 42);+ byte[] message = "hello".getBytes(StandardCharsets.UTF_8);+ importInto(key, rawMaterial, OAEP_SHA_256);++ byte[] mac = kmsService.generateMac(key.getKeyId(), message, "HMAC_SHA_256", REGION);++ Mac expected = Mac.getInstance("HmacSHA256");+ expected.init(new SecretKeySpec(rawMaterial, "HmacSHA256"));+ assertArrayEquals(expected.doFinal(message), mac);+ }++ @Test+ void macIsRejectedWhileTheHmacKeyHasNoMaterial() {+ String keyId = externalKey("HMAC_256", "GENERATE_VERIFY_MAC").getKeyId();+ byte[] message = "hello".getBytes(StandardCharsets.UTF_8);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.generateMac(keyId, message, "HMAC_SHA_256", REGION));+ assertEquals("KMSInvalidStateException", ex.getErrorCode());+ }++ @Test+ void cancellingDeletionLeavesAKeyWithNoMaterialInPendingImport() {+ KmsKey key = externalSymmetricKey();+ kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);++ kmsService.cancelKeyDeletion(key.getKeyId(), REGION);++ KmsKey restored = kmsService.describeKey(key.getKeyId(), REGION);+ assertEquals("PendingImport", restored.getKeyState());+ assertFalse(restored.isEnabled());+ }++ @Test+ void cancellingDeletionAfterTheMaterialWasDeletedKeepsTheKeyUnusable() throws Exception {+ KmsKey key = externalSymmetricKey();+ importInto(key, material(32, (byte) 5), OAEP_SHA_256);+ kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);+ kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);++ kmsService.cancelKeyDeletion(key.getKeyId(), REGION);++ String keyId = key.getKeyId();+ assertEquals("PendingImport", kmsService.describeKey(keyId, REGION).getKeyState());+ byte[] plaintext = "hello".getBytes(StandardCharsets.UTF_8);+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(keyId, plaintext, REGION));+ assertEquals("KMSInvalidStateException", ex.getErrorCode());+ }++ @Test+ void cancellingDeletionRestoresAKeyThatStillHasItsMaterial() throws Exception {+ KmsKey key = externalSymmetricKey();+ importInto(key, material(32, (byte) 5), OAEP_SHA_256);+ kmsService.scheduleKeyDeletion(key.getKeyId(), 7, REGION);++ kmsService.cancelKeyDeletion(key.getKeyId(), REGION);++ KmsKey restored = kmsService.describeKey(key.getKeyId(), REGION);+ assertEquals("Enabled", restored.getKeyState());+ assertTrue(restored.isEnabled());+ assertNotNull(kmsService.encrypt(key.getKeyId(), "hello".getBytes(StandardCharsets.UTF_8), REGION));+ }++ /**+ * The AWS key state table marks DeleteImportedKeyMaterial as successful in the Pending+ * import column, so a key with nothing to delete is not an error.+ */+ @Test+ void deletingMaterialFromAKeyThatHasNoneSucceeds() {+ String keyId = externalSymmetricKey().getKeyId();++ KmsKey deleted = kmsService.deleteImportedKeyMaterial(keyId, REGION);++ assertEquals("PendingImport", deleted.getKeyState());+ assertNull(deleted.getKeyMaterialId());+ }++ @Test+ void asymmetricKeySpecsCannotUseExternalOrigin() {+ AwsException ex = assertThrows(AwsException.class, () ->+ externalKey("RSA_2048", "ENCRYPT_DECRYPT"));+ assertEquals("UnsupportedOperationException", ex.getErrorCode());+ }++ @Test+ void importIsRejectedOnAKeyWhoseMaterialKmsGenerated() {+ String keyId = kmsService.createKey("aws managed", REGION).getKeyId();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.getParametersForImport(keyId, OAEP_SHA_256, "RSA_2048", REGION));+ assertEquals("UnsupportedOperationException", ex.getErrorCode());+ }++ @Test+ void automaticRotationIsRejectedForImportedMaterial() throws Exception {+ KmsKey key = externalSymmetricKey();+ importInto(key, material(32, (byte) 5), OAEP_SHA_256);++ String keyId = key.getKeyId();+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.enableKeyRotation(keyId, REGION));+ assertEquals("UnsupportedOperationException", ex.getErrorCode());+ }++ @Test+ void anUnsupportedWrappingAlgorithmIsRejectedBeforeParametersAreIssued() {+ String keyId = externalSymmetricKey().getKeyId();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.getParametersForImport(keyId, "RSA_AES_KEY_WRAP_SHA_256", "RSA_2048", REGION));+ assertEquals("UnsupportedOperationException", ex.getErrorCode());+ }+ }}