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

@@ -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);
}
@@ -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 ──────────────────────────────────────────────────────────────────
@@ -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) {