mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(kms): list completed key rotations (#8146)
Record completed rotation history, validate filtering and pagination, preserve concurrent key updates, and publish primary and replica material as one atomic storage batch. Revalidate the initially resolved key before atomically publishing import parameters, preserving deletion safety and alias identity. Share the malformed rotation request fixture. Use shared striped monitors keyed by resolved key ID, preserving replica publication and import identity while permitting unrelated key operations. Reuse shared concurrency and SDK fixtures. Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
919f25ea0b
commit
c3551d351e
12 files changed
+1330
-202
No files matched your search
@@ -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();
|
||||
|
||||
+104
@@ -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<KmsService.ImportParameters> pending = fixture.start(key.getKeyId());
|
||||
Future<KmsKey> 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<KmsService.ImportParameters> 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<KmsService.ImportParameters> 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<KmsService.ImportParameters> start(String keyId) throws InterruptedException {
|
||||
Future<KmsService.ImportParameters> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, KmsKey> 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<KmsService.KeyRotation> 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<KmsService.KeyRotation> 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<KmsService.KeyRotation> 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<KmsService.KeyRotation> expected = list(key, "ALL_KEY_MATERIAL").items();
|
||||
List<KmsService.KeyRotation> walked = new ArrayList<>();
|
||||
String marker = null;
|
||||
do {
|
||||
KmsService.Page<KmsService.KeyRotation> 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<KmsService.KeyRotation> 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<String, String> 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<KmsService.KeyRotation> 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<KmsService.KeyRotation> 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());
|
||||
}
|
||||
}
|
||||
@@ -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<Void> metadata = start(() -> {
|
||||
service.updateKeyDescription(key.getKeyId(), "after", REGION);
|
||||
return null;
|
||||
});
|
||||
keys.awaitPaused();
|
||||
Worker<byte[]> 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<String> rotation = start(() -> service.rotateKeyOnDemand(key.getKeyId(), REGION));
|
||||
keys.awaitPaused();
|
||||
Worker<Void> 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<KmsKey> replication = start(() -> service.replicateKey(
|
||||
primary.getKeyId(), "replica", null, Map.of(), REPLICA_REGION, REGION));
|
||||
keys.awaitPaused();
|
||||
Worker<byte[]> 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<Void> writer = start(() -> {
|
||||
if (rotate) {
|
||||
service.rotateKeyOnDemand(blocked.getKeyId(), REGION);
|
||||
} else {
|
||||
service.updateKeyDescription(blocked.getKeyId(), "after", REGION);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
keys.awaitPaused();
|
||||
Worker<byte[]> 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 <T> Worker<T> start(Callable<T> operation) {
|
||||
CompletableFuture<T> 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<T>(Thread thread, CompletableFuture<T> future) {
|
||||
private T result() throws Exception {
|
||||
return future.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class PausingKeys extends InMemoryStorage<String, KmsKey> {
|
||||
private final CountDownLatch paused = new CountDownLatch(1);
|
||||
private final CountDownLatch resume = new CountDownLatch(1);
|
||||
private final AtomicBoolean claimed = new AtomicBoolean();
|
||||
private BiPredicate<String, KmsKey> pause;
|
||||
|
||||
private void pauseWhen(BiPredicate<String, KmsKey> 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<String, KmsKey> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, KmsKey> {
|
||||
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<String, KmsKey> 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<String, KmsKey> 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<String, KmsKey> 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<String, KmsKey> 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<String, KmsKey> persistentKeys(String mode) {
|
||||
TypeReference<Map<String, KmsKey>> 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<String, KmsKey> keys, String region) {
|
||||
return new KmsService(keys, new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(region, "000000000000"));
|
||||
}
|
||||
|
||||
private static void close(StorageBackend<String, KmsKey> keys) {
|
||||
if (keys instanceof HybridStorage<String, KmsKey> hybrid) {
|
||||
hybrid.shutdown();
|
||||
} else if (keys instanceof WalStorage<String, KmsKey> wal) {
|
||||
wal.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user