fix(kms): honour DryRun on the grant and cryptographic calls (#9226)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-22 20:28:46 -04:00
1 parent cd85191a24
commit 6aff785875
9 files changed
+463 -30

No files matched your search

@@ -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);
};
}
}
@@ -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<String> 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<String> 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.
@@ -471,6 +471,16 @@ public class KmsService implements ResourceProvider {
public KmsGrant createGrant(String keyId, String granteePrincipal, List<String> operations,
String retiringPrincipal, String name, Map<String, Object> 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<String> operations,
String retiringPrincipal, String name, Map<String, Object> 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);
}
@@ -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);