fix(kms): grant fidelity (#2639)

* fix: preserve KMS grant metadata

* fix(kms): reject GrantOperation values outside the modeled enum

CreateGrant stored the Operations list verbatim, so a grant could be
persisted and echoed back with an operation name AWS would have refused.
Validate each element against the GrantOperation enum and raise
ValidationException, matching the other CreateGrant input guards.

* fix(kms): validate CreateGrant Name against GrantNameType constraint

Real AWS enforces GrantNameType's pattern (^[a-zA-Z0-9:/_-]+$) and
256-char max length on CreateGrant's Name field. Add the same
validation so malformed names are rejected the way AWS rejects them.

* fix(kms): validate CreateGrant Constraints and fix name-length error message

Two review findings on CreateGrant:
- Constraints previously passed through unvalidated: an unknown member,
  a non-map EncryptionContextSubset/EncryptionContextEquals, or a
  malformed SourceArn would be persisted and echoed back on ListGrants
  even though real KMS rejects the request. Validate against the
  modeled GrantConstraints shape (kms/2014-11-01/service-2.json).
- Name's length check used the max-length message for both the empty
  and over-256 cases; an empty name now cites the min-length-1
  constraint instead.

* fix(kms): reject non-object CreateGrant Constraints instead of silently dropping it

The handler converted Constraints to null whenever it wasn't a JSON object, so a raw string or
array value was treated as absent and the grant was created without ever reaching
validateGrantConstraints, instead of rejecting the malformed request as real KMS does.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-27 21:35:32 -04:00
1 parent bf6c7b001c
commit 5400204563
5 files changed
+277 -2

No files matched your search

@@ -154,6 +154,12 @@ public class KmsJsonHandler {
entry.put("KeyId", (String) grant.get("KeyId"));
entry.put("GranteePrincipal", (String) grant.get("GranteePrincipal"));
entry.put("CreationDate", ((Number) grant.get("CreationDate")).longValue());
if (grant.get("Name") != null) {
entry.put("Name", (String) grant.get("Name"));
}
if (grant.get("Constraints") != null) {
entry.set("Constraints", objectMapper.valueToTree(grant.get("Constraints")));
}
ArrayNode operations = entry.putArray("Operations");
@SuppressWarnings("unchecked")
List<String> operationValues = (List<String>) grant.get("Operations");
@@ -186,6 +192,12 @@ public class KmsJsonHandler {
entry.put("KeyId", (String) grant.get("KeyId"));
entry.put("GranteePrincipal", (String) grant.get("GranteePrincipal"));
entry.put("CreationDate", ((Number) grant.get("CreationDate")).longValue());
if (grant.get("Name") != null) {
entry.put("Name", (String) grant.get("Name"));
}
if (grant.get("Constraints") != null) {
entry.set("Constraints", objectMapper.valueToTree(grant.get("Constraints")));
}
ArrayNode operations = entry.putArray("Operations");
@SuppressWarnings("unchecked")
List<String> operationValues = (List<String>) grant.get("Operations");
@@ -208,8 +220,19 @@ public class KmsJsonHandler {
request.path("Operations").forEach(operation -> operations.add(operation.asText()));
String retiringPrincipal = request.path("RetiringPrincipal").isMissingNode()
? null : request.path("RetiringPrincipal").asText(null);
String name = request.path("Name").isMissingNode() ? null : request.path("Name").asText(null);
JsonNode constraintsNode = request.path("Constraints");
if (!constraintsNode.isMissingNode() && !constraintsNode.isNull() && !constraintsNode.isObject()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'constraints' failed to satisfy constraint: "
+ "Member must be a structure", 400);
}
Map<String, Object> constraints = constraintsNode.isObject()
? objectMapper.convertValue(constraintsNode, Map.class)
: null;
KmsGrant grant = service.createGrant(keyId, granteePrincipal, operations, retiringPrincipal, region);
KmsGrant grant = service.createGrant(
keyId, granteePrincipal, operations, retiringPrincipal, name, constraints, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("GrantId", grant.getGrantId());
response.put("GrantToken", grant.getGrantToken());
@@ -272,12 +272,79 @@ public class KmsService implements ResourceProvider {
return keyStore.scan(k -> k.startsWith(prefix));
}
/** GrantOperation enum from the KMS model (kms/2014-11-01/service-2.json). */
private static final Set<String> GRANT_OPERATIONS = new LinkedHashSet<>(List.of(
"Decrypt", "Encrypt", "GenerateDataKey", "GenerateDataKeyWithoutPlaintext",
"ReEncryptFrom", "ReEncryptTo", "Sign", "Verify", "GetPublicKey", "CreateGrant",
"RetireGrant", "DescribeKey", "GenerateDataKeyPair", "GenerateDataKeyPairWithoutPlaintext",
"GenerateMac", "VerifyMac", "DeriveSharedSecret"));
/** GrantNameType pattern/length from the KMS model (kms/2014-11-01/service-2.json). */
private static final java.util.regex.Pattern GRANT_NAME_PATTERN =
java.util.regex.Pattern.compile("^[a-zA-Z0-9:/_-]+$");
/** GrantConstraintSourceArnType pattern from the KMS model (kms/2014-11-01/service-2.json). */
private static final java.util.regex.Pattern GRANT_CONSTRAINT_SOURCE_ARN_PATTERN =
java.util.regex.Pattern.compile("^arn:aws[a-z0-9-]*:[a-z0-9-]+:[a-z0-9-]*:[0-9]{12}:.+$");
private static final Set<String> GRANT_CONSTRAINT_MEMBERS =
Set.of("EncryptionContextSubset", "EncryptionContextEquals", "SourceArn");
/** Validates a CreateGrant Constraints map against the modeled GrantConstraints shape. */
private void validateGrantConstraints(Map<String, Object> constraints) {
if (constraints == null) {
return;
}
for (String member : constraints.keySet()) {
if (!GRANT_CONSTRAINT_MEMBERS.contains(member)) {
throw new AwsException("ValidationException",
"1 validation error detected: Unknown parameter in 'constraints': \"" + member
+ "\", must be one of: " + String.join(", ", GRANT_CONSTRAINT_MEMBERS), 400);
}
}
for (String encryptionContextMember : List.of("EncryptionContextSubset", "EncryptionContextEquals")) {
Object value = constraints.get(encryptionContextMember);
if (value == null) {
continue;
}
if (!(value instanceof Map<?, ?> map)) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'constraints." + encryptionContextMember
+ "' failed to satisfy constraint: Member must be a map of string to string", 400);
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof String)) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'constraints." + encryptionContextMember
+ "' failed to satisfy constraint: Member must be a map of string to string", 400);
}
}
}
Object sourceArn = constraints.get("SourceArn");
if (sourceArn != null) {
if (!(sourceArn instanceof String sourceArnValue)
|| sourceArnValue.length() < 20 || sourceArnValue.length() > 512
|| !GRANT_CONSTRAINT_SOURCE_ARN_PATTERN.matcher(sourceArnValue).matches()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value at 'constraints.sourceArn' failed to satisfy "
+ "constraint: Member must satisfy regular expression pattern: "
+ "^arn:aws[a-z0-9-]*:[a-z0-9-]+:[a-z0-9-]*:[0-9]{12}:.+$", 400);
}
}
}
public KmsGrant createGrant(String keyId, String granteePrincipal, List<String> operations, String region) {
return createGrant(keyId, granteePrincipal, operations, null, region);
return createGrant(keyId, granteePrincipal, operations, null, null, null, region);
}
public KmsGrant createGrant(String keyId, String granteePrincipal, List<String> operations,
String retiringPrincipal, String region) {
return createGrant(keyId, granteePrincipal, operations, retiringPrincipal, null, null, region);
}
public KmsGrant createGrant(String keyId, String granteePrincipal, List<String> operations,
String retiringPrincipal, String name, Map<String, Object> constraints,
String region) {
if (keyId == null || keyId.isBlank()) {
throw new AwsException("ValidationException", "KeyId is required", 400);
}
@@ -287,6 +354,33 @@ public class KmsService implements ResourceProvider {
if (operations == null || operations.isEmpty()) {
throw new AwsException("ValidationException", "Operations is required", 400);
}
for (String operation : operations) {
if (!GRANT_OPERATIONS.contains(operation)) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + operation + "' at 'operations' failed to satisfy "
+ "constraint: Member must satisfy enum value set: ["
+ String.join(", ", GRANT_OPERATIONS) + "]", 400);
}
}
if (name != null) {
if (name.isEmpty()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + name + "' at 'name' failed to satisfy "
+ "constraint: Member must have length greater than or equal to 1", 400);
}
if (name.length() > 256) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + name + "' at 'name' failed to satisfy "
+ "constraint: Member must have length less than or equal to 256", 400);
}
if (!GRANT_NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + name + "' at 'name' failed to satisfy "
+ "constraint: Member must satisfy regular expression pattern: "
+ "^[a-zA-Z0-9:/_-]+$", 400);
}
}
validateGrantConstraints(constraints);
KmsKey key = resolveKey(keyId, region);
String grantId = UUID.randomUUID().toString();
@@ -296,11 +390,13 @@ public class KmsService implements ResourceProvider {
KmsGrant grant = new KmsGrant();
grant.setGrantId(grantId);
grant.setGrantToken(Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes));
grant.setName(name);
grant.setKeyId(key.getKeyId());
grant.setKeyArn(key.getArn());
grant.setGranteePrincipal(granteePrincipal);
grant.setRetiringPrincipal(retiringPrincipal);
grant.setOperations(new ArrayList<>(operations));
grant.setConstraints(constraints == null ? null : new HashMap<>(constraints));
grantStore.put(region + "::" + grantId, grant);
LOG.infov("Created KMS grant: {0} for key {1} in {2}", grantId, key.getKeyId(), region);
@@ -465,6 +561,12 @@ public class KmsService implements ResourceProvider {
result.put("GranteePrincipal", grant.getGranteePrincipal());
result.put("Operations", grant.getOperations());
result.put("CreationDate", grant.getCreationDate());
if (grant.getName() != null) {
result.put("Name", grant.getName());
}
if (grant.getConstraints() != null) {
result.put("Constraints", grant.getConstraints());
}
if (grant.getRetiringPrincipal() != null) {
result.put("RetiringPrincipal", grant.getRetiringPrincipal());
}
@@ -6,17 +6,20 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class KmsGrant {
private String grantId;
private String grantToken;
private String name;
private String keyId;
private String keyArn;
private String granteePrincipal;
private String retiringPrincipal;
private List<String> operations = new ArrayList<>();
private Map<String, Object> constraints;
private long creationDate;
public KmsGrant() {
@@ -29,6 +32,9 @@ public class KmsGrant {
public String getGrantToken() { return grantToken; }
public void setGrantToken(String grantToken) { this.grantToken = grantToken; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getKeyId() { return keyId; }
public void setKeyId(String keyId) { this.keyId = keyId; }
@@ -44,6 +50,9 @@ public class KmsGrant {
public List<String> getOperations() { return operations; }
public void setOperations(List<String> operations) { this.operations = operations; }
public Map<String, Object> getConstraints() { return constraints; }
public void setConstraints(Map<String, Object> constraints) { this.constraints = constraints; }
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
}