diff --git a/docs/services/index.md b/docs/services/index.md index f7e2d9a7f4..3bdef73759 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -30,7 +30,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 91 | | [Cognito Identity](cognitoidentity.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityService.*` | JSON 1.1 | 12 | | [Global Accelerator](globalaccelerator.md) | `POST /` + `X-Amz-Target: GlobalAccelerator_V20180706.*` | JSON 1.1 | 22 | -| [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 44 | +| [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 45 | | [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 | | [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 32 | | [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 15 | diff --git a/docs/services/kms.md b/docs/services/kms.md index 729f34a6a9..8d870166b1 100644 --- a/docs/services/kms.md +++ b/docs/services/kms.md @@ -49,6 +49,7 @@ | `EnableKey` | Enable a key | | `DisableKey` | Disable a key | | `RotateKeyOnDemand` | Rotate key material on demand (symmetric keys only) | +| `ListKeyRotations` | List completed rotations or all key materials, with pagination | | `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` | @@ -92,6 +93,26 @@ blob (header, IV, ciphertext or tag), all fail GCM tag verification the same way backing keys in the key's state, so ciphertext encrypted before a rotation keeps decrypting after it, matching real AWS KMS, which also retains prior backing keys. +### Rotation history + +`ListKeyRotations` returns the material identifier, completion time and `ON_DEMAND` rotation type +for each completed `RotateKeyOnDemand` call. By default it lists only rotated material. +`IncludeKeyMaterial=ALL_KEY_MATERIAL` also includes the first material, which has no rotation date +or type. `KeyMaterialState` identifies the `CURRENT` encryption material and the `NON_CURRENT` +material retained for decryption. Each entry returns the bare key ID in `KeyId`, including when +the request uses a key ARN. The listing accepts a key ID or key ARN, with `Limit` from 1 to +1000 (default 100) and `Marker`/`NextMarker` pagination. + +History is stored with the key and follows multi-Region material replication. Disabling a key +or scheduling its deletion does not remove the history. For imported symmetric material, the +all-material listing includes `ImportState`, and the configured expiration while the material +is imported. The existing limitation on rotating imported material still applies. + +Rotation dates are recorded for rotations performed by versions supporting this operation. +Older persisted backing material remains usable and appears in the all-material listing, but +Floci cannot reconstruct its historical rotation dates. Enabling automatic rotation stores the +setting; it does not schedule rotations or create synthetic rotation-history entries. + ### Legacy blob formats (read-only) Two older, unauthenticated formats are still accepted by `Decrypt` for backward compatibility with @@ -172,8 +193,7 @@ own the material and cannot rotate it. `CreateKey` with `UnsupportedOperationException`. - 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. + already has key material is rejected with `UnsupportedOperationException`. ## AWS Managed Keys diff --git a/pom.xml b/pom.xml index 5591397a06..233038e85d 100644 --- a/pom.xml +++ b/pom.xml @@ -683,6 +683,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + kms + ${aws.sdk.version} + test + org.awaitility awaitility diff --git a/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java b/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java index 81b63d2407..6effea2fad 100644 --- a/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java @@ -45,14 +45,14 @@ public class KmsJsonHandler { "GenerateDataKeyWithoutPlaintext", "GenerateDataKeyPair", "GenerateDataKeyPairWithoutPlaintext", "Sign", "Verify", "GenerateMac", "VerifyMac", "ScheduleKeyDeletion", "CancelKeyDeletion", "TagResource", "UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy", "ListKeyPolicies", "UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation", - "DisableKeyRotation", "EnableKey", "DisableKey", "RotateKeyOnDemand", "GetParametersForImport", + "DisableKeyRotation", "EnableKey", "DisableKey", "RotateKeyOnDemand", "ListKeyRotations", "GetParametersForImport", "ImportKeyMaterial", "DeleteImportedKeyMaterial"); private static final Set KEY_ONLY_OPERATIONS = Set.of( "ReplicateKey", "CreateGrant", "ListGrants", "RevokeGrant", "ScheduleKeyDeletion", "CancelKeyDeletion", "TagResource", "UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy", "ListKeyPolicies", "UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation", "DisableKeyRotation", "EnableKey", - "DisableKey", "RotateKeyOnDemand", "GetParametersForImport", "ImportKeyMaterial", + "DisableKey", "RotateKeyOnDemand", "ListKeyRotations", "GetParametersForImport", "ImportKeyMaterial", "DeleteImportedKeyMaterial"); public Response handle(String action, JsonNode request, String region) { @@ -109,6 +109,7 @@ public class KmsJsonHandler { case "EnableKey" -> handleEnableKey(request, region); case "DisableKey" -> handleDisableKey(request, region); case "RotateKeyOnDemand" -> handleRotateKeyOnDemand(request, region); + case "ListKeyRotations" -> handleListKeyRotations(request, region); case "GetParametersForImport" -> handleGetParametersForImport(request, region); case "ImportKeyMaterial" -> handleImportKeyMaterial(request, region); case "DeleteImportedKeyMaterial" -> handleDeleteImportedKeyMaterial(request, region); @@ -118,6 +119,38 @@ public class KmsJsonHandler { }; } + private Response handleListKeyRotations(JsonNode request, String region) { + JsonNode include = request.path("IncludeKeyMaterial"); + if (!include.isMissingNode() && !include.isNull() && !include.isTextual()) { + throw new AwsException("SerializationException", jsonToken(include) + " can not be converted to a String", 400); + } + KmsService.Page page = service.listKeyRotations(request.path("KeyId").asText(), + include.asText(null), region, marker(request), limit(request)); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode rotations = response.putArray("Rotations"); + for (KmsService.KeyRotation rotation : page.items()) { + ObjectNode entry = rotations.addObject(); + entry.put("KeyId", rotation.keyId()); + entry.put("KeyMaterialId", rotation.keyMaterialId()); + entry.put("KeyMaterialState", rotation.keyMaterialState()); + if (rotation.rotationDate() != null) { + entry.put("RotationDate", rotation.rotationDate() / 1000.0); + entry.put("RotationType", "ON_DEMAND"); + } + if (rotation.importState() != null) { + entry.put("ImportState", rotation.importState()); + } + if (rotation.expirationModel() != null) { + entry.put("ExpirationModel", rotation.expirationModel()); + } + if (rotation.validTo() != null) { + entry.put("ValidTo", rotation.validTo()); + } + } + putTruncation(response, page); + return Response.ok(response).build(); + } + private Response handleCreateKey(JsonNode request, String region) { String description = request.path("Description").asText(null); String keyUsage = request.path("KeyUsage").asText("ENCRYPT_DECRYPT"); diff --git a/src/main/java/io/floci/aws/services/kms/KmsService.java b/src/main/java/io/floci/aws/services/kms/KmsService.java index cd95e328a7..46679cdb32 100644 --- a/src/main/java/io/floci/aws/services/kms/KmsService.java +++ b/src/main/java/io/floci/aws/services/kms/KmsService.java @@ -9,6 +9,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.ReservedTags; import io.floci.aws.core.common.SignedMarkers; import io.floci.aws.core.common.SmithyValidationErrors; +import io.floci.aws.core.common.StripedLocks; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; @@ -36,6 +37,7 @@ import java.security.*; import java.time.Duration; import java.time.Instant; import java.util.*; +import java.util.LinkedHashMap; import java.util.function.Function; import java.util.regex.Pattern; @@ -67,7 +69,10 @@ public class KmsService implements ResourceProvider { private final KmsKeyTypes keyTypes; // Guards the check-generate-put sequence in ensureBackingKeyMaterial so two concurrent // first uses of the same legacy key cannot each mint a different backing key. - private final Object backingKeyMaterialLock = new Object(); + // Hold from resolving a stored key through publishing its changes. Rotation publishes a + // copy, so a writer holding an older live storage value must never put that value back. + // Replica registration uses the same lock so rotation cannot miss a new replica. + private final StripedLocks backingKeyMaterialLocks = new StripedLocks(256); // Guards the scan-and-mint sequence in ensureAwsManagedKeys so two concurrent first reads of // a region's alias namespace cannot each mint a key for the same alias/aws/* name. private final Object awsManagedKeyLock = new Object(); @@ -221,15 +226,10 @@ public class KmsService implements ResourceProvider { * missing field). Material is generated lazily on first use and persisted immediately, * mirroring how {@link #expireImportedKeyMaterialIfDue} self-heals imported-key state. * - *

Double-checked: the cheap unsynchronized check below lets an already-healed key (the - * overwhelming majority of calls, once a key has been used once) return without taking the - * lock. Only a key that still needs healing pays for entering the {@code synchronized} - * block, where the key is re-read from {@code keyStore} and re-checked before generating, - * so that if two callers race to heal the same legacy key concurrently, only one backing key - * is ever minted and every caller ends up with (and returns) the same persisted instance. - * Without this, two concurrent first uses could each generate a different backing key and - * each {@code put} their own copy, leaving one of the two backing keys, and any ciphertext - * encrypted under it, unreachable from the persisted key. + *

The caller resolves the stored key and runs healing under the same lock used by + * rotation and metadata writers. Re-reading before generating legacy material preserves + * the current stored instance, so concurrent first uses cannot publish different backing + * keys and invalidate each other's ciphertext. * * @return the key instance to use for this call: either {@code key} unchanged, or the * re-read, healed instance that was just persisted. @@ -240,7 +240,7 @@ public class KmsService implements ResourceProvider { } if (EXTERNAL_ORIGIN.equals(key.getOrigin())) { if (!hasBackingKeyMaterialSafely(key) && key.getPrivateKeyEncoded() != null) { - synchronized (backingKeyMaterialLock) { + synchronized (backingKeyMaterialLocks.lockFor(key.getKeyId())) { if (!hasBackingKeyMaterial(key)) { byte[] material = decodeBackingMaterial(key.getPrivateKeyEncoded()); String materialId = key.getKeyMaterialId() == null @@ -255,7 +255,7 @@ public class KmsService implements ResourceProvider { if (hasBackingKeyMaterialSafely(key)) { return key; } - synchronized (backingKeyMaterialLock) { + synchronized (backingKeyMaterialLocks.lockFor(key.getKeyId())) { KmsKey current = keyStore.get(region + "::" + key.getKeyId()).orElse(key); if (hasBackingKeyMaterial(current)) { return current; @@ -273,7 +273,7 @@ public class KmsService implements ResourceProvider { } private boolean hasBackingKeyMaterialSafely(KmsKey key) { - synchronized (backingKeyMaterialLock) { + synchronized (backingKeyMaterialLocks.lockFor(key.getKeyId())) { return hasBackingKeyMaterial(key); } } @@ -316,54 +316,57 @@ public class KmsService implements ResourceProvider { if (replicaRegion == null || replicaRegion.isBlank()) { throw new AwsException("ValidationException", "ReplicaRegion is required.", 400); } + String storedKeyId = resolveStoredKeyId(keyId, primaryRegion); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey primary = resolveKey(keyId, storedKeyId, primaryRegion); + if (!primary.isMultiRegion() || !MULTI_REGION_PRIMARY.equals(primary.getMultiRegionKeyType())) { + throw new AwsException("UnsupportedOperationException", + primary.getArn() + " is not a multi-Region primary key.", 400); + } + requireKeyCanBeReplicated(primary); + if (!AwsRegions.partitionFor(primaryRegion).equals(AwsRegions.partitionFor(replicaRegion))) { + throw new AwsException("UnsupportedOperationException", + "The replica region must be in the same AWS partition as the primary key.", 400); + } - KmsKey primary = resolveKey(keyId, primaryRegion); - if (!primary.isMultiRegion() || !MULTI_REGION_PRIMARY.equals(primary.getMultiRegionKeyType())) { - throw new AwsException("UnsupportedOperationException", - primary.getArn() + " is not a multi-Region primary key.", 400); - } - requireKeyCanBeReplicated(primary); - if (!AwsRegions.partitionFor(primaryRegion).equals(AwsRegions.partitionFor(replicaRegion))) { - throw new AwsException("UnsupportedOperationException", - "The replica region must be in the same AWS partition as the primary key.", 400); - } + String storageKey = replicaRegion + "::" + primary.getKeyId(); + if (keyStore.get(storageKey).isPresent()) { + throw new AwsException("AlreadyExistsException", + "A replica for this multi-Region key already exists in " + replicaRegion + ".", 400); + } - String storageKey = replicaRegion + "::" + primary.getKeyId(); - if (keyStore.get(storageKey).isPresent()) { - throw new AwsException("AlreadyExistsException", - "A replica for this multi-Region key already exists in " + replicaRegion + ".", 400); - } + KmsKey replica = new KmsKey(); + replica.setKeyId(primary.getKeyId()); + replica.setArn(regionResolver.buildArn("kms", replicaRegion, "key/" + primary.getKeyId())); + replica.setDescription(description == null ? "" : description); + replica.setKeyUsage(primary.getKeyUsage()); + replica.setKeySpec(primary.getKeySpec()); + replica.setPolicy(policy == null ? buildDefaultKeyPolicy() : policy); + replica.getTags().putAll(ReservedTags.stripReservedTags(tags)); + replica.setOrigin(primary.getOrigin()); + replica.setKeyRotationEnabled(primary.isKeyRotationEnabled()); + replica.setMultiRegion(true); + replica.setMultiRegionKeyType(MULTI_REGION_REPLICA); + replica.setMultiRegionPrimaryRegion(primaryRegion); + replica.setKeyMaterialId(primary.getKeyMaterialId()); + if (EXTERNAL_ORIGIN.equals(primary.getOrigin())) { + replica.setEnabled(false); + replica.setKeyState(PENDING_IMPORT); + replica.setBackingKeys(new HashMap<>()); + } else { + replica.setEnabled(primary.isEnabled()); + replica.setKeyState(primary.getKeyState()); + replica.setPrivateKeyEncoded(primary.getPrivateKeyEncoded()); + replica.setPublicKeyEncoded(primary.getPublicKeyEncoded()); + replica.setBackingKeys(new HashMap<>(primary.getBackingKeys())); + replica.setCurrentBackingKeyId(primary.getCurrentBackingKeyId()); + replica.setBackingKeyRotationDates(new HashMap<>(primary.getBackingKeyRotationDates())); + } + keyStore.put(storageKey, replica); - KmsKey replica = new KmsKey(); - replica.setKeyId(primary.getKeyId()); - replica.setArn(regionResolver.buildArn("kms", replicaRegion, "key/" + primary.getKeyId())); - replica.setDescription(description == null ? "" : description); - replica.setKeyUsage(primary.getKeyUsage()); - replica.setKeySpec(primary.getKeySpec()); - replica.setPolicy(policy == null ? buildDefaultKeyPolicy() : policy); - replica.getTags().putAll(ReservedTags.stripReservedTags(tags)); - replica.setOrigin(primary.getOrigin()); - replica.setKeyRotationEnabled(primary.isKeyRotationEnabled()); - replica.setMultiRegion(true); - replica.setMultiRegionKeyType(MULTI_REGION_REPLICA); - replica.setMultiRegionPrimaryRegion(primaryRegion); - replica.setKeyMaterialId(primary.getKeyMaterialId()); - if (EXTERNAL_ORIGIN.equals(primary.getOrigin())) { - replica.setEnabled(false); - replica.setKeyState(PENDING_IMPORT); - replica.setBackingKeys(new HashMap<>()); - } else { - replica.setEnabled(primary.isEnabled()); - replica.setKeyState(primary.getKeyState()); - replica.setPrivateKeyEncoded(primary.getPrivateKeyEncoded()); - replica.setPublicKeyEncoded(primary.getPublicKeyEncoded()); - replica.setBackingKeys(new HashMap<>(primary.getBackingKeys())); - replica.setCurrentBackingKeyId(primary.getCurrentBackingKeyId()); + LOG.infov("Replicated KMS key {0} from {1} to {2}", primary.getKeyId(), primaryRegion, replicaRegion); + return replica; } - keyStore.put(storageKey, replica); - - LOG.infov("Replicated KMS key {0} from {1} to {2}", primary.getKeyId(), primaryRegion, replicaRegion); - return replica; } private static void requireKeyCanBeReplicated(KmsKey key) { @@ -757,12 +760,15 @@ public class KmsService implements ResourceProvider { } public void scheduleKeyDeletion(String keyId, int pendingWindowInDays, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:ScheduleKeyDeletion"); - requireNotPendingDeletion(key); - key.setKeyState("PendingDeletion"); - key.setDeletionDate(Instant.now().plusSeconds((long) pendingWindowInDays * 86400).getEpochSecond()); - keyStore.put(region + "::" + key.getKeyId(), key); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:ScheduleKeyDeletion"); + requireNotPendingDeletion(key); + key.setKeyState("PendingDeletion"); + key.setDeletionDate(Instant.now().plusSeconds((long) pendingWindowInDays * 86400).getEpochSecond()); + keyStore.put(region + "::" + key.getKeyId(), key); + } } /** @@ -771,16 +777,19 @@ public class KmsService implements ResourceProvider { * state that no cryptographic operation could actually serve. */ public void cancelKeyDeletion(String keyId, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:CancelKeyDeletion"); - if (lacksImportedKeyMaterial(key)) { - key.setKeyState(PENDING_IMPORT); - key.setEnabled(false); - } else { - key.setKeyState("Enabled"); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:CancelKeyDeletion"); + if (lacksImportedKeyMaterial(key)) { + key.setKeyState(PENDING_IMPORT); + key.setEnabled(false); + } else { + key.setKeyState("Enabled"); + } + key.setDeletionDate(0); + keyStore.put(region + "::" + key.getKeyId(), key); } - key.setDeletionDate(0); - keyStore.put(region + "::" + key.getKeyId(), key); } private static boolean lacksImportedKeyMaterial(KmsKey key) { @@ -796,11 +805,14 @@ public class KmsService implements ResourceProvider { } public void putKeyPolicy(String keyId, String policy, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:PutKeyPolicy"); - key.setPolicy(policy); - keyStore.put(region + "::" + key.getKeyId(), key); - LOG.infov("Updated key policy for KMS key: {0} in {1}", key.getKeyId(), region); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:PutKeyPolicy"); + key.setPolicy(policy); + keyStore.put(region + "::" + key.getKeyId(), key); + LOG.infov("Updated key policy for KMS key: {0} in {1}", key.getKeyId(), region); + } } /** @@ -825,16 +837,68 @@ public class KmsService implements ResourceProvider { } public void updateKeyDescription(String keyId, String description, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:UpdateKeyDescription"); - requireNotPendingDeletion(key); - key.setDescription(description); - keyStore.put(region + "::" + key.getKeyId(), key); - LOG.infov("Updated description for KMS key: {0} in {1}", key.getKeyId(), region); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:UpdateKeyDescription"); + requireNotPendingDeletion(key); + key.setDescription(description); + keyStore.put(region + "::" + key.getKeyId(), key); + LOG.infov("Updated description for KMS key: {0} in {1}", key.getKeyId(), region); + } } // ──────────────────────────── Key Rotation ──────────────────────────── + public record KeyRotation(String keyId, String keyMaterialId, String keyMaterialState, + Long rotationDate, String importState, String expirationModel, Long validTo) { + private String cursor() { + return String.format(Locale.ROOT, "%019d:%s", rotationDate == null ? 0L : rotationDate, keyMaterialId); + } + } + + public Page listKeyRotations(String keyId, String includeKeyMaterial, String region, + String marker, Integer limit) { + String include = includeKeyMaterial == null ? "ROTATIONS_ONLY" : includeKeyMaterial; + if (!Set.of("ROTATIONS_ONLY", "ALL_KEY_MATERIAL").contains(include)) { + throw SmithyValidationErrors.validationException("Value '" + include + + "' at 'includeKeyMaterial' failed to satisfy constraint: Member must satisfy enum value set: " + + "[ALL_KEY_MATERIAL, ROTATIONS_ONLY]"); + } + if (limit != null && (limit < 1 || limit > MAX_LIST_KEYS_LIMIT)) { + throw SmithyValidationErrors.validationException("Limit must be between 1 and 1000."); + } + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + if (includeKeyMaterial != null) { + validateRotationKeySpec(key); + } + List rotations = new ArrayList<>(); + boolean includeAll = "ALL_KEY_MATERIAL".equals(include); + boolean external = EXTERNAL_ORIGIN.equals(key.getOrigin()); + if (key.getBackingKeys() != null) { + for (Map.Entry material : key.getBackingKeys().entrySet()) { + Long rotationDate = key.getBackingKeyRotationDates().get(material.getKey()); + if (includeAll || rotationDate != null) { + String materialId = keyMaterialId(key.getKeyId(), decodeBackingMaterial(material.getValue())); + String state = material.getKey().equals(key.getCurrentBackingKeyId()) ? "CURRENT" : "NON_CURRENT"; + rotations.add(new KeyRotation(key.getKeyId(), materialId, state, rotationDate, + external ? "IMPORTED" : null, external ? key.getExpirationModel() : null, + external && KEY_MATERIAL_EXPIRES.equals(key.getExpirationModel()) ? key.getValidTo() : null)); + } + } + } + if (includeAll && external && rotations.isEmpty() && key.getKeyMaterialId() != null) { + rotations.add(new KeyRotation(key.getKeyId(), key.getKeyMaterialId(), "CURRENT", null, + "PENDING_IMPORT", null, null)); + } + return page(rotations, KeyRotation::cursor, + "ListKeyRotations\n" + key.getArn() + "\n" + include, marker, + limit == null ? 100 : limit, MAX_LIST_KEYS_LIMIT); + } + } + public boolean getKeyRotationStatus(String keyId, String region) { KmsKey key = resolveKey(keyId, region); if (KmsKeyUsage.ENCRYPT_DECRYPT != key.getKeyUsage() @@ -845,52 +909,65 @@ public class KmsService implements ResourceProvider { } public void enableKeyRotation(String keyId, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:EnableKeyRotation"); - 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); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:EnableKeyRotation"); + 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); + } } public void disableKeyRotation(String keyId, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:DisableKeyRotation"); - 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); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:DisableKeyRotation"); + 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); + } } public void enableKey(String keyId, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:EnableKey"); - requireNotPendingDeletion(key); - requireImportedKeyMaterial(key); - key.setEnabled(true); - key.setKeyState("Enabled"); - keyStore.put(region + "::" + key.getKeyId(), key); - LOG.infov("Enabled KMS key: {0} in {1}", key.getKeyId(), region); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:EnableKey"); + requireNotPendingDeletion(key); + requireImportedKeyMaterial(key); + key.setEnabled(true); + key.setKeyState("Enabled"); + keyStore.put(region + "::" + key.getKeyId(), key); + LOG.infov("Enabled KMS key: {0} in {1}", key.getKeyId(), region); + } } public void disableKey(String keyId, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:DisableKey"); - requireNotPendingDeletion(key); - requireImportedKeyMaterial(key); - key.setEnabled(false); - key.setKeyState("Disabled"); - keyStore.put(region + "::" + key.getKeyId(), key); - LOG.infov("Disabled KMS key: {0} in {1}", key.getKeyId(), region); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:DisableKey"); + requireNotPendingDeletion(key); + requireImportedKeyMaterial(key); + key.setEnabled(false); + key.setKeyState("Disabled"); + keyStore.put(region + "::" + key.getKeyId(), key); + LOG.infov("Disabled KMS key: {0} in {1}", key.getKeyId(), region); + } } private static final int ON_DEMAND_ROTATION_LIMIT = 25; public String rotateKeyOnDemand(String keyId, String region) { - synchronized (backingKeyMaterialLock) { - KmsKey key = resolveKey(keyId, region); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); requireCustomerManaged(key, "kms:RotateKeyOnDemand"); validateKeyIsUsableForCryptoOperations(key); if (MULTI_REGION_REPLICA.equals(key.getMultiRegionKeyType())) { @@ -906,28 +983,37 @@ public class KmsService implements ResourceProvider { throw new AwsException("LimitExceededException", "On-demand rotation quota for KMS key " + key.getKeyId() + " is exceeded.", 400); } - key.setOnDemandRotationCount(key.getOnDemandRotationCount() + 1); + KmsKey rotated = new KmsKey(key); + rotated.setOnDemandRotationCount(rotated.getOnDemandRotationCount() + 1); // AWS keeps prior backing keys after rotation so ciphertext encrypted under them keeps // decrypting. - keyTypes.symmetric().addBackingKey(key); - keyStore.put(region + "::" + key.getKeyId(), key); - if (MULTI_REGION_PRIMARY.equals(key.getMultiRegionKeyType())) { - synchronizeMultiRegionReplicas(key); + keyTypes.symmetric().addBackingKey(rotated); + rotated.getBackingKeyRotationDates().put(rotated.getCurrentBackingKeyId(), Instant.now().toEpochMilli()); + if (MULTI_REGION_PRIMARY.equals(rotated.getMultiRegionKeyType())) { + publishMultiRegionRotation(rotated); + } else { + keyStore.put(region + "::" + rotated.getKeyId(), rotated); } - return key.getKeyId(); + return rotated.getKeyId(); } } - private void synchronizeMultiRegionReplicas(KmsKey primary) { + private void publishMultiRegionRotation(KmsKey primary) { + Map updates = new LinkedHashMap<>(); + String primaryRegion = AwsArnUtils.parse(primary.getArn()).region(); + updates.put(primaryRegion + "::" + primary.getKeyId(), primary); for (KmsKey candidate : listAllMultiRegionKeys(primary.getKeyId())) { if (!MULTI_REGION_REPLICA.equals(candidate.getMultiRegionKeyType())) { continue; } - candidate.setBackingKeys(new HashMap<>(primary.getBackingKeys())); - candidate.setCurrentBackingKeyId(primary.getCurrentBackingKeyId()); - String replicaRegion = AwsArnUtils.parse(candidate.getArn()).region(); - keyStore.put(replicaRegion + "::" + candidate.getKeyId(), candidate); + KmsKey replica = new KmsKey(candidate); + replica.setBackingKeys(new HashMap<>(primary.getBackingKeys())); + replica.setCurrentBackingKeyId(primary.getCurrentBackingKeyId()); + replica.setBackingKeyRotationDates(new HashMap<>(primary.getBackingKeyRotationDates())); + String replicaRegion = AwsArnUtils.parse(replica.getArn()).region(); + updates.put(replicaRegion + "::" + replica.getKeyId(), replica); } + keyStore.putAllAtomically(updates); } private static void validateRotationOrigin(KmsKey key) { @@ -950,24 +1036,39 @@ public class KmsService implements ResourceProvider { public ImportParameters getParametersForImport(String keyId, String wrappingAlgorithm, String wrappingKeySpec, String region) { - KmsKey key = resolveKey(keyId, region); - requireExternalOrigin(key); - requireNotPendingDeletion(key); - KmsKeyImport.validateWrappingAlgorithm(key.getKeySpec(), wrappingAlgorithm, wrappingKeySpec); + String keyArn; + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireExternalOrigin(key); + requireNotPendingDeletion(key); + KmsKeyImport.validateWrappingAlgorithm(key.getKeySpec(), wrappingAlgorithm, wrappingKeySpec); + keyArn = key.getArn(); + } - KmsKeyImport.WrappingKeyPair wrappingKeyPair = KmsKeyImport.generateWrappingKeyPair(wrappingKeySpec); + KmsKeyImport.WrappingKeyPair wrappingKeyPair = generateImportWrappingKeyPair(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); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyArn, storedKeyId, region); + requireExternalOrigin(key); + requireNotPendingDeletion(key); + KmsKeyImport.validateWrappingAlgorithm(key.getKeySpec(), wrappingAlgorithm, wrappingKeySpec); + 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()); + 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()); + } + } + + KmsKeyImport.WrappingKeyPair generateImportWrappingKeyPair(String wrappingKeySpec) { + return KmsKeyImport.generateWrappingKeyPair(wrappingKeySpec); } /** @@ -976,40 +1077,43 @@ 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); - requireNotPendingDeletion(key); - validateImportType(importType, key); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireExternalOrigin(key); + 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); + 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); + String keyMaterialId = keyMaterialId(key.getKeyId(), material); + requireSameMaterialAsFirstImport(key, keyMaterialId); + + KmsKeyType keyType = keyTypes.of(key.getKeySpec()); + keyType.importKeyMaterial(key, material); + + if (KmsKeySpec.SYMMETRIC_DEFAULT == key.getKeySpec()) { + installImportedBackingKey(key, keyMaterialId, 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; } - String effectiveExpirationModel = resolveExpirationModel(expirationModel, validTo); - - byte[] material = KmsKeyImport.unwrap(parameters.getWrappingPrivateKeyEncoded(), - parameters.getWrappingAlgorithm(), encryptedKeyMaterial); - String keyMaterialId = keyMaterialId(key.getKeyId(), material); - requireSameMaterialAsFirstImport(key, keyMaterialId); - - KmsKeyType keyType = keyTypes.of(key.getKeySpec()); - keyType.importKeyMaterial(key, material); - - if (KmsKeySpec.SYMMETRIC_DEFAULT == key.getKeySpec()) { - installImportedBackingKey(key, keyMaterialId, 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; } /** @@ -1018,7 +1122,7 @@ public class KmsService implements ResourceProvider { * material after a delete or expiry reinstates the id that earlier ciphertext names. */ private void installImportedBackingKey(KmsKey key, String keyMaterialId, byte[] material) { - synchronized (backingKeyMaterialLock) { + synchronized (backingKeyMaterialLocks.lockFor(key.getKeyId())) { Map backingKeys = new HashMap<>(); backingKeys.put(keyMaterialId, Base64.getEncoder().encodeToString(material)); key.setBackingKeys(backingKeys); @@ -1031,12 +1135,15 @@ public class KmsService implements ResourceProvider { * 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); - 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; + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + 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); + return key; + } } /** @@ -1065,7 +1172,7 @@ public class KmsService implements ResourceProvider { * a later re-import, so what the key was originally given has to outlive the material itself. */ private void clearImportedKeyMaterial(KmsKey key) { - synchronized (backingKeyMaterialLock) { + synchronized (backingKeyMaterialLocks.lockFor(key.getKeyId())) { key.setPrivateKeyEncoded(null); key.setBackingKeys(new HashMap<>()); key.setCurrentBackingKeyId(null); @@ -1753,7 +1860,7 @@ public class KmsService implements ResourceProvider { private byte[] encryptEnvelope(KmsKey key, byte[] plaintext, Map encryptionContext) { String backingKeyId; byte[] dek; - synchronized (backingKeyMaterialLock) { + synchronized (backingKeyMaterialLocks.lockFor(key.getKeyId())) { backingKeyId = key.getCurrentBackingKeyId(); String materialB64 = key.getBackingKeys() == null ? null : key.getBackingKeys().get(backingKeyId); if (materialB64 == null) { @@ -1800,7 +1907,7 @@ public class KmsService implements ResourceProvider { */ private byte[] decryptEnvelopeV3(EnvelopeV3 envelope, KmsKey key, Map encryptionContext) { String materialB64; - synchronized (backingKeyMaterialLock) { + synchronized (backingKeyMaterialLocks.lockFor(key.getKeyId())) { materialB64 = key.getBackingKeys() == null ? null : key.getBackingKeys().get(envelope.backingKeyId()); } if (materialB64 == null) { @@ -2177,31 +2284,42 @@ public class KmsService implements ResourceProvider { // ──────────────────────────── Tags ──────────────────────────── public void tagResource(String keyId, Map tags, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:TagResource"); - requireNotPendingDeletion(key); - ReservedTags.rejectReservedTagsOnUpdate(tags); - key.getTags().putAll(tags); - keyStore.put(region + "::" + key.getKeyId(), key); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:TagResource"); + requireNotPendingDeletion(key); + ReservedTags.rejectReservedTagsOnUpdate(tags); + key.getTags().putAll(tags); + keyStore.put(region + "::" + key.getKeyId(), key); + } } public void untagResource(String keyId, List tagKeys, String region) { - KmsKey key = resolveKey(keyId, region); - requireCustomerManaged(key, "kms:UntagResource"); - requireNotPendingDeletion(key); - tagKeys.forEach(key.getTags()::remove); - keyStore.put(region + "::" + key.getKeyId(), key); + String storedKeyId = resolveStoredKeyId(keyId, region); + synchronized (backingKeyMaterialLocks.lockFor(storedKeyId)) { + KmsKey key = resolveKey(keyId, storedKeyId, region); + requireCustomerManaged(key, "kms:UntagResource"); + requireNotPendingDeletion(key); + tagKeys.forEach(key.getTags()::remove); + keyStore.put(region + "::" + key.getKeyId(), key); + } } // ──────────────────────────── Helpers ──────────────────────────── private KmsKey resolveKey(String keyIdOrArn, String region) { - String keyId = resolveStoredKeyId(keyIdOrArn, region); - KmsKey key = keyStore.get(region + "::" + keyId) - .orElseThrow(() -> keyNotFound(keyIdOrArn, keyId, region)); - key = expireImportedKeyMaterialIfDue(key, region); - key = ensureBackingKeyMaterial(key, region); - return key; + return resolveKey(keyIdOrArn, resolveStoredKeyId(keyIdOrArn, region), region); + } + + private KmsKey resolveKey(String keyIdOrArn, String keyId, String region) { + synchronized (backingKeyMaterialLocks.lockFor(keyId)) { + KmsKey key = keyStore.get(region + "::" + keyId) + .orElseThrow(() -> keyNotFound(keyIdOrArn, keyId, region)); + key = expireImportedKeyMaterialIfDue(key, region); + key = ensureBackingKeyMaterial(key, region); + return key; + } } /** diff --git a/src/main/java/io/floci/aws/services/kms/model/KmsKey.java b/src/main/java/io/floci/aws/services/kms/model/KmsKey.java index e52bcb062e..94d965dbad 100644 --- a/src/main/java/io/floci/aws/services/kms/model/KmsKey.java +++ b/src/main/java/io/floci/aws/services/kms/model/KmsKey.java @@ -45,11 +45,44 @@ public class KmsKey { // and KmsService lazily generates material for them on first use. private Map backingKeys = new HashMap<>(); private String currentBackingKeyId; + // Only completed rotations have a timestamp. The first material and material loaded + // from older snapshots have no recorded rotation date. + private Map backingKeyRotationDates = new HashMap<>(); public KmsKey() { this.creationDate = Instant.now().getEpochSecond(); } + public KmsKey(KmsKey source) { + this.keyId = source.keyId; + this.arn = source.arn; + this.description = source.description; + this.enabled = source.enabled; + this.keyState = source.keyState; + this.origin = source.origin; + this.keyManager = source.keyManager; + this.expirationModel = source.expirationModel; + this.validTo = source.validTo; + this.importParameters = source.importParameters; + this.keyMaterialId = source.keyMaterialId; + this.keyUsage = source.keyUsage; + this.keySpec = source.keySpec; + this.multiRegion = source.multiRegion; + this.multiRegionKeyType = source.multiRegionKeyType; + this.multiRegionPrimaryRegion = source.multiRegionPrimaryRegion; + this.creationDate = source.creationDate; + this.deletionDate = source.deletionDate; + this.policy = source.policy; + this.keyRotationEnabled = source.keyRotationEnabled; + this.tags = source.tags == null ? null : new HashMap<>(source.tags); + this.privateKeyEncoded = source.privateKeyEncoded; + this.publicKeyEncoded = source.publicKeyEncoded; + this.onDemandRotationCount = source.onDemandRotationCount; + this.backingKeys = source.backingKeys == null ? null : new HashMap<>(source.backingKeys); + this.currentBackingKeyId = source.currentBackingKeyId; + this.backingKeyRotationDates = source.backingKeyRotationDates == null ? null : new HashMap<>(source.backingKeyRotationDates); + } + public String getKeyId() { return keyId; } public void setKeyId(String keyId) { this.keyId = keyId; } @@ -131,4 +164,9 @@ public class KmsKey { public String getCurrentBackingKeyId() { return currentBackingKeyId; } public void setCurrentBackingKeyId(String currentBackingKeyId) { this.currentBackingKeyId = currentBackingKeyId; } + + public Map getBackingKeyRotationDates() { return backingKeyRotationDates; } + public void setBackingKeyRotationDates(Map dates) { + this.backingKeyRotationDates = dates == null ? new HashMap<>() : dates; + } } diff --git a/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java index 3a886613d0..39bb492113 100644 --- a/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java @@ -60,6 +60,21 @@ class KmsKeyArnEnforcementIntegrationTest { RestAssuredJsonUtils.configureAwsContentTypes(); } + @Test + void rotationHistoryUsesTheNamedKeyForAuthorization() { + String allowedArn = createKey(); + String otherArn = createKey(); + Session session = assumeRoleWith(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"kms:ListKeyRotations","Resource":"%s"}]}""" + .formatted(allowedArn)); + + keyCall(session, "ListKeyRotations", "{\"KeyId\":\"" + allowedArn + "\"}") + .then().statusCode(200).body("Truncated", equalTo(false)); + keyCall(session, "ListKeyRotations", "{\"KeyId\":\"" + otherArn + "\"}") + .then().statusCode(400).body("__type", equalTo("AccessDeniedException")); + } + @Test void aPolicyAllowingOneKeyArnAllowsThatKeyAndNoOther() { String allowedArn = createKey(); diff --git a/src/test/java/io/floci/aws/services/kms/KmsImportGenerationConcurrencyServiceTest.java b/src/test/java/io/floci/aws/services/kms/KmsImportGenerationConcurrencyServiceTest.java new file mode 100644 index 0000000000..2d7b7dfa12 --- /dev/null +++ b/src/test/java/io/floci/aws/services/kms/KmsImportGenerationConcurrencyServiceTest.java @@ -0,0 +1,104 @@ +package io.floci.aws.services.kms; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.kms.model.KmsKey; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +class KmsImportGenerationConcurrencyServiceTest { + private static final String REGION = "us-east-1"; + + @Test + void unrelatedLookupCompletesWhileWrappingKeyGenerationIsParked() throws Exception { + try (Fixture fixture = new Fixture()) { + KmsKey key = fixture.externalKey(); + KmsKey other = fixture.service.createKey("unrelated", REGION); + Future pending = fixture.start(key.getKeyId()); + Future lookup = fixture.workers.submit(() -> fixture.service.describeKey(other.getKeyId(), REGION)); + assertEquals(other.getArn(), lookup.get(5, TimeUnit.SECONDS).getArn()); + fixture.release.countDown(); + assertEquals(key.getArn(), pending.get(10, TimeUnit.SECONDS).keyArn()); + } + } + + @Test + void deletionDuringGenerationPreventsParameterPublication() throws Exception { + try (Fixture fixture = new Fixture()) { + KmsKey key = fixture.externalKey(); + Future pending = fixture.start(key.getKeyId()); + Future deletion = fixture.workers.submit(() -> fixture.service.scheduleKeyDeletion(key.getKeyId(), 7, REGION)); + deletion.get(5, TimeUnit.SECONDS); + fixture.release.countDown(); + ExecutionException failure = assertThrows(ExecutionException.class, () -> pending.get(10, TimeUnit.SECONDS)); + assertInstanceOf(AwsException.class, failure.getCause()); + assertNull(fixture.service.describeKey(key.getKeyId(), REGION).getImportParameters()); + assertEquals("PendingDeletion", fixture.service.describeKey(key.getKeyId(), REGION).getKeyState()); + } + } + + @Test + void aliasRetargetDuringGenerationKeepsTheInitiallyResolvedKey() throws Exception { + try (Fixture fixture = new Fixture()) { + KmsKey key = fixture.externalKey(); + KmsKey other = fixture.externalKey(); + fixture.service.createAlias("alias/import-target", key.getKeyId(), REGION); + Future pending = fixture.start("alias/import-target"); + Future retarget = fixture.workers.submit( + () -> fixture.service.updateAlias("alias/import-target", other.getKeyId(), REGION)); + retarget.get(5, TimeUnit.SECONDS); + fixture.release.countDown(); + assertEquals(key.getArn(), pending.get(10, TimeUnit.SECONDS).keyArn()); + assertNotNull(fixture.service.describeKey(key.getKeyId(), REGION).getImportParameters()); + assertNull(fixture.service.describeKey(other.getKeyId(), REGION).getImportParameters()); + } + } + + private static final class Fixture implements AutoCloseable { + private final CountDownLatch entered = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + private final ExecutorService workers = Executors.newFixedThreadPool(2); + private final KmsService service = new KmsService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")) { + @Override + KmsKeyImport.WrappingKeyPair generateImportWrappingKeyPair(String wrappingKeySpec) { + entered.countDown(); + try { + assertTrue(release.await(10, TimeUnit.SECONDS), "Wrapping generation was not released"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + return super.generateImportWrappingKeyPair(wrappingKeySpec); + } + }; + + private KmsKey externalKey() { + return service.createKey("import", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", null, + Map.of(), "EXTERNAL", REGION); + } + + private Future start(String keyId) throws InterruptedException { + Future pending = workers.submit( + () -> service.getParametersForImport(keyId, "RSAES_OAEP_SHA_256", "RSA_2048", REGION)); + assertTrue(entered.await(10, TimeUnit.SECONDS), "Wrapping generation did not start"); + return pending; + } + + @Override + public void close() { + release.countDown(); + workers.close(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/kms/KmsKeyRotationsIntegrationTest.java b/src/test/java/io/floci/aws/services/kms/KmsKeyRotationsIntegrationTest.java new file mode 100644 index 0000000000..4f90bcb7ab --- /dev/null +++ b/src/test/java/io/floci/aws/services/kms/KmsKeyRotationsIntegrationTest.java @@ -0,0 +1,116 @@ +package io.floci.aws.services.kms; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.common.http.TestHTTPResource; +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; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.awssdk.services.kms.model.InvalidMarkerException; +import software.amazon.awssdk.services.kms.model.ListKeyRotationsResponse; +import software.amazon.awssdk.services.kms.model.RotationsListEntry; + +import java.net.URI; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.*; + +@QuarkusTest +class KmsKeyRotationsIntegrationTest { + @TestHTTPResource + URI endpoint; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void sdkReadsRotationDatesAndPaginatesWithoutBreakingDecryption() { + try (KmsClient kms = client()) { + String keyId = kms.createKey().keyMetadata().keyId(); + try { + assertTrue(kms.listKeyRotations(b -> b.keyId(keyId)).rotations().isEmpty()); + SdkBytes plaintext = SdkBytes.fromUtf8String("encrypted before rotation"); + SdkBytes ciphertext = kms.encrypt(b -> b.keyId(keyId).plaintext(plaintext)).ciphertextBlob(); + Instant before = Instant.now().minusSeconds(1); + kms.rotateKeyOnDemand(b -> b.keyId(keyId)); + kms.rotateKeyOnDemand(b -> b.keyId(keyId)); + + ListKeyRotationsResponse first = kms.listKeyRotations(b -> b.keyId(keyId).limit(1)); + assertTrue(first.truncated()); + assertEquals(1, first.rotations().size()); + assertNotNull(first.nextMarker()); + ListKeyRotationsResponse second = kms.listKeyRotations( + b -> b.keyId(keyId).marker(first.nextMarker()).limit(1)); + assertFalse(second.truncated()); + assertNull(second.nextMarker()); + Set materials = new HashSet<>(); + for (RotationsListEntry entry : List.of(first.rotations().getFirst(), second.rotations().getFirst())) { + assertTrue(materials.add(entry.keyMaterialId())); + assertEquals(keyId, entry.keyId()); + assertEquals("ON_DEMAND", entry.rotationTypeAsString()); + assertNotNull(entry.rotationDate()); + assertTrue(entry.rotationDate().isAfter(before)); + assertTrue(entry.rotationDate().isBefore(Instant.now().plusSeconds(1))); + } + ListKeyRotationsResponse all = kms.listKeyRotations( + b -> b.keyId(keyId).includeKeyMaterial("ALL_KEY_MATERIAL")); + assertEquals(3, all.rotations().size()); + String arn = kms.describeKey(b -> b.keyId(keyId)).keyMetadata().arn(); + for (String identifier : List.of(keyId, arn)) { + assertTrue(kms.listKeyRotations(b -> b.keyId(identifier).includeKeyMaterial("ALL_KEY_MATERIAL")) + .rotations().stream().allMatch(entry -> keyId.equals(entry.keyId()))); + } + assertEquals(1, all.rotations().stream().filter(r -> "CURRENT".equals(r.keyMaterialStateAsString())).count()); + assertEquals(1, all.rotations().stream().filter(r -> r.rotationDate() == null).count()); + assertNull(all.rotations().getFirst().rotationType()); + assertEquals(plaintext, kms.decrypt(b -> b.ciphertextBlob(ciphertext)).plaintext()); + assertThrows(InvalidMarkerException.class, () -> kms.listKeyRotations( + b -> b.keyId(keyId).includeKeyMaterial("ALL_KEY_MATERIAL").marker(first.nextMarker()))); + } finally { + kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7)); + } + } + } + + @ParameterizedTest + @ValueSource(strings = { + "{}", + "{\"KeyId\":\"\"}", + "{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",\"Limit\":0}", + "{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",\"Limit\":1001}", + "{\"KeyId\":\"00000000-0000-0000-0000-000000000000\",\"IncludeKeyMaterial\":\"invalid\"}" + }) + void malformedRequestsReturnAwsValidationErrors(String request) { + listRotations(request) + .then().statusCode(400).body("__type", equalTo("ValidationException")); + } + + @Test + void aliasesAreRejectedForKeyOnlyListing() { + listRotations("{\"KeyId\":\"alias/rotation-history\"}") + .then().statusCode(400).body("__type", equalTo("InvalidArnException")); + } + + private Response listRotations(String request) { + return given().contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "TrentService.ListKeyRotations") + .body(request).post("/"); + } + + private KmsClient client() { + return AwsTestClients.create(KmsClient.builder(), "test", Region.US_EAST_1, endpoint); + } +} diff --git a/src/test/java/io/floci/aws/services/kms/KmsKeyRotationsServiceTest.java b/src/test/java/io/floci/aws/services/kms/KmsKeyRotationsServiceTest.java new file mode 100644 index 0000000000..db7c0866e5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/kms/KmsKeyRotationsServiceTest.java @@ -0,0 +1,239 @@ +package io.floci.aws.services.kms; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.kms.model.KmsKey; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +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.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class KmsKeyRotationsServiceTest { + private static final String REGION = "us-east-1"; + private final InMemoryStorage keys = new InMemoryStorage<>(); + private final KmsService service = new KmsService(keys, new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")); + + @Test + void firstMaterialIsOnlyIncludedWhenRequested() { + KmsKey key = service.createKey("rotation history", REGION); + assertTrue(list(key, null).items().isEmpty()); + KmsService.Page all = list(key, "ALL_KEY_MATERIAL"); + assertFalse(all.truncated()); + assertNull(all.nextMarker()); + KmsService.KeyRotation first = all.items().getFirst(); + assertEquals(key.getKeyId(), first.keyId()); + assertTrue(first.keyMaterialId().matches("[a-f0-9]{64}")); + assertEquals("CURRENT", first.keyMaterialState()); + assertNull(first.rotationDate()); + assertNull(first.importState()); + assertNull(first.expirationModel()); + assertNull(first.validTo()); + } + + @Test + void rotationsTrackMaterialsWithoutInvalidatingEarlierCiphertexts() { + KmsKey key = service.createKey("rotation history", REGION); + String firstMaterial = list(key, "ALL_KEY_MATERIAL").items().getFirst().keyMaterialId(); + byte[] plaintext = "before rotation".getBytes(StandardCharsets.UTF_8); + byte[] ciphertext = service.encrypt(key.getKeyId(), plaintext, REGION); + long before = Instant.now().toEpochMilli(); + service.rotateKeyOnDemand(key.getKeyId(), REGION); + service.rotateKeyOnDemand(key.getKeyId(), REGION); + long after = Instant.now().toEpochMilli(); + + List rotations = list(key, null).items(); + assertEquals(2, rotations.size()); + assertEquals(rotations, list(key, "ROTATIONS_ONLY").items()); + assertEquals(1, rotations.stream().filter(r -> "CURRENT".equals(r.keyMaterialState())).count()); + for (KmsService.KeyRotation rotation : rotations) { + assertTrue(rotation.rotationDate() >= before && rotation.rotationDate() <= after); + assertNotEquals(firstMaterial, rotation.keyMaterialId()); + assertTrue(rotation.keyMaterialId().matches("[a-f0-9]{64}")); + } + List all = list(key, "ALL_KEY_MATERIAL").items(); + assertEquals(3, all.size()); + assertEquals(firstMaterial, all.getFirst().keyMaterialId()); + assertEquals("NON_CURRENT", all.getFirst().keyMaterialState()); + assertNull(all.getFirst().rotationDate()); + assertArrayEquals(plaintext, service.decrypt(ciphertext, REGION)); + } + + @Test + void paginationWalksEachMaterialOnceAndBindsMarkersToTheKeyAndFilter() { + KmsKey key = service.createKey("paged history", REGION); + for (int i = 0; i < 4; i++) { + service.rotateKeyOnDemand(key.getKeyId(), REGION); + } + List expected = list(key, "ALL_KEY_MATERIAL").items(); + List walked = new ArrayList<>(); + String marker = null; + do { + KmsService.Page page = service.listKeyRotations( + key.getArn(), "ALL_KEY_MATERIAL", REGION, marker, 2); + assertTrue(page.items().size() <= 2); + walked.addAll(page.items()); + marker = page.nextMarker(); + assertEquals(marker != null, page.truncated()); + } while (marker != null); + assertEquals(expected, walked); + assertEquals(5, new HashSet<>(walked.stream().map(KmsService.KeyRotation::keyMaterialId).toList()).size()); + + String issued = service.listKeyRotations(key.getKeyId(), "ALL_KEY_MATERIAL", REGION, null, 1).nextMarker(); + KmsKey other = service.createKey("another key", REGION); + assertError("InvalidMarkerException", () -> service.listKeyRotations( + other.getKeyId(), "ALL_KEY_MATERIAL", REGION, issued, 1)); + assertError("InvalidMarkerException", () -> service.listKeyRotations( + key.getKeyId(), null, REGION, issued, 1)); + assertError("InvalidMarkerException", () -> service.listKeyRotations( + key.getKeyId(), "ALL_KEY_MATERIAL", REGION, issued + "changed", 1)); + } + + @Test + void historyAndCiphertextSurviveAStoredKeyRoundTrip() throws Exception { + KmsKey key = service.createKey("persisted history", REGION); + byte[] plaintext = "stored ciphertext".getBytes(StandardCharsets.UTF_8); + byte[] ciphertext = service.encrypt(key.getKeyId(), plaintext, REGION); + service.rotateKeyOnDemand(key.getKeyId(), REGION); + List expected = list(key, "ALL_KEY_MATERIAL").items(); + ObjectMapper mapper = new ObjectMapper(); + KmsKey reloaded = mapper.readValue(mapper.writeValueAsBytes(service.describeKey(key.getKeyId(), REGION)), KmsKey.class); + keys.put(REGION + "::" + key.getKeyId(), reloaded); + + KmsService restarted = new KmsService(keys, new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000")); + assertEquals(expected, restarted.listKeyRotations(key.getKeyId(), "ALL_KEY_MATERIAL", REGION, null, null).items()); + assertArrayEquals(plaintext, restarted.decrypt(ciphertext, REGION)); + } + + @Test + void aLegacySnapshotDoesNotInventRotationDatesOrReplaceItsMaterial() throws Exception { + KmsKey key = service.createKey("legacy history", REGION); + service.rotateKeyOnDemand(key.getKeyId(), REGION); + ObjectMapper mapper = new ObjectMapper(); + String snapshot = mapper.writeValueAsString(service.describeKey(key.getKeyId(), REGION)); + ObjectNode node = (ObjectNode) mapper.readTree(snapshot); + node.remove("backingKeyRotationDates"); + KmsKey reloaded = mapper.treeToValue(node, KmsKey.class); + keys.put(REGION + "::" + key.getKeyId(), reloaded); + Map materials = Map.copyOf(reloaded.getBackingKeys()); + assertTrue(list(reloaded, null).items().isEmpty()); + assertEquals(2, list(reloaded, "ALL_KEY_MATERIAL").items().size()); + assertTrue(list(reloaded, "ALL_KEY_MATERIAL").items().stream().allMatch(r -> r.rotationDate() == null)); + assertEquals(materials, reloaded.getBackingKeys()); + } + + @Test + void primaryRotationHistoryFollowsExistingAndNewReplicas() { + KmsKey primary = service.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", + null, Map.of(), null, true, REGION); + service.replicateKey(primary.getKeyId(), null, null, Map.of(), "us-west-2", REGION); + service.rotateKeyOnDemand(primary.getKeyId(), REGION); + service.replicateKey(primary.getKeyId(), null, null, Map.of(), "eu-west-1", REGION); + KmsService.KeyRotation expected = list(primary, null).items().getFirst(); + for (String region : List.of("us-west-2", "eu-west-1")) { + KmsService.KeyRotation actual = service.listKeyRotations(primary.getKeyId(), null, region, null, null) + .items().getFirst(); + assertEquals(expected.keyMaterialId(), actual.keyMaterialId()); + assertEquals(expected.rotationDate(), actual.rotationDate()); + assertEquals("CURRENT", actual.keyMaterialState()); + assertEquals(primary.getKeyId(), actual.keyId()); + } + } + + @Test + void disabledAndPendingDeletionKeysRetainTheirHistory() { + KmsKey key = service.createKey("disabled history", REGION); + service.rotateKeyOnDemand(key.getKeyId(), REGION); + List expected = list(key, null).items(); + service.disableKey(key.getKeyId(), REGION); + assertEquals(expected, list(key, null).items()); + service.scheduleKeyDeletion(key.getKeyId(), 7, REGION); + assertEquals(expected, list(key, null).items()); + } + + @Test + void importedMaterialReportsItsImportAndExpirationState() throws Exception { + KmsKey key = service.createKey("import history", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", + null, Map.of(), "EXTERNAL", REGION); + assertTrue(list(key, "ALL_KEY_MATERIAL").items().isEmpty()); + KmsService.ImportParameters parameters = + service.getParametersForImport(key.getKeyId(), "RSAES_OAEP_SHA_256", "RSA_2048", REGION); + PublicKey wrappingKey = KeyFactory.getInstance("RSA") + .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(parameters.publicKeyEncoded()))); + Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); + cipher.init(Cipher.ENCRYPT_MODE, wrappingKey, new OAEPParameterSpec("SHA-256", "MGF1", + MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); + long validTo = Instant.now().plusSeconds(3600).getEpochSecond(); + KmsKey imported = service.importKeyMaterial(key.getKeyId(), parameters.importToken(), + cipher.doFinal(new byte[32]), "KEY_MATERIAL_EXPIRES", validTo, null, REGION); + + assertTrue(list(key, null).items().isEmpty()); + KmsService.KeyRotation first = list(key, "ALL_KEY_MATERIAL").items().getFirst(); + assertEquals(imported.getKeyMaterialId(), first.keyMaterialId()); + assertEquals("IMPORTED", first.importState()); + assertEquals("KEY_MATERIAL_EXPIRES", first.expirationModel()); + assertEquals(validTo, first.validTo()); + assertNull(first.rotationDate()); + service.deleteImportedKeyMaterial(key.getKeyId(), REGION); + KmsService.KeyRotation deleted = list(key, "ALL_KEY_MATERIAL").items().getFirst(); + assertEquals(first.keyMaterialId(), deleted.keyMaterialId()); + assertEquals(key.getKeyId(), deleted.keyId()); + assertEquals(deleted, service.listKeyRotations(key.getArn(), "ALL_KEY_MATERIAL", REGION, null, null) + .items().getFirst()); + assertEquals("PENDING_IMPORT", deleted.importState()); + assertTrue(list(key, null).items().isEmpty()); + } + + @Test + void unrotatableKeysHaveNoHistoryAndRejectIncludeKeyMaterial() { + KmsKey key = service.createKey("hmac history", "GENERATE_VERIFY_MAC", "HMAC_256", + null, Map.of(), REGION); + assertTrue(list(key, null).items().isEmpty()); + assertError("UnsupportedOperationException", () -> list(key, "ALL_KEY_MATERIAL")); + assertError("UnsupportedOperationException", () -> list(key, "ROTATIONS_ONLY")); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1001}) + void invalidPageSizeIsRejected(int limit) { + KmsKey key = service.createKey("limit", REGION); + assertError("ValidationException", () -> service.listKeyRotations(key.getKeyId(), null, REGION, null, limit)); + } + + @Test + void invalidFilterAndMissingKeyAreRejected() { + KmsKey key = service.createKey("filter", REGION); + assertError("ValidationException", () -> list(key, "everything")); + assertError("NotFoundException", () -> service.listKeyRotations( + "00000000-0000-0000-0000-000000000000", null, REGION, null, null)); + } + + private KmsService.Page list(KmsKey key, String include) { + return service.listKeyRotations(key.getKeyId(), include, REGION, null, null); + } + + private static void assertError(String code, Executable call) { + assertEquals(code, assertThrows(AwsException.class, call).getErrorCode()); + } +} diff --git a/src/test/java/io/floci/aws/services/kms/KmsRotationConcurrencyServiceTest.java b/src/test/java/io/floci/aws/services/kms/KmsRotationConcurrencyServiceTest.java new file mode 100644 index 0000000000..605c17cf9d --- /dev/null +++ b/src/test/java/io/floci/aws/services/kms/KmsRotationConcurrencyServiceTest.java @@ -0,0 +1,234 @@ +package io.floci.aws.services.kms; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.kms.model.KmsKey; +import io.floci.aws.testing.ThreadStates; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BiPredicate; + +import static org.junit.jupiter.api.Assertions.*; + +class KmsRotationConcurrencyServiceTest { + private static final String REGION = "us-east-1"; + private static final String REPLICA_REGION = "us-west-2"; + private static final byte[] PLAINTEXT = "concurrent rotation".getBytes(StandardCharsets.UTF_8); + + @Test + void aMetadataWriterCannotRepublishMaterialFromBeforeRotation() throws Exception { + PausingKeys keys = new PausingKeys(); + KmsService service = service(keys); + KmsKey key = service.createKey("before", REGION); + keys.pauseWhen((name, value) -> "after".equals(value.getDescription())); + Worker metadata = start(() -> { + service.updateKeyDescription(key.getKeyId(), "after", REGION); + return null; + }); + keys.awaitPaused(); + Worker rotation = start(() -> { + service.rotateKeyOnDemand(key.getKeyId(), REGION); + return service.encrypt(key.getKeyId(), PLAINTEXT, REGION); + }); + try { + ThreadStates.awaitBlockedOrDone(rotation.thread()); + } finally { + keys.resume(); + } + metadata.result(); + byte[] ciphertext = rotation.result(); + + KmsKey current = service.describeKey(key.getKeyId(), REGION); + assertEquals("after", current.getDescription()); + assertEquals(1, current.getOnDemandRotationCount()); + assertEquals(2, current.getBackingKeys().size()); + assertEquals(1, service.listKeyRotations(key.getKeyId(), null, REGION, null, null).items().size()); + assertArrayEquals(PLAINTEXT, service.decrypt(ciphertext, REGION)); + } + + @Test + void rotationPublicationCannotEraseAConcurrentDeletionSchedule() throws Exception { + PausingKeys keys = new PausingKeys(); + KmsService service = service(keys); + KmsKey key = service.createKey("pending deletion", REGION); + keys.pauseWhen((name, value) -> value.getOnDemandRotationCount() == 1); + Worker rotation = start(() -> service.rotateKeyOnDemand(key.getKeyId(), REGION)); + keys.awaitPaused(); + Worker deletion = start(() -> { + service.scheduleKeyDeletion(key.getKeyId(), 7, REGION); + return null; + }); + try { + ThreadStates.awaitBlockedOrDone(deletion.thread()); + } finally { + keys.resume(); + } + rotation.result(); + deletion.result(); + + KmsKey current = service.describeKey(key.getKeyId(), REGION); + assertEquals("PendingDeletion", current.getKeyState()); + assertTrue(current.getDeletionDate() > 0); + assertEquals(1, current.getOnDemandRotationCount()); + assertEquals(2, current.getBackingKeys().size()); + assertEquals(1, service.listKeyRotations(key.getKeyId(), null, REGION, null, null).items().size()); + } + + @Test + void aReplicaPublishedDuringRotationReceivesTheNewMaterialAndHistory() throws Exception { + PausingKeys keys = new PausingKeys(); + KmsService service = service(keys); + KmsKey primary = service.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", + null, Map.of(), null, true, REGION); + keys.pauseWhen((name, value) -> name.startsWith(REPLICA_REGION + "::")); + Worker replication = start(() -> service.replicateKey( + primary.getKeyId(), "replica", null, Map.of(), REPLICA_REGION, REGION)); + keys.awaitPaused(); + Worker rotation = start(() -> { + service.rotateKeyOnDemand(primary.getKeyId(), REGION); + return service.encrypt(primary.getKeyId(), PLAINTEXT, REGION); + }); + try { + ThreadStates.awaitBlockedOrDone(rotation.thread()); + } finally { + keys.resume(); + } + replication.result(); + byte[] ciphertext = rotation.result(); + + KmsKey current = service.describeKey(primary.getKeyId(), REGION); + KmsKey replica = service.describeKey(primary.getKeyId(), REPLICA_REGION); + assertEquals(current.getBackingKeys(), replica.getBackingKeys()); + assertEquals(current.getCurrentBackingKeyId(), replica.getCurrentBackingKeyId()); + assertEquals(service.listKeyRotations(primary.getKeyId(), null, REGION, null, null).items(), + service.listKeyRotations(primary.getKeyId(), null, REPLICA_REGION, null, null).items()); + assertArrayEquals(PLAINTEXT, service.decrypt(ciphertext, REPLICA_REGION)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void anUnrelatedKeyRemainsUsableWhileAnotherKeyIsPublishing(boolean rotate) throws Exception { + PausingKeys keys = new PausingKeys(); + KmsService service = service(keys); + KmsKey blocked = service.createKey("blocked", REGION); + KmsKey other = service.createKey("unrelated", REGION); + while (Math.floorMod(blocked.getKeyId().hashCode(), 256) + == Math.floorMod(other.getKeyId().hashCode(), 256)) { + other = service.createKey("unrelated", REGION); + } + String otherId = other.getKeyId(); + keys.pauseWhen((name, value) -> name.equals(REGION + "::" + blocked.getKeyId())); + Worker writer = start(() -> { + if (rotate) { + service.rotateKeyOnDemand(blocked.getKeyId(), REGION); + } else { + service.updateKeyDescription(blocked.getKeyId(), "after", REGION); + } + return null; + }); + keys.awaitPaused(); + Worker independent = start(() -> { + assertEquals(otherId, service.describeKey(otherId, REGION).getKeyId()); + service.updateKeyDescription(otherId, "still usable", REGION); + byte[] encrypted = service.encrypt(otherId, PLAINTEXT, REGION); + return service.decrypt(encrypted, REGION); + }); + try { + assertArrayEquals(PLAINTEXT, independent.future().get(2, TimeUnit.SECONDS)); + } finally { + keys.resume(); + writer.result(); + independent.result(); + } + assertEquals("still usable", service.describeKey(otherId, REGION).getDescription()); + } + + @Test + void writersPreserveMalformedKeyArnErrors() { + KmsService service = service(new PausingKeys()); + String arn = "arn:aws:kms:" + REGION + ":000000000000:key/invalid-id"; + AwsException rotation = assertThrows(AwsException.class, () -> service.rotateKeyOnDemand(arn, REGION)); + AwsException metadata = assertThrows(AwsException.class, + () -> service.updateKeyDescription(arn, "updated", REGION)); + assertEquals("Invalid keyId invalid-id", rotation.getMessage()); + assertEquals(rotation.getMessage(), metadata.getMessage()); + } + + private static KmsService service(PausingKeys keys) { + return new KmsService(keys, new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver(REGION, "000000000000")); + } + + private static Worker start(Callable operation) { + CompletableFuture result = new CompletableFuture<>(); + Thread thread = Thread.ofPlatform().daemon().start(() -> { + try { + result.complete(operation.call()); + } catch (Throwable error) { + result.completeExceptionally(error); + } + }); + return new Worker<>(thread, result); + } + + private record Worker(Thread thread, CompletableFuture future) { + private T result() throws Exception { + return future.get(5, TimeUnit.SECONDS); + } + } + + private static final class PausingKeys extends InMemoryStorage { + private final CountDownLatch paused = new CountDownLatch(1); + private final CountDownLatch resume = new CountDownLatch(1); + private final AtomicBoolean claimed = new AtomicBoolean(); + private BiPredicate pause; + + private void pauseWhen(BiPredicate condition) { + pause = condition; + } + + private void awaitPaused() throws InterruptedException { + assertTrue(paused.await(5, TimeUnit.SECONDS), "writer did not reach its publication"); + } + + private void resume() { + resume.countDown(); + } + + @Override + public void put(String name, KmsKey key) { + pausePublication(name, key); + super.put(name, key); + } + + @Override + public void putAllAtomically(Map entries) { + entries.forEach(this::pausePublication); + super.putAllAtomically(entries); + } + + private void pausePublication(String name, KmsKey key) { + if (pause != null && pause.test(name, key) && claimed.compareAndSet(false, true)) { + paused.countDown(); + try { + if (!resume.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("test did not release paused publication"); + } + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("paused publication interrupted", error); + } + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/kms/KmsRotationPublicationServiceTest.java b/src/test/java/io/floci/aws/services/kms/KmsRotationPublicationServiceTest.java new file mode 100644 index 0000000000..580b04bc60 --- /dev/null +++ b/src/test/java/io/floci/aws/services/kms/KmsRotationPublicationServiceTest.java @@ -0,0 +1,205 @@ +package io.floci.aws.services.kms; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.HybridStorage; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.PersistentStorage; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.WalStorage; +import io.floci.aws.services.kms.model.KmsKey; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class KmsRotationPublicationServiceTest { + @TempDir + Path directory; + + private static class Keys extends InMemoryStorage { + private boolean reject; + private final IllegalStateException fault = new IllegalStateException("synthetic rejected write"); + + @Override + public void put(String name, KmsKey key) { + if (reject) { + throw fault; + } + super.put(name, key); + } + } + + @Test + void rejectedWritePreservesSnapshotAndSuccessfulRetryPublishesOnce() throws Exception { + Keys keys = new Keys(); + KmsService service = new KmsService(keys, new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000")); + KmsKey key = service.createKey("synthetic publication regression", "us-east-1"); + ObjectMapper mapper = new ObjectMapper(); + byte[] plaintext = "before rejected rotation".getBytes(StandardCharsets.UTF_8); + byte[] ciphertext = service.encrypt(key.getKeyId(), plaintext, "us-east-1"); + String location = "us-east-1::" + key.getKeyId(); + ObjectNode before = mapper.valueToTree(keys.get(location).orElseThrow()); + keys.reject = true; + + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> service.rotateKeyOnDemand(key.getKeyId(), "us-east-1")); + + assertSame(keys.fault, failure); + assertEquals(before, mapper.valueToTree(keys.get(location).orElseThrow())); + assertTrue(service.listKeyRotations(key.getKeyId(), null, "us-east-1", null, null).items().isEmpty()); + assertArrayEquals(plaintext, service.decrypt(ciphertext, "us-east-1")); + keys.reject = false; + + service.rotateKeyOnDemand(key.getKeyId(), "us-east-1"); + + KmsKey rotated = keys.get(location).orElseThrow(); + assertNotSame(key, rotated); + assertEquals(1, rotated.getOnDemandRotationCount()); + assertEquals(2, rotated.getBackingKeys().size()); + assertEquals(1, service.listKeyRotations(key.getKeyId(), null, "us-east-1", null, null).items().size()); + assertArrayEquals(plaintext, service.decrypt(ciphertext, "us-east-1")); + ObjectNode after = mapper.valueToTree(rotated); + for (String field : List.of("onDemandRotationCount", "backingKeys", "currentBackingKeyId", + "backingKeyRotationDates")) { + before.remove(field); + after.remove(field); + } + assertEquals(before, after); + } + + @Test + void rejectedReplicaWritePreservesBothSnapshotsAndRetryPublishesOnce() throws Exception { + String primaryRegion = "us-east-1"; + String replicaRegion = "us-west-2"; + IllegalStateException fault = new IllegalStateException("synthetic replica rejection"); + boolean[] reject = {false}; + InMemoryStorage keys = new InMemoryStorage<>() { + @Override + public void put(String name, KmsKey key) { + if (reject[0] && name.startsWith(replicaRegion + "::")) { + throw fault; + } + super.put(name, key); + } + + @Override + public void putAllAtomically(Map entries) { + if (reject[0] && entries.keySet().stream() + .anyMatch(name -> name.startsWith(replicaRegion + "::"))) { + throw fault; + } + super.putAllAtomically(entries); + } + }; + KmsService service = new KmsService(keys, new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver(primaryRegion, "000000000000")); + KmsKey primary = service.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", + null, Map.of(), null, true, primaryRegion); + service.replicateKey(primary.getKeyId(), "replica", null, Map.of(), replicaRegion, primaryRegion); + ObjectMapper mapper = new ObjectMapper(); + ObjectNode primaryBefore = mapper.valueToTree(service.describeKey(primary.getKeyId(), primaryRegion)); + ObjectNode replicaBefore = mapper.valueToTree(service.describeKey(primary.getKeyId(), replicaRegion)); + byte[] plaintext = "replica publication".getBytes(StandardCharsets.UTF_8); + byte[] oldCiphertext = service.encrypt(primary.getKeyId(), plaintext, primaryRegion); + reject[0] = true; + + assertSame(fault, assertThrows(IllegalStateException.class, + () -> service.rotateKeyOnDemand(primary.getKeyId(), primaryRegion))); + + assertEquals(primaryBefore, mapper.valueToTree(service.describeKey(primary.getKeyId(), primaryRegion))); + assertEquals(replicaBefore, mapper.valueToTree(service.describeKey(primary.getKeyId(), replicaRegion))); + assertEquals(0, service.describeKey(primary.getKeyId(), primaryRegion).getOnDemandRotationCount()); + for (String region : List.of(primaryRegion, replicaRegion)) { + assertTrue(service.listKeyRotations(primary.getKeyId(), null, region, null, null).items().isEmpty()); + assertArrayEquals(plaintext, service.decrypt(oldCiphertext, region)); + } + reject[0] = false; + + service.rotateKeyOnDemand(primary.getKeyId(), primaryRegion); + + byte[] newCiphertext = service.encrypt(primary.getKeyId(), plaintext, primaryRegion); + assertEquals(1, service.describeKey(primary.getKeyId(), primaryRegion).getOnDemandRotationCount()); + for (String region : List.of(primaryRegion, replicaRegion)) { + assertEquals(1, service.listKeyRotations(primary.getKeyId(), null, region, null, null).items().size()); + assertArrayEquals(plaintext, service.decrypt(oldCiphertext, region)); + assertArrayEquals(plaintext, service.decrypt(newCiphertext, region)); + } + } + + @ParameterizedTest + @ValueSource(strings = {"persistent", "hybrid", "wal"}) + void acceptedReplicaRotationSurvivesStorageRestart(String mode) { + StorageBackend keys = persistentKeys(mode); + keys.load(); + String primaryRegion = "us-east-1"; + String replicaRegion = "us-west-2"; + String keyId; + byte[] plaintext = "persistent rotation".getBytes(StandardCharsets.UTF_8); + byte[] oldCiphertext; + byte[] newCiphertext; + try { + KmsService service = service(keys, primaryRegion); + KmsKey primary = service.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", + null, Map.of(), null, true, primaryRegion); + keyId = primary.getKeyId(); + service.replicateKey(keyId, "replica", null, Map.of(), replicaRegion, primaryRegion); + oldCiphertext = service.encrypt(keyId, plaintext, primaryRegion); + service.rotateKeyOnDemand(keyId, primaryRegion); + newCiphertext = service.encrypt(keyId, plaintext, primaryRegion); + keys.flush(); + } finally { + close(keys); + } + + StorageBackend reopened = persistentKeys(mode); + reopened.load(); + try { + KmsService service = service(reopened, primaryRegion); + assertEquals(1, service.describeKey(keyId, primaryRegion).getOnDemandRotationCount()); + for (String region : List.of(primaryRegion, replicaRegion)) { + assertEquals(1, service.listKeyRotations(keyId, null, region, null, null).items().size()); + assertArrayEquals(plaintext, service.decrypt(oldCiphertext, region)); + assertArrayEquals(plaintext, service.decrypt(newCiphertext, region)); + } + assertEquals(service.describeKey(keyId, primaryRegion).getBackingKeys(), + service.describeKey(keyId, replicaRegion).getBackingKeys()); + } finally { + close(reopened); + } + } + + private StorageBackend persistentKeys(String mode) { + TypeReference> type = new TypeReference<>() {}; + Path snapshot = directory.resolve("keys.json"); + return switch (mode) { + case "persistent" -> new PersistentStorage<>(snapshot, type); + case "hybrid" -> new HybridStorage<>(snapshot, type, Long.MAX_VALUE); + case "wal" -> new WalStorage<>(snapshot, directory.resolve("keys.wal"), type, Long.MAX_VALUE); + default -> throw new IllegalArgumentException("Unsupported test storage mode: " + mode); + }; + } + + private static KmsService service(StorageBackend keys, String region) { + return new KmsService(keys, new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver(region, "000000000000")); + } + + private static void close(StorageBackend keys) { + if (keys instanceof HybridStorage hybrid) { + hybrid.shutdown(); + } else if (keys instanceof WalStorage wal) { + wal.shutdown(); + } + } +}