From 760115db14d6f101b0f282b71f81a11deefc9922 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 5 Aug 2026 23:36:07 -0500 Subject: [PATCH] feat(kms): implement ListKeyPolicies (#2046) * feat(kms): implement ListKeyPolicies ListKeyPolicies failed with UnsupportedOperation, so clients enumerating policy names before a GetKeyPolicy call could not proceed. GetKeyPolicy and PutKeyPolicy were already supported, so this was a hole in an otherwise complete area. Returns the single `default` policy name, which is what the model prescribes ("The only valid value is default"), with Truncated false and NextMarker omitted rather than serialized as null, since AWS only emits NextMarker when Truncated is true. Limit and Marker are accepted and ignored. One policy name cannot be paginated, and ListKeyPolicies is the one KMS list operation that does not declare InvalidMarkerException, unlike ListKeys, ListAliases, ListGrants, ListKeyRotations, ListResourceTags, ListRetirableGrants and DescribeCustomKeyStores. There is therefore no marker it could legitimately reject, and no undeclared error code is invented for one. Closes #1528 Co-authored-by: Marcel Herhold * chore: drop hand-written ListKeyPolicies changelog entry (semantic-release owns CHANGELOG.md) * fix(kms): drop unused ListKeyPolicies pagination params and fix test claims Review follow-up, validated against the local AWS references: Limit/Marker are accepted at the wire by never being read (matching moto's list_key_policies), so the service signature drops the dead parameters and the structurally vacuous paging unit test goes with them; the integration test remains the real coverage. The javadoc justification now states the leniency honestly: SDKs do not fully enforce LimitType [1..1000] client-side (botocore validates only the minimum), so out-of-range values can arrive and are deliberately tolerated. The ARN resolution test no longer claims alias coverage the operation does not have. --------- Signed-off-by: Hector Ventura Co-authored-by: Marcel Herhold --- docs/services/kms.md | 1 + .../floci/services/kms/KmsJsonHandler.java | 9 +++ .../floci/services/kms/KmsService.java | 21 +++++ .../services/kms/KmsIntegrationTest.java | 77 +++++++++++++++++++ .../floci/services/kms/KmsServiceTest.java | 34 ++++++++ 5 files changed, 142 insertions(+) diff --git a/docs/services/kms.md b/docs/services/kms.md index 6c37207957..8cbae83f50 100644 --- a/docs/services/kms.md +++ b/docs/services/kms.md @@ -37,6 +37,7 @@ | `ListResourceTags` | List tags | | `GetKeyPolicy` | Get a key's resource policy | | `PutKeyPolicy` | Update a key's resource policy | +| `ListKeyPolicies` | List a key's policy names (always the single `default` policy) | | `UpdateKeyDescription` | Update a key's description | | `GetKeyRotationStatus` | Check if automatic key rotation is enabled | | `EnableKeyRotation` | Enable automatic key rotation (symmetric keys only) | diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java index ca87355e0d..8710655780 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 @@ -67,6 +67,7 @@ public class KmsJsonHandler { case "ListResourceTags" -> handleListResourceTags(request, region); case "GetKeyPolicy" -> handleGetKeyPolicy(request, region); case "PutKeyPolicy" -> handlePutKeyPolicy(request, region); + case "ListKeyPolicies" -> handleListKeyPolicies(request, region); case "UpdateKeyDescription" -> handleUpdateKeyDescription(request, region); case "GetKeyRotationStatus" -> handleGetKeyRotationStatus(request, region); case "EnableKeyRotation" -> handleEnableKeyRotation(request, region); @@ -474,6 +475,14 @@ public class KmsJsonHandler { return Response.ok(objectMapper.createObjectNode()).build(); } + private Response handleListKeyPolicies(JsonNode request, String region) { + // Limit and Marker are accepted by simply not being read; see the service javadoc. + Map result = service.listKeyPolicies( + requiredText(request, "KeyId"), + region); + return Response.ok(objectMapper.valueToTree(result)).build(); + } + private Response handleUpdateKeyDescription(JsonNode request, String region) { service.updateKeyDescription( request.path("KeyId").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.java index a5f717635c..9cd7a23a3d 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 @@ -489,6 +489,27 @@ public class KmsService { LOG.infov("Updated key policy for KMS key: {0} in {1}", key.getKeyId(), region); } + /** + * Lists the policy names attached to a key. KMS supports exactly one key policy, named + * {@code default}, so the result can never be truncated: {@code Truncated} is always false and + * {@code NextMarker} is omitted. + * + *

{@code Limit} and {@code Marker} are accepted at the wire and ignored: the handler simply + * never reads them, which is exactly what moto's KMS does for this operation. A single policy + * name fits inside any limit, so the values cannot change the response. Real AWS rejects an + * out-of-range {@code Limit} server-side (the model bounds LimitType to [1..1000], but SDKs do + * not fully enforce that client-side — botocore checks only the minimum); not re-validating it + * here is deliberate leniency, consistent with the emulator's general posture. + */ + public Map listKeyPolicies(String keyId, String region) { + String policyName = (String) getKeyPolicy(keyId, region).get("PolicyName"); + + Map result = new HashMap<>(); + result.put("PolicyNames", List.of(policyName)); + result.put("Truncated", false); + return result; + } + public void updateKeyDescription(String keyId, String description, String region) { KmsKey key = resolveKey(keyId, region); key.setDescription(description); diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java index 62c071fdc7..5d858e7456 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 @@ -13,6 +13,8 @@ import java.util.List; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -1106,4 +1108,79 @@ class KmsIntegrationTest { .then() .statusCode(expectedStatusCode); } + + // ── Issue #1528 — ListKeyPolicies ──────────────────────────────────────── + + @Test + void listKeyPoliciesReturnsDefaultPolicyThroughJsonHandler() { + String keyId = given() + .header("X-Amz-Target", "TrentService.CreateKey") + .contentType(KMS_CONTENT_TYPE) + .body("{\"Description\":\"list-key-policies\"}") + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("KeyMetadata.KeyId"); + + given() + .header("X-Amz-Target", "TrentService.ListKeyPolicies") + .contentType(KMS_CONTENT_TYPE) + .body(""" + {"KeyId":"%s"} + """.formatted(keyId)) + .when() + .post("/") + .then() + .statusCode(200) + .body("PolicyNames.size()", equalTo(1)) + .body("PolicyNames[0]", equalTo("default")) + .body("Truncated", equalTo(false)) + // Truncated is always false, so NextMarker must be absent rather than null. + .body("$", not(hasKey("NextMarker"))); + } + + @Test + void listKeyPoliciesIgnoresLimitAndMarker() { + String keyId = given() + .header("X-Amz-Target", "TrentService.CreateKey") + .contentType(KMS_CONTENT_TYPE) + .body("{\"Description\":\"list-key-policies-paging\"}") + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("KeyMetadata.KeyId"); + + // A single policy name cannot be paginated, and ListKeyPolicies does not declare + // InvalidMarkerException, so both parameters are accepted without error. + given() + .header("X-Amz-Target", "TrentService.ListKeyPolicies") + .contentType(KMS_CONTENT_TYPE) + .body(""" + {"KeyId":"%s","Limit":1,"Marker":"anything"} + """.formatted(keyId)) + .when() + .post("/") + .then() + .statusCode(200) + .body("PolicyNames[0]", equalTo("default")) + .body("Truncated", equalTo(false)); + } + + @Test + void listKeyPoliciesReturnsNotFoundForUnknownKey() { + // Asserting the error type only. Floci returns 404 where real KMS uses 400 for + // NotFoundException, a pre-existing service-wide deviation that is not this change's to fix. + given() + .header("X-Amz-Target", "TrentService.ListKeyPolicies") + .contentType(KMS_CONTENT_TYPE) + .body("{\"KeyId\":\"non-existent-id\"}") + .when() + .post("/") + .then() + .body("__type", equalTo("NotFoundException")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java index 43fa45ee7c..c23a236259 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 @@ -1054,6 +1054,40 @@ class KmsServiceTest { kmsService.putKeyPolicy("non-existent", "{}", REGION)); } + // ── Issue #1528 — ListKeyPolicies ──────────────────────────────────────── + + @Test + void listKeyPoliciesReturnsDefaultPolicy() { + KmsKey key = kmsService.createKey("list-policy-key", REGION); + + Map result = kmsService.listKeyPolicies(key.getKeyId(), REGION); + + @SuppressWarnings("unchecked") + List policyNames = (List) result.get("PolicyNames"); + assertEquals(1, policyNames.size()); + assertEquals("default", policyNames.getFirst()); + assertFalse((Boolean) result.get("Truncated")); + // Truncated is always false, so NextMarker must not be emitted at all. + assertFalse(result.containsKey("NextMarker")); + } + + @Test + void listKeyPoliciesResolvesByArn() { + // The model documents KeyId for this operation as key ID or key ARN only; alias + // acceptance is a Floci-wide resolveKey superset, not this operation's AWS contract. + KmsKey key = kmsService.createKey("list-policy-arn", REGION); + + assertEquals(List.of("default"), + kmsService.listKeyPolicies(key.getArn(), REGION).get("PolicyNames")); + } + + @Test + void listKeyPoliciesOnNonExistentKeyThrows() { + AwsException ex = assertThrows(AwsException.class, () -> + kmsService.listKeyPolicies("non-existent", REGION)); + assertEquals("NotFoundException", ex.getErrorCode()); + } + // ── Issue #290 — Key Rotation ─────────────────────────────────────────── @Test