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

This commit is contained in:
XuJian authored and GitHub committed 2026-09-23 00:21:23 -04:00
1 parent e947b6a2a1
commit 9dd2bd62e4
6 files changed
+461 -6

No files matched your search

@@ -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);
@@ -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);
@@ -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; }