fix(iam): authorize KMS operations against the key named in the request (#6458)

* fix(iam): authorize KMS operations against the key named in the request

KMS is JSON 1.1 posted to /, so the path-based key extraction never
found a key and every action was evaluated against key/*: a policy
allowing kms:Decrypt on one key refused that very key, and a policy
restricted to a key restricted nothing. Enforcement now derives the
request's resources the way the KMS permissions reference gives them:
the key-scoped operations name the key the KeyId member names, resolving
an id, an alias or an ARN to the stored key's own ARN; Decrypt without
a KeyId reads the key out of the CiphertextBlob; the alias operations
name the alias and the keys the alias pages give; CreateKey,
GenerateRandom, ListKeys, ListAliases and ListRetirableGrants stay at *.
A request nothing resolves falls back to key/* so the handler answers
its own NotFoundException. ReEncrypt stays the single action AWS splits
into ReEncryptFrom and ReEncryptTo, evaluated against both keys.

Closes #6256

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(iam): authorize ReEncrypt and the grant operations against the keys they act on

A ReEncrypt without SourceKeyId resolved its source through Decrypt's
reader and trusted a KeyId member ReEncrypt does not even have, so a
caller allowed only on key B could send ciphertext encrypted by a
denied key A, name B everywhere, and get A's data back under B. The
source now resolves the way the handler decrypts: SourceKeyId when the
request names one, otherwise the key the CiphertextBlob itself names.
A RetireGrant carrying only a GrantToken was checked against key/*,
which a key-scoped policy never matches; it now answers the key its
grant belongs to, with the documented key/* fallback for a token nothing
resolves. RevokeGrant and the KeyId-plus-GrantId form of RetireGrant
now name the grant's own key beside the key the request names, so a
pair naming one key while the grant belongs to another can no longer
retire or revoke it.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(iam): resolve a RevokeGrant target by its GrantId, never a GrantToken

The revoke target lookup preferred a GrantToken the RevokeGrant handler
never reads: a request could name the grant of an allowed key in a token
while its GrantId named the grant of a denied one, pass the check on the
token's key, and have the handler revoke the other grant. The lookup now
passes the GrantId alone, so the checked key is the key of the grant the
handler deletes.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(iam): fall back when a CiphertextBlob is not a string

A Decrypt or ReEncrypt carrying a CiphertextBlob that is not a string
made binaryValue answer null on the enforcement path and blow up before
the handler could answer its own client error. A blob that is not text
now names every key the account holds, the documented fallback, so the
request is authorized and the handler answers the error AWS answers for
a malformed blob.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(kms): share the grant token scan and its enforcement lookup

retireGrant scanned the region's grants for a token the same way the
enforcement lookup did; both now go through one findGrantByToken. The
builder's revoke target resolves through the shared grantKeyArn helper
with the members each handler actually reads, the token and the id for
RetireGrant and the id alone for RevokeGrant, whose handler never reads
a token. The two test javadocs that described the enforcement gap as a
review's finding now describe the gap itself.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-25 21:19:18 -04:00
1 parent 74a932bc50
commit 9b4e27c80a
8 files changed
+1032 -19

No files matched your search

@@ -0,0 +1,307 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.EnforcementFixtures.Session;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* With {@code iam.enforcement-enabled=true}, a KMS operation that names a key is authorized
* against that key's ARN, resolving a key named by its id, an alias name, an alias ARN or a key
* ARN to the key it points at, exactly as the KMS API reference resolves the request's key
* identifier, and a {@code Decrypt} that names no {@code KeyId} against the key that encrypted
* its {@code CiphertextBlob}. A policy can therefore allow one key and no other, as the IAM
* User Guide's "Allow access to a KMS key" pattern scopes the policy's Resource to one key ARN,
* and a Deny scoped to one key ARN fires for that key: the gap issue #6256 describes, where
* every KMS call was evaluated against {@code key/*}.
*
* <p>The same mirror rule covers the members a handler reads that a plain {@code KeyId} does
* not name: a {@code ReEncrypt} that names no {@code SourceKeyId} is authorized against the key
* that encrypted its {@code CiphertextBlob}, never against a {@code KeyId} it carries, which
* the handler ignores, and a token-only {@code RetireGrant} against the key its grant belongs
* to, which is the key the handler retires the grant under.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class KmsKeyArnEnforcementIntegrationTest {
private static final String ACCOUNT = "111111111111";
private static final String KMS_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String KEY_ARN_PREFIX = "arn:aws:kms:us-east-1:" + ACCOUNT + ":key/";
private static final String ALIAS_ARN_PREFIX = "arn:aws:kms:us-east-1:" + ACCOUNT + ":alias/";
private static final String PLAINTEXT =
Base64.getEncoder().encodeToString("kms-iam-enforcement".getBytes(StandardCharsets.UTF_8));
@TestHTTPResource
URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void aPolicyAllowingOneKeyArnAllowsThatKeyAndNoOther() {
String allowedArn = createKey();
String otherArn = createKey();
Session session = assumeRoleWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["kms:Encrypt","kms:DescribeKey"],"Resource":"%s"}]}"""
.formatted(allowedArn));
keyCall(session, "Encrypt", encryptBody(allowedArn))
.then().statusCode(200).body("KeyId", equalTo(allowedArn));
keyCall(session, "DescribeKey", "{\"KeyId\": \"" + allowedArn + "\"}")
.then().statusCode(200).body("KeyMetadata.Arn", equalTo(allowedArn));
keyCall(session, "Encrypt", encryptBody(otherArn))
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
keyCall(session, "DescribeKey", "{\"KeyId\": \"" + otherArn + "\"}")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
}
@Test
void aDenyScopedToOneKeyArnFiresOnlyForThatKey() {
String keptArn = createKey();
String deniedArn = createKey();
Session session = assumeRoleWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"kms:Encrypt","Resource":"%s*"},
{"Effect":"Deny","Action":"kms:Encrypt","Resource":"%s"}]}"""
.formatted(KEY_ARN_PREFIX, deniedArn));
keyCall(session, "Encrypt", encryptBody(keptArn))
.then().statusCode(200).body("KeyId", equalTo(keptArn));
keyCall(session, "Encrypt", encryptBody(deniedArn))
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
}
@Test
void aKeyNamedByAnAliasIsAuthorizedAgainstTheKeyItPointsAt() {
String keyArn = createKey();
String aliasName = "alias/" + UUID.randomUUID().toString().substring(0, 8);
createAlias(aliasName, keyArn);
String aliasArn = ALIAS_ARN_PREFIX + aliasName.substring("alias/".length());
Session session = assumeRoleWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"kms:Encrypt","Resource":"%s"}]}"""
.formatted(keyArn));
keyCall(session, "Encrypt", encryptBody(aliasName))
.then().statusCode(200).body("KeyId", equalTo(keyArn));
keyCall(session, "Encrypt", encryptBody(aliasArn))
.then().statusCode(200).body("KeyId", equalTo(keyArn));
}
@Test
void aDecryptNamingNoKeyIdIsAuthorizedAgainstTheKeyThatEncryptedTheCiphertext() {
String keyArn = createKey();
String otherArn = createKey();
String ciphertext = accountCall("Encrypt", encryptBody(keyArn))
.then().statusCode(200).extract().path("CiphertextBlob");
Session onThatKey = assumeRoleWith(decryptOn(keyArn));
Session onAnotherKey = assumeRoleWith(decryptOn(otherArn));
keyCall(onThatKey, "Decrypt", "{\"CiphertextBlob\": \"" + ciphertext + "\"}")
.then().statusCode(200)
.body("Plaintext", equalTo(PLAINTEXT)).body("KeyId", equalTo(keyArn));
keyCall(onAnotherKey, "Decrypt", "{\"CiphertextBlob\": \"" + ciphertext + "\"}")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
}
@Test
void aDecryptNamingNoKeyTheStoreHoldsFallsBackToEveryKeyAndTheHandlerRefusesIt() {
Session session = assumeRoleWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"kms:Decrypt","Resource":"%s*"}]}"""
.formatted(KEY_ARN_PREFIX));
// A ciphertext no stored key answers to names every key, so a wildcard policy still
// matches it and the handler, not enforcement, refuses it.
keyCall(session, "Decrypt", "{\"CiphertextBlob\": \"AAAA\"}")
.then().statusCode(400).body("__type", equalTo("InvalidCiphertextException"));
}
/**
* A caller allowed on one key submits ciphertext another, denied key encrypted and
* carries a KeyId naming the allowed one, which the handler never reads. The source the
* request is authorized against is the key that encrypted the ciphertext, so the denied
* key's data does not come out re-encrypted under the allowed one.
*/
@Test
void aReEncryptIsAuthorizedAgainstTheKeyThatEncryptedTheCiphertextNotAKeyIdItCarries() {
String deniedArn = createKey();
String allowedArn = createKey();
String deniedCiphertext = accountCall("Encrypt", encryptBody(deniedArn))
.then().statusCode(200).extract().path("CiphertextBlob");
String allowedCiphertext = accountCall("Encrypt", encryptBody(allowedArn))
.then().statusCode(200).extract().path("CiphertextBlob");
Session session = assumeRoleWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"kms:ReEncrypt","Resource":"%s*"},
{"Effect":"Deny","Action":"kms:ReEncrypt","Resource":"%s"}]}"""
.formatted(KEY_ARN_PREFIX, deniedArn));
keyCall(session, "ReEncrypt",
"{\"CiphertextBlob\": \"" + deniedCiphertext + "\", \"KeyId\": \"" + allowedArn
+ "\", \"DestinationKeyId\": \"" + allowedArn + "\"}")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
keyCall(session, "ReEncrypt",
"{\"CiphertextBlob\": \"" + allowedCiphertext + "\", \"DestinationKeyId\": \""
+ allowedArn + "\"}")
.then().statusCode(200).body("KeyId", equalTo(allowedArn))
.body("SourceKeyId", equalTo(allowedArn));
}
/**
* A token-only RetireGrant is authorized against the key the token's grant belongs to, the
* key the handler finds the grant under, so a policy allowing retirement on that key alone
* permits it and one allowing another key does not.
*/
@Test
void aTokenOnlyRetireGrantIsAuthorizedAgainstTheKeyItsGrantBelongsTo() {
String keyArn = createKey();
String otherArn = createKey();
Grant grant = createGrantOn(keyArn);
Session onTheGrantsKey = assumeRoleWith(grantOperationOn("kms:RetireGrant", keyArn));
Session onAnotherKey = assumeRoleWith(grantOperationOn("kms:RetireGrant", otherArn));
keyCall(onAnotherKey, "RetireGrant", "{\"GrantToken\": \"" + grant.token() + "\"}")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
keyCall(onTheGrantsKey, "RetireGrant", "{\"GrantToken\": \"" + grant.token() + "\"}")
.then().statusCode(200);
accountCall("ListGrants", "{\"KeyId\": \"" + keyArn + "\"}")
.then().statusCode(200).body("Grants.size()", equalTo(0));
}
/** A wildcard allow with a Deny on the grant's key still fires for a token-only RetireGrant. */
@Test
void aDenyOnTheGrantsKeyFiresForATokenOnlyRetireGrant() {
String keyArn = createKey();
Grant grant = createGrantOn(keyArn);
Session session = assumeRoleWith("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"kms:RetireGrant","Resource":"%s*"},
{"Effect":"Deny","Action":"kms:RetireGrant","Resource":"%s"}]}"""
.formatted(KEY_ARN_PREFIX, keyArn));
keyCall(session, "RetireGrant", "{\"GrantToken\": \"" + grant.token() + "\"}")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
accountCall("ListGrants", "{\"KeyId\": \"" + keyArn + "\"}")
.then().statusCode(200).body("Grants.size()", equalTo(1));
}
/**
* A RevokeGrant naming one key while the grant belongs to another is denied: the request is
* authorized against both, so the pair cannot revoke a grant the named key does not hold.
*/
@Test
void aRevokeGrantNamingOneKeyWhileTheGrantBelongsToAnotherIsDenied() {
String grantKeyArn = createKey();
String otherArn = createKey();
Grant grant = createGrantOn(grantKeyArn);
Session onTheNamedKey = assumeRoleWith(grantOperationOn("kms:RevokeGrant", otherArn));
keyCall(onTheNamedKey, "RevokeGrant",
"{\"KeyId\": \"" + otherArn + "\", \"GrantId\": \"" + grant.id() + "\"}")
.then().statusCode(400).body("__type", equalTo("AccessDeniedException"));
accountCall("ListGrants", "{\"KeyId\": \"" + grantKeyArn + "\"}")
.then().statusCode(200).body("Grants.size()", equalTo(1));
Session onTheGrantsKey = assumeRoleWith(grantOperationOn("kms:RevokeGrant", grantKeyArn));
keyCall(onTheGrantsKey, "RevokeGrant",
"{\"KeyId\": \"" + grantKeyArn + "\", \"GrantId\": \"" + grant.id() + "\"}")
.then().statusCode(200);
accountCall("ListGrants", "{\"KeyId\": \"" + grantKeyArn + "\"}")
.then().statusCode(200).body("Grants.size()", equalTo(0));
}
private static String decryptOn(String keyArn) {
return """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"kms:Decrypt","Resource":"%s"}]}"""
.formatted(keyArn);
}
private static String grantOperationOn(String action, String keyArn) {
return """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"%s","Resource":"%s"}]}"""
.formatted(action, keyArn);
}
private static String encryptBody(String keyId) {
return "{\"KeyId\": \"" + keyId + "\", \"Plaintext\": \"" + PLAINTEXT + "\"}";
}
private String createKey() {
return accountCall("CreateKey", "{\"Description\": \"kms-iam-enforcement\"}")
.then().statusCode(200).extract().path("KeyMetadata.Arn");
}
/** 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\"]}");
created.then().statusCode(200);
return new Grant(created.jsonPath().getString("GrantId"),
created.jsonPath().getString("GrantToken"));
}
private void createAlias(String aliasName, String keyArn) {
cleanup.register(() -> accountCall("DeleteAlias", "{\"AliasName\": \"" + aliasName + "\"}")
.then().statusCode(200));
accountCall("CreateAlias",
"{\"AliasName\": \"" + aliasName + "\", \"TargetKeyId\": \"" + keyArn + "\"}")
.then().statusCode(200);
}
/** A session of a new role that its own account may assume, with {@code policy} inline. */
private Session assumeRoleWith(String policy) {
int port = baseUri.getPort();
String roleArn = EnforcementFixtures.createRole(cleanup, port, ACCOUNT, "/",
"kms-key-arn-" + UUID.randomUUID().toString().substring(0, 8), policy);
return EnforcementFixtures.assumeRole(port, ACCOUNT, roleArn);
}
/** A call as the account itself, which the cleanup also makes after RestAssured's port is reset. */
private Response accountCall(String action, String body) {
return given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "kms"))
.header("X-Amz-Target", "TrentService." + action)
.contentType(KMS_CONTENT_TYPE)
.body(body)
.when().post("/");
}
private static Response keyCall(Session session, String action, String body) {
return given().header("Authorization", auth(session.accessKeyId(), "kms"))
.header("X-Amz-Security-Token", session.sessionToken())
.header("X-Amz-Target", "TrentService." + action)
.contentType(KMS_CONTENT_TYPE)
.body(body)
.when().post("/");
}
}
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import jakarta.enterprise.inject.Instance;
@@ -1133,6 +1134,303 @@ class ResourceArnBuilderTest {
ACCOUNT, "aws-us-gov"));
}
// ── KMS ──────────────────────────────────────────────────────────────────────
private static final String KMS_KEY_ID = "1234abcd-12ab-34cd-56ef-1234567890ab";
private static final String KMS_KEY_ARN = "arn:aws:kms:us-east-1:000000000000:key/" + KMS_KEY_ID;
private static final String KMS_OTHER_KEY_ARN = "arn:aws:kms:us-east-1:000000000000:key/5678efab-34cd-12ab-90ef-1234567890ab";
private static final String KMS_ALIAS_ARN = "arn:aws:kms:us-east-1:000000000000:alias/app";
/** A builder reading {@code kms}, for a key named by an id, an alias or an ARN. */
private static ResourceArnBuilder backedBy(KmsService kms) {
@SuppressWarnings("unchecked")
Instance<KmsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(kms);
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, instance);
}
/**
* The gap issue 6256 describes. KMS is a JSON protocol on {@code /} with the key in the body,
* so reading a {@code /keys/<id>} path segment named nothing and every call was evaluated
* against {@code key/*}: an {@code Allow} scoped to one key ARN never matched, and a
* {@code Deny} scoped to one never fired. A key-scoped operation is now evaluated against the
* key its request names.
*/
@Test
void kmsNamesTheKeyAKeyScopedOperationActsOn() {
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
when(kms.findKeyArn(KMS_KEY_ID, "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
ResourceArnBuilder backed = backedBy(kms);
for (String action : List.of("kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey",
"kms:GenerateDataKeyWithoutPlaintext", "kms:DescribeKey", "kms:GetPublicKey",
"kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion", "kms:CreateGrant", "kms:ListGrants",
"kms:RevokeGrant", "kms:Sign", "kms:Verify", "kms:GenerateMac", "kms:VerifyMac",
"kms:TagResource", "kms:UntagResource", "kms:ListResourceTags", "kms:GetKeyPolicy",
"kms:PutKeyPolicy", "kms:ListKeyPolicies", "kms:UpdateKeyDescription",
"kms:EnableKey", "kms:DisableKey", "kms:EnableKeyRotation", "kms:DisableKeyRotation",
"kms:GetKeyRotationStatus", "kms:RotateKeyOnDemand", "kms:GetParametersForImport",
"kms:ImportKeyMaterial", "kms:DeleteImportedKeyMaterial", "kms:ReplicateKey",
"kms:RetireGrant")) {
setJsonBody("{\"KeyId\":\"" + KMS_KEY_ID + "\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources(action, ctx, "us-east-1", ACCOUNT, "aws"), action);
}
}
/** A key named by an alias is authorized against the key it points at, as the handler resolves it. */
@Test
void kmsResolvesAnAliasToTheKeyItPointsAt() {
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn("alias/app", "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
when(kms.findKeyArn(KMS_ALIAS_ARN, "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
ResourceArnBuilder backed = backedBy(kms);
setJsonBody("{\"KeyId\":\"alias/app\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:Encrypt", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"KeyId\":\"" + KMS_ALIAS_ARN + "\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:Encrypt", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* The operations the KMS permissions reference gives no resource, which it also requires a
* policy to name {@code *} for, stay at the wildcard; a key-scoped operation that names no
* key keeps the permissive fallback rather than being refused here, since the handler
* refuses it with its own error.
*/
@Test
void kmsLeavesTheActionsThatNameNoKeyAtTheirOwnResources() {
ResourceArnBuilder backed = backedBy(mock(KmsService.class));
for (String action : List.of("kms:CreateKey", "kms:GenerateRandom", "kms:ListKeys",
"kms:ListAliases", "kms:ListRetirableGrants")) {
setJsonBody("{\"KeyId\":\"" + KMS_KEY_ID + "\"}");
assertEquals(List.of("*"),
backed.buildKmsResources(action, ctx, "us-east-1", ACCOUNT, "aws"), action);
}
setJsonBody("{}");
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backed.buildKmsResources("kms:RetireGrant", ctx, "us-east-1", ACCOUNT, "aws"));
assertEquals(List.of("arn:aws-cn:kms:cn-north-1:000000000000:key/*"),
backed.buildKmsResources("kms:RetireGrant", ctx, "cn-north-1", ACCOUNT, "aws-cn"));
}
/**
* A request with no body at all keeps the action's own resources: the operations the reference
* gives no resource stay at {@code *}, and a key-scoped one falls back to every key the
* account holds rather than being refused here.
*/
@Test
void kmsKeepsEachActionsOwnResourcesForARequestWithNoBody() {
ResourceArnBuilder backed = backedBy(mock(KmsService.class));
assertEquals(List.of("*"),
backed.buildKmsResources("kms:CreateKey", ctx, "us-east-1", ACCOUNT, "aws"));
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backed.buildKmsResources("kms:Encrypt", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* A key ARN the account holds nothing of is kept as the caller spelled it, a bare key id is
* minted in the request's partition, and an alias that resolves to nothing names every key:
* the operation fails before a policy matters.
*/
@Test
void kmsMintsKeyArnsInTheRequestPartitionAndFallsBackForTheUnresolvable() {
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
ResourceArnBuilder backed = backedBy(kms);
setJsonBody("{\"KeyId\":\"" + KMS_KEY_ARN + "\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:Encrypt", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"KeyId\":\"" + KMS_KEY_ID + "\"}");
assertEquals(List.of("arn:aws-cn:kms:cn-north-1:000000000000:key/" + KMS_KEY_ID),
backed.buildKmsResources("kms:Encrypt", ctx, "cn-north-1", ACCOUNT, "aws-cn"));
setJsonBody("{\"KeyId\":\"alias/gone\"}");
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backed.buildKmsResources("kms:Encrypt", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* A {@code Decrypt} names its key in an optional {@code KeyId}; without one the key is the
* one that encrypted the {@code CiphertextBlob}, read the same way the handler reads it.
*/
@Test
void kmsDecryptResolvesTheKeyFromTheCiphertextItNames() {
byte[] blob = "ciphertext".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(blob);
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
when(kms.decryptToKeyArn(blob, "us-east-1")).thenReturn(KMS_KEY_ARN);
ResourceArnBuilder backed = backedBy(kms);
setJsonBody("{\"CiphertextBlob\":\"" + encoded + "\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:Decrypt", ctx, "us-east-1", ACCOUNT, "aws"));
when(kms.findKeyArn("alias/app", "us-east-1")).thenReturn(Optional.of(KMS_OTHER_KEY_ARN));
setJsonBody("{\"KeyId\":\"alias/app\",\"CiphertextBlob\":\"" + encoded + "\"}");
assertEquals(List.of(KMS_OTHER_KEY_ARN),
backed.buildKmsResources("kms:Decrypt", ctx, "us-east-1", ACCOUNT, "aws"));
KmsService unresolvable = mock(KmsService.class);
when(unresolvable.findKeyArn(any(), any())).thenReturn(Optional.empty());
when(unresolvable.decryptToKeyArn(any(), any())).thenReturn(null);
setJsonBody("{\"CiphertextBlob\":\"" + encoded + "\"}");
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backedBy(unresolvable).buildKmsResources("kms:Decrypt", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"CiphertextBlob\":629}");
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backed.buildKmsResources("kms:Decrypt", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"CiphertextBlob\":{\"KeyId\":\"x\"}}");
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backed.buildKmsResources("kms:Decrypt", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"CiphertextBlob\":[\"aGk=\"]}");
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backed.buildKmsResources("kms:Decrypt", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* The alias operations name their resources as the alias permissions page gives them:
* {@code CreateAlias} the alias and the key, {@code UpdateAlias} the alias, the key it points
* at and the key it will point at, and {@code DeleteAlias} the alias and the key it points
* at. A request naming no alias AWS would accept the name of names nothing.
*/
@Test
void kmsAliasOperationsNameTheAliasAndTheKeysTheyTouch() {
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
when(kms.findKeyArn(KMS_KEY_ID, "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
when(kms.findKeyArn("alias/app", "us-east-1")).thenReturn(Optional.of(KMS_OTHER_KEY_ARN));
ResourceArnBuilder backed = backedBy(kms);
setJsonBody("{\"AliasName\":\"alias/app\",\"TargetKeyId\":\"" + KMS_KEY_ID + "\"}");
assertEquals(List.of(KMS_ALIAS_ARN, KMS_KEY_ARN),
backed.buildKmsResources("kms:CreateAlias", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"AliasName\":\"alias/app\",\"TargetKeyId\":\"" + KMS_KEY_ID + "\"}");
assertEquals(List.of(KMS_ALIAS_ARN, KMS_OTHER_KEY_ARN, KMS_KEY_ARN),
backed.buildKmsResources("kms:UpdateAlias", ctx, "us-east-1", ACCOUNT, "aws"));
// A retarget onto the key the alias already points at names that key once.
when(kms.findKeyArn("alias/app", "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
setJsonBody("{\"AliasName\":\"alias/app\",\"TargetKeyId\":\"" + KMS_KEY_ID + "\"}");
assertEquals(List.of(KMS_ALIAS_ARN, KMS_KEY_ARN),
backed.buildKmsResources("kms:UpdateAlias", ctx, "us-east-1", ACCOUNT, "aws"));
when(kms.findKeyArn("alias/app", "us-east-1")).thenReturn(Optional.of(KMS_OTHER_KEY_ARN));
setJsonBody("{\"AliasName\":\"alias/app\"}");
assertEquals(List.of(KMS_ALIAS_ARN, KMS_OTHER_KEY_ARN),
backed.buildKmsResources("kms:DeleteAlias", ctx, "us-east-1", ACCOUNT, "aws"));
// A name AWS would refuse contributes no alias resource, and a request naming no alias
// at all names nothing but the wildcard.
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
setJsonBody("{\"AliasName\":\"app\",\"TargetKeyId\":\"" + KMS_KEY_ID + "\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:CreateAlias", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{}");
assertEquals(List.of("*"),
backed.buildKmsResources("kms:DeleteAlias", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* A {@code ReEncrypt} acts on two keys, and the filter authorizes a request once per
* resource, so both are named: the source the ciphertext or its optional {@code SourceKeyId}
* resolves to, and the destination its {@code DestinationKeyId} names.
*/
@Test
void kmsReEncryptNamesBothKeysItActsOn() {
byte[] blob = "ciphertext".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(blob);
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
when(kms.decryptToKeyArn(blob, "us-east-1")).thenReturn(KMS_KEY_ARN);
when(kms.findKeyArn("alias/destination", "us-east-1")).thenReturn(Optional.of(KMS_OTHER_KEY_ARN));
ResourceArnBuilder backed = backedBy(kms);
setJsonBody("{\"CiphertextBlob\":\"" + encoded + "\",\"DestinationKeyId\":\"alias/destination\"}");
assertEquals(List.of(KMS_KEY_ARN, KMS_OTHER_KEY_ARN),
backed.buildKmsResources("kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws"));
when(kms.findKeyArn("alias/source", "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
setJsonBody("{\"SourceKeyId\":\"alias/source\",\"DestinationKeyId\":\"alias/destination\"}");
assertEquals(List.of(KMS_KEY_ARN, KMS_OTHER_KEY_ARN),
backed.buildKmsResources("kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* A {@code ReEncrypt} never reads a {@code KeyId}: its source is the key that encrypted the
* ciphertext when the request names no {@code SourceKeyId}, so a {@code KeyId} naming
* another key cannot choose the key the request is authorized against. A caller allowed
* on the claimed key only could otherwise submit another key's ciphertext and have it
* re-encrypted under the allowed one.
*/
@Test
void kmsReEncryptNamesTheSourceTheHandlerDecryptsWithNotAKeyId() {
byte[] blob = "ciphertext".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(blob);
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
when(kms.decryptToKeyArn(blob, "us-east-1")).thenReturn(KMS_KEY_ARN);
when(kms.findKeyArn("alias/claimed", "us-east-1")).thenReturn(Optional.of(KMS_OTHER_KEY_ARN));
ResourceArnBuilder backed = backedBy(kms);
setJsonBody("{\"CiphertextBlob\":\"" + encoded
+ "\",\"KeyId\":\"alias/claimed\",\"DestinationKeyId\":\"" + KMS_OTHER_KEY_ARN + "\"}");
assertEquals(List.of(KMS_KEY_ARN, KMS_OTHER_KEY_ARN),
backed.buildKmsResources("kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws"));
}
/**
* A grant operation names the key the grant it acts on belongs to: a token-only
* {@code RetireGrant} the key the token's grant belongs to, since the handler finds the
* grant by the token alone, and a {@code RetireGrant} or a {@code RevokeGrant} identifying
* its grant by {@code KeyId} and {@code GrantId} the key it names together with that grant's
* key. A token naming no grant the account holds keeps the permissive fallback.
*/
@Test
void kmsGrantOperationsNameTheKeyTheGrantTheyActOnBelongsTo() {
KmsService kms = mock(KmsService.class);
when(kms.findKeyArn(any(), any())).thenReturn(Optional.empty());
when(kms.findKeyArn(KMS_KEY_ID, "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
when(kms.findKeyArn("other-key", "us-east-1")).thenReturn(Optional.of(KMS_OTHER_KEY_ARN));
when(kms.findGrantKeyArn("grant-token", null, "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
when(kms.findGrantKeyArn(null, "grant-id", "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN));
when(kms.findGrantKeyArn("unknown-token", null, "us-east-1")).thenReturn(Optional.empty());
ResourceArnBuilder backed = backedBy(kms);
setJsonBody("{\"GrantToken\":\"grant-token\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:RetireGrant", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"GrantToken\":\"unknown-token\"}");
assertEquals(List.of("arn:aws:kms:us-east-1:000000000000:key/*"),
backed.buildKmsResources("kms:RetireGrant", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"KeyId\":\"" + KMS_KEY_ID + "\",\"GrantId\":\"grant-id\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:RetireGrant", ctx, "us-east-1", ACCOUNT, "aws"));
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:RevokeGrant", ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"KeyId\":\"other-key\",\"GrantId\":\"grant-id\"}");
assertEquals(List.of(KMS_OTHER_KEY_ARN, KMS_KEY_ARN),
backed.buildKmsResources("kms:RevokeGrant", ctx, "us-east-1", ACCOUNT, "aws"));
when(kms.findGrantKeyArn("grant-token", "grant-id", "us-east-1"))
.thenReturn(Optional.of(KMS_OTHER_KEY_ARN));
setJsonBody("{\"KeyId\":\"" + KMS_KEY_ID + "\",\"GrantId\":\"grant-id\",\"GrantToken\":\"grant-token\"}");
assertEquals(List.of(KMS_KEY_ARN),
backed.buildKmsResources("kms:RevokeGrant", ctx, "us-east-1", ACCOUNT, "aws"));
}
// ── SSM ──────────────────────────────────────────────────────────────────────
@Test
@@ -68,6 +68,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -130,6 +131,54 @@ class KmsServiceTest {
assertEquals("Enabled", key.getKeyState());
}
/**
* The enforcement filter resolves the key a request names through this lookup rather than
* through {@code describeKey}, which throws: an operation naming no key the account holds
* answers its own {@code NotFoundException}, so the check must not refuse the request first.
*/
@Test
void findKeyArnResolvesEverySpellingWithoutRefusing() {
KmsKey created = kmsService.createKey("described", REGION);
assertEquals(Optional.of(created.getArn()), kmsService.findKeyArn(created.getKeyId(), REGION));
assertEquals(Optional.of(created.getArn()), kmsService.findKeyArn(created.getArn(), REGION));
kmsService.createAlias("alias/app", created.getKeyId(), REGION);
assertEquals(Optional.of(created.getArn()), kmsService.findKeyArn("alias/app", REGION));
assertEquals(Optional.of(created.getArn()),
kmsService.findKeyArn("arn:aws:kms:us-east-1:000000000000:alias/app", REGION));
assertEquals(Optional.empty(), kmsService.findKeyArn("1234abcd-12ab-34cd-56ef-1234567890ab", REGION));
assertEquals(Optional.empty(), kmsService.findKeyArn("alias/missing", REGION));
assertEquals(Optional.empty(), kmsService.findKeyArn(created.getArn(), "eu-west-1"));
assertEquals(Optional.empty(), kmsService.findKeyArn(null, REGION));
assertEquals(Optional.empty(), kmsService.findKeyArn(" ", REGION));
}
/**
* The enforcement filter resolves the key a grant operation acts on through this lookup for
* the same reason it reads {@code findKeyArn}: a request naming no grant the account holds
* answers its own {@code NotFoundException}, so the check must not refuse the request first.
* The token wins over the id, as {@code retireGrant} resolves the grant it deletes.
*/
@Test
void findGrantKeyArnResolvesTheTokenFirstAndRefusesNothing() {
KmsKey key = kmsService.createKey("granted", REGION);
KmsGrant grant = kmsService.createGrant(key.getKeyId(),
"arn:aws:iam::000000000000:user/grantee", List.of("Encrypt"), REGION);
assertEquals(Optional.of(key.getArn()),
kmsService.findGrantKeyArn(grant.getGrantToken(), null, REGION));
assertEquals(Optional.of(key.getArn()),
kmsService.findGrantKeyArn(grant.getGrantToken(), grant.getGrantId(), REGION));
assertEquals(Optional.of(key.getArn()),
kmsService.findGrantKeyArn(null, grant.getGrantId(), REGION));
assertEquals(Optional.empty(),
kmsService.findGrantKeyArn("no-such-token", grant.getGrantId(), REGION));
assertEquals(Optional.empty(), kmsService.findGrantKeyArn(null, "no-such-grant", REGION));
assertEquals(Optional.empty(), kmsService.findGrantKeyArn(null, null, REGION));
assertEquals(Optional.empty(), kmsService.findGrantKeyArn(" ", " ", REGION));
}
@Test
void createMultiRegionKeyUsesMrkIdAndPrimaryMetadata() {
KmsKey key = kmsService.createKey("multi-region key", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT",