Skip to content

armgit / floci

Public Imported from GitHub
0

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

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

Matheus Oliveira9b4e27c80ab7
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 5d6d4dadbf..53cac931e0 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1957,6 +1957,20 @@ it does on AWS, and a `Deny` on the full ARN applies. `CreateSecret` is evaluate
policy scoped to a name prefix such as `secret:app/*` allows it. A name that matches no secret in the
request's account and region is evaluated as `secret:<name>`, and an ARN that matches none as given.
+**KMS keys.** A request that names a key by its id, an alias name, an alias ARN or a key ARN is
+evaluated against the stored key's ARN, as the KMS API reference resolves the request's key
+identifier, 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 `Decrypt` that names no `KeyId` is evaluated against the key that encrypted
+its `CiphertextBlob`. `CreateAlias`, `UpdateAlias` and `DeleteAlias` are evaluated against the alias
+ARN and the key it points at, `UpdateAlias` also against the key it will point at, the resource
+types the Service Authorization Reference lists for them. `CreateKey`, `GenerateRandom`, `ListKeys`,
+`ListAliases` and `ListRetirableGrants` name no key resource and are evaluated against `*`, the
+resource a policy must name for them on AWS. `ReEncrypt` is evaluated against both keys it acts on
+under the single `kms:ReEncrypt` action; AWS authorizes the two halves separately as
+`kms:ReEncryptFrom` and `kms:ReEncryptTo`, which Floci does not split yet. A request that names no
+key the account holds is evaluated against every key the account holds, so a permissive `key/*`
+policy still matches it and the operation fails in the handler with its own error.
+
**Redshift GetClusterCredentials options.** Besides `redshift:GetClusterCredentials`, a request with
`DbGroups` needs `redshift:JoinGroup` on each group's `dbgroup:<cluster>/<group>` ARN, and a request with
`AutoCreate` set to `true` needs `redshift:CreateClusterUser` on the user's `dbuser:<cluster>/<user>` ARN,
diff --git a/docs/services/kms.md b/docs/services/kms.md
index b7dd9e13b5..729f34a6a9 100644
--- a/docs/services/kms.md
+++ b/docs/services/kms.md
@@ -228,6 +228,12 @@ 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.
+## IAM Enforcement
+
+With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, an operation that names a key is evaluated against that key's ARN, as on AWS. A `KeyId` given as a key id, an alias name, an alias ARN or a key ARN resolves to the key it names, 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 `Decrypt` that names no `KeyId` is evaluated against the key that encrypted its `CiphertextBlob`.
+
+`CreateAlias`, `UpdateAlias` and `DeleteAlias` are evaluated against the alias ARN and the key it points at, `UpdateAlias` also against the key it will point at, the two resource types the Service Authorization Reference lists for them. `ReEncrypt` is evaluated against both keys it acts on, under the single `kms:ReEncrypt` action: the source its `SourceKeyId` names, or when it names none the key that encrypted its `CiphertextBlob` (never a `KeyId`, which the operation does not read), and the destination its `DestinationKeyId` names. AWS authorizes the two halves separately as `kms:ReEncryptFrom` and `kms:ReEncryptTo`, which Floci does not split yet. The grant operations name the key the grant they act on belongs to: a `RetireGrant` carrying a `GrantToken` the key that grant belongs to, since the handler finds the grant by the token alone, and a `RetireGrant` or `RevokeGrant` identifying its grant by `KeyId` and `GrantId` the key it names together with the key that grant belongs to. A request nothing resolves keeps the permissive `key/*` pattern, and the operation then fails with its own error. `CreateKey`, `GenerateRandom`, `ListKeys`, `ListAliases` and `ListRetirableGrants` name no key resource and are evaluated against `*`, the resource a policy must name for them on AWS too.
+
## Configuration
| Variable | Default | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index a40d01f5fc..15bb5fa718 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -1585,7 +1585,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
/**
- * Logs and Secrets Manager targets depend on the serving operation and the request's partition, STS
+ * Logs, Secrets Manager and KMS targets depend on the serving operation and the request's partition, STS
* targets on the serving operation;
* Scheduler and Pipes targets on the request's partition, which those services mint their ARNs in; and the
* targets of a namespace the table of request resources reads on {@code operation}, the one the request is
@@ -1599,6 +1599,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if ("secretsmanager".equals(credentialScope)) {
return arnBuilder.buildSecretsManagerResources(action, ctx, region, accountId, requestPartition());
}
+ if ("kms".equals(credentialScope)) {
+ return arnBuilder.buildKmsResources(action, ctx, region, accountId, requestPartition());
+ }
if ("sts".equals(credentialScope)) {
return arnBuilder.buildStsResources(action, ctx);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
index 991ee6428d..ae13a18a55 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.MissingNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
@@ -11,6 +12,7 @@ import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget;
import io.github.hectorvent.floci.services.eks.EksService;
+import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
@@ -71,17 +73,28 @@ public class ResourceArnBuilder {
private final Instance<LambdaMicrovmsService> microvmsService;
/** Looked up lazily for the same reason, to read the ARN an EKS cluster or what it holds is stored under. */
private final Instance<EksService> eksService;
+ /** Looked up lazily for the same reason, to resolve a key named by an id, an alias or an ARN to its stored ARN. */
+ private final Instance<KmsService> kmsService;
@Inject
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<SecretsManagerService> secretsManagerService,
Instance<LambdaMicrovmsService> microvmsService,
- Instance<EksService> eksService) {
+ Instance<EksService> eksService,
+ Instance<KmsService> kmsService) {
this.objectMapper = objectMapper;
this.iamService = iamService;
this.secretsManagerService = secretsManagerService;
this.microvmsService = microvmsService;
this.eksService = eksService;
+ this.kmsService = kmsService;
+ }
+
+ public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
+ Instance<SecretsManagerService> secretsManagerService,
+ Instance<LambdaMicrovmsService> microvmsService,
+ Instance<EksService> eksService) {
+ this(objectMapper, iamService, secretsManagerService, microvmsService, eksService, null);
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
@@ -147,7 +160,6 @@ public class ResourceArnBuilder {
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
case "kinesis" -> List.of(buildKinesisArn(ctx, region, accountId));
case "ssm" -> List.of(buildSsmArn(ctx, region, accountId));
- case "kms" -> List.of(buildKmsArn(path, region, accountId));
case "iam" -> buildIamArns(ctx, region, accountId);
case "resource-groups" -> List.of(buildResourceGroupArn(ctx, region, accountId));
case "scheduler" -> List.of(buildSchedulerArn(path, ctx, region, accountId, partition));
@@ -1590,10 +1602,278 @@ public class ResourceArnBuilder {
}
// ── KMS ──────────────────────────────────────────────────────────────────────
- private String buildKmsArn(String path, String region, String accountId) {
- String keyId = extractSegmentAfter(path, "keys");
- if (keyId == null) return AwsArnUtils.Arn.of("kms", region, accountId, "key/*").toString();
- return AwsArnUtils.Arn.of("kms", region, accountId, "key/" + keyId).toString();
+
+ /**
+ * The resources a KMS request is evaluated against, as the KMS permissions reference gives
+ * them (Developer Guide, "AWS KMS permissions"). A key-scoped operation, which is every
+ * crypto operation and every key-management one Floci dispatches, is evaluated against the
+ * key its {@code KeyId} names, resolving an alias name or an alias ARN to the key it points
+ * at exactly as the handler resolves it. {@code Decrypt} names its key in an optional
+ * {@code KeyId}; without one the key is the one that encrypted the {@code CiphertextBlob},
+ * read out of the blob the same way the handler reads it.
+ *
+ * <p>{@code CreateKey}, {@code GenerateRandom}, {@code ListKeys}, {@code ListAliases} and
+ * {@code ListRetirableGrants} apply to no particular resource, so they stay at {@code *},
+ * the element the reference itself requires a policy to name for them. The alias operations
+ * name their resources the way 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.
+ *
+ * <p>{@code ReEncrypt} is a stopgap here: AWS authorizes it as {@code kms:ReEncryptFrom} on
+ * the source key and {@code kms:ReEncryptTo} on the destination, while this evaluates the
+ * single {@code kms:ReEncrypt} action against both keys, so a policy naming either action
+ * AWS publishes still binds to nothing. The source is the key its optional
+ * {@code SourceKeyId} names and otherwise the key that encrypted the
+ * {@code CiphertextBlob}, never a {@code KeyId} member, which the handler does not read on
+ * {@code ReEncrypt}.
+ *
+ * <p>The grant operations name the key the grant they act on belongs to, the way the handler
+ * resolves it: a {@code RetireGrant} carrying a {@code GrantToken} the key the grant it
+ * names belongs to, a {@code RetireGrant} or a {@code RevokeGrant} identifying its grant by
+ * {@code KeyId} and {@code GrantId} the key it names together with the key that grant
+ * belongs to. They coincide for a request naming a grant on its own key; naming both closes
+ * the pair that names one key while retiring or revoking another key's grant.
+ *
+ * <p>A request nothing resolves names every key the account holds, which the permissive
+ * {@code key/*} pattern a policy may scope to still matches; the operation then fails in the
+ * handler with its own {@code NotFoundException}.
+ */
+ public List<String> buildKmsResources(String action, ContainerRequestContext ctx,
+ String region, String accountId, String partition) {
+ JsonNode body = readJsonBody(ctx);
+ if (body == null) {
+ body = MissingNode.getInstance();
+ }
+ return switch (action) {
+ case "kms:CreateKey", "kms:GenerateRandom", "kms:ListKeys", "kms:ListAliases",
+ "kms:ListRetirableGrants" -> List.of("*");
+ case "kms:CreateAlias" -> createAliasTargets(body, region, accountId, partition);
+ case "kms:UpdateAlias" -> updateAliasTargets(body, region, accountId, partition);
+ case "kms:DeleteAlias" -> deleteAliasTargets(body, region, accountId, partition);
+ case "kms:Decrypt" -> List.of(decryptTarget(body, region, accountId, partition));
+ case "kms:ReEncrypt" -> reEncryptTargets(body, region, accountId, partition);
+ case "kms:RetireGrant" -> retireGrantTargets(body, region, accountId, partition);
+ case "kms:RevokeGrant" -> revokeGrantTargets(body, region, accountId, partition);
+ default -> List.of(keyTarget(body, "KeyId", region, accountId, partition));
+ };
+ }
+
+ /** The key a request names in {@code member}, or every key the account holds when it names none. */
+ private String keyTarget(JsonNode body, String member, String region, String accountId,
+ String partition) {
+ String keyId = body.path(member).asText(null);
+ return keyId == null || keyId.isBlank()
+ ? keyWildcard(region, accountId, partition)
+ : keyArn(keyId, region, accountId, partition);
+ }
+
+ /**
+ * The key ARN a request's identifier names: the stored key's own ARN when the account holds
+ * it, in the partition it was created in; a key ARN the account holds nothing of as given,
+ * which is the caller's own naming of the key the operation will refuse; and a bare key id
+ * minted in the request's partition, the partition the create mints in. An alias that
+ * resolves to nothing names every key, since the operation then fails before a policy
+ * matters.
+ */
+ private String keyArn(String keyIdOrAliasOrArn, String region, String accountId, String partition) {
+ if (kmsService != null) {
+ Optional<String> stored = kmsService.get().findKeyArn(keyIdOrAliasOrArn, region);
+ if (stored.isPresent()) {
+ return stored.get();
+ }
+ }
+ if (AwsArnUtils.isArnFor(keyIdOrAliasOrArn, "kms")) {
+ return keyIdOrAliasOrArn;
+ }
+ if (keyIdOrAliasOrArn.startsWith("alias/") || keyIdOrAliasOrArn.contains(":alias/")) {
+ return keyWildcard(region, accountId, partition);
+ }
+ return new AwsArnUtils.Arn(partition, "kms", region, accountId,
+ "key/" + keyIdOrAliasOrArn).toString();
+ }
+
+ /**
+ * The key a {@code Decrypt} names: the optional {@code KeyId} when the request carries one,
+ * and otherwise the key that encrypted the {@code CiphertextBlob}, which is the key the
+ * service decrypts with and answers.
+ */
+ private String decryptTarget(JsonNode body, String region, String accountId, String partition) {
+ String keyId = body.path("KeyId").asText(null);
+ if (keyId != null && !keyId.isBlank()) {
+ return keyArn(keyId, region, accountId, partition);
+ }
+ return ciphertextKeyTarget(body, region, accountId, partition);
+ }
+
+ /**
+ * The key that encrypted the request's {@code CiphertextBlob}, read out of the blob the
+ * same way the handler reads it, or every key the account holds when the blob names none
+ * the account holds.
+ */
+ private String ciphertextKeyTarget(JsonNode body, String region, String accountId, String partition) {
+ JsonNode ciphertext = body.path("CiphertextBlob");
+ if (kmsService != null && !ciphertext.isMissingNode() && !ciphertext.isNull()) {
+ if (!ciphertext.isTextual() && !ciphertext.isBinary()) {
+ return keyWildcard(region, accountId, partition);
+ }
+ byte[] blob;
+ try {
+ blob = ciphertext.binaryValue();
+ } catch (IOException e) {
+ return keyWildcard(region, accountId, partition);
+ }
+ String keyArn = blob == null ? null : kmsService.get().decryptToKeyArn(blob, region);
+ if (keyArn != null) {
+ return keyArn;
+ }
+ }
+ return keyWildcard(region, accountId, partition);
+ }
+
+ /**
+ * Both keys a {@code ReEncrypt} acts on: the source its optional {@code SourceKeyId} names
+ * and otherwise the key that encrypted the {@code CiphertextBlob}, which is the key the
+ * service decrypts with, and the destination its {@code DestinationKeyId} names. The
+ * handler never reads a {@code KeyId} on {@code ReEncrypt}, so neither does this. The
+ * filter authorizes a request once per resource, so the caller has to be allowed on both.
+ */
+ private List<String> reEncryptTargets(JsonNode body, String region, String accountId,
+ String partition) {
+ Set<String> keys = new LinkedHashSet<>();
+ String sourceKeyId = body.path("SourceKeyId").asText(null);
+ keys.add(sourceKeyId == null || sourceKeyId.isBlank()
+ ? ciphertextKeyTarget(body, region, accountId, partition)
+ : keyArn(sourceKeyId, region, accountId, partition));
+ keys.add(keyTarget(body, "DestinationKeyId", region, accountId, partition));
+ return new ArrayList<>(keys);
+ }
+
+ /**
+ * The key a {@code RetireGrant} acts on, as the handler resolves it: the key the grant its
+ * {@code GrantToken} names belongs to, since the handler finds the grant by the token
+ * alone and only cross-verifies the other members against it, and for a request identifying
+ * its grant by {@code KeyId} and {@code GrantId} the key it names together with the key
+ * that grant belongs to, which the pair identifies for the handler. A token naming no
+ * grant the account holds keeps the permissive fallback; the handler refuses the request
+ * with its own {@code NotFoundException}.
+ */
+ private List<String> retireGrantTargets(JsonNode body, String region, String accountId,
+ String partition) {
+ String grantToken = body.path("GrantToken").asText(null);
+ if (grantToken != null && !grantToken.isBlank()) {
+ String grantKey = grantKeyArn(grantToken, body.path("GrantId").asText(null), region);
+ return grantKey == null
+ ? List.of(keyWildcard(region, accountId, partition))
+ : List.of(grantKey);
+ }
+ Set<String> resources = new LinkedHashSet<>();
+ resources.add(keyTarget(body, "KeyId", region, accountId, partition));
+ String grantKey = grantKeyArn(grantToken, body.path("GrantId").asText(null), region);
+ if (grantKey != null) {
+ resources.add(grantKey);
+ }
+ return new ArrayList<>(resources);
+ }
+
+ /**
+ * The keys a {@code RevokeGrant} acts on: the key its {@code KeyId} names, which the
+ * handler resolves, and the key the grant its {@code GrantId} names belongs to, which the
+ * handler deletes. They coincide for a request naming a grant on its own key, and naming
+ * both closes the pair that names one key while revoking another key's grant. The
+ * handler never reads a {@code GrantToken} on {@code RevokeGrant}, so the grant resolves
+ * by its {@code GrantId} alone.
+ */
+ private List<String> revokeGrantTargets(JsonNode body, String region, String accountId,
+ String partition) {
+ Set<String> resources = new LinkedHashSet<>();
+ resources.add(keyTarget(body, "KeyId", region, accountId, partition));
+ String grantKey = grantKeyArn(null, body.path("GrantId").asText(null), region);
+ if (grantKey != null) {
+ resources.add(grantKey);
+ }
+ return new ArrayList<>(resources);
+ }
+
+ /** The stored ARN of the key the request's grant belongs to, or null when none resolves. */
+ private String grantKeyArn(String grantToken, String grantId, String region) {
+ if (kmsService == null) {
+ return null;
+ }
+ return kmsService.get()
+ .findGrantKeyArn(grantToken, grantId, region)
+ .orElse(null);
+ }
+
+ /**
+ * The alias and the key a {@code CreateAlias} names, as the alias permissions page requires
+ * the caller to hold {@code kms:CreateAlias} on both.
+ */
+ private List<String> createAliasTargets(JsonNode body, String region, String accountId,
+ String partition) {
+ Set<String> resources = new LinkedHashSet<>();
+ String aliasArn = aliasArn(body.path("AliasName").asText(null), region, accountId, partition);
+ if (aliasArn != null) {
+ resources.add(aliasArn);
+ }
+ resources.add(keyTarget(body, "TargetKeyId", region, accountId, partition));
+ return new ArrayList<>(resources);
+ }
+
+ /**
+ * The three resources an {@code UpdateAlias} acts on, as the alias permissions page lists
+ * them: the alias, the key it points at and the key it will point at.
+ */
+ private List<String> updateAliasTargets(JsonNode body, String region, String accountId,
+ String partition) {
+ Set<String> resources = new LinkedHashSet<>();
+ addAliasAndItsKey(resources, body, region, accountId, partition);
+ resources.add(keyTarget(body, "TargetKeyId", region, accountId, partition));
+ return new ArrayList<>(resources);
+ }
+
+ /**
+ * The alias and the key it points at, the two resources a {@code DeleteAlias} acts on. A
+ * request naming no alias AWS would accept the name of names nothing to authorize against
+ * but the wildcard, and the handler refuses it.
+ */
+ private List<String> deleteAliasTargets(JsonNode body, String region, String accountId,
+ String partition) {
+ Set<String> resources = new LinkedHashSet<>();
+ addAliasAndItsKey(resources, body, region, accountId, partition);
+ return resources.isEmpty() ? List.of("*") : new ArrayList<>(resources);
+ }
+
+ /**
+ * The alias the request's {@code AliasName} names, and the key that alias points at when it
+ * resolves to one. Nothing is added for a name that is missing or that AWS would refuse.
+ */
+ private void addAliasAndItsKey(Set<String> resources, JsonNode body, String region,
+ String accountId, String partition) {
+ String aliasName = body.path("AliasName").asText(null);
+ String aliasArn = aliasArn(aliasName, region, accountId, partition);
+ if (aliasArn == null) {
+ return;
+ }
+ resources.add(aliasArn);
+ if (kmsService != null) {
+ String keyArn = kmsService.get().findKeyArn(aliasName, region).orElse(null);
+ if (keyArn != null) {
+ resources.add(keyArn);
+ }
+ }
+ }
+
+ /** The alias's ARN, or null when the request names no alias AWS would accept the name of. */
+ private static String aliasArn(String aliasName, String region, String accountId, String partition) {
+ if (aliasName == null || !aliasName.startsWith("alias/")) {
+ return null;
+ }
+ return new AwsArnUtils.Arn(partition, "kms", region, accountId, aliasName).toString();
+ }
+
+ /** Every key the account holds in the region, the pattern a permissive policy still matches. */
+ private static String keyWildcard(String region, String accountId, String partition) {
+ return new AwsArnUtils.Arn(partition, "kms", region, accountId, "key/*").toString();
}
// ── Helpers ──────────────────────────────────────────────────────────────────
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 4b84389612..8e40419d35 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
@@ -601,10 +601,7 @@ public class KmsService implements ResourceProvider {
// Token-based retirement: scan all grants in the region for matching token
if (hasToken) {
- String prefix = region + "::";
- KmsGrant found = grantStore.scan(k -> k.startsWith(prefix)).stream()
- .filter(g -> grantToken.equals(g.getGrantToken()))
- .findFirst()
+ KmsGrant found = findGrantByToken(grantToken, region)
.orElseThrow(() -> new AwsException("NotFoundException",
"Grant not found for the given grant token", 400));
@@ -2191,6 +2188,72 @@ public class KmsService implements ResourceProvider {
// ──────────────────────────── Helpers ────────────────────────────
private KmsKey resolveKey(String keyIdOrArn, String region) {
+ String keyId = resolveStoredKeyId(keyIdOrArn, region);
+ KmsKey key = keyStore.get(region + "::" + keyId)
+ .orElseThrow(() -> keyNotFound(keyIdOrArn, keyId, region));
+ key = expireImportedKeyMaterialIfDue(key, region);
+ key = ensureBackingKeyMaterial(key, region);
+ return key;
+ }
+
+ /**
+ * The stored ARN of the key a request names by its id, an alias name, an alias ARN or a key
+ * ARN, or empty when the account holds no such key in the region. The enforcement filter reads
+ * this rather than {@link #resolveKey}: an operation naming no key the account holds answers
+ * its own {@code NotFoundException} whether a policy allows it or not, so the check keeps its
+ * permissive fallback instead of refusing the request before the handler can.
+ */
+ public Optional<String> findKeyArn(String keyIdOrArn, String region) {
+ if (keyIdOrArn == null || keyIdOrArn.isBlank()) {
+ return Optional.empty();
+ }
+ try {
+ return keyStore.get(region + "::" + resolveStoredKeyId(keyIdOrArn, region))
+ .map(KmsKey::getArn)
+ .filter(arn -> !arn.isBlank());
+ } catch (AwsException e) {
+ return Optional.empty();
+ }
+ }
+
+ /**
+ * The stored ARN of the key the grant a retirement or a revocation acts on belongs to: the
+ * grant its {@code GrantToken} names when the request carries one, and otherwise the grant
+ * its {@code GrantId} names, or empty when the account holds no such grant in the region.
+ * The enforcement filter reads this rather than {@link #retireGrant} and
+ * {@link #revokeGrant}: a request naming no grant the account holds answers its own
+ * {@code NotFoundException} whether a policy allows it or not, so the check keeps its
+ * permissive fallback instead of refusing the request before the handler can. The token wins
+ * over the id exactly as {@link #retireGrant} resolves the grant it deletes.
+ */
+ public Optional<String> findGrantKeyArn(String grantToken, String grantId, String region) {
+ if (grantToken != null && !grantToken.isBlank()) {
+ return findGrantByToken(grantToken, region)
+ .map(KmsGrant::getKeyArn)
+ .filter(arn -> !arn.isBlank());
+ }
+ if (grantId == null || grantId.isBlank()) {
+ return Optional.empty();
+ }
+ return grantStore.get(region + "::" + grantId)
+ .map(KmsGrant::getKeyArn)
+ .filter(arn -> !arn.isBlank());
+ }
+
+ /** The grant a token names in a region, from the same scan the token-based retirement uses. */
+ private Optional<KmsGrant> findGrantByToken(String grantToken, String region) {
+ String prefix = region + "::";
+ return grantStore.scan(k -> k.startsWith(prefix)).stream()
+ .filter(grant -> grantToken.equals(grant.getGrantToken()))
+ .findFirst();
+ }
+
+ /**
+ * The stored key id a request's identifier names, resolving an alias name or an alias ARN to
+ * the key it points at and a key ARN to its trailing id, and refusing an ARN from another
+ * region as the crypto paths refuse it.
+ */
+ private String resolveStoredKeyId(String keyIdOrArn, String region) {
if (referencesReservedAlias(keyIdOrArn)) {
ensureAwsManagedKeys(region);
}
@@ -2221,14 +2284,7 @@ public class KmsService implements ResourceProvider {
.map(KmsAlias::getTargetKeyId)
.orElseThrow(() -> aliasNotFound(keyIdOrArn, region));
}
-
- // Key id
- String keyId = id;
- KmsKey key = keyStore.get(region + "::" + id)
- .orElseThrow(() -> keyNotFound(keyIdOrArn, keyId, region));
- key = expireImportedKeyMaterialIfDue(key, region);
- key = ensureBackingKeyMaterial(key, region);
- return key;
+ return id;
}
private AwsException aliasNotFound(String aliasName, String region) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/KmsKeyArnEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/KmsKeyArnEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..eabbd2491e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/KmsKeyArnEnforcementIntegrationTest.java
@@ -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("/");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
index 981040b597..ac276532b9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
@@ -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
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 955e0bec0b..ca5ee4bc8d 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
@@ -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",