Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(kms): implement ReplicateKey for multi-region keys (#4176)

XuJian9dd2bd62e44a
diff --git a/docs/services/kms.md b/docs/services/kms.md
index 6bb29580cc..41892c6fd6 100644
--- a/docs/services/kms.md
+++ b/docs/services/kms.md
@@ -12,6 +12,7 @@
| `GenerateRandom` | Generate random bytes |
| `GetPublicKey` | Get public key material for asymmetric keys |
| `DescribeKey` | Get key metadata |
+| `ReplicateKey` | Create a multi-Region replica of a primary key |
| `ListKeys` | List all keys |
| `CreateGrant` | Create a grant for a KMS key |
| `ListGrants` | List grants for a KMS key |
diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java
index 7ccd6ecd44..f47eb948ae 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java
@@ -37,7 +37,7 @@ public class KmsJsonHandler {
}
private static final Set<String> KEY_ID_OPERATIONS = Set.of(
- "GetPublicKey", "DescribeKey", "CreateGrant", "ListGrants", "RevokeGrant", "Encrypt", "GenerateDataKey",
+ "GetPublicKey", "DescribeKey", "ReplicateKey", "CreateGrant", "ListGrants", "RevokeGrant", "Encrypt", "GenerateDataKey",
"GenerateDataKeyWithoutPlaintext", "Sign", "Verify", "GenerateMac", "VerifyMac", "ScheduleKeyDeletion",
"CancelKeyDeletion", "TagResource", "UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy",
"ListKeyPolicies", "UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation",
@@ -45,7 +45,7 @@ public class KmsJsonHandler {
"ImportKeyMaterial", "DeleteImportedKeyMaterial");
private static final Set<String> KEY_ONLY_OPERATIONS = Set.of(
- "CreateGrant", "ListGrants", "RevokeGrant", "ScheduleKeyDeletion", "CancelKeyDeletion", "TagResource",
+ "ReplicateKey", "CreateGrant", "ListGrants", "RevokeGrant", "ScheduleKeyDeletion", "CancelKeyDeletion", "TagResource",
"UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy", "ListKeyPolicies",
"UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation", "DisableKeyRotation", "EnableKey",
"DisableKey", "RotateKeyOnDemand", "GetParametersForImport", "ImportKeyMaterial",
@@ -68,6 +68,7 @@ public class KmsJsonHandler {
case "GenerateRandom" -> handleGenerateRandom(request, region);
case "GetPublicKey" -> handleGetPublicKey(request, region);
case "DescribeKey" -> handleDescribeKey(request, region);
+ case "ReplicateKey" -> handleReplicateKey(request, region);
case "ListKeys" -> handleListKeys(request, region);
case "CreateGrant" -> handleCreateGrant(request, region);
case "ListGrants" -> handleListGrants(request, region);
@@ -122,12 +123,31 @@ public class KmsJsonHandler {
request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText()));
rejectUnknownReservedTags(tags,"TagException");
String origin = request.path("Origin").asText(null);
- KmsKey key = service.createKey(description, keyUsage, keySpec, policy, tags, origin, region);
+ boolean multiRegion = request.path("MultiRegion").asBoolean(false);
+ KmsKey key = service.createKey(description, keyUsage, keySpec, policy, tags, origin, multiRegion, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("KeyMetadata", addKeyMetadata(key));
return Response.ok(response).build();
}
+ private Response handleReplicateKey(JsonNode request, String region) {
+ String description = request.path("Description").asText(null);
+ String policy = request.path("Policy").isMissingNode() ? null : request.path("Policy").asText(null);
+ String replicaRegion = requiredText(request, "ReplicaRegion");
+ Map<String, String> tags = new HashMap<>();
+ request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText()));
+ rejectUnknownReservedTags(tags, "TagException");
+
+ KmsKey replica = service.replicateKey(request.path("KeyId").asText(), description, policy,
+ tags, replicaRegion, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("ReplicaKeyMetadata", addKeyMetadata(replica));
+ response.put("ReplicaPolicy", replica.getPolicy());
+ ArrayNode replicaTags = response.putArray("ReplicaTags");
+ addTags(replicaTags, replica);
+ return Response.ok(response).build();
+ }
+
private Response handleGetPublicKey(JsonNode request, String region) {
String keyId = request.path("KeyId").asText();
KmsKey key = service.getPublicKey(keyId, region);
@@ -754,6 +774,10 @@ public class KmsJsonHandler {
keyMetadata.put("KeyManager", "CUSTOMER");
keyMetadata.put("CustomerMasterKeySpec", k.getKeySpec().name());
keyMetadata.put("KeySpec", k.getKeySpec().name());
+ keyMetadata.put("MultiRegion", k.isMultiRegion());
+ if (k.isMultiRegion()) {
+ keyMetadata.set("MultiRegionConfiguration", addMultiRegionConfiguration(k));
+ }
addAlgorithms(k, keyMetadata);
if (k.getDeletionDate() > 0) {
keyMetadata.put("DeletionDate", k.getDeletionDate());
@@ -761,6 +785,49 @@ public class KmsJsonHandler {
return keyMetadata;
}
+ private ObjectNode addMultiRegionConfiguration(KmsKey key) {
+ ObjectNode configuration = objectMapper.createObjectNode();
+ configuration.put("MultiRegionKeyType", key.getMultiRegionKeyType());
+
+ String primaryRegion = key.getMultiRegionPrimaryRegion();
+ KmsKey primary = service.listKeys(primaryRegion).stream()
+ .filter(candidate -> candidate.isMultiRegion())
+ .filter(candidate -> key.getKeyId().equals(candidate.getKeyId()))
+ .filter(candidate -> "PRIMARY".equals(candidate.getMultiRegionKeyType()))
+ .findFirst()
+ .orElseGet(() -> {
+ KmsKey fallback = new KmsKey();
+ fallback.setArn(regionResolver.buildArn("kms", primaryRegion, "key/" + key.getKeyId()));
+ return fallback;
+ });
+ ObjectNode primaryKey = configuration.putObject("PrimaryKey");
+ primaryKey.put("Arn", primary.getArn());
+ primaryKey.put("Region", primaryRegion);
+
+ ArrayNode replicas = configuration.putArray("ReplicaKeys");
+ for (KmsKey candidate : service.listAllMultiRegionKeys(key.getKeyId())) {
+ if (!"PRIMARY".equals(candidate.getMultiRegionKeyType())) {
+ ObjectNode replica = replicas.addObject();
+ replica.put("Arn", candidate.getArn());
+ replica.put("Region", regionFromArn(candidate.getArn()));
+ }
+ }
+ return configuration;
+ }
+
+ private static String regionFromArn(String arn) {
+ String[] parts = arn.split(":", 6);
+ return parts.length > 3 ? parts[3] : "";
+ }
+
+ private static void addTags(ArrayNode array, KmsKey key) {
+ key.getTags().forEach((keyName, value) -> {
+ ObjectNode tag = array.addObject();
+ tag.put("TagKey", keyName);
+ tag.put("TagValue", value);
+ });
+ }
+
private ObjectNode errorResponse(String code, String message) {
ObjectNode error = objectMapper.createObjectNode();
error.put("__type", code);
diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java
index 41475f1e91..11acdb8ece 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.kms;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
@@ -44,6 +45,8 @@ public class KmsService implements ResourceProvider {
private static final String EXTERNAL_ORIGIN = "EXTERNAL";
private static final String PENDING_IMPORT = "PendingImport";
private static final String PENDING_DELETION = "PendingDeletion";
+ private static final String MULTI_REGION_PRIMARY = "PRIMARY";
+ private static final String MULTI_REGION_REPLICA = "REPLICA";
private static final String KEY_MATERIAL_EXPIRES = "KEY_MATERIAL_EXPIRES";
private static final String KEY_MATERIAL_DOES_NOT_EXPIRE = "KEY_MATERIAL_DOES_NOT_EXPIRE";
private static final Duration IMPORT_PARAMETERS_VALIDITY = Duration.ofHours(24);
@@ -126,7 +129,12 @@ public class KmsService implements ResourceProvider {
public KmsKey createKey(String description, String keyUsage, String keySpec, String policy,
Map<String, String> tags, String origin, String region) {
- String keyId = resolveKeyId(tags);
+ return createKey(description, keyUsage, keySpec, policy, tags, origin, false, region);
+ }
+
+ public KmsKey createKey(String description, String keyUsage, String keySpec, String policy,
+ Map<String, String> tags, String origin, boolean multiRegion, String region) {
+ String keyId = resolveKeyId(tags, multiRegion);
if (keyStore.get(region + "::" + keyId).isPresent()) {
throw new AwsException("AlreadyExistsException", "Key already exists", 400);
}
@@ -149,6 +157,11 @@ public class KmsService implements ResourceProvider {
key.setPolicy(policy != null ? policy : buildDefaultKeyPolicy());
key.getTags().putAll(ReservedTags.stripReservedTags(tags));
key.setOrigin(resolveOrigin(origin, effectiveSpec));
+ key.setMultiRegion(multiRegion);
+ if (multiRegion) {
+ key.setMultiRegionKeyType(MULTI_REGION_PRIMARY);
+ key.setMultiRegionPrimaryRegion(region);
+ }
if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {
key.setKeyState(PENDING_IMPORT);
@@ -163,10 +176,11 @@ public class KmsService implements ResourceProvider {
return key;
}
- private String resolveKeyId(Map<String, String> tags) {
+ private String resolveKeyId(Map<String, String> tags, boolean multiRegion) {
String overrideId = ReservedTags.extractOverrideKeyId(tags);
if (overrideId == null) {
- return UUID.randomUUID().toString();
+ String generatedId = UUID.randomUUID().toString();
+ return multiRegion ? "mrk-" + generatedId.replace("-", "") : generatedId;
}
String normalized = overrideId.trim();
@@ -176,6 +190,9 @@ public class KmsService implements ResourceProvider {
if (normalized.length() > 256) {
throw new AwsException("TagException", "Override resource ID must be 256 characters or fewer.", 400);
}
+ if (multiRegion && !normalized.startsWith("mrk-")) {
+ throw new AwsException("TagException", "Multi-Region key IDs must start with 'mrk-'.", 400);
+ }
return normalized;
}
@@ -284,11 +301,81 @@ public class KmsService implements ResourceProvider {
return resolveKey(keyId, region);
}
+ public KmsKey replicateKey(String keyId, String description, String policy,
+ Map<String, String> tags, String replicaRegion, String primaryRegion) {
+ if (replicaRegion == null || replicaRegion.isBlank()) {
+ throw new AwsException("ValidationException", "ReplicaRegion is required.", 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);
+ }
+
+ 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());
+ }
+ 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) {
+ requireNotPendingDeletion(key);
+ requireImportedKeyMaterial(key);
+ if (!key.isEnabled()) {
+ throw new AwsException("DisabledException", key.getArn() + " is disabled.", 400);
+ }
+ }
+
public List<KmsKey> listKeys(String region) {
String prefix = region + "::";
return keyStore.scan(k -> k.startsWith(prefix));
}
+ public List<KmsKey> listAllMultiRegionKeys(String keyId) {
+ String suffix = "::" + keyId;
+ return keyStore.scan(key -> key.endsWith(suffix)).stream()
+ .filter(KmsKey::isMultiRegion)
+ .toList();
+ }
+
/** GrantOperation enum from the KMS model (kms/2014-11-01/service-2.json). */
private static final Set<String> GRANT_OPERATIONS = new LinkedHashSet<>(List.of(
"Decrypt", "Encrypt", "GenerateDataKey", "GenerateDataKeyWithoutPlaintext",
@@ -719,6 +806,10 @@ public class KmsService implements ResourceProvider {
synchronized (backingKeyMaterialLock) {
KmsKey key = resolveKey(keyId, region);
validateKeyIsUsableForCryptoOperations(key);
+ if (MULTI_REGION_REPLICA.equals(key.getMultiRegionKeyType())) {
+ throw new AwsException("UnsupportedOperationException",
+ "On-demand rotation is only supported for the multi-Region primary key.", 400);
+ }
validateRotationKeySpec(key);
if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {
throw new AwsException("KMSInvalidStateException",
@@ -733,10 +824,25 @@ public class KmsService implements ResourceProvider {
// decrypting.
keyTypes.symmetric().addBackingKey(key);
keyStore.put(region + "::" + key.getKeyId(), key);
+ if (MULTI_REGION_PRIMARY.equals(key.getMultiRegionKeyType())) {
+ synchronizeMultiRegionReplicas(key);
+ }
return key.getKeyId();
}
}
+ private void synchronizeMultiRegionReplicas(KmsKey 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);
+ }
+ }
+
private static void validateRotationOrigin(KmsKey key) {
if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {
throw invalidOrigin(key);
diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java
index eb99a0470e..1aeb4e119e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java
+++ b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsKey.java
@@ -22,6 +22,9 @@ public class KmsKey {
private String keyMaterialId;
private KmsKeyUsage keyUsage = KmsKeyUsage.ENCRYPT_DECRYPT;
private KmsKeySpec keySpec = KmsKeySpec.SYMMETRIC_DEFAULT;
+ private boolean multiRegion;
+ private String multiRegionKeyType;
+ private String multiRegionPrimaryRegion;
private long creationDate;
private long deletionDate;
private String policy;
@@ -81,6 +84,17 @@ public class KmsKey {
public KmsKeySpec getKeySpec() { return keySpec; }
public void setKeySpec(KmsKeySpec spec) { this.keySpec = spec; }
+ public boolean isMultiRegion() { return multiRegion; }
+ public void setMultiRegion(boolean multiRegion) { this.multiRegion = multiRegion; }
+
+ public String getMultiRegionKeyType() { return multiRegionKeyType; }
+ public void setMultiRegionKeyType(String multiRegionKeyType) { this.multiRegionKeyType = multiRegionKeyType; }
+
+ public String getMultiRegionPrimaryRegion() { return multiRegionPrimaryRegion; }
+ public void setMultiRegionPrimaryRegion(String multiRegionPrimaryRegion) {
+ this.multiRegionPrimaryRegion = multiRegionPrimaryRegion;
+ }
+
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java
index 175509e63b..4c03c93eb5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java
@@ -41,6 +41,87 @@ class KmsIntegrationTest {
RestAssuredJsonUtils.configureAwsContentTypes();
}
+ @Test
+ void replicateKeyReturnsMultiRegionMetadataThroughJsonHandler() {
+ String keyId = given()
+ .header("X-Amz-Target", "TrentService.CreateKey")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "Description": "multi-region-primary",
+ "MultiRegion": true
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("KeyMetadata.MultiRegion", equalTo(true))
+ .body("KeyMetadata.KeyId", matchesPattern("mrk-[0-9a-f]{32}"))
+ .body("KeyMetadata.MultiRegionConfiguration.MultiRegionKeyType", equalTo("PRIMARY"))
+ .extract().path("KeyMetadata.KeyId");
+
+ String replicaKeyArn = given()
+ .header("X-Amz-Target", "TrentService.ReplicateKey")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "KeyId": "%s",
+ "ReplicaRegion": "us-west-2",
+ "Description": "multi-region-replica",
+ "Tags": [{"TagKey":"environment","TagValue":"test"}]
+ }
+ """.formatted(keyId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ReplicaKeyMetadata.KeyId", equalTo(keyId))
+ .body("ReplicaKeyMetadata.MultiRegion", equalTo(true))
+ .body("ReplicaKeyMetadata.MultiRegionConfiguration.MultiRegionKeyType", equalTo("REPLICA"))
+ .body("ReplicaKeyMetadata.MultiRegionConfiguration.PrimaryKey.Region", equalTo("us-east-1"))
+ .body("ReplicaKeyMetadata.MultiRegionConfiguration.ReplicaKeys[0].Region", equalTo("us-west-2"))
+ .body("ReplicaPolicy", notNullValue())
+ .body("ReplicaTags[0].TagKey", equalTo("environment"))
+ .body("ReplicaTags[0].TagValue", equalTo("test"))
+ .extract().path("ReplicaKeyMetadata.Arn");
+
+ String plaintext = Base64.getEncoder().encodeToString(
+ "multi-region payload".getBytes(StandardCharsets.UTF_8));
+ String ciphertext = given()
+ .header("X-Amz-Target", "TrentService.Encrypt")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "KeyId": "%s",
+ "Plaintext": "%s"
+ }
+ """.formatted(keyId, plaintext))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("CiphertextBlob");
+
+ given()
+ .header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=AKID/20260922/us-west-2/kms/aws4_request")
+ .header("X-Amz-Target", "TrentService.Decrypt")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("""
+ {
+ "KeyId": "%s",
+ "CiphertextBlob": "%s"
+ }
+ """.formatted(keyId, ciphertext))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Plaintext", equalTo(plaintext))
+ .body("KeyId", equalTo(replicaKeyArn));
+ }
+
@Test
void updateKeyDescriptionRoundTripThroughJsonHandler() {
var key = given()
diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java
index b3f4840530..bffde6f1ff 100644
--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java
@@ -1,5 +1,8 @@
package io.github.hectorvent.floci.services.kms;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
@@ -10,6 +13,7 @@ import io.github.hectorvent.floci.services.kms.model.KmsKey;
import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;
import io.github.hectorvent.floci.services.kms.model.KmsKeyUsage;
import io.github.hectorvent.floci.services.kms.model.KmsMessageType;
+import jakarta.ws.rs.core.Response;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -103,6 +107,170 @@ class KmsServiceTest {
assertEquals("Enabled", key.getKeyState());
}
+ @Test
+ void createMultiRegionKeyUsesMrkIdAndPrimaryMetadata() {
+ KmsKey key = kmsService.createKey("multi-region key", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+
+ assertTrue(key.isMultiRegion());
+ assertTrue(key.getKeyId().startsWith("mrk-"));
+ assertEquals("PRIMARY", key.getMultiRegionKeyType());
+ assertEquals(REGION, key.getMultiRegionPrimaryRegion());
+ }
+
+ @Test
+ void replicateMultiRegionKeySharesKeyMaterialAndIdentity() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+
+ KmsKey replica = kmsService.replicateKey(primary.getKeyId(), "replica", null,
+ Map.of("environment", "test"), "us-west-2", REGION);
+
+ assertEquals(primary.getKeyId(), replica.getKeyId());
+ assertEquals("us-west-2", replica.getArn().split(":", 6)[3]);
+ assertEquals("REPLICA", replica.getMultiRegionKeyType());
+ assertEquals(REGION, replica.getMultiRegionPrimaryRegion());
+ assertEquals(primary.getBackingKeys(), replica.getBackingKeys());
+ assertEquals(replica, kmsService.describeKey(primary.getKeyId(), "us-west-2"));
+ }
+
+ @Test
+ void replicaDecryptsCiphertextCreatedByPrimary() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+ kmsService.replicateKey(primary.getKeyId(), "replica", null, Map.of(), "us-west-2", REGION);
+ byte[] plaintext = "multi-region payload".getBytes(StandardCharsets.UTF_8);
+
+ byte[] ciphertext = kmsService.encrypt(primary.getKeyId(), plaintext, REGION);
+ KmsService.DecryptResult result = kmsService.decryptAndResolveKey(
+ ciphertext, Map.of(), "us-west-2", primary.getKeyId());
+
+ assertArrayEquals(plaintext, result.plaintext());
+ assertEquals("arn:aws:kms:us-west-2:000000000000:key/" + primary.getKeyId(), result.keyArn());
+ }
+
+ @Test
+ void rotatingPrimarySynchronizesBackingMaterialToReplica() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+ kmsService.replicateKey(primary.getKeyId(), "replica", null, Map.of(), "us-west-2", REGION);
+
+ byte[] beforePlaintext = "before".getBytes(StandardCharsets.UTF_8);
+ byte[] afterPlaintext = "after".getBytes(StandardCharsets.UTF_8);
+ byte[] beforeRotation = kmsService.encrypt(primary.getKeyId(), beforePlaintext, REGION);
+ kmsService.rotateKeyOnDemand(primary.getKeyId(), REGION);
+ byte[] afterRotation = kmsService.encrypt(primary.getKeyId(), afterPlaintext, REGION);
+
+ assertArrayEquals(beforePlaintext, kmsService.decrypt(beforeRotation, "us-west-2"));
+ assertArrayEquals(afterPlaintext, kmsService.decrypt(afterRotation, "us-west-2"));
+
+ KmsKey storedPrimary = keyStore.get(REGION + "::" + primary.getKeyId()).orElseThrow();
+ KmsKey storedReplica = keyStore.get("us-west-2::" + primary.getKeyId()).orElseThrow();
+ assertEquals(storedPrimary.getBackingKeys(), storedReplica.getBackingKeys());
+ assertEquals(storedPrimary.getCurrentBackingKeyId(), storedReplica.getCurrentBackingKeyId());
+ }
+
+ @Test
+ void rotatingMultiRegionReplicaIsRejected() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+ KmsKey replica = kmsService.replicateKey(primary.getKeyId(), "replica", null, Map.of(), "us-west-2", REGION);
+
+ AwsException exception = assertThrows(AwsException.class,
+ () -> kmsService.rotateKeyOnDemand(replica.getKeyId(), "us-west-2"));
+
+ assertEquals("UnsupportedOperationException", exception.getErrorCode());
+ }
+
+ @Test
+ void missingPrimaryUsesFallbackArnInThePrimaryRegion() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+ KmsKey replica = kmsService.replicateKey(primary.getKeyId(), "replica", null, Map.of(), "us-west-2", REGION);
+ keyStore.delete(REGION + "::" + primary.getKeyId());
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ KmsJsonHandler handler = new KmsJsonHandler(kmsService, objectMapper,
+ new RegionResolver("us-east-1", "000000000000"));
+ ObjectNode request = objectMapper.createObjectNode();
+ request.put("KeyId", replica.getKeyId());
+
+ Response response = handler.handle("DescribeKey", request, "us-west-2");
+ JsonNode body = (JsonNode) response.getEntity();
+ JsonNode primaryKey = body.path("KeyMetadata").path("MultiRegionConfiguration").path("PrimaryKey");
+
+ assertEquals("us-east-1", primaryKey.path("Region").asText());
+ assertEquals("arn:aws:kms:us-east-1:000000000000:key/" + primary.getKeyId(),
+ primaryKey.path("Arn").asText());
+ }
+
+ @Test
+ void replicateNonMultiRegionKeyIsRejected() {
+ KmsKey key = kmsService.createKey("regional", REGION);
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ kmsService.replicateKey(key.getKeyId(), null, null, Map.of(), "us-west-2", REGION));
+
+ assertEquals("UnsupportedOperationException", exception.getErrorCode());
+ }
+
+ @Test
+ void replicateDisabledMultiRegionKeyIsRejected() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+ kmsService.disableKey(primary.getKeyId(), REGION);
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ kmsService.replicateKey(primary.getKeyId(), null, null, Map.of(), "us-west-2", REGION));
+
+ assertEquals("DisabledException", exception.getErrorCode());
+ }
+
+ @Test
+ void replicateMultiRegionKeyPendingDeletionIsRejected() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+ kmsService.scheduleKeyDeletion(primary.getKeyId(), 7, REGION);
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ kmsService.replicateKey(primary.getKeyId(), null, null, Map.of(), "us-west-2", REGION));
+
+ assertEquals("KMSInvalidStateException", exception.getErrorCode());
+ }
+
+ @Test
+ void replicateMultiRegionKeyPendingImportIsRejected() {
+ KmsKey primary = kmsService.createKey("imported primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), "EXTERNAL", true, REGION);
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ kmsService.replicateKey(primary.getKeyId(), null, null, Map.of(), "us-west-2", REGION));
+
+ assertEquals("KMSInvalidStateException", exception.getErrorCode());
+ }
+
+ @Test
+ void replicateToPrimaryRegionIsReportedAsAlreadyExisting() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ kmsService.replicateKey(primary.getKeyId(), null, null, Map.of(), REGION, REGION));
+
+ assertEquals("AlreadyExistsException", exception.getErrorCode());
+ }
+
+ @Test
+ void replicateAcrossPartitionsIsRejectedAsUnsupported() {
+ KmsKey primary = kmsService.createKey("primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), null, true, REGION);
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ kmsService.replicateKey(primary.getKeyId(), null, null, Map.of(), "cn-north-1", REGION));
+
+ assertEquals("UnsupportedOperationException", exception.getErrorCode());
+ }
+
@ParameterizedTest
@ValueSource(strings = {"us-east-1", "cn-fake-1"})
void createSm2KeyReportsRegionUnsupportedOperation(String region) {
@@ -2284,6 +2452,24 @@ class KmsServiceTest {
assertNull(key.getPrivateKeyEncoded());
}
+ @Test
+ void replicatedExternalKeyStartsPendingImportWithoutExpiration() throws Exception {
+ KmsKey primary = kmsService.createKey("external primary", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",
+ null, Map.of(), "EXTERNAL", true, REGION);
+ importInto(primary, material(32, (byte) 0x5A), OAEP_SHA_256);
+
+ KmsKey replica = kmsService.replicateKey(
+ primary.getKeyId(), null, null, Map.of(), "us-west-2", REGION);
+
+ assertEquals("EXTERNAL", replica.getOrigin());
+ assertEquals("PendingImport", replica.getKeyState());
+ assertFalse(replica.isEnabled());
+ assertTrue(replica.getBackingKeys().isEmpty());
+ assertEquals(primary.getKeyMaterialId(), replica.getKeyMaterialId());
+ assertNull(replica.getExpirationModel());
+ assertEquals(0, replica.getValidTo());
+ }
+
@Test
void encryptIsRejectedWhileTheKeyHasNoMaterial() {
String keyId = externalSymmetricKey().getKeyId();