Light, fluffy, and always free - The AWS Local Emulator alternative
feat(kms): implement UpdateAlias (#2324)
Priamo Germosen984886f6972a
diff --git a/compatibility-tests/compat-terraform/test/kms-update-alias-tf/main.tf b/compatibility-tests/compat-terraform/test/kms-update-alias-tf/main.tfnew file mode 100644index 0000000000..b39638de7f--- /dev/null+++ b/compatibility-tests/compat-terraform/test/kms-update-alias-tf/main.tf@@ -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+}diff --git a/compatibility-tests/compat-terraform/test/kms-update-alias-tf/provider.tf b/compatibility-tests/compat-terraform/test/kms-update-alias-tf/provider.tfnew file mode 100644index 0000000000..e631e9c4ec--- /dev/null+++ b/compatibility-tests/compat-terraform/test/kms-update-alias-tf/provider.tf@@ -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+ }+}diff --git a/compatibility-tests/compat-terraform/test/kms_update_alias.bats b/compatibility-tests/compat-terraform/test/kms_update_alias.batsnew file mode 100644index 0000000000..a87f2ac192--- /dev/null+++ b/compatibility-tests/compat-terraform/test/kms_update_alias.bats@@ -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" ]+}diff --git a/docs/services/kms.md b/docs/services/kms.mdindex 8cbae83f50..e4ebc3fa36 100644--- a/docs/services/kms.md+++ b/docs/services/kms.md@@ -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 |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.javaindex cd64e0b983..9fff8bd7a9 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@@ -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();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.javaindex e8db0c9ed1..225f688b1c 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@@ -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()) {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.javaindex 5d858e7456..e40a822078 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@@ -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"));+ }}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.javaindex ca65a7f37f..d63eb9610d 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@@ -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());+ }+@Testvoid deleteAlias() {KmsKey key = kmsService.createKey(null, REGION);