Light, fluffy, and always free - The AWS Local Emulator alternative
feat(kms) Add KMS Grant APIs (#1073)
nblomquist9d1e24a582a6
diff --git a/compatibility-tests/sdk-test-awscli/test/kms.bats b/compatibility-tests/sdk-test-awscli/test/kms.batsindex a693981400..39d190929b 100644--- a/compatibility-tests/sdk-test-awscli/test/kms.bats+++ b/compatibility-tests/sdk-test-awscli/test/kms.bats@@ -39,6 +39,17 @@ teardown() {[ "$found" = "true" ]}+@test "KMS: list grants" {+ out=$(aws_cmd kms create-key --description "bats-test-key")+ KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId')+ [ -n "$KEY_ID" ]++ run aws_cmd kms list-grants --key-id "$KEY_ID"+ assert_success+ has_grants=$(echo "$output" | jq 'has("Grants") and (.Grants | type == "array")')+ [ "$has_grants" = "true" ]+}+@test "KMS: encrypt and decrypt" {out=$(aws_cmd kms create-key --description "bats-test-key")KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId')diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsGrantLifecycleTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsGrantLifecycleTest.javanew file mode 100644index 0000000000..a2bb211dad--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsGrantLifecycleTest.java@@ -0,0 +1,145 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.kms.KmsClient;+import software.amazon.awssdk.services.kms.model.CreateGrantResponse;+import software.amazon.awssdk.services.kms.model.CreateKeyResponse;+import software.amazon.awssdk.services.kms.model.GrantOperation;+import software.amazon.awssdk.services.kms.model.ListGrantsResponse;++import static org.assertj.core.api.Assertions.assertThat;++@DisplayName("KMS grant lifecycle compatibility")+class KmsGrantLifecycleTest {++ private static final String GRANTEE_PRINCIPAL = "arn:aws:iam::000000000000:role/grantee";++ private static KmsClient kms;++ @BeforeAll+ static void setup() {+ kms = TestFixtures.kmsClient();+ }++ @AfterAll+ static void cleanup() {+ if (kms != null) {+ kms.close();+ }+ }++ @Test+ void createListGrantRoundTrip() {+ final String[] keyId = new String[1];+ try {+ CreateKeyResponse keyResponse = kms.createKey(b -> b.description("grant-create-list-key"));+ keyId[0] = keyResponse.keyMetadata().keyId();++ CreateGrantResponse grantResponse = kms.createGrant(b -> b+ .keyId(keyId[0])+ .granteePrincipal(GRANTEE_PRINCIPAL)+ .operations(GrantOperation.DECRYPT));++ String grantId = grantResponse.grantId();+ String grantToken = grantResponse.grantToken();++ assertThat(grantId).isNotBlank();+ assertThat(grantToken).isNotBlank();++ ListGrantsResponse grantsResponse = kms.listGrants(b -> b.keyId(keyId[0]));+ assertThat(grantsResponse.truncated()).isFalse();+ assertThat(grantsResponse.grants())+ .anySatisfy(grant -> {+ assertThat(grant.grantId()).isEqualTo(grantId);+ assertThat(grant.keyId()).contains(keyId[0]);+ assertThat(grant.granteePrincipal()).isEqualTo(GRANTEE_PRINCIPAL);+ assertThat(grant.operations()).contains(GrantOperation.DECRYPT);+ });+ } finally {+ if (keyId[0] != null) {+ kms.scheduleKeyDeletion(b -> b+ .keyId(keyId[0])+ .pendingWindowInDays(7));+ }+ }+ }++ @Test+ void createListRevokeGrantRoundTrip() {+ final String[] keyId = new String[1];+ try {+ CreateKeyResponse keyResponse = kms.createKey(b -> b.description("grant-revoke-key"));+ keyId[0] = keyResponse.keyMetadata().keyId();++ CreateGrantResponse grantResponse = kms.createGrant(b -> b+ .keyId(keyId[0])+ .granteePrincipal(GRANTEE_PRINCIPAL)+ .operations(GrantOperation.DECRYPT));++ String grantId = grantResponse.grantId();+ String grantToken = grantResponse.grantToken();++ assertThat(grantId).isNotBlank();+ assertThat(grantToken).isNotBlank();++ ListGrantsResponse beforeRevoke = kms.listGrants(b -> b.keyId(keyId[0]));+ assertThat(beforeRevoke.grants())+ .anyMatch(grant -> grantId.equals(grant.grantId()));++ kms.revokeGrant(b -> b+ .keyId(keyId[0])+ .grantId(grantId));++ ListGrantsResponse afterRevoke = kms.listGrants(b -> b.keyId(keyId[0]));+ assertThat(afterRevoke.grants())+ .noneMatch(grant -> grantId.equals(grant.grantId()));+ } finally {+ if (keyId[0] != null) {+ kms.scheduleKeyDeletion(b -> b+ .keyId(keyId[0])+ .pendingWindowInDays(7));+ }+ }+ }++ @Test+ void createListRetireGrantRoundTrip() {+ final String[] keyId = new String[1];+ try {+ CreateKeyResponse keyResponse = kms.createKey(b -> b.description("grant-retire-key"));+ keyId[0] = keyResponse.keyMetadata().keyId();++ CreateGrantResponse grantResponse = kms.createGrant(b -> b+ .keyId(keyId[0])+ .granteePrincipal(GRANTEE_PRINCIPAL)+ .operations(GrantOperation.DECRYPT));++ String grantId = grantResponse.grantId();+ String grantToken = grantResponse.grantToken();++ assertThat(grantId).isNotBlank();+ assertThat(grantToken).isNotBlank();++ ListGrantsResponse beforeRetire = kms.listGrants(b -> b.keyId(keyId[0]));+ assertThat(beforeRetire.grants())+ .anyMatch(grant -> grantId.equals(grant.grantId()));++ kms.retireGrant(b -> b+ .grantId(grantId)+ .grantToken(grantToken));++ ListGrantsResponse afterRetire = kms.listGrants(b -> b.keyId(keyId[0]));+ assertThat(afterRetire.grants())+ .noneMatch(grant -> grantId.equals(grant.grantId()));+ } finally {+ if (keyId[0] != null) {+ kms.scheduleKeyDeletion(b -> b+ .keyId(keyId[0])+ .pendingWindowInDays(7));+ }+ }+ }+}diff --git a/compatibility-tests/sdk-test-python/tests/test_kms.py b/compatibility-tests/sdk-test-python/tests/test_kms.pyindex c53b10fba0..21a37bace6 100644--- a/compatibility-tests/sdk-test-python/tests/test_kms.py+++ b/compatibility-tests/sdk-test-python/tests/test_kms.py@@ -37,6 +37,36 @@ class TestKMSKey:assert response["KeyMetadata"]["KeyState"] == "PendingDeletion"+class TestKMSGrants:+ """Test KMS grant operations."""++ def test_list_grants(self, kms_client):+ """Test ListGrants returns an empty grant list for a new key."""+ response = kms_client.create_key(Description="pytest-grant-test-key")+ key_id = response["KeyMetadata"]["KeyId"]++ try:+ response = kms_client.list_grants(KeyId=key_id)+ assert response["Grants"] == []+ finally:+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)++ def test_list_grants_paginator(self, kms_client):+ """Test ListGrants paginator returns pages with Grants."""+ response = kms_client.create_key(Description="pytest-grant-test-key")+ key_id = response["KeyMetadata"]["KeyId"]++ try:+ paginator = kms_client.get_paginator("list_grants")+ pages = list(paginator.paginate(KeyId=key_id))++ assert pages+ assert all("Grants" in page for page in pages)+ assert [grant for page in pages for grant in page["Grants"]] == []+ finally:+ kms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)++class TestKMSAlias:"""Test KMS alias operations."""@@ -78,7 +108,9 @@ class TestKMSAlias:kms_client.delete_alias(AliasName=alias_name)response = kms_client.list_aliases()- assert not any(a["AliasName"] == alias_name for a in response.get("Aliases", []))+ assert not any(+ a["AliasName"] == alias_name for a in response.get("Aliases", [])+ )# Cleanupkms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)diff --git a/docs/services/kms.md b/docs/services/kms.mdindex dc6ce1f169..53953a1cfe 100644--- a/docs/services/kms.md+++ b/docs/services/kms.md@@ -31,6 +31,15 @@| `EnableKeyRotation` | Enable automatic key rotation (symmetric keys only) || `DisableKeyRotation` | Disable automatic key rotation || `RotateKeyOnDemand` | Rotate key material on demand (symmetric keys only) |+| `CreateGrant` | Create a grant for a KMS key |+| `ListGrants` | List grants for a KMS key |+| `ListRetirableGrants` | List grants retirable by a principal |+| `RevokeGrant` | Revoke (administratively delete) a grant |+| `RetireGrant` | Retire a grant (token- or key+grant-based) |++## Grant Support Scope++Grant lifecycle operations (`CreateGrant`, `ListGrants`, `ListRetirableGrants`, `RevokeGrant`, `RetireGrant`) are supported. However, grant lifecycle support **does not** imply grant-based authorization enforcement on cryptographic operations (`Encrypt`, `Decrypt`, `Sign`, `Verify`, `GenerateDataKey`, etc.). Grants are stored and queryable but are not evaluated during crypto operations.## Configurationdiff --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 7ee4c35d1b..9f58b69a7e 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@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsErrorResponse;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.ReservedTags;import io.github.hectorvent.floci.services.kms.model.KmsAlias;+import io.github.hectorvent.floci.services.kms.model.KmsGrant;import io.github.hectorvent.floci.services.kms.model.KmsKey;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;@@ -38,6 +39,11 @@ public class KmsJsonHandler {case "GetPublicKey" -> handleGetPublicKey(request, region);case "DescribeKey" -> handleDescribeKey(request, region);case "ListKeys" -> handleListKeys(request, region);+ case "CreateGrant" -> handleCreateGrant(request, region);+ case "ListGrants" -> handleListGrants(request, region);+ case "ListRetirableGrants" -> handleListRetirableGrants(request, region);+ case "RevokeGrant" -> handleRevokeGrant(request, region);+ case "RetireGrant" -> handleRetireGrant(request, region);case "Encrypt" -> handleEncrypt(request, region);case "Decrypt" -> handleDecrypt(request, region);case "ReEncrypt" -> handleReEncrypt(request, region);@@ -139,6 +145,107 @@ public class KmsJsonHandler {return Response.ok(response).build();}+ private Response handleListGrants(JsonNode request, String region) {+ String keyId = request.path("KeyId").asText();+ String marker = request.path("Marker").isMissingNode() ? null : request.path("Marker").asText(null);+ Integer limit = request.path("Limit").isMissingNode() ? null : request.path("Limit").asInt();+ String grantId = request.path("GrantId").isMissingNode() ? null : request.path("GrantId").asText(null);+ String granteePrincipal = request.path("GranteePrincipal").isMissingNode() ? null : request.path("GranteePrincipal").asText(null);++ Map<String, Object> result = service.listGrants(keyId, region, marker, limit, grantId, granteePrincipal);++ ObjectNode response = objectMapper.createObjectNode();+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");+ ArrayNode array = response.putArray("Grants");+ for (Map<String, Object> grant : grants) {+ ObjectNode entry = array.addObject();+ entry.put("GrantId", (String) grant.get("GrantId"));+ entry.put("KeyId", (String) grant.get("KeyId"));+ entry.put("GranteePrincipal", (String) grant.get("GranteePrincipal"));+ entry.put("CreationDate", ((Number) grant.get("CreationDate")).longValue());+ ArrayNode operations = entry.putArray("Operations");+ @SuppressWarnings("unchecked")+ List<String> operationValues = (List<String>) grant.get("Operations");+ operationValues.forEach(operations::add);+ if (grant.get("RetiringPrincipal") != null) {+ entry.put("RetiringPrincipal", (String) grant.get("RetiringPrincipal"));+ }+ }+ response.put("Truncated", (boolean) result.get("Truncated"));+ if (Boolean.TRUE.equals(result.get("Truncated"))) {+ response.put("NextMarker", (String) result.get("NextMarker"));+ }+ return Response.ok(response).build();+ }++ private Response handleListRetirableGrants(JsonNode request, String region) {+ String retiringPrincipal = request.path("RetiringPrincipal").asText(null);+ String marker = request.path("Marker").isMissingNode() ? null : request.path("Marker").asText(null);+ Integer limit = request.path("Limit").isMissingNode() ? null : request.path("Limit").asInt();++ Map<String, Object> result = service.listRetirableGrants(retiringPrincipal, region, marker, limit);++ ObjectNode response = objectMapper.createObjectNode();+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");+ ArrayNode array = response.putArray("Grants");+ for (Map<String, Object> grant : grants) {+ ObjectNode entry = array.addObject();+ entry.put("GrantId", (String) grant.get("GrantId"));+ entry.put("KeyId", (String) grant.get("KeyId"));+ entry.put("GranteePrincipal", (String) grant.get("GranteePrincipal"));+ entry.put("CreationDate", ((Number) grant.get("CreationDate")).longValue());+ ArrayNode operations = entry.putArray("Operations");+ @SuppressWarnings("unchecked")+ List<String> operationValues = (List<String>) grant.get("Operations");+ operationValues.forEach(operations::add);+ if (grant.get("RetiringPrincipal") != null) {+ entry.put("RetiringPrincipal", (String) grant.get("RetiringPrincipal"));+ }+ }+ response.put("Truncated", (boolean) result.get("Truncated"));+ if (Boolean.TRUE.equals(result.get("Truncated"))) {+ response.put("NextMarker", (String) result.get("NextMarker"));+ }+ return Response.ok(response).build();+ }++ private Response handleCreateGrant(JsonNode request, String region) {+ String keyId = request.path("KeyId").asText(null);+ String granteePrincipal = request.path("GranteePrincipal").asText(null);+ List<String> operations = new java.util.ArrayList<>();+ request.path("Operations").forEach(operation -> operations.add(operation.asText()));+ String retiringPrincipal = request.path("RetiringPrincipal").isMissingNode()+ ? null : request.path("RetiringPrincipal").asText(null);++ KmsGrant grant = service.createGrant(keyId, granteePrincipal, operations, retiringPrincipal, region);+ ObjectNode response = objectMapper.createObjectNode();+ response.put("GrantId", grant.getGrantId());+ response.put("GrantToken", grant.getGrantToken());+ return Response.ok(response).build();+ }++ private Response handleRevokeGrant(JsonNode request, String region) {+ String keyId = request.path("KeyId").asText(null);+ String grantId = request.path("GrantId").asText(null);++ service.revokeGrant(keyId, grantId, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleRetireGrant(JsonNode request, String region) {+ String grantToken = request.path("GrantToken").isMissingNode()+ ? null : request.path("GrantToken").asText(null);+ String keyId = request.path("KeyId").isMissingNode()+ ? null : request.path("KeyId").asText(null);+ String grantId = request.path("GrantId").isMissingNode()+ ? null : request.path("GrantId").asText(null);++ service.retireGrant(grantToken, keyId, grantId, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }+private Response handleEncrypt(JsonNode request, String region) {String keyId = request.path("KeyId").asText();byte[] plaintext = Base64.getDecoder().decode(request.path("Plaintext").asText());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 55b5b25007..4fd0fdf817 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@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.ReservedTags;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.kms.model.KmsAlias;+import io.github.hectorvent.floci.services.kms.model.KmsGrant;import io.github.hectorvent.floci.services.kms.model.KmsKey;import com.fasterxml.jackson.core.type.TypeReference;import jakarta.enterprise.context.ApplicationScoped;@@ -49,6 +50,7 @@ public class KmsService {private final StorageBackend<String, KmsKey> keyStore;private final StorageBackend<String, KmsAlias> aliasStore;+ private final StorageBackend<String, KmsGrant> grantStore;private final RegionResolver regionResolver;@Inject@@ -57,14 +59,18 @@ public class KmsService {new TypeReference<Map<String, KmsKey>>() {}),storageFactory.create("kms", "kms-aliases.json",new TypeReference<Map<String, KmsAlias>>() {}),+ storageFactory.create("kms", "kms-grants.json",+ new TypeReference<Map<String, KmsGrant>>() {}),regionResolver);}KmsService(StorageBackend<String, KmsKey> keyStore,- StorageBackend<String, KmsAlias> aliasStore,- RegionResolver regionResolver) {+ StorageBackend<String, KmsAlias> aliasStore,+ StorageBackend<String, KmsGrant> grantStore,+ RegionResolver regionResolver) {this.keyStore = keyStore;this.aliasStore = aliasStore;+ this.grantStore = grantStore;this.regionResolver = regionResolver;}@@ -234,6 +240,205 @@ public class KmsService {return keyStore.scan(k -> k.startsWith(prefix));}+ public KmsGrant createGrant(String keyId, String granteePrincipal, List<String> operations, String region) {+ return createGrant(keyId, granteePrincipal, operations, null, region);+ }++ public KmsGrant createGrant(String keyId, String granteePrincipal, List<String> operations,+ String retiringPrincipal, String region) {+ if (keyId == null || keyId.isBlank()) {+ throw new AwsException("ValidationException", "KeyId is required", 400);+ }+ if (granteePrincipal == null || granteePrincipal.isBlank()) {+ throw new AwsException("ValidationException", "GranteePrincipal is required", 400);+ }+ if (operations == null || operations.isEmpty()) {+ throw new AwsException("ValidationException", "Operations is required", 400);+ }++ KmsKey key = resolveKey(keyId, region);+ String grantId = UUID.randomUUID().toString();+ byte[] tokenBytes = new byte[32];+ ThreadLocalRandom.current().nextBytes(tokenBytes);++ KmsGrant grant = new KmsGrant();+ grant.setGrantId(grantId);+ grant.setGrantToken(Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes));+ grant.setKeyId(key.getKeyId());+ grant.setKeyArn(key.getArn());+ grant.setGranteePrincipal(granteePrincipal);+ grant.setRetiringPrincipal(retiringPrincipal);+ grant.setOperations(new ArrayList<>(operations));++ grantStore.put(region + "::" + grantId, grant);+ LOG.infov("Created KMS grant: {0} for key {1} in {2}", grantId, key.getKeyId(), region);+ return grant;+ }++ private static final int DEFAULT_GRANT_LIMIT = 50;+ private static final int MAX_GRANT_LIMIT = 100;++ public Map<String, Object> listGrants(String keyId, String region, String marker, Integer limit,+ String grantIdFilter, String granteePrincipalFilter) {+ // Validate filter mutual exclusivity+ if (grantIdFilter != null && (grantIdFilter.length() > 128)) {+ throw new AwsException("ValidationException", "GrantId exceeds maximum length of 128", 400);+ }++ KmsKey key = resolveKey(keyId, region);+ String prefix = region + "::";++ // Collect and sort grants deterministically by grantId+ List<KmsGrant> sortedGrants = grantStore.scan(k -> k.startsWith(prefix)).stream()+ .filter(grant -> key.getKeyId().equals(grant.getKeyId()))+ .filter(grant -> grantIdFilter == null || grantIdFilter.isBlank()+ || grantIdFilter.equals(grant.getGrantId()))+ .filter(grant -> granteePrincipalFilter == null || granteePrincipalFilter.isBlank()+ || granteePrincipalFilter.equals(grant.getGranteePrincipal()))+ .sorted(Comparator.comparing(KmsGrant::getGrantId))+ .toList();++ return paginateGrants(sortedGrants, marker, limit);+ }++ public Map<String, Object> listRetirableGrants(String retiringPrincipal, String region,+ String marker, Integer limit) {+ if (retiringPrincipal == null || retiringPrincipal.isBlank()) {+ throw new AwsException("ValidationException", "RetiringPrincipal is required", 400);+ }++ String prefix = region + "::";++ List<KmsGrant> sortedGrants = grantStore.scan(k -> k.startsWith(prefix)).stream()+ .filter(grant -> retiringPrincipal.equals(grant.getRetiringPrincipal()))+ .sorted(Comparator.comparing(KmsGrant::getGrantId))+ .toList();++ return paginateGrants(sortedGrants, marker, limit);+ }++ public void revokeGrant(String keyId, String grantId, String region) {+ if (keyId == null || keyId.isBlank()) {+ throw new AwsException("ValidationException", "KeyId is required", 400);+ }+ if (grantId == null || grantId.isBlank()) {+ throw new AwsException("ValidationException", "GrantId is required", 400);+ }++ // Resolve the key to validate it exists+ resolveKey(keyId, region);++ String storageKey = region + "::" + grantId;+ if (grantStore.get(storageKey).isEmpty()) {+ throw new AwsException("NotFoundException", "Grant not found: " + grantId, 400);+ }++ grantStore.delete(storageKey);+ LOG.infov("Revoked KMS grant: {0} for key {1} in {2}", grantId, keyId, region);+ }++ public void retireGrant(String grantToken, String keyId, String grantId, String region) {+ boolean hasToken = grantToken != null && !grantToken.isBlank();+ boolean hasKeyAndGrant = keyId != null && !keyId.isBlank() && grantId != null && !grantId.isBlank();++ if (!hasToken && !hasKeyAndGrant) {+ throw new AwsException("ValidationException",+ "Either GrantToken or both KeyId and GrantId must be provided", 400);+ }++ // Token-based retirement: scan all grants in the region for matching token+ if (hasToken) {+ String prefix = region + "::";+ KmsGrant found = grantStore.scan(k -> k.startsWith(prefix)).stream()+ .filter(g -> grantToken.equals(g.getGrantToken()))+ .findFirst()+ .orElseThrow(() -> new AwsException("NotFoundException",+ "Grant not found for the given grant token", 400));++ // Cross-verify GrantId if provided+ if (grantId != null && !grantId.isBlank() && !grantId.equals(found.getGrantId())) {+ throw new AwsException("NotFoundException", "Grant not found", 400);+ }++ // Cross-verify KeyId if provided+ if (keyId != null && !keyId.isBlank()) {+ KmsKey key = resolveKey(keyId, region);+ if (!key.getKeyId().equals(found.getKeyId())) {+ throw new AwsException("NotFoundException",+ "Grant not found for the given key", 400);+ }+ }++ grantStore.delete(region + "::" + found.getGrantId());+ LOG.infov("Retired KMS grant: {0} by token in {1}", found.getGrantId(), region);+ return;+ }++ // KeyId + GrantId retirement (administrative, distinct from RevokeGrant surface)+ resolveKey(keyId, region);+ String storageKey = region + "::" + grantId;+ if (grantStore.get(storageKey).isEmpty()) {+ throw new AwsException("NotFoundException", "Grant not found: " + grantId, 400);+ }+ grantStore.delete(storageKey);+ LOG.infov("Retired KMS grant: {0} for key {1} in {2}", grantId, keyId, region);+ }++ private Map<String, Object> paginateGrants(List<KmsGrant> sortedGrants, String marker, Integer limit) {+ int effectiveLimit = limit != null ? Math.clamp(limit, 1, MAX_GRANT_LIMIT) : DEFAULT_GRANT_LIMIT;++ int startIndex = 0;+ if (marker != null && !marker.isBlank()) {+ String decodedMarker;+ try {+ decodedMarker = new String(Base64.getDecoder().decode(marker), StandardCharsets.UTF_8);+ } catch (IllegalArgumentException e) {+ throw new AwsException("InvalidMarkerException",+ "The request was rejected because the marker is not valid.", 400);+ }+ String lastGrantId = decodedMarker;+ boolean found = false;+ for (int i = 0; i < sortedGrants.size(); i++) {+ if (sortedGrants.get(i).getGrantId().equals(lastGrantId)) {+ startIndex = i + 1;+ found = true;+ break;+ }+ }+ if (!found) {+ throw new AwsException("InvalidMarkerException",+ "The request was rejected because the marker that specifies where pagination should next begin is not valid.", 400);+ }+ }++ int endIndex = Math.min(startIndex + effectiveLimit, sortedGrants.size());+ List<KmsGrant> page = sortedGrants.subList(startIndex, endIndex);+ boolean truncated = endIndex < sortedGrants.size();++ Map<String, Object> result = new HashMap<>();+ result.put("Grants", page.stream().map(this::grantToMap).toList());+ result.put("Truncated", truncated);+ if (truncated && !page.isEmpty()) {+ String lastGrantId = page.getLast().getGrantId();+ String nextMarker = Base64.getEncoder().encodeToString(lastGrantId.getBytes(StandardCharsets.UTF_8));+ result.put("NextMarker", nextMarker);+ }+ return result;+ }++ private Map<String, Object> grantToMap(KmsGrant grant) {+ Map<String, Object> result = new HashMap<>();+ result.put("GrantId", grant.getGrantId());+ result.put("KeyId", grant.getKeyArn());+ result.put("GranteePrincipal", grant.getGranteePrincipal());+ result.put("Operations", grant.getOperations());+ result.put("CreationDate", grant.getCreationDate());+ if (grant.getRetiringPrincipal() != null) {+ result.put("RetiringPrincipal", grant.getRetiringPrincipal());+ }+ return result;+ }+public void scheduleKeyDeletion(String keyId, int pendingWindowInDays, String region) {KmsKey key = resolveKey(keyId, region);key.setKeyState("PendingDeletion");diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsGrant.java b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsGrant.javanew file mode 100644index 0000000000..ea84041784--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/kms/model/KmsGrant.java@@ -0,0 +1,49 @@+package io.github.hectorvent.floci.services.kms.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.ArrayList;+import java.util.List;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class KmsGrant {+ private String grantId;+ private String grantToken;+ private String keyId;+ private String keyArn;+ private String granteePrincipal;+ private String retiringPrincipal;+ private List<String> operations = new ArrayList<>();+ private long creationDate;++ public KmsGrant() {+ this.creationDate = Instant.now().getEpochSecond();+ }++ public String getGrantId() { return grantId; }+ public void setGrantId(String grantId) { this.grantId = grantId; }++ public String getGrantToken() { return grantToken; }+ public void setGrantToken(String grantToken) { this.grantToken = grantToken; }++ public String getKeyId() { return keyId; }+ public void setKeyId(String keyId) { this.keyId = keyId; }++ public String getKeyArn() { return keyArn; }+ public void setKeyArn(String keyArn) { this.keyArn = keyArn; }++ public String getGranteePrincipal() { return granteePrincipal; }+ public void setGranteePrincipal(String granteePrincipal) { this.granteePrincipal = granteePrincipal; }++ public String getRetiringPrincipal() { return retiringPrincipal; }+ public void setRetiringPrincipal(String retiringPrincipal) { this.retiringPrincipal = retiringPrincipal; }++ public List<String> getOperations() { return operations; }+ public void setOperations(List<String> operations) { this.operations = operations; }++ 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.javaindex a8ce8d9ca8..c438fecb19 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@@ -132,4 +132,467 @@ class KmsIntegrationTest {.statusCode(200).body("KeyId", equalTo(keyId));}++ @Test+ void listGrantsReturnsEmptyGrantListThroughJsonHandler() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"list-grants-empty\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract()+ .path("KeyMetadata.KeyId");++ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(0))+ .body("Truncated", equalTo(false));+ }++ @Test+ void listGrantsReturnsNotFoundForUnknownKey() {+ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"non-existent-id\"}")+ .when()+ .post("/")+ .then()+ .statusCode(404)+ .body("__type", equalTo("NotFoundException"));+ }++ @Test+ void createGrantAndListGrantsRoundTripThroughJsonHandler() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"create-grant-round-trip\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract()+ .path("KeyMetadata.KeyId");++ String grantId = given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("""+ {+ "KeyId": "%s",+ "GranteePrincipal": "arn:aws:iam::000000000000:user/grantee",+ "Operations": ["Encrypt", "Decrypt"]+ }+ """.formatted(keyId))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GrantId", notNullValue())+ .body("GrantToken", notNullValue())+ .extract()+ .path("GrantId");++ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(1))+ .body("Grants[0].GrantId", equalTo(grantId))+ .body("Grants[0].KeyId", startsWith("arn:aws:kms:"))+ .body("Grants[0].GranteePrincipal", equalTo("arn:aws:iam::000000000000:user/grantee"))+ .body("Grants[0].Operations[0]", equalTo("Encrypt"))+ .body("Grants[0].Operations[1]", equalTo("Decrypt"))+ .body("Truncated", equalTo(false));+ }++ @Test+ void createGrantReturnsValidationForMissingRequiredFields() {+ given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"GranteePrincipal\":\"arn:aws:iam::000000000000:user/grantee\",\"Operations\":[\"Encrypt\"]}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ void createGrantReturnsNotFoundForUnknownKey() {+ given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("""+ {+ "KeyId": "non-existent-id",+ "GranteePrincipal": "arn:aws:iam::000000000000:user/grantee",+ "Operations": ["Encrypt"]+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(404)+ .body("__type", equalTo("NotFoundException"));+ }++ // ──────────────────────────── Phase 4: Pagination, Filters, ListRetirableGrants ────────────────────────────++ @Test+ void listGrantsSupportsPaginationThroughJsonHandler() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"pagination-key\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ for (int i = 0; i < 3; i++) {+ given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\",\"GranteePrincipal\":\"arn:aws:iam::000000000000:user/grantee\",\"Operations\":[\"Encrypt\"]}")+ .when().post("/")+ .then().statusCode(200);+ }++ String nextMarker = given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\",\"Limit\":2}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(2))+ .body("Truncated", equalTo(true))+ .body("NextMarker", notNullValue())+ .extract().path("NextMarker");++ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\",\"Marker\":\"" + nextMarker + "\",\"Limit\":2}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(1))+ .body("Truncated", equalTo(false));+ }++ @Test+ void listGrantsReturnsInvalidMarkerForBadMarker() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"bad-marker-key\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\",\"Marker\":\"bad-marker\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidMarkerException"));+ }++ @Test+ void listRetirableGrantsReturnsMatchingGrantsThroughJsonHandler() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"retirable-key\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("""+ {+ "KeyId": "%s",+ "GranteePrincipal": "arn:aws:iam::000000000000:user/grantee",+ "RetiringPrincipal": "arn:aws:iam::000000000000:role/retirer",+ "Operations": ["Encrypt"]+ }+ """.formatted(keyId))+ .when().post("/")+ .then().statusCode(200);++ given()+ .header("X-Amz-Target", "TrentService.ListRetirableGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"RetiringPrincipal\":\"arn:aws:iam::000000000000:role/retirer\"}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(1))+ .body("Grants[0].RetiringPrincipal", equalTo("arn:aws:iam::000000000000:role/retirer"))+ .body("Truncated", equalTo(false));+ }++ // ──────────────────────────── Phase 5: RevokeGrant ────────────────────────────++ @Test+ void createRevokeAndListGrantsRoundTripThroughJsonHandler() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"revoke-round-trip\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ String grantId = given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("""+ {+ "KeyId": "%s",+ "GranteePrincipal": "arn:aws:iam::000000000000:user/grantee",+ "Operations": ["Encrypt", "Decrypt"]+ }+ """.formatted(keyId))+ .when().post("/")+ .then().statusCode(200)+ .body("GrantId", notNullValue())+ .body("GrantToken", notNullValue())+ .extract().path("GrantId");++ // Grant is listed before revoke+ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(1))+ .body("Grants[0].GrantId", equalTo(grantId));++ // Revoke the grant+ given()+ .header("X-Amz-Target", "TrentService.RevokeGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\",\"GrantId\":\"" + grantId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200);++ // Grant is gone after revoke+ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(0))+ .body("Truncated", equalTo(false));+ }++ @Test+ void revokeGrantReturnsNotFoundForUnknownGrant() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"revoke-unknown-grant\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ given()+ .header("X-Amz-Target", "TrentService.RevokeGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\",\"GrantId\":\"non-existent-grant-id\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("NotFoundException"));+ }++ @Test+ void revokeGrantReturnsNotFoundForUnknownKey() {+ given()+ .header("X-Amz-Target", "TrentService.RevokeGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"non-existent-key\",\"GrantId\":\"some-grant-id\"}")+ .when().post("/")+ .then()+ .statusCode(404)+ .body("__type", equalTo("NotFoundException"));+ }++ @Test+ void revokeGrantReturnsValidationForMissingRequiredFields() {+ given()+ .header("X-Amz-Target", "TrentService.RevokeGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"some-key-id\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ // ──────────────────────────── Phase 6: RetireGrant ────────────────────────────++ @Test+ void createRetireByTokenAndListGrantsRoundTripThroughJsonHandler() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"retire-by-token-round-trip\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ String grantToken = given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("""+ {+ "KeyId": "%s",+ "GranteePrincipal": "arn:aws:iam::000000000000:user/grantee",+ "Operations": ["Encrypt", "Decrypt"]+ }+ """.formatted(keyId))+ .when().post("/")+ .then().statusCode(200)+ .body("GrantId", notNullValue())+ .body("GrantToken", notNullValue())+ .extract().path("GrantToken");++ // Grant is listed before retire+ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(1));++ // Retire by grant token+ given()+ .header("X-Amz-Target", "TrentService.RetireGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"GrantToken\":\"" + grantToken + "\"}")+ .when().post("/")+ .then()+ .statusCode(200);++ // Grant is gone after retire+ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(0))+ .body("Truncated", equalTo(false));+ }++ @Test+ void createRetireByKeyAndGrantIdAndListGrantsRoundTripThroughJsonHandler() {+ String keyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"retire-admin-round-trip\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");++ String grantId = given()+ .header("X-Amz-Target", "TrentService.CreateGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("""+ {+ "KeyId": "%s",+ "GranteePrincipal": "arn:aws:iam::000000000000:user/grantee",+ "Operations": ["Encrypt", "Decrypt"]+ }+ """.formatted(keyId))+ .when().post("/")+ .then().statusCode(200)+ .body("GrantId", notNullValue())+ .body("GrantToken", notNullValue())+ .extract().path("GrantId");++ // Grant is listed before retire+ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(1));++ // Administrative retire by KeyId + GrantId+ given()+ .header("X-Amz-Target", "TrentService.RetireGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\",\"GrantId\":\"" + grantId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200);++ // Grant is gone after retire+ given()+ .header("X-Amz-Target", "TrentService.ListGrants")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Grants.size()", equalTo(0))+ .body("Truncated", equalTo(false));+ }++ @Test+ void retireGrantReturnsNotFoundForInvalidToken() {+ given()+ .header("X-Amz-Target", "TrentService.RetireGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"GrantToken\":\"invalid-token-value\"}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("NotFoundException"));+ }++ @Test+ void retireGrantReturnsValidationForMissingAllIdentifiers() {+ given()+ .header("X-Amz-Target", "TrentService.RetireGrant")+ .contentType(KMS_CONTENT_TYPE)+ .body("{}")+ .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 c4ddae6463..9c530eb05c 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@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.ReservedTags;import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.services.kms.model.KmsAlias;+import io.github.hectorvent.floci.services.kms.model.KmsGrant;import io.github.hectorvent.floci.services.kms.model.KmsKey;import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.junit.jupiter.api.BeforeAll;@@ -42,6 +43,7 @@ class KmsServiceTest {@BeforeEachvoid setUp() {kmsService = new KmsService(+ new InMemoryStorage<>(),new InMemoryStorage<>(),new InMemoryStorage<>(),new RegionResolver("us-east-1", "000000000000")@@ -69,6 +71,368 @@ class KmsServiceTest {assertEquals(2, keys.size());}+ @Test+ void listGrantsReturnsEmptyListForExistingKey() {+ KmsKey key = kmsService.createKey("grant key", REGION);++ Map<String, Object> result = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");++ assertTrue(grants.isEmpty());+ }++ @Test+ void listGrantsUnknownKeyThrowsNotFound() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.listGrants("non-existent-id", REGION, null, null, null, null));++ assertEquals("NotFoundException", ex.getErrorCode());+ }++ @Test+ void createGrantAndListGrantsRoundTrip() {+ KmsKey key = kmsService.createKey("grant key", REGION);++ KmsGrant grant = kmsService.createGrant(+ key.getKeyId(),+ "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt", "Decrypt"),+ REGION);++ assertNotNull(grant.getGrantId());+ assertFalse(grant.getGrantId().isBlank());+ assertNotNull(grant.getGrantToken());+ assertFalse(grant.getGrantToken().isBlank());++ Map<String, Object> result = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");++ assertEquals(1, grants.size());+ Map<String, Object> listedGrant = grants.getFirst();+ assertEquals(grant.getGrantId(), listedGrant.get("GrantId"));+ assertEquals(key.getArn(), listedGrant.get("KeyId"));+ assertEquals("arn:aws:iam::000000000000:user/grantee", listedGrant.get("GranteePrincipal"));+ assertEquals(List.of("Encrypt", "Decrypt"), listedGrant.get("Operations"));+ assertEquals(false, result.get("Truncated"));+ }++ @Test+ void createGrantMissingKeyIdThrowsValidation() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.createGrant(null, "arn:aws:iam::000000000000:user/grantee", List.of("Encrypt"), REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void createGrantMissingGranteePrincipalThrowsValidation() {+ KmsKey key = kmsService.createKey("grant key", REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.createGrant(key.getKeyId(), "", List.of("Encrypt"), REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void createGrantMissingOperationsThrowsValidation() {+ KmsKey key = kmsService.createKey("grant key", REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee", List.of(), REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void createGrantUnknownKeyThrowsNotFound() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.createGrant("non-existent-id", "arn:aws:iam::000000000000:user/grantee", List.of("Encrypt"), REGION));++ assertEquals("NotFoundException", ex.getErrorCode());+ }++ // ──────────────────────────── Phase 4: Pagination, Filters, ListRetirableGrants ────────────────────────────++ @Test+ void listGrantsPaginatesWithLimit() {+ KmsKey key = kmsService.createKey("pagination key", REGION);+ for (int i = 0; i < 5; i++) {+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee-" + i,+ List.of("Encrypt"), REGION);+ }++ Map<String, Object> page1 = kmsService.listGrants(key.getKeyId(), REGION, null, 3, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants1 = (List<Map<String, Object>>) page1.get("Grants");+ assertEquals(3, grants1.size());+ assertEquals(true, page1.get("Truncated"));+ assertNotNull(page1.get("NextMarker"));++ Map<String, Object> page2 = kmsService.listGrants(key.getKeyId(), REGION,+ (String) page1.get("NextMarker"), 3, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants2 = (List<Map<String, Object>>) page2.get("Grants");+ assertEquals(2, grants2.size());+ assertEquals(false, page2.get("Truncated"));+ }++ @Test+ void listGrantsInvalidMarkerThrows() {+ KmsKey key = kmsService.createKey("marker key", REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.listGrants(key.getKeyId(), REGION, "invalid-marker", null, null, null));++ assertEquals("InvalidMarkerException", ex.getErrorCode());+ }++ @Test+ void listGrantsRespectsDefaultLimit() {+ KmsKey key = kmsService.createKey("default limit key", REGION);+ for (int i = 0; i < 60; i++) {+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee-" + i,+ List.of("Encrypt"), REGION);+ }++ Map<String, Object> result = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");+ assertEquals(50, grants.size());+ assertEquals(true, result.get("Truncated"));+ }++ @Test+ void listGrantsEnforcesMaxLimit() {+ KmsKey key = kmsService.createKey("max limit key", REGION);++ Map<String, Object> result = kmsService.listGrants(key.getKeyId(), REGION, null, 200, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");+ assertTrue(grants.size() <= 100);+ }++ @Test+ void listGrantsFiltersByGrantId() {+ KmsKey key = kmsService.createKey("filter key", REGION);+ KmsGrant grant1 = kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt"), REGION);+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",+ List.of("Decrypt"), REGION);++ Map<String, Object> result = kmsService.listGrants(key.getKeyId(), REGION, null, null,+ grant1.getGrantId(), null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");+ assertEquals(1, grants.size());+ assertEquals(grant1.getGrantId(), grants.getFirst().get("GrantId"));+ }++ @Test+ void listGrantsFiltersByGranteePrincipal() {+ KmsKey key = kmsService.createKey("principal filter key", REGION);+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/alice",+ List.of("Encrypt"), REGION);+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/bob",+ List.of("Decrypt"), REGION);++ Map<String, Object> result = kmsService.listGrants(key.getKeyId(), REGION, null, null, null,+ "arn:aws:iam::000000000000:user/alice");+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");+ assertEquals(1, grants.size());+ assertEquals("arn:aws:iam::000000000000:user/alice", grants.getFirst().get("GranteePrincipal"));+ }++ @Test+ void listRetirableGrantsReturnsMatchingGrants() {+ KmsKey key = kmsService.createKey("retirable key", REGION);+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt"), "arn:aws:iam::000000000000:role/retirer", REGION);+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",+ List.of("Decrypt"), null, REGION);++ Map<String, Object> result = kmsService.listRetirableGrants(+ "arn:aws:iam::000000000000:role/retirer", REGION, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> grants = (List<Map<String, Object>>) result.get("Grants");+ assertEquals(1, grants.size());+ assertEquals("arn:aws:iam::000000000000:role/retirer", grants.getFirst().get("RetiringPrincipal"));+ }++ @Test+ void listRetirableGrantsMissingPrincipalThrowsValidation() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.listRetirableGrants("", REGION, null, null));+ assertEquals("ValidationException", ex.getErrorCode());+ }++ // ──────────────────────────── Phase 5: RevokeGrant ────────────────────────────++ @Test+ void revokeGrantRemovesGrant() {+ KmsKey key = kmsService.createKey("revoke key", REGION);+ KmsGrant grant = kmsService.createGrant(+ key.getKeyId(),+ "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt"),+ REGION);++ // Grant exists before revoke+ Map<String, Object> before = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> beforeGrants = (List<Map<String, Object>>) before.get("Grants");+ assertEquals(1, beforeGrants.size());++ // Revoke the grant+ kmsService.revokeGrant(key.getKeyId(), grant.getGrantId(), REGION);++ // Grant is gone after revoke+ Map<String, Object> after = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> afterGrants = (List<Map<String, Object>>) after.get("Grants");+ assertTrue(afterGrants.isEmpty());+ }++ @Test+ void revokeGrantUnknownGrantThrowsNotFound() {+ KmsKey key = kmsService.createKey("revoke unknown grant key", REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.revokeGrant(key.getKeyId(), "non-existent-grant-id", REGION));++ assertEquals("NotFoundException", ex.getErrorCode());+ }++ @Test+ void revokeGrantUnknownKeyThrowsNotFound() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.revokeGrant("non-existent-key", "some-grant-id", REGION));++ assertEquals("NotFoundException", ex.getErrorCode());+ }++ @Test+ void revokeGrantMissingKeyIdThrowsValidation() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.revokeGrant(null, "some-grant-id", REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void revokeGrantMissingGrantIdThrowsValidation() {+ KmsKey key = kmsService.createKey("revoke missing grant key", REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.revokeGrant(key.getKeyId(), null, REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ // ──────────────────────────── Phase 6: RetireGrant ────────────────────────────++ @Test+ void retireGrantByTokenRemovesGrant() {+ KmsKey key = kmsService.createKey("retire token key", REGION);+ KmsGrant grant = kmsService.createGrant(+ key.getKeyId(),+ "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt"),+ REGION);++ // Grant exists before retire+ Map<String, Object> before = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> beforeGrants = (List<Map<String, Object>>) before.get("Grants");+ assertEquals(1, beforeGrants.size());++ // Retire by grant token+ kmsService.retireGrant(grant.getGrantToken(), null, null, REGION);++ // Grant is gone after retire+ Map<String, Object> after = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> afterGrants = (List<Map<String, Object>>) after.get("Grants");+ assertTrue(afterGrants.isEmpty());+ }++ @Test+ void retireGrantByTokenWithMatchingGrantIdSucceeds() {+ KmsKey key = kmsService.createKey("retire token+grant key", REGION);+ KmsGrant grant = kmsService.createGrant(+ key.getKeyId(),+ "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt"),+ REGION);++ kmsService.retireGrant(grant.getGrantToken(), null, grant.getGrantId(), REGION);++ Map<String, Object> after = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> afterGrants = (List<Map<String, Object>>) after.get("Grants");+ assertTrue(afterGrants.isEmpty());+ }++ @Test+ void retireGrantByTokenWithMismatchedGrantIdThrowsNotFound() {+ KmsKey key = kmsService.createKey("retire mismatch key", REGION);+ KmsGrant grant = kmsService.createGrant(+ key.getKeyId(),+ "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt"),+ REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.retireGrant(grant.getGrantToken(), null, "wrong-grant-id", REGION));++ assertEquals("NotFoundException", ex.getErrorCode());+ }++ @Test+ void retireGrantByKeyAndGrantIdRemovesGrant() {+ KmsKey key = kmsService.createKey("retire admin key", REGION);+ KmsGrant grant = kmsService.createGrant(+ key.getKeyId(),+ "arn:aws:iam::000000000000:user/grantee",+ List.of("Encrypt"),+ REGION);++ // Administrative retire by KeyId + GrantId+ kmsService.retireGrant(null, key.getKeyId(), grant.getGrantId(), REGION);++ Map<String, Object> after = kmsService.listGrants(key.getKeyId(), REGION, null, null, null, null);+ @SuppressWarnings("unchecked")+ List<Map<String, Object>> afterGrants = (List<Map<String, Object>>) after.get("Grants");+ assertTrue(afterGrants.isEmpty());+ }++ @Test+ void retireGrantUnknownTokenThrowsNotFound() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.retireGrant("nonexistent-token-value", null, null, REGION));++ assertEquals("NotFoundException", ex.getErrorCode());+ }++ @Test+ void retireGrantUnknownKeyThrowsNotFound() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.retireGrant(null, "non-existent-key", "some-grant-id", REGION));++ assertEquals("NotFoundException", ex.getErrorCode());+ }++ @Test+ void retireGrantMissingAllIdentifiersThrowsValidation() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.retireGrant(null, null, null, REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }+@Testvoid describeKeyNotFound() {AwsException ex = assertThrows(AwsException.class, () ->