feat(kms): implement UpdateAlias (#2324)

* feat(kms): implement UpdateAlias

Repoints an existing alias at a different KMS key, following the
existing createAlias/deleteAlias/resolveKey patterns. Required by the
Terraform AWS provider, which treats a target_key_id change on
aws_kms_alias as an in-place update.

* fix(kms): reject invalid replacement keys in UpdateAlias

UpdateAlias accepted any existing key as a replacement target,
including keys pending deletion or with a different key usage/spec
than the alias's current target. Real AWS KMS rejects both: the
replacement key must be in a compatible state and match the current
target's key usage and key spec.

* fix(kms): compare key type instead of exact key spec in UpdateAlias

The exact KeySpec comparison rejected valid updates between same-type
keys with different specs (e.g. RSA_2048 to RSA_3072), which AWS KMS
accepts as long as both keys share the same key type and usage.

* test(kms): add Terraform compatibility test for UpdateAlias

Verifies the exact scenario from #2291: the Terraform AWS provider
treats target_key_id on aws_kms_alias as an in-place update, so
re-applying with a different target must call UpdateAlias and update
the alias without a destroy/recreate. Self-contained config, mirroring
the eni-destroy-tf pattern, since it needs a second apply with a
different var rather than the shared single-apply main.tf.

* fix(kms): compare key family instead of KeyType in UpdateAlias

Comparing the fine-grained KeyType enum rejected valid cross-family
asymmetric updates (e.g. RSA_2048 to ECC_NIST_P256) that AWS KMS
accepts. AWS only requires the current and new key to be "the same
type (both symmetric or both asymmetric or both HMAC)" - a coarser
three-way split - so compare on that instead.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-15 12:54:39 -04:00
1 parent b45de1bb7d
commit 984886f697
8 files changed
+460

No files matched your search

@@ -0,0 +1,31 @@
# Verifies https://github.com/floci-io/floci/issues/2291
#
# The Terraform AWS provider treats target_key_id on aws_kms_alias as an
# in-place update, not a replacement. Flipping which key the alias points at
# must therefore call UpdateAlias, not CreateAlias/DeleteAlias.
resource "aws_kms_key" "a" {
description = "floci-kms-update-alias-test key A"
}
resource "aws_kms_key" "b" {
description = "floci-kms-update-alias-test key B"
}
variable "use_second_key" {
type = bool
default = false
}
resource "aws_kms_alias" "test" {
name = "alias/floci-kms-update-alias-test"
target_key_id = var.use_second_key ? aws_kms_key.b.key_id : aws_kms_key.a.key_id
}
output "key_a_id" {
value = aws_kms_key.a.key_id
}
output "key_b_id" {
value = aws_kms_key.b.key_id
}
@@ -0,0 +1,28 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
variable "endpoint" {
type = string
default = "http://localhost:4566"
}
provider "aws" {
region = "us-east-1"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
s3_use_path_style = true
endpoints {
kms = var.endpoint
}
}
@@ -0,0 +1,87 @@
#!/usr/bin/env bats
# KMS UpdateAlias Compatibility Test
#
# Reproduces https://github.com/floci-io/floci/issues/2291
#
# The Terraform AWS provider treats a target_key_id change on aws_kms_alias
# as an in-place update (not a replacement), which requires the emulator to
# support the UpdateAlias action. This verifies that re-applying with a
# different target key updates the existing alias rather than erroring or
# recreating it.
setup_file() {
load 'test_helper/common-setup'
KMS_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/kms-update-alias-tf" && pwd)"
cd "$KMS_TF_DIR"
echo "# === KMS UpdateAlias Test ===" >&3
echo "# Endpoint: $FLOCI_ENDPOINT" >&3
echo "# Config: $KMS_TF_DIR" >&3
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
echo "# --- terraform init ---" >&3
run terraform init -input=false -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform init failed: $output" >&3
return 1
fi
echo "# --- terraform apply (alias -> key A) ---" >&3
run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform apply failed: $output" >&3
return 1
fi
}
teardown_file() {
load 'test_helper/common-setup'
KMS_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/kms-update-alias-tf" && pwd)"
cd "$KMS_TF_DIR"
terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
}
setup() {
load 'test_helper/common-setup'
KMS_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/kms-update-alias-tf" && pwd)"
}
@test "KMS UpdateAlias: alias initially targets key A" {
KEY_A=$(terraform -chdir="$KMS_TF_DIR" output -raw key_a_id)
run aws_cmd kms list-aliases --key-id "$KEY_A" \
--query "Aliases[?AliasName=='alias/floci-kms-update-alias-test'].TargetKeyId | [0]" --output text
assert_success
assert_output "$KEY_A"
}
# The critical assertion: re-applying with a different target_key_id must
# update the existing alias in place, not destroy/recreate it and not fail.
@test "KMS UpdateAlias: re-apply with a different target updates in place" {
cd "$KMS_TF_DIR"
echo "# --- terraform apply (alias -> key B) ---" >&3
run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -var="use_second_key=true" \
-input=false -auto-approve -no-color
assert_success
assert_output --partial "1 changed"
refute_output --partial "1 destroyed"
KEY_B=$(terraform -chdir="$KMS_TF_DIR" output -raw key_b_id)
run aws_cmd kms list-aliases --key-id "$KEY_B" \
--query "Aliases[?AliasName=='alias/floci-kms-update-alias-test'].TargetKeyId | [0]" --output text
assert_success
assert_output "$KEY_B"
}
@test "KMS UpdateAlias: alias no longer resolves under key A" {
KEY_A=$(terraform -chdir="$KMS_TF_DIR" output -raw key_a_id)
run aws_cmd kms list-aliases --key-id "$KEY_A" \
--query "Aliases[?AliasName=='alias/floci-kms-update-alias-test']" --output text
assert_success
[ -z "$output" ]
}
+1
View File
@@ -28,6 +28,7 @@
| `GenerateMac` | Generate a MAC with an HMAC key |
| `VerifyMac` | Verify a MAC with an HMAC key |
| `CreateAlias` | Create a friendly name for a key |
| `UpdateAlias` | Repoint an alias at a different key |
| `DeleteAlias` | Remove an alias |
| `ListAliases` | List all aliases |
| `ScheduleKeyDeletion` | Mark a key for deletion |
@@ -58,6 +58,7 @@ public class KmsJsonHandler {
case "GenerateMac" -> handleGenerateMac(request, region);
case "VerifyMac" -> handleVerifyMac(request, region);
case "CreateAlias" -> handleCreateAlias(request, region);
case "UpdateAlias" -> handleUpdateAlias(request, region);
case "DeleteAlias" -> handleDeleteAlias(request, region);
case "ListAliases" -> handleListAliases(request, region);
case "ScheduleKeyDeletion" -> handleScheduleKeyDeletion(request, region);
@@ -393,6 +394,11 @@ public class KmsJsonHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleUpdateAlias(JsonNode request, String region) {
service.updateAlias(request.path("AliasName").asText(), request.path("TargetKeyId").asText(), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleDeleteAlias(JsonNode request, String region) {
service.deleteAlias(request.path("AliasName").asText(), region);
return Response.ok(objectMapper.createObjectNode()).build();
@@ -227,6 +227,13 @@ public class KmsService {
return spec != null && spec.getKeyType() == KmsKeySpec.KeyType.HMAC;
}
// AWS UpdateAlias only requires the current and new key to be "the same type (both
// symmetric or both asymmetric or both HMAC)" - not an exact KeySpec match, so e.g.
// RSA_2048 and ECC_NIST_P256 are compatible, but SYMMETRIC_DEFAULT and RSA_2048 are not.
private static boolean sameKeyFamily(KmsKeySpec a, KmsKeySpec b) {
return isHmac(a) == isHmac(b) && (a == KmsKeySpec.SYMMETRIC_DEFAULT) == (b == KmsKeySpec.SYMMETRIC_DEFAULT);
}
private static void validateKeyUsageForSpec(KmsKeyUsage keyUsage, KmsKeySpec spec) {
if (isHmac(spec) && KmsKeyUsage.GENERATE_VERIFY_MAC != keyUsage) {
throw new AwsException("ValidationException",
@@ -605,6 +612,30 @@ public class KmsService {
LOG.infov("Created KMS alias: {0} -> {1}", aliasName, key.getKeyId());
}
public void updateAlias(String aliasName, String targetKeyId, String region) {
String storageKey = region + "::" + aliasName;
KmsAlias existing = aliasStore.get(storageKey)
.orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + aliasName, 404));
KmsKey currentKey = resolveKey(existing.getTargetKeyId(), region);
KmsKey newKey = resolveKey(targetKeyId, region); // Validate key exists and normalize to plain key ID
if ("PendingDeletion".equals(newKey.getKeyState())) {
throw new AwsException("KMSInvalidStateException",
"KMS key " + newKey.getKeyId() + " is pending deletion.", 400);
}
if (currentKey.getKeyUsage() != newKey.getKeyUsage() || !sameKeyFamily(currentKey.getKeySpec(), newKey.getKeySpec())) {
throw new AwsException("ValidationException",
"The replacement KMS key must have the same key usage and key type "
+ "(symmetric, asymmetric, or HMAC) as the alias's current target key.",
400);
}
existing.setTargetKeyId(newKey.getKeyId());
aliasStore.put(storageKey, existing);
LOG.infov("Updated KMS alias: {0} -> {1}", aliasName, newKey.getKeyId());
}
public void deleteAlias(String aliasName, String region) {
String key = region + "::" + aliasName;
if (aliasStore.get(key).isEmpty()) {
@@ -1183,4 +1183,184 @@ class KmsIntegrationTest {
.then()
.body("__type", equalTo("NotFoundException"));
}
@Test
void updateAliasRoundTripThroughJsonHandler() {
String keyId1 = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
String keyId2 = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
given()
.header("X-Amz-Target", "TrentService.CreateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-test\",\"TargetKeyId\":\"" + keyId1 + "\"}")
.when().post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "TrentService.UpdateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-test\",\"TargetKeyId\":\"" + keyId2 + "\"}")
.when().post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "TrentService.ListAliases")
.contentType(KMS_CONTENT_TYPE)
.body("{\"KeyId\":\"" + keyId2 + "\"}")
.when().post("/")
.then()
.statusCode(200)
.body("Aliases.find { it.AliasName == 'alias/update-alias-test' }.TargetKeyId", equalTo(keyId2));
}
@Test
void updateAliasReturnsNotFoundForUnknownAlias() {
String keyId = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
given()
.header("X-Amz-Target", "TrentService.UpdateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/non-existent\",\"TargetKeyId\":\"" + keyId + "\"}")
.when().post("/")
.then()
.statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
void updateAliasReturnsNotFoundForUnknownTargetKey() {
String keyId = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
given()
.header("X-Amz-Target", "TrentService.CreateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-missing-target\",\"TargetKeyId\":\"" + keyId + "\"}")
.when().post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "TrentService.UpdateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-missing-target\",\"TargetKeyId\":\"non-existent-key\"}")
.when().post("/")
.then()
.statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
void updateAliasReturnsInvalidStateForPendingDeletionTarget() {
String keyId1 = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
String keyId2 = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
given()
.header("X-Amz-Target", "TrentService.ScheduleKeyDeletion")
.contentType(KMS_CONTENT_TYPE)
.body("{\"KeyId\":\"" + keyId2 + "\",\"PendingWindowInDays\":7}")
.when().post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "TrentService.CreateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-pending-deletion\",\"TargetKeyId\":\"" + keyId1 + "\"}")
.when().post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "TrentService.UpdateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-pending-deletion\",\"TargetKeyId\":\"" + keyId2 + "\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("KMSInvalidStateException"));
}
@Test
void updateAliasReturnsValidationForIncompatibleKeyUsage() {
String symmetricKeyId = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
String hmacKeyId = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{\"KeyUsage\":\"GENERATE_VERIFY_MAC\",\"KeySpec\":\"HMAC_256\"}")
.when().post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
given()
.header("X-Amz-Target", "TrentService.CreateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-incompatible-usage\",\"TargetKeyId\":\"" + symmetricKeyId + "\"}")
.when().post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "TrentService.UpdateAlias")
.contentType(KMS_CONTENT_TYPE)
.body("{\"AliasName\":\"alias/update-alias-incompatible-usage\",\"TargetKeyId\":\"" + hmacKeyId + "\"}")
.when().post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
@@ -501,6 +501,102 @@ class KmsServiceTest {
kmsService.createAlias("alias/test", "no-such-key", REGION));
}
@Test
void updateAlias() {
KmsKey keyA = kmsService.createKey(null, REGION);
KmsKey keyB = kmsService.createKey(null, REGION);
kmsService.createAlias("alias/my-key", keyA.getKeyId(), REGION);
kmsService.updateAlias("alias/my-key", keyB.getKeyId(), REGION);
List<KmsAlias> aliases = kmsService.listAliases(REGION);
assertEquals(1, aliases.size());
assertEquals(keyB.getKeyId(), aliases.getFirst().getTargetKeyId());
}
@Test
void updateAliasNotFoundThrows() {
KmsKey key = kmsService.createKey(null, REGION);
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.updateAlias("alias/missing", key.getKeyId(), REGION));
assertEquals("NotFoundException", ex.getErrorCode());
}
@Test
void updateAliasForNonExistentTargetKeyThrows() {
KmsKey key = kmsService.createKey(null, REGION);
kmsService.createAlias("alias/my-key", key.getKeyId(), REGION);
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.updateAlias("alias/my-key", "no-such-key", REGION));
assertEquals("NotFoundException", ex.getErrorCode());
assertEquals(key.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
}
@Test
void updateAliasForPendingDeletionTargetThrows() {
KmsKey keyA = kmsService.createKey(null, REGION);
KmsKey keyB = kmsService.createKey(null, REGION);
kmsService.createAlias("alias/my-key", keyA.getKeyId(), REGION);
kmsService.scheduleKeyDeletion(keyB.getKeyId(), 7, REGION);
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.updateAlias("alias/my-key", keyB.getKeyId(), REGION));
assertEquals("KMSInvalidStateException", ex.getErrorCode());
assertEquals(keyA.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
}
@Test
void updateAliasForIncompatibleKeyUsageThrows() {
KmsKey symmetricKey = kmsService.createKey(null, REGION);
KmsKey hmacKey = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", "HMAC_256", null, Map.of(), REGION);
kmsService.createAlias("alias/my-key", symmetricKey.getKeyId(), REGION);
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.updateAlias("alias/my-key", hmacKey.getKeyId(), REGION));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals(symmetricKey.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
}
@Test
void updateAliasAllowsSameTypeDifferentSpec() {
KmsKey rsa2048 = kmsService.createKey("rsa 2048", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
KmsKey rsa3072 = kmsService.createKey("rsa 3072", "SIGN_VERIFY", "RSA_3072", null, Map.of(), REGION);
kmsService.createAlias("alias/my-key", rsa2048.getKeyId(), REGION);
kmsService.updateAlias("alias/my-key", rsa3072.getKeyId(), REGION);
assertEquals(rsa3072.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
}
@Test
void updateAliasAllowsSameUsageDifferentAsymmetricFamily() {
KmsKey rsaKey = kmsService.createKey("rsa key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
KmsKey eccKey = kmsService.createKey("ecc key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);
kmsService.createAlias("alias/my-key", rsaKey.getKeyId(), REGION);
kmsService.updateAlias("alias/my-key", eccKey.getKeyId(), REGION);
assertEquals(eccKey.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
}
@Test
void updateAliasRejectsSymmetricToAsymmetricEvenWithSameUsage() {
KmsKey symmetricKey = kmsService.createKey(null, REGION);
KmsKey rsaEncryptKey = kmsService.createKey("rsa encrypt key", "ENCRYPT_DECRYPT", "RSA_2048", null, Map.of(), REGION);
kmsService.createAlias("alias/my-key", symmetricKey.getKeyId(), REGION);
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.updateAlias("alias/my-key", rsaEncryptKey.getKeyId(), REGION));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals(symmetricKey.getKeyId(), kmsService.listAliases(REGION).getFirst().getTargetKeyId());
}
@Test
void deleteAlias() {
KmsKey key = kmsService.createKey(null, REGION);