From 6aff7858751a370f056dd53f0f03cca58ecf14ec Mon Sep 17 00:00:00 2001 From: mrfelek <17274927+mrfelek@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:28:46 +0100 Subject: [PATCH] fix(kms): honour DryRun on the grant and cryptographic calls (#9226) --- docs/services/kms.md | 4 + .../aws/core/common/JsonBooleanCoercion.java | 26 ++ .../aws/services/kms/KmsJsonHandler.java | 86 +++++-- .../io/floci/aws/services/kms/KmsService.java | 49 ++++ .../io/floci/aws/services/ses/SesV2Json.java | 9 +- .../core/common/JsonBooleanCoercionTest.java | 27 ++ .../KmsKeyArnEnforcementIntegrationTest.java | 43 +++- .../kms/KmsDryRunIntegrationTest.java | 241 ++++++++++++++++++ .../aws/testing/RestAssuredJsonUtils.java | 8 + 9 files changed, 463 insertions(+), 30 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/JsonBooleanCoercion.java create mode 100644 src/test/java/io/floci/aws/core/common/JsonBooleanCoercionTest.java create mode 100644 src/test/java/io/floci/aws/services/kms/KmsDryRunIntegrationTest.java diff --git a/docs/services/kms.md b/docs/services/kms.md index 9068e8e01f..e3ec350a67 100644 --- a/docs/services/kms.md +++ b/docs/services/kms.md @@ -248,6 +248,10 @@ there. 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. +## DryRun + +`CreateGrant`, `RetireGrant`, `RevokeGrant`, `Encrypt`, `Decrypt`, `ReEncrypt`, the four `GenerateDataKey` actions, `Sign`, `Verify`, `GenerateMac` and `VerifyMac` take `DryRun`. A dry run is checked as the call is, so a request the call would refuse keeps its error. One the call would accept is answered with `DryRunOperationException` (HTTP 400) and changes nothing: no grant is created or removed, and no result is returned. `DryRun` is read as AWS reads it: a boolean, or a string naming one in any case (`true`, `yes`, `y`, `t`, `1`, `false`, `no`, `n`, `f`, `0`), with any other value refused with `SerializationException`. `DryRunModifiers` is not read, so a `Decrypt` or `ReEncrypt` dry run always checks its ciphertext. + ## IAM Enforcement With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, a KMS request is checked as AWS checks it, read from the generated tables like other services' requests. An operation that names a key is evaluated against that key's ARN. A `KeyId` given as a key id, an alias name, an alias ARN or a key ARN resolves to the key it names, whatever the key's state, so a policy scoped to one key ARN allows that key and no other, and a `Deny` scoped to one fires for that key. A key KMS holds none of is checked on its id in the request's partition. A `Decrypt` that names no `KeyId` is evaluated against the key that encrypted its `CiphertextBlob`, as the [API reference](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) says KMS reads it from the ciphertext's metadata. A request whose ciphertext names no key KMS holds is checked on `*`. diff --git a/src/main/java/io/floci/aws/core/common/JsonBooleanCoercion.java b/src/main/java/io/floci/aws/core/common/JsonBooleanCoercion.java new file mode 100644 index 0000000000..b0d35ae815 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/JsonBooleanCoercion.java @@ -0,0 +1,26 @@ +package io.floci.aws.core.common; + +import java.util.Locale; + +/** The boolean a JSON string names, as AWS's JSON protocol deserializers read one. */ +public final class JsonBooleanCoercion { + + private JsonBooleanCoercion() { + } + + /** + * The boolean {@code value} names, in any case and untrimmed: {@code true}, {@code yes}, {@code y}, + * {@code t} or {@code 1}, and {@code false}, {@code no}, {@code n}, {@code f} or {@code 0}, as SES v2's + * and KMS's deserializers read a string (measured on AWS). Any other string is refused with the + * deserializer's {@code SerializationException}. Callers read the member's other JSON types themselves, + * each service's deserializer answering them in its own way. + */ + public static boolean fromString(String value) { + return switch (value.toLowerCase(Locale.ROOT)) { + case "true", "yes", "y", "t", "1" -> true; + case "false", "no", "n", "f", "0" -> false; + default -> throw new AwsException("SerializationException", + "STRING_VALUE can not be converted to an Boolean", 400); + }; + } +} diff --git a/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java b/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java index 6effea2fad..cb007e31dd 100644 --- a/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java +++ b/src/main/java/io/floci/aws/services/kms/KmsJsonHandler.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsErrorResponse; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.JsonBooleanCoercion; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.ReservedTags; import io.floci.aws.core.common.SmithyValidationErrors; @@ -55,7 +56,18 @@ public class KmsJsonHandler { "DisableKey", "RotateKeyOnDemand", "ListKeyRotations", "GetParametersForImport", "ImportKeyMaterial", "DeleteImportedKeyMaterial"); + /** + * The operations whose request takes {@code DryRun}. A dry run of one is checked as the call itself + * is, and is then answered with DryRunOperationException: the grant calls answer before they change + * anything, and the others, which change nothing, in place of their result. + */ + private static final Set DRY_RUN_OPERATIONS = Set.of( + "CreateGrant", "RetireGrant", "RevokeGrant", "Encrypt", "Decrypt", "ReEncrypt", "GenerateDataKey", + "GenerateDataKeyWithoutPlaintext", "GenerateDataKeyPair", "GenerateDataKeyPairWithoutPlaintext", + "Sign", "Verify", "GenerateMac", "VerifyMac"); + public Response handle(String action, JsonNode request, String region) { + boolean dryRun = DRY_RUN_OPERATIONS.contains(action) && dryRun(request); if (KEY_ID_OPERATIONS.contains(action)) { validateKeyIdMember(request, "KeyId"); String keyId = request.path("KeyId").asText(); @@ -74,22 +86,24 @@ public class KmsJsonHandler { case "DescribeKey" -> handleDescribeKey(request, region); case "ReplicateKey" -> handleReplicateKey(request, region); case "ListKeys" -> handleListKeys(request, region); - case "CreateGrant" -> handleCreateGrant(request, region); + case "CreateGrant" -> handleCreateGrant(request, region, dryRun); 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); - case "GenerateDataKey" -> handleGenerateDataKey(request, region); - case "GenerateDataKeyWithoutPlaintext" -> handleGenerateDataKeyWithoutPlaintext(request, region); - case "GenerateDataKeyPair" -> handleGenerateDataKeyPair(request, region); - case "GenerateDataKeyPairWithoutPlaintext" -> handleGenerateDataKeyPairWithoutPlaintext(request, region); - case "Sign" -> handleSign(request, region); - case "Verify" -> handleVerify(request, region); - case "GenerateMac" -> handleGenerateMac(request, region); - case "VerifyMac" -> handleVerifyMac(request, region); + case "RevokeGrant" -> handleRevokeGrant(request, region, dryRun); + case "RetireGrant" -> handleRetireGrant(request, region, dryRun); + case "Encrypt" -> resultUnlessDryRun(dryRun, handleEncrypt(request, region)); + case "Decrypt" -> resultUnlessDryRun(dryRun, handleDecrypt(request, region)); + case "ReEncrypt" -> resultUnlessDryRun(dryRun, handleReEncrypt(request, region)); + case "GenerateDataKey" -> resultUnlessDryRun(dryRun, handleGenerateDataKey(request, region)); + case "GenerateDataKeyWithoutPlaintext" -> + resultUnlessDryRun(dryRun, handleGenerateDataKeyWithoutPlaintext(request, region)); + case "GenerateDataKeyPair" -> resultUnlessDryRun(dryRun, handleGenerateDataKeyPair(request, region)); + case "GenerateDataKeyPairWithoutPlaintext" -> + resultUnlessDryRun(dryRun, handleGenerateDataKeyPairWithoutPlaintext(request, region)); + case "Sign" -> resultUnlessDryRun(dryRun, handleSign(request, region)); + case "Verify" -> resultUnlessDryRun(dryRun, handleVerify(request, region)); + case "GenerateMac" -> resultUnlessDryRun(dryRun, handleGenerateMac(request, region)); + case "VerifyMac" -> resultUnlessDryRun(dryRun, handleVerifyMac(request, region)); case "CreateAlias" -> handleCreateAlias(request, region); case "UpdateAlias" -> handleUpdateAlias(request, region); case "DeleteAlias" -> handleDeleteAlias(request, region); @@ -319,7 +333,7 @@ public class KmsJsonHandler { return Response.ok(response).build(); } - private Response handleCreateGrant(JsonNode request, String region) { + private Response handleCreateGrant(JsonNode request, String region, boolean dryRun) { String keyId = request.path("KeyId").asText(null); String granteePrincipal = request.path("GranteePrincipal").asText(null); List operations = new ArrayList<>(); @@ -338,22 +352,22 @@ public class KmsJsonHandler { : null; KmsGrant grant = service.createGrant( - keyId, granteePrincipal, operations, retiringPrincipal, name, constraints, region); + keyId, granteePrincipal, operations, retiringPrincipal, name, constraints, region, dryRun); 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) { + private Response handleRevokeGrant(JsonNode request, String region, boolean dryRun) { String keyId = request.path("KeyId").asText(null); String grantId = request.path("GrantId").asText(null); - service.revokeGrant(keyId, grantId, region); + service.revokeGrant(keyId, grantId, region, dryRun); return Response.ok().build(); } - private Response handleRetireGrant(JsonNode request, String region) { + private Response handleRetireGrant(JsonNode request, String region, boolean dryRun) { String grantToken = request.path("GrantToken").isMissingNode() ? null : request.path("GrantToken").asText(null); String keyId = request.path("KeyId").isMissingNode() @@ -361,10 +375,42 @@ public class KmsJsonHandler { String grantId = request.path("GrantId").isMissingNode() ? null : request.path("GrantId").asText(null); - service.retireGrant(grantToken, keyId, grantId, region); + service.retireGrant(grantToken, keyId, grantId, region, dryRun); return Response.ok().build(); } + /** + * The request's {@code DryRun}, read as KMS's JSON deserializer reads a boolean (measured on AWS): + * true or false, or a string naming one in any case ({@code true}, {@code yes}, {@code y}, {@code t} + * or {@code 1}, and {@code false}, {@code no}, {@code n}, {@code f} or {@code 0}); absent or null is + * false. Any other value is refused with the deserializer's SerializationException. + */ + private static boolean dryRun(JsonNode request) { + JsonNode node = request.path("DryRun"); + if (node.isMissingNode() || node.isNull()) { + return false; + } + if (node.isBoolean()) { + return node.booleanValue(); + } + if (node.isTextual()) { + return JsonBooleanCoercion.fromString(node.textValue()); + } + String message = node.isIntegralNumber() ? "NUMBER_VALUE can not be converted to a Boolean" + : node.isNumber() ? "DECIMAL_VALUE cannot be converted to Boolean" + : node.isArray() ? "Start of list found where not expected" + : "Start of structure or map found where not expected."; + throw new AwsException("SerializationException", message, 400); + } + + /** The result of a call that changes nothing, or DryRunOperationException in its place for a dry run. */ + private static Response resultUnlessDryRun(boolean dryRun, Response result) { + if (dryRun) { + throw KmsService.dryRunOperation(); + } + return result; + } + // Blob fields arrive base64-encoded on the wire. A value that is not valid base64 is a // client deserialization error, not a server fault — without this the IllegalArgumentException // escapes to the dispatcher's generic catch and surfaces as 500 InternalFailure. diff --git a/src/main/java/io/floci/aws/services/kms/KmsService.java b/src/main/java/io/floci/aws/services/kms/KmsService.java index 18b01ff3fb..4a3d0dc8f6 100644 --- a/src/main/java/io/floci/aws/services/kms/KmsService.java +++ b/src/main/java/io/floci/aws/services/kms/KmsService.java @@ -471,6 +471,16 @@ public class KmsService implements ResourceProvider { public KmsGrant createGrant(String keyId, String granteePrincipal, List operations, String retiringPrincipal, String name, Map constraints, String region) { + return createGrant(keyId, granteePrincipal, operations, retiringPrincipal, name, constraints, region, false); + } + + /** + * As above; with {@code dryRun} the request passes every check the grant's creation makes, and is + * then answered with DryRunOperationException, no grant created. + */ + public KmsGrant createGrant(String keyId, String granteePrincipal, List operations, + String retiringPrincipal, String name, Map constraints, + String region, boolean dryRun) { if (keyId == null || keyId.isBlank()) { throw new AwsException("ValidationException", "KeyId is required", 400); } @@ -513,6 +523,9 @@ public class KmsService implements ResourceProvider { // it (a kms:ViaService condition), never to the account directly. requireCustomerManaged(key, "kms:CreateGrant"); requireNotPendingDeletion(key); + if (dryRun) { + throw dryRunOperation(); + } String grantId = UUID.randomUUID().toString(); byte[] tokenBytes = new byte[32]; secureRandom.nextBytes(tokenBytes); @@ -533,6 +546,16 @@ public class KmsService implements ResourceProvider { return grant; } + /** + * What KMS answers a dry run with once the request has passed every check the call makes: + * DryRunOperationException, with the message KMS answers it with, HTTP 400 as every KMS + * client error is; nothing changed and no result returned. + */ + static AwsException dryRunOperation() { + return new AwsException("DryRunOperationException", + "The request would have succeeded, but the DryRun option is set.", 400); + } + private static final int DEFAULT_GRANT_LIMIT = 50; private static final int MAX_GRANT_LIMIT = 100; @@ -576,6 +599,15 @@ public class KmsService implements ResourceProvider { } public void revokeGrant(String keyId, String grantId, String region) { + revokeGrant(keyId, grantId, region, false); + } + + /** + * As above; with {@code dryRun} the key must exist, and the request is then answered with + * DryRunOperationException before the grant is looked up, as AWS answers a dry run naming a grant id + * that doesn't exist or that is another key's (measured); no grant is revoked. + */ + public void revokeGrant(String keyId, String grantId, String region, boolean dryRun) { if (keyId == null || keyId.isBlank()) { throw new AwsException("ValidationException", "KeyId is required", 400); } @@ -585,6 +617,9 @@ public class KmsService implements ResourceProvider { // Resolve the key to validate it exists resolveKey(keyId, region); + if (dryRun) { + throw dryRunOperation(); + } String storageKey = region + "::" + grantId; if (grantStore.get(storageKey).isEmpty()) { @@ -596,6 +631,14 @@ public class KmsService implements ResourceProvider { } public void retireGrant(String grantToken, String keyId, String grantId, String region) { + retireGrant(grantToken, keyId, grantId, region, false); + } + + /** + * As above; with {@code dryRun} the grant must be found as the retirement finds it, and the request is + * then answered with DryRunOperationException, the grant kept. + */ + public void retireGrant(String grantToken, String keyId, String grantId, String region, boolean dryRun) { boolean hasToken = grantToken != null && !grantToken.isBlank(); boolean hasKeyAndGrant = keyId != null && !keyId.isBlank() && grantId != null && !grantId.isBlank(); @@ -623,6 +666,9 @@ public class KmsService implements ResourceProvider { "Grant not found for the given key", 400); } } + if (dryRun) { + throw dryRunOperation(); + } grantStore.delete(region + "::" + found.getGrantId()); LOG.infov("Retired KMS grant: {0} by token in {1}", found.getGrantId(), region); @@ -635,6 +681,9 @@ public class KmsService implements ResourceProvider { if (grantStore.get(storageKey).isEmpty()) { throw new AwsException("NotFoundException", "Grant not found: " + grantId, 400); } + if (dryRun) { + throw dryRunOperation(); + } grantStore.delete(storageKey); LOG.infov("Retired KMS grant: {0} for key {1} in {2}", grantId, keyId, region); } diff --git a/src/main/java/io/floci/aws/services/ses/SesV2Json.java b/src/main/java/io/floci/aws/services/ses/SesV2Json.java index a4dd38ea63..d33656a806 100644 --- a/src/main/java/io/floci/aws/services/ses/SesV2Json.java +++ b/src/main/java/io/floci/aws/services/ses/SesV2Json.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.EpochSeconds; +import io.floci.aws.core.common.JsonBooleanCoercion; import io.floci.aws.core.common.JsonNumberCoercion; import io.floci.aws.core.common.SmithyValidationErrors; import io.floci.aws.services.ses.model.Tag; @@ -15,7 +16,6 @@ import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.function.Predicate; @@ -165,12 +165,7 @@ final class SesV2Json { return node.booleanValue(); } if (node.isTextual()) { - return switch (node.textValue().toLowerCase(Locale.ROOT)) { - case "true", "yes", "y", "t", "1" -> true; - case "false", "no", "n", "f", "0" -> false; - default -> throw new AwsException(SERIALIZATION_EXCEPTION, - "STRING_VALUE can not be converted to an Boolean", 400); - }; + return JsonBooleanCoercion.fromString(node.textValue()); } if (node.isNull()) { throw new AwsException(SERIALIZATION_EXCEPTION, null, 400); diff --git a/src/test/java/io/floci/aws/core/common/JsonBooleanCoercionTest.java b/src/test/java/io/floci/aws/core/common/JsonBooleanCoercionTest.java new file mode 100644 index 0000000000..55f44ecea2 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/JsonBooleanCoercionTest.java @@ -0,0 +1,27 @@ +package io.floci.aws.core.common; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class JsonBooleanCoercionTest { + + @ParameterizedTest + @CsvSource({"true,true", "YES,true", "y,true", "T,true", "1,true", + "false,false", "No,false", "n,false", "F,false", "0,false"}) + void aStringNamingABooleanInAnyCaseIsThatBoolean(String value, boolean expected) { + assertEquals(expected, JsonBooleanCoercion.fromString(value)); + } + + @ParameterizedTest + @ValueSource(strings = {"", " true", "false ", "on", "2", "maybe"}) + void anyOtherStringIsRefusedAsTheDeserializerRefusesIt(String value) { + AwsException error = assertThrows(AwsException.class, () -> JsonBooleanCoercion.fromString(value)); + assertEquals("SerializationException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("STRING_VALUE can not be converted to an Boolean", error.getMessage()); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java index 2f6a50fa99..01ec3681ff 100644 --- a/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/KmsKeyArnEnforcementIntegrationTest.java @@ -329,6 +329,39 @@ class KmsKeyArnEnforcementIntegrationTest { .then().statusCode(200).body("Grants.size()", equalTo(0)); } + /** + * A dry run needs the permission the call does: the key the policy allows answers + * DryRunOperationException, and another key AccessDeniedException, and neither dry run creates a grant. + */ + @Test + void aDryRunIsAuthorizedAsTheCallIs() { + String allowedArn = createKey(); + String otherArn = createKey(); + Session session = assumeRoleWith(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["kms:Encrypt","kms:CreateGrant"],"Resource":"%s"}]}""" + .formatted(allowedArn)); + + keyCall(session, "Encrypt", dryRun(encryptBody(allowedArn))) + .then().statusCode(400).body("__type", equalTo("DryRunOperationException")); + keyCall(session, "Encrypt", dryRun(encryptBody(otherArn))) + .then().statusCode(400).body("__type", equalTo("AccessDeniedException")); + keyCall(session, "CreateGrant", dryRun(grantBody(allowedArn))) + .then().statusCode(400).body("__type", equalTo("DryRunOperationException")); + keyCall(session, "CreateGrant", dryRun(grantBody(otherArn))) + .then().statusCode(400).body("__type", equalTo("AccessDeniedException")); + + accountCall("ListGrants", "{\"KeyId\": \"" + allowedArn + "\"}") + .then().statusCode(200).body("Grants.size()", equalTo(0)); + accountCall("ListGrants", "{\"KeyId\": \"" + otherArn + "\"}") + .then().statusCode(200).body("Grants.size()", equalTo(0)); + } + + /** {@code body} with {@code "DryRun": true} added. */ + private static String dryRun(String body) { + return RestAssuredJsonUtils.withMember(body, "DryRun", "true"); + } + private static String decryptOn(String keyArn) { return """ {"Version":"2012-10-17","Statement":[ @@ -352,13 +385,17 @@ class KmsKeyArnEnforcementIntegrationTest { .then().statusCode(200).extract().path("KeyMetadata.Arn"); } + /** A CreateGrant request giving a user of the account Encrypt on {@code keyArn}. */ + private static String grantBody(String keyArn) { + return "{\"KeyId\": \"" + keyArn + "\", \"GranteePrincipal\": \"arn:aws:iam::" + ACCOUNT + + ":user/grantee\", \"Operations\": [\"Encrypt\"]}"; + } + /** The id and the token of a grant the account itself creates on {@code keyArn}. */ private record Grant(String id, String token) {} private Grant createGrantOn(String keyArn) { - Response created = accountCall("CreateGrant", - "{\"KeyId\": \"" + keyArn + "\", \"GranteePrincipal\": \"arn:aws:iam::" + ACCOUNT - + ":user/grantee\", \"Operations\": [\"Encrypt\"]}"); + Response created = accountCall("CreateGrant", grantBody(keyArn)); created.then().statusCode(200); return new Grant(created.jsonPath().getString("GrantId"), created.jsonPath().getString("GrantToken")); diff --git a/src/test/java/io/floci/aws/services/kms/KmsDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/kms/KmsDryRunIntegrationTest.java new file mode 100644 index 0000000000..e5c2f37803 --- /dev/null +++ b/src/test/java/io/floci/aws/services/kms/KmsDryRunIntegrationTest.java @@ -0,0 +1,241 @@ +package io.floci.aws.services.kms; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * DryRun on the KMS calls that take it is answered with DryRunOperationException once the request has passed + * the checks the call makes: CreateGrant, RetireGrant and RevokeGrant change no grant, and the cryptographic + * calls return no result. A dry run the call would refuse keeps the call's error, and a DryRun value KMS's + * JSON deserializer does not read as a boolean is refused as it refuses one. + */ +@QuarkusTest +class KmsDryRunIntegrationTest { + + private static final String KMS_CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String MESSAGE = Base64.getEncoder() + .encodeToString("kms dry run".getBytes(StandardCharsets.UTF_8)); + private static final String GRANTEE = "arn:aws:iam::000000000000:role/kms-dry-run"; + private static final String MISSING_KEY = "11111111-2222-3333-4444-555555555555"; + + /** The fixture's values by the names the request bodies give them in braces, such as {key}. */ + private final Map values = new HashMap<>(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + /** + * A symmetric key holding one grant, with a ciphertext of the message; an HMAC key with the message's + * MAC; and an ECC signing key with the message's signature. + */ + @BeforeEach + void createTheKeys() { + values.clear(); + values.put("message", MESSAGE); + values.put("key", createKey("{}")); + values.put("macKey", createKey("{'KeyUsage': 'GENERATE_VERIFY_MAC', 'KeySpec': 'HMAC_256'}")); + values.put("signingKey", createKey("{'KeyUsage': 'SIGN_VERIFY', 'KeySpec': 'ECC_NIST_P256'}")); + values.put("ciphertext", result("Encrypt", "{'KeyId': '{key}', 'Plaintext': '{message}'}", "CiphertextBlob")); + values.put("mac", result("GenerateMac", + "{'KeyId': '{macKey}', 'Message': '{message}', 'MacAlgorithm': 'HMAC_SHA_256'}", "Mac")); + values.put("signature", result("Sign", + "{'KeyId': '{signingKey}', 'Message': '{message}', 'SigningAlgorithm': 'ECDSA_SHA_256'}", "Signature")); + ExtractableResponse grant = call("CreateGrant", + "{'KeyId': '{key}', 'GranteePrincipal': '" + GRANTEE + "', 'Operations': ['Encrypt']}") + .statusCode(200).extract(); + values.put("grantId", grant.path("GrantId")); + values.put("grantToken", grant.path("GrantToken")); + } + + /** A request each call accepts in the fixture. */ + static Stream acceptedRequests() { + return Stream.of( + new String[] {"CreateGrant", + "{'KeyId': '{key}', 'GranteePrincipal': '" + GRANTEE + "', 'Operations': ['Encrypt']}"}, + new String[] {"RetireGrant", "{'GrantToken': '{grantToken}'}"}, + new String[] {"RevokeGrant", "{'KeyId': '{key}', 'GrantId': '{grantId}'}"}, + new String[] {"Encrypt", "{'KeyId': '{key}', 'Plaintext': '{message}'}"}, + new String[] {"Decrypt", "{'CiphertextBlob': '{ciphertext}'}"}, + new String[] {"ReEncrypt", "{'CiphertextBlob': '{ciphertext}', 'DestinationKeyId': '{key}'}"}, + new String[] {"GenerateDataKey", "{'KeyId': '{key}', 'KeySpec': 'AES_256'}"}, + new String[] {"GenerateDataKeyWithoutPlaintext", "{'KeyId': '{key}', 'KeySpec': 'AES_256'}"}, + new String[] {"GenerateDataKeyPair", "{'KeyId': '{key}', 'KeyPairSpec': 'ECC_NIST_P256'}"}, + new String[] {"GenerateDataKeyPairWithoutPlaintext", + "{'KeyId': '{key}', 'KeyPairSpec': 'ECC_NIST_P256'}"}, + new String[] {"Sign", + "{'KeyId': '{signingKey}', 'Message': '{message}', 'SigningAlgorithm': 'ECDSA_SHA_256'}"}, + new String[] {"Verify", "{'KeyId': '{signingKey}', 'Message': '{message}', 'Signature': '{signature}'," + + " 'SigningAlgorithm': 'ECDSA_SHA_256'}"}, + new String[] {"GenerateMac", + "{'KeyId': '{macKey}', 'Message': '{message}', 'MacAlgorithm': 'HMAC_SHA_256'}"}, + new String[] {"VerifyMac", + "{'KeyId': '{macKey}', 'Message': '{message}', 'Mac': '{mac}', 'MacAlgorithm': 'HMAC_SHA_256'}"}); + } + + @ParameterizedTest + @MethodSource("acceptedRequests") + void aDryRunIsAnsweredWithDryRunOperationExceptionAndChangesNothing(String action, String body) { + String before = grants(); + + call(action, withDryRun(body, "true")) + .statusCode(400) + .body("__type", equalTo("DryRunOperationException")) + .body("message", equalTo("The request would have succeeded, but the DryRun option is set.")); + + assertEquals(before, grants()); + } + + @ParameterizedTest + @MethodSource("acceptedRequests") + void aDryRunValueThatIsNotABooleanIsRefused(String action, String body) { + String before = grants(); + + call(action, withDryRun(body, "'maybe'")) + .statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("STRING_VALUE can not be converted to an Boolean")); + + assertEquals(before, grants()); + } + + /** A string naming true, in any case, is read as true, as KMS's deserializer reads it. */ + @ParameterizedTest + @ValueSource(strings = {"'true'", "'TRUE'", "'yes'", "'y'", "'t'", "'1'"}) + void aStringNamingTrueIsADryRun(String value) { + call("Encrypt", withDryRun("{'KeyId': '{key}', 'Plaintext': '{message}'}", value)) + .statusCode(400) + .body("__type", equalTo("DryRunOperationException")); + } + + /** False, null, and a string naming false in any case, make the call itself. */ + @ParameterizedTest + @ValueSource(strings = {"false", "null", "'false'", "'No'", "'n'", "'f'", "'0'"}) + void aValueNamingFalseMakesTheCall(String value) { + call("Encrypt", withDryRun("{'KeyId': '{key}', 'Plaintext': '{message}'}", value)) + .statusCode(200) + .body("CiphertextBlob", notNullValue()); + } + + /** Any other value is refused with the deserializer's message for it (measured on AWS). */ + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '"', value = { + "2 | NUMBER_VALUE can not be converted to a Boolean", + "1.5 | DECIMAL_VALUE cannot be converted to Boolean", + "[true] | Start of list found where not expected", + "{} | Start of structure or map found where not expected." + }) + void anyOtherDryRunValueIsRefused(String value, String message) { + call("Encrypt", withDryRun("{'KeyId': '{key}', 'Plaintext': '{message}'}", value)) + .statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo(message)); + } + + /** The call refuses each of these; its dry run keeps the same error, and neither changes a grant. */ + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '"', value = { + "CreateGrant | {'KeyId': '{key}', 'GranteePrincipal': '" + GRANTEE + "', 'Operations': ['Bogus']}" + + " | ValidationException", + "Encrypt | {'KeyId': '" + MISSING_KEY + "', 'Plaintext': '{message}'} | NotFoundException", + "Decrypt | {'CiphertextBlob': 'AAAA'} | InvalidCiphertextException", + "GenerateDataKey | {'KeyId': '{signingKey}', 'KeySpec': 'AES_256'} | InvalidKeyUsageException", + "Sign | {'KeyId': '{macKey}', 'Message': '{message}', 'SigningAlgorithm': 'ECDSA_SHA_256'}" + + " | InvalidKeyUsageException", + "Verify | {'KeyId': '{signingKey}', 'Message': '{message}', 'Signature': '{mac}'," + + " 'SigningAlgorithm': 'ECDSA_SHA_256'} | KMSInvalidSignatureException", + "VerifyMac | {'KeyId': '{macKey}', 'Message': '{message}', 'Mac': '{message}'," + + " 'MacAlgorithm': 'HMAC_SHA_256'} | KMSInvalidMacException" + }) + void aDryRunTheCallWouldRefuseKeepsItsError(String action, String body, String code) { + String before = grants(); + + for (String dryRun : List.of("true", "false")) { + call(action, withDryRun(body, dryRun)) + .statusCode(400) + .body("__type", equalTo(code)); + } + + assertEquals(before, grants()); + } + + /** The symmetric key's grants, the only state these calls can change. */ + /** + * A RevokeGrant dry run is answered once its key is found, before its grant is looked up, as AWS answers one + * naming a grant id that doesn't exist or that is another key's (measured): the real call refuses the first, + * and neither changes a grant. + */ + @Test + void aRevokeGrantDryRunIsAnsweredBeforeItsGrantIsLookedUp() { + String before = grants(); + + call("RevokeGrant", withDryRun("{'KeyId': '{key}', 'GrantId': '0123456789abcdef'}", "true")) + .statusCode(400) + .body("__type", equalTo("DryRunOperationException")); + call("RevokeGrant", withDryRun("{'KeyId': '{signingKey}', 'GrantId': '{grantId}'}", "true")) + .statusCode(400) + .body("__type", equalTo("DryRunOperationException")); + call("RevokeGrant", "{'KeyId': '{key}', 'GrantId': '0123456789abcdef'}") + .statusCode(400) + .body("__type", equalTo("NotFoundException")); + + assertEquals(before, grants()); + } + + private String grants() { + return call("ListGrants", "{'KeyId': '{key}'}").statusCode(200).extract().asString(); + } + + private String createKey(String body) { + return result("CreateKey", body, "KeyMetadata.KeyId"); + } + + private String result(String action, String body, String path) { + return call(action, body).statusCode(200).extract().path(path); + } + + /** {@code body} with a DryRun member holding {@code value}, written with single quotes for double ones. */ + private static String withDryRun(String body, String value) { + return RestAssuredJsonUtils.withMember(body, "DryRun", value); + } + + /** + * Sends {@code body}, written with single quotes for JSON's double ones and with a fixture's name in braces + * standing for its value, to {@code action}. + */ + private ValidatableResponse call(String action, String body) { + String json = body.replace('\'', '"'); + for (Map.Entry value : values.entrySet()) { + json = json.replace("{" + value.getKey() + "}", value.getValue()); + } + return given() + .header("X-Amz-Target", "TrentService." + action) + .contentType(KMS_CONTENT_TYPE) + .body(json) + .when().post("/") + .then(); + } +} diff --git a/src/test/java/io/floci/aws/testing/RestAssuredJsonUtils.java b/src/test/java/io/floci/aws/testing/RestAssuredJsonUtils.java index ff98bbbc6c..d3c6817f8a 100644 --- a/src/test/java/io/floci/aws/testing/RestAssuredJsonUtils.java +++ b/src/test/java/io/floci/aws/testing/RestAssuredJsonUtils.java @@ -70,6 +70,14 @@ public class RestAssuredJsonUtils { return OBJECT_MAPPER.readTree(response); } + /** + * {@code jsonObject}, a request body written as one JSON object, with {@code member} added holding + * {@code rawValue}, written as it goes into the body. + */ + public static String withMember(String jsonObject, String member, String rawValue) { + return jsonObject.substring(0, jsonObject.lastIndexOf('}')) + ", \"" + member + "\": " + rawValue + "}"; + } + } /**