Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(kms): grant fidelity (#2639)

Sam Fakhreddine540020456358
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 9fff8bd7a9..368ea0765e 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
@@ -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());
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 7d113332ff..984c607eb7 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
@@ -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());
}
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.java
index ea84041784..43de1a49ac 100644
--- 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.java
@@ -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; }
}
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 e40a822078..6284130bcd 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
@@ -563,6 +563,8 @@ class KmsIntegrationTest {
{
"KeyId": "%s",
"GranteePrincipal": "arn:aws:iam::000000000000:user/grantee",
+ "Name": "vellum-tenant-round-trip",
+ "Constraints": {"EncryptionContextEquals": {"tenant_id": "tenant-001"}},
"Operations": ["Encrypt", "Decrypt"]
}
""".formatted(keyId))
@@ -587,6 +589,8 @@ class KmsIntegrationTest {
.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].Name", equalTo("vellum-tenant-round-trip"))
+ .body("Grants[0].Constraints.EncryptionContextEquals.tenant_id", equalTo("tenant-001"))
.body("Grants[0].Operations[0]", equalTo("Encrypt"))
.body("Grants[0].Operations[1]", equalTo("Decrypt"))
.body("Truncated", equalTo(false));
@@ -784,6 +788,36 @@ class KmsIntegrationTest {
.body("Truncated", equalTo(false));
}
+ @Test
+ void createGrantWithNonObjectConstraintsReturnsValidationException() {
+ // The handler previously converted any non-object Constraints (e.g. a raw string or
+ // array) to null before it reached KmsService, so a malformed request was silently
+ // treated as "no constraints" instead of rejected.
+ String keyId = given()
+ .header("X-Amz-Target", "TrentService.CreateKey")
+ .contentType(KMS_CONTENT_TYPE)
+ .body("{\"Description\":\"constraints-type-check\"}")
+ .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",
+ "Operations": ["Encrypt"],
+ "Constraints": "not-an-object"
+ }
+ """.formatted(keyId))
+ .when().post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
@Test
void revokeGrantReturnsNotFoundForUnknownGrant() {
String keyId = given()
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 d63eb9610d..7c6244d60c 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
@@ -162,6 +162,113 @@ class KmsServiceTest {
assertEquals("ValidationException", ex.getErrorCode());
}
+ @Test
+ void createGrantUnknownOperationThrowsValidation() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt", "NotARealOperation"), REGION));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertTrue(ex.getMessage().contains("NotARealOperation"),
+ "message should name the rejected operation, was: " + ex.getMessage());
+ }
+
+ @Test
+ void createGrantInvalidNameCharacterThrowsValidation() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt"), null, "invalid name with spaces", null, REGION));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertTrue(ex.getMessage().contains("'name'"),
+ "message should name the rejected field, was: " + ex.getMessage());
+ }
+
+ @Test
+ void createGrantNameTooLongThrowsValidation() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+ String tooLong = "a".repeat(257);
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt"), null, tooLong, null, REGION));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertTrue(ex.getMessage().contains("less than or equal to 256"),
+ "too-long-name message should cite the max-length constraint, was: " + ex.getMessage());
+ }
+
+ @Test
+ void createGrantEmptyNameThrowsValidationWithMinLengthMessage() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt"), null, "", null, REGION));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertTrue(ex.getMessage().contains("greater than or equal to 1"),
+ "empty-name message should cite the min-length constraint, was: " + ex.getMessage());
+ }
+
+ @Test
+ void createGrantConstraintsUnknownMemberThrowsValidation() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+ Map<String, Object> constraints = new LinkedHashMap<>();
+ constraints.put("NotARealConstraint", "value");
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt"), null, null, constraints, REGION));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void createGrantConstraintsStringValuedEncryptionContextEqualsThrowsValidation() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+ Map<String, Object> constraints = new LinkedHashMap<>();
+ constraints.put("EncryptionContextEquals", "not-a-map");
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt"), null, null, constraints, REGION));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void createGrantConstraintsInvalidSourceArnThrowsValidation() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+ Map<String, Object> constraints = new LinkedHashMap<>();
+ constraints.put("SourceArn", "not-an-arn");
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt"), null, null, constraints, REGION));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void createGrantConstraintsValidEncryptionContextRoundTrips() {
+ KmsKey key = kmsService.createKey("grant key", REGION);
+ Map<String, Object> constraints = new LinkedHashMap<>();
+ Map<String, String> encryptionContext = new LinkedHashMap<>();
+ encryptionContext.put("purpose", "test");
+ constraints.put("EncryptionContextEquals", encryptionContext);
+ constraints.put("SourceArn", "arn:aws:iam::123456789012:role/test-role");
+
+ KmsGrant grant = kmsService.createGrant(key.getKeyId(), "arn:aws:iam::000000000000:user/grantee",
+ List.of("Encrypt"), null, null, constraints, REGION);
+
+ assertEquals(constraints, grant.getConstraints());
+ }
+
@Test
void createGrantUnknownKeyThrowsNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->