mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iam): read KMS from the generated tables, its permissions from the developer guide (#9221)
KMS is read from iam-request-resources.json now, and ResourceArnBuilder's KMS branch and the enforcement filter's call around the table are gone, leaving dynamodb and iam in HAND_BUILT. What botocore and the Service Reference do not say comes from the KMS documentation, vendored by fetch_kms_api_permissions.py into tools/aws/sources/kms-api-permissions.json and read under PERMISSION_SOURCES: the developer guide's permissions table, the API reference's sentence that Decrypt and ReEncrypt read their key from the ciphertext's metadata, and the guide's key identifier formats. - ReEncrypt is checked as kms:ReEncryptFrom on its source key, or the ciphertext's key without one, and kms:ReEncryptTo on its destination key, ReplicateKey as kms:ReplicateKey and kms:CreateKey. An operation checked as several actions records them (actions, action), which RequestResources.checkedAs reads and the filter checks. - CreateAlias, UpdateAlias and DeleteAlias are checked on the alias and the keys the table names, the alias's current key through the alias. - Decrypt with no KeyId is checked on the ciphertext's key. - KmsStoredResourceArns finds a key in any state, uses only an enabled one for a forwarded request, reaches the key of an alias, a grant or a ciphertext, and gives a key's tags.
This commit is contained in:
1 parent
81b25c66bc
commit
739a22ab32
19 files changed
+2256
-629
No files matched your search
@@ -519,7 +519,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
List<String> resources = resolveResourceArns(credentialScope,
|
||||
targetResources(credentialScope, action, resolvedOperation.operation(), ctx, region, accountId));
|
||||
targetResources(credentialScope, resolvedOperation.operation(), ctx, region, accountId));
|
||||
|
||||
Optional<PresignedScope> presignedScope = iamService.presignedScope(akid);
|
||||
if (presignedScope.isPresent()) {
|
||||
@@ -612,8 +612,24 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (abortIfDenied(ctx, caller, principal, action, credentialScope, resources, targetContexts,
|
||||
region, accountId, akid)) {
|
||||
// An operation AWS authorizes by several actions (KMS's ReEncrypt, by kms:ReEncryptFrom on the key it decrypts
|
||||
// with and kms:ReEncryptTo on the one it encrypts with) is checked as each on the resources the table gives
|
||||
// it, with that action's condition keys, and not as the operation's own.
|
||||
Map<String, List<String>> checkedAs = arnBuilder.checkedAs(credentialScope, resolvedOperation.operation(), ctx,
|
||||
region, accountId, requestPartition());
|
||||
for (Map.Entry<String, List<String>> checked : checkedAs.entrySet()) {
|
||||
Map<String, List<String>> resolved =
|
||||
conditionContextResolver.resolve(credentialScope, checked.getKey(), ctx);
|
||||
Map<String, List<String>> checkedContext = resolved == null ? new HashMap<>() : new HashMap<>(resolved);
|
||||
callerArns.ifPresent(arns -> arns.putPrincipalKeys(checkedContext));
|
||||
if (abortIfDenied(ctx, caller, principal, checked.getKey(), action, credentialScope,
|
||||
resolveResourceArns(credentialScope, checked.getValue()), List.of(checkedContext), region,
|
||||
accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (checkedAs.isEmpty() && abortIfDenied(ctx, caller, principal, action, credentialScope, resources,
|
||||
targetContexts, region, accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
if (abortIfRolePassDenied(ctx, caller, principal, callerArns.orElse(null), action, credentialScope,
|
||||
@@ -1787,15 +1803,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
/**
|
||||
* KMS targets depend on the serving operation and the request's partition, and the targets of a namespace the
|
||||
* table of request resources reads on {@code operation}, the one the request is dispatched as (see
|
||||
* {@link RequestResources}).
|
||||
* The targets of a request, which the table of request resources reads on {@code operation}, the one the request
|
||||
* is dispatched as, for a namespace it reads (see {@link RequestResources}).
|
||||
*/
|
||||
private List<String> targetResources(String credentialScope, String action, String operation,
|
||||
ContainerRequestContext ctx, String region, String accountId) {
|
||||
if ("kms".equals(credentialScope)) {
|
||||
return arnBuilder.buildKmsResources(action, ctx, region, accountId, requestPartition());
|
||||
}
|
||||
private List<String> targetResources(String credentialScope, String operation, ContainerRequestContext ctx,
|
||||
String region, String accountId) {
|
||||
// ARNs the table renders take the request's partition, which a Region Floci does not know cannot be mapped to.
|
||||
return arnBuilder.buildResources(credentialScope, operation, ctx, region, accountId, requestPartition());
|
||||
}
|
||||
|
||||
@@ -2,10 +2,12 @@ package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@@ -340,7 +342,10 @@ final class RequestResourceMembers {
|
||||
* client ({@code locatedApart}), whose vendored route tells a request's client. Each operation's {@code forwarded}
|
||||
* requests are those its service makes to another as the caller, and its {@code statements} those it makes as the
|
||||
* caller to run each statement its request may carry. An {@code unread} operation names what it acts on in a body
|
||||
* the reader does not read.
|
||||
* the reader does not read. An operation AWS authorizes by several actions, none of its own name, has its
|
||||
* resources under the one each is checked as ({@code checkedAs}, in the order the file gives the actions: KMS's
|
||||
* ReEncrypt, {@code kms:ReEncryptFrom} on its source key and {@code kms:ReEncryptTo} on its destination key), and
|
||||
* none in {@code operations}.
|
||||
*/
|
||||
record Table(Map<String, List<Resource>> operations, Map<String, List<String>> types,
|
||||
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
|
||||
@@ -351,7 +356,8 @@ final class RequestResourceMembers {
|
||||
Map<String, Map<String, Map<String, ResourceKey>>> resourceKeys,
|
||||
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces,
|
||||
Map<String, List<Forwarded>> forwarded, Map<String, Map<String, List<StatementRequest>>> statements,
|
||||
Map<String, Map<String, Map<String, String>>> locatedApart, Set<String> unread) {
|
||||
Map<String, Map<String, Map<String, String>>> locatedApart, Set<String> unread,
|
||||
Map<String, Map<String, List<Resource>>> checkedAs) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
@@ -454,6 +460,7 @@ final class RequestResourceMembers {
|
||||
});
|
||||
Map<String, Map<String, Map<String, ResourceKey>>> resourceKeys = resourceKeys(document, formats);
|
||||
Map<String, List<Resource>> entries = new LinkedHashMap<>();
|
||||
Map<String, Map<String, List<Resource>>> checkedAs = new LinkedHashMap<>();
|
||||
Map<String, List<String>> actsOn = new LinkedHashMap<>();
|
||||
Map<String, List<Created>> creates = new LinkedHashMap<>();
|
||||
Map<String, List<Resource>> makes = new LinkedHashMap<>();
|
||||
@@ -471,10 +478,26 @@ final class RequestResourceMembers {
|
||||
+ ", of no namespace it reads");
|
||||
}
|
||||
List<Resource> resources = new ArrayList<>();
|
||||
// An operation checked as several actions has each resource checked as one of them.
|
||||
Map<String, List<Resource>> byAction = new LinkedHashMap<>();
|
||||
operation.getValue().path("actions").propertyStream()
|
||||
.forEach(action -> byAction.put(action.getKey(), new ArrayList<>()));
|
||||
for (JsonNode resource : operation.getValue().path("resources")) {
|
||||
resources.add(resource(operation.getKey(), resource, formats.getOrDefault(namespace, Map.of())));
|
||||
String action = resource.path("action").asText(null);
|
||||
if (byAction.isEmpty() != (action == null) || action != null && !byAction.containsKey(action)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " checks a resource of " + operation.getKey()
|
||||
+ " as " + action + ", none of the actions it records for the operation");
|
||||
}
|
||||
(action == null ? resources : byAction.get(action)).add(resource(operation.getKey(),
|
||||
action == null ? resource : ((ObjectNode) resource.deepCopy()).without("action"),
|
||||
formats.getOrDefault(namespace, Map.of())));
|
||||
}
|
||||
entries.put(operation.getKey(), List.copyOf(resources));
|
||||
if (!byAction.isEmpty()) {
|
||||
Map<String, List<Resource>> actions = new LinkedHashMap<>();
|
||||
byAction.forEach((action, named) -> actions.put(action, List.copyOf(named)));
|
||||
checkedAs.put(operation.getKey(), Collections.unmodifiableMap(actions));
|
||||
}
|
||||
List<String> types = operation.getValue().path("types").valueStream().map(JsonNode::asText).toList();
|
||||
actsOn.put(operation.getKey(), types);
|
||||
List<Resource> made = new ArrayList<>();
|
||||
@@ -606,7 +629,7 @@ final class RequestResourceMembers {
|
||||
names(document.path("handBuilt")),
|
||||
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
names(document.path("otherNamespaces")), Map.copyOf(forwarded), statements(document, formats),
|
||||
Map.copyOf(locatedApart), Set.copyOf(unread));
|
||||
Map.copyOf(locatedApart), Set.copyOf(unread), Map.copyOf(checkedAs));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -9,9 +9,11 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -200,6 +202,35 @@ public final class RequestResources {
|
||||
: named(operation, resources, formats(table, operation), form, body, partition, region, accountId, stored);
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions an operation AWS authorizes by several actions, none of its own name, is checked as instead of its
|
||||
* own, each with the ARNs of the resources the request names that it is checked on, as {@link #of} reads them:
|
||||
* KMS's ReEncrypt, {@code kms:ReEncryptFrom} on its source key and {@code kms:ReEncryptTo} on its destination key.
|
||||
* An action the request names no resource of is checked on {@code *}. Empty for every other operation, which is
|
||||
* checked as its own action on what {@link #of} gives.
|
||||
*/
|
||||
public static Map<String, List<String>> checkedAs(String operation, ContainerRequestContext ctx, String partition,
|
||||
String region, String accountId, StoredResourceArns stored,
|
||||
Map<String, String> labels) {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
Map<String, List<RequestResourceMembers.Resource>> actions = !readable(table, operation) ? null
|
||||
: table.checkedAs().get(operation);
|
||||
if (actions == null) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> sent = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = sent.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null;
|
||||
Map<String, String> form = ec2Query(table, operation, located(table, operation, sent, ctx, labels));
|
||||
Map<String, List<String>> checked = new LinkedHashMap<>();
|
||||
actions.forEach((action, resources) -> {
|
||||
List<RequestResourceMembers.Resource> read = served(resources, ctx);
|
||||
List<String> arns = read.isEmpty() ? List.of() : named(operation, read, formats(table, operation), form,
|
||||
body, partition, region, accountId, stored);
|
||||
checked.put(action, arns.isEmpty() ? List.of("*") : arns);
|
||||
});
|
||||
return Collections.unmodifiableMap(checked);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources a JSON request body names, for a call that is not an HTTP request of its own, as a
|
||||
* state machine's task to its integrated service: as {@link #of} reads the same request, whatever endpoint it
|
||||
@@ -235,7 +266,8 @@ public final class RequestResources {
|
||||
* resources the request is checked on: for each of {@code resources} of the type whose record holds what the
|
||||
* action acts on, the resource that record's member names, as the action's service finds it in the account and
|
||||
* Region of the ARN, the caller's ({@code find}) or another's ({@code findInAccount}), or the value itself, not
|
||||
* held, when it finds none. None for a resource whose service records nothing there (a snapshot under AWS's own
|
||||
* held, when it finds none or one it does not act on for such a request ({@link StoredResourceArns#usable}: a
|
||||
* disabled key). None for a resource whose service records nothing there (a snapshot under AWS's own
|
||||
* key records no key of the account's), or one whose policy lets every principal of its account have the service
|
||||
* act on it ({@link StoredResourceArns#grantsItsAccountThroughServices}: an AWS managed key). {@code held} is the
|
||||
* operation's service, and {@code services} gives the action's.
|
||||
@@ -268,7 +300,7 @@ public final class RequestResources {
|
||||
Optional<String> target = arn.accountId().equals(accountId)
|
||||
? service.find(use.type(), List.of(named.get()), arn.region())
|
||||
: service.findInAccount(use.type(), List.of(named.get()), arn.accountId(), arn.region());
|
||||
if (target.isEmpty()) {
|
||||
if (target.isEmpty() || !service.usable(target.get())) {
|
||||
found.add(new Forwarded(use.action(), named.get(), use.viaService(), use.endpoint(), false));
|
||||
} else if (!service.grantsItsAccountThroughServices(target.get())) {
|
||||
found.add(new Forwarded(use.action(), target.get(), use.viaService(), use.endpoint(), true));
|
||||
|
||||
@@ -23,7 +23,9 @@ import java.util.Optional;
|
||||
* <p>Implemented by the service that owns such resources or whose requests name them (EventBridge, for its
|
||||
* connections and API destinations; Application Auto Scaling, for its scalable targets and their tags; Redshift
|
||||
* Data, for the Redshift Serverless workgroups it runs statements on and the targets of its sessions; Payment
|
||||
* Cryptography, for the key an alias names and the tags of a key; EMR, for the clusters of its instance groups and a
|
||||
* Cryptography, for the key an alias names and the tags of a key; KMS, for the key an id, an alias or an
|
||||
* ARN names, the key an alias points at, a grant is on or a ciphertext was encrypted under, and the tags of a key;
|
||||
* EMR, for the clusters of its instance groups and a
|
||||
* tag call's resource and the tags of a cluster or a session; IAM Identity Center, for the accounts its permission
|
||||
* sets are provisioned to and the tags of an instance,
|
||||
* a permission set, an application or a trusted token issuer; Resource Explorer, for its default view and the tags
|
||||
@@ -137,6 +139,15 @@ public interface StoredResourceArns {
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the service acts on the resource {@code arn} names, one {@link #find} gave, for a request another service
|
||||
* forwards as the caller: false for a KMS key disabled or pending deletion, which KMS refuses such a request with,
|
||||
* as for a resource it does not hold. True for any other.
|
||||
*/
|
||||
default boolean usable(String arn) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the resource {@code arn} names, one {@link #find} gave, lets every principal of its account have a
|
||||
* service act on it through that service, as the key policy AWS writes for an AWS managed KMS key does: a request
|
||||
|
||||
@@ -2,9 +2,7 @@ package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsQueryServiceResolver;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.RequestPathLabels;
|
||||
@@ -12,7 +10,6 @@ import io.floci.aws.core.common.RequestResources;
|
||||
import io.floci.aws.core.common.ServicePrincipals;
|
||||
import io.floci.aws.core.common.SigV4CredentialScope;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.kms.KmsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -57,8 +54,6 @@ public class ResourceArnBuilder {
|
||||
* which IamService itself does not depend on, and a direct injection would close that loop.
|
||||
*/
|
||||
private final Instance<IamService> iamService;
|
||||
/** 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;
|
||||
/**
|
||||
* Looked up lazily for the same reason, to read the ARN a resource the request-resources table names by a name
|
||||
* its service follows with a minted id, or by members its minted ARN does not hold, is stored under.
|
||||
@@ -72,25 +67,17 @@ public class ResourceArnBuilder {
|
||||
|
||||
@Inject
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<KmsService> kmsService,
|
||||
Instance<StoredResourceArns> storedResourceArns,
|
||||
Instance<RequestPathLabels> requestPathLabels) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.iamService = iamService;
|
||||
this.kmsService = kmsService;
|
||||
this.storedResourceArns = storedResourceArns;
|
||||
this.requestPathLabels = requestPathLabels;
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<KmsService> kmsService,
|
||||
Instance<StoredResourceArns> storedResourceArns) {
|
||||
this(objectMapper, iamService, kmsService, storedResourceArns, null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
|
||||
Instance<KmsService> kmsService) {
|
||||
this(objectMapper, iamService, kmsService, null);
|
||||
this(objectMapper, iamService, storedResourceArns, null);
|
||||
}
|
||||
|
||||
ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
|
||||
@@ -98,11 +85,11 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
|
||||
public ResourceArnBuilder() {
|
||||
this(new ObjectMapper(), null, null);
|
||||
this(new ObjectMapper(), null);
|
||||
}
|
||||
|
||||
public ResourceArnBuilder(ObjectMapper objectMapper) {
|
||||
this(objectMapper, null, null);
|
||||
this(objectMapper, null);
|
||||
}
|
||||
|
||||
public String build(String credentialScope, ContainerRequestContext ctx,
|
||||
@@ -157,17 +144,41 @@ public class ResourceArnBuilder {
|
||||
if (operation == null || !operation.startsWith(credentialScope + ":")) {
|
||||
return List.of("*");
|
||||
}
|
||||
List<String> named = RequestResources.of(operation, ctx, partition, region, accountId,
|
||||
storedResourceArns(credentialScope), labels(credentialScope, ctx));
|
||||
return named.isEmpty() ? List.of("*") : named;
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions an operation AWS authorizes by several actions is checked as instead of its own, each with the
|
||||
* resources the request names that it is checked on (see {@link RequestResources#checkedAs}), read as
|
||||
* {@link #buildResources} reads the others: KMS's ReEncrypt, {@code kms:ReEncryptFrom} on its source key and
|
||||
* {@code kms:ReEncryptTo} on its destination key. Empty for every other operation.
|
||||
*/
|
||||
public Map<String, List<String>> checkedAs(String credentialScope, String operation, ContainerRequestContext ctx,
|
||||
String region, String accountId, String partition) {
|
||||
if (credentialScope == null || operation == null || !operation.startsWith(credentialScope + ":")
|
||||
|| !RequestResources.reads(operation)) {
|
||||
return Map.of();
|
||||
}
|
||||
return RequestResources.checkedAs(operation, ctx, partition, region, accountId,
|
||||
storedResourceArns(credentialScope), labels(credentialScope, ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* The labels of the request's path, as the route it was routed by gives them, each read as the namespace's
|
||||
* {@link RequestPathLabels} reads it where it reads one otherwise.
|
||||
*/
|
||||
private Map<String, String> labels(String credentialScope, ContainerRequestContext ctx) {
|
||||
Map<String, String> labels = IamActionRegistry.pathLabels(credentialScope, ctx);
|
||||
RequestPathLabels read = requestPathLabels(credentialScope);
|
||||
Map<String, String> otherwise = read == null ? Map.of() : read.labels(ctx, labels);
|
||||
if (!otherwise.isEmpty()) {
|
||||
Map<String, String> merged = new HashMap<>(labels);
|
||||
merged.putAll(otherwise);
|
||||
labels = Map.copyOf(merged);
|
||||
if (otherwise.isEmpty()) {
|
||||
return labels;
|
||||
}
|
||||
List<String> named = RequestResources.of(operation, ctx, partition, region, accountId,
|
||||
storedResourceArns(credentialScope), labels);
|
||||
return named.isEmpty() ? List.of("*") : named;
|
||||
Map<String, String> merged = new HashMap<>(labels);
|
||||
merged.putAll(otherwise);
|
||||
return Map.copyOf(merged);
|
||||
}
|
||||
|
||||
/** The registered reader of the namespace's path labels; null when there is none. */
|
||||
@@ -929,281 +940,6 @@ public class ResourceArnBuilder {
|
||||
return AwsArnUtils.Arn.of("dynamodb", region, accountId, "table/" + tableName).toString();
|
||||
}
|
||||
|
||||
// ── KMS ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 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 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/** The request's JSON or CBOR body, buffered so the handler still reads it, or null when it has none. */
|
||||
|
||||
@@ -2411,6 +2411,15 @@ public class KmsService implements ResourceProvider {
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the key {@code keyArn} names, read in the account and Region of the ARN, whoever is calling; none
|
||||
* when that account holds no such key, or for an alias.
|
||||
*/
|
||||
public Map<String, String> findKeyTags(String keyArn) {
|
||||
return keyAt(keyArn).map(KmsKey::getTags).filter(Objects::nonNull)
|
||||
.<Map<String, String>>map(LinkedHashMap::new).orElse(Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The key policy of the key {@code keyArn} names, read in the account and Region of the ARN, whoever is calling,
|
||||
* which IAM evaluates as the key's resource policy; empty when that account holds no such key, or for an alias.
|
||||
|
||||
@@ -5,14 +5,16 @@ import io.floci.aws.core.common.StoredResourceArns;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Finds the key a KMS key id, alias or ARN names, for a request another service forwards to KMS as the caller on a
|
||||
* key its own resource records (a snapshot's): the key's stored ARN, in the caller's account or in the one that
|
||||
* resource is in, when KMS would use it; none for a key disabled or pending deletion, which KMS refuses such a
|
||||
* request with.
|
||||
* Finds what KMS holds for the request-resources table: the key a key id, alias or ARN names, whatever its state, in
|
||||
* the caller's account or in the one an ARN names, which a request naming it acts on; the key an alias points at, the
|
||||
* key a grant is on and the key a ciphertext was encrypted under, which a request naming the alias, the grant or the
|
||||
* ciphertext reaches; and the tags of a key.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class KmsStoredResourceArns implements StoredResourceArns {
|
||||
@@ -39,13 +41,49 @@ public class KmsStoredResourceArns implements StoredResourceArns {
|
||||
@Override
|
||||
public Optional<String> findInAccount(String type, List<String> names, String account, String region) {
|
||||
return "key".equals(type) && names.size() == 1
|
||||
? kms.findKeyArnOfAccount(names.getFirst(), account, region).filter(kms::isEnabledKey)
|
||||
? kms.findKeyArnOfAccount(names.getFirst(), account, region)
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
/** Whether KMS uses the key for a request another service forwards: enabled, not disabled or pending deletion. */
|
||||
@Override
|
||||
public boolean usable(String arn) {
|
||||
return kms.isEnabledKey(arn);
|
||||
}
|
||||
|
||||
/** Whether the key is one AWS manages, whose policy lets every principal of its account use it through a service. */
|
||||
@Override
|
||||
public boolean grantsItsAccountThroughServices(String arn) {
|
||||
return kms.isAwsManagedKey(arn);
|
||||
}
|
||||
|
||||
/**
|
||||
* The key the caller's alias an {@code AliasName} names points at, the key the grant a {@code GrantId} names is
|
||||
* on, or the key the {@code CiphertextBlob} was encrypted under, which KMS reads out of the blob's metadata; none
|
||||
* when the caller holds no such alias, grant or key, or the blob is none KMS made.
|
||||
*/
|
||||
@Override
|
||||
public List<String> through(String member, String value, String region) {
|
||||
Optional<String> key = switch (member) {
|
||||
case "AliasName" -> kms.findKeyArn(value, region);
|
||||
case "GrantId" -> kms.findGrantKeyArn(null, value, region);
|
||||
case "CiphertextBlob" -> ciphertextKey(value, region);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
return key.stream().toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> storedTags(String arn) {
|
||||
return StoredResourceArns.withEmptyValues(kms.findKeyTags(arn));
|
||||
}
|
||||
|
||||
/** The key a base64 ciphertext blob was encrypted under, as KMS reads it out of the blob to decrypt it. */
|
||||
private Optional<String> ciphertextKey(String blob, String region) {
|
||||
try {
|
||||
return Optional.ofNullable(kms.decryptToKeyArn(Base64.getDecoder().decode(blob), region));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user