feat(redshift): require kms:Decrypt on an encrypted snapshot's key to restore it (#8309)

AWS requires the customer managed key of an encrypted snapshot to be shared
with the account restoring it (Redshift Management Guide, "Sharing a
snapshot"). Neither botocore nor the Service Reference says so, so the
request-resources generator states it in FORWARDED, an evidence entry under
MEASURED's rules: the action and the snapshot type, with the rest read from
the metadata (the key type and format kms:Decrypt acts on, the snapshot
record's KmsKeyId member, the endpoint prefix, kms:ViaService).

Under IAM enforcement a Redshift or Redshift Serverless restore is then also
checked as kms:Decrypt on the key the snapshot records, found in the
snapshot's account, against the key policy and the caller's own policies,
with aws:ViaAWSService and kms:ViaService naming the service's endpoint. KMS
key policies are now evaluated as resource policies.

A key KMS would not use, disabled, pending deletion or not held, refuses the
restore, as KMS refuses the request the service makes with it. A snapshot
under AWS's own key records none, and one under an AWS managed key (a copy
grant made without a key) needs nothing, as AWS writes that key's policy to
let the account use it through the service.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 11:04:31 -04:00
1 parent ddc844b48e
commit f09468fb19
22 files changed
+1234 -43

No files matched your search

@@ -615,6 +615,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
region, accountId, akid)) {
return;
}
if (abortIfForwardedDenied(ctx, caller, principal, callerArns.orElse(null), action,
resolvedAuthorization.operation(), credentialScope, resources, region, accountId, akid)) {
return;
}
if (tagOnCreate.isPresent() && abortIfTagOnCreateDenied(ctx, caller, principal, callerArns.orElse(null),
action, resolvedAuthorization.operation(), tagOnCreate.get(), credentialScope, resources, region,
accountId, akid)) {
@@ -1093,6 +1097,47 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return false;
}
/**
* A request whose service then asks another service, as the caller, to act on what a resource it is checked on
* holds (see {@link RequestResources#forwarded}) also needs that action on that resource, checked as the caller
* against the resource's own policy in its own account (a snapshot's KMS key, against its key policy), with
* {@code aws:ViaAWSService} true, as AWS's forward access sessions carry it, the action's {@code ViaService}
* key naming the service's endpoint in the request's Region and partition where it takes one, and the keys that
* say who is calling. One naming what the action's service does not hold (a key since deleted) is refused, as
* that service refuses it. Returns true when the request was aborted.
*/
private boolean abortIfForwardedDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal,
CallerArns callerArns, String action, String operation,
String credentialScope, List<String> resources, String region,
String accountId, String akid) {
for (RequestResources.Forwarded forwarded : arnBuilder.forwarded(operation, resources, accountId)) {
if (!forwarded.held()) {
// The service would ask for what the action's service no longer holds (a deleted key), which that
// service refuses, failing the request whatever the policies say.
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}, which its service does not hold",
akid, forwarded.action(), forwarded.resource());
ctx.abortWith(accessDeniedForRequest(forwarded.action(), credentialScope, ctx, forwarded.resource()));
return true;
}
Map<String, List<String>> context = new HashMap<>();
if (callerArns != null) {
callerArns.putPrincipalKeys(context);
}
context.put("aws:ViaAWSService", List.of("true"));
if (forwarded.viaService() != null) {
// The endpoint in the request's partition, which a custom Region of a China or GovCloud deployment keeps.
AwsPartition partition = AwsPartitions.find(requestPartition())
.orElseGet(() -> AwsPartitions.forRegionOrCommercial(region));
context.put(forwarded.viaService(), List.of(partition.regionalHostname(forwarded.endpoint(), region)));
}
if (abortIfDenied(ctx, caller, principal, forwarded.action(), action, credentialScope,
List.of(forwarded.resource()), List.of(context), region, accountId, akid)) {
return true;
}
}
return false;
}
/**
* The context once for each set of tags the request carries, with that set's keys where the context has
* none of its own, so each resource's tags are checked apart; the context alone when it carries none.
@@ -202,20 +202,32 @@ final class RequestResourceMembers {
record Targets(Member member, String query, Map<String, String> prefixes) {
}
/**
* A request an operation's service makes to another service as the caller: {@code action}, on that service's
* resource of {@code type} which the record of the operation's resource of type {@code of} holds in
* {@code member} (a Redshift Serverless snapshot's {@code kmsKeyId}), sent from the operation's endpoint prefix
* {@code endpoint}, which the action's namespace's {@code viaService} key names where the Service Reference lists
* one for the action, null otherwise.
*/
record Forwarded(String action, String type, String of, String member, String endpoint, String viaService) {
}
/**
* The file: each operation's resources, the resource types its action acts on, the resources it creates under a
* parent and the one a create whose action acts on no type makes ({@code makes}), as
* {@code <namespace>:<Operation>}, the members a REST operation's request carries outside its body, each
* namespace's ARN formats, and the namespaces it reads, those built by hand, those not read yet, and the others
* with resource types. A located member is a label of the request's path, {@code {Label}}, or a parameter of its
* query, {@code ?name}, by the member's name.
* query, {@code ?name}, by the member's name. Each operation's {@code forwarded} requests are those its service
* makes to another as the caller.
*/
record Table(Map<String, List<Resource>> operations, Map<String, List<String>> types,
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
Map<String, Targets> targets,
Map<String, Map<String, String>> located, Map<String, Map<String, ArnFormat>> formats,
Map<String, Map<String, List<String>>> resourceTagKeys,
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces) {
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces,
Map<String, List<Forwarded>> forwarded) {
}
private static final class Holder {
@@ -300,6 +312,8 @@ final class RequestResourceMembers {
Map<String, List<Resource>> makes = new LinkedHashMap<>();
Map<String, Targets> targets = new LinkedHashMap<>();
Map<String, Map<String, String>> located = new LinkedHashMap<>();
Map<String, List<Forwarded>> forwarded = new LinkedHashMap<>();
JsonNode forwardedActions = document.path("forwardedActions");
operations.properties().forEach(operation -> {
String namespace = operation.getKey().substring(0, Math.max(0, operation.getKey().indexOf(':')));
if (!namespaces.contains(namespace)) {
@@ -371,12 +385,43 @@ final class RequestResourceMembers {
if (!where.isEmpty()) {
located.put(operation.getKey(), Map.copyOf(where));
}
List<Forwarded> forwards = new ArrayList<>();
for (JsonNode use : operation.getValue().path("forwarded")) {
forwards.add(forwarded(operation.getKey(), use, types, formats.getOrDefault(namespace, Map.of()),
forwardedActions));
}
if (!forwards.isEmpty()) {
forwarded.put(operation.getKey(), List.copyOf(forwards));
}
});
return new Table(Map.copyOf(entries), Map.copyOf(actsOn), Map.copyOf(creates), Map.copyOf(makes),
Map.copyOf(targets), Map.copyOf(located), Map.copyOf(formats), Map.copyOf(resourceTagKeys), namespaces,
names(document.path("handBuilt")),
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
names(document.path("otherNamespaces")));
names(document.path("otherNamespaces")), Map.copyOf(forwarded));
}
/**
* A request the operation's service makes to another as the caller, joined with what the file records of its
* action: the type it acts on and the {@code ViaService} key of its namespace, if any.
*/
private static Forwarded forwarded(String operation, JsonNode use, List<String> types,
Map<String, ArnFormat> formats, JsonNode actions) {
String action = use.path("action").asText("");
JsonNode facts = actions.path(action);
String type = facts.path("type").asText("");
String of = use.path("of").asText("");
String member = use.path("member").asText("");
String endpoint = use.path("endpoint").asText("");
String viaService = facts.has("viaService") ? facts.path("viaService").asText("") : null;
if (!use.isObject() || use.size() != 4 || !facts.isObject() || type.isEmpty() || !types.contains(of)
|| !formats.containsKey(of) || !LOCATED_MEMBER.matcher(member).matches() || endpoint.isEmpty()
|| viaService != null
&& !viaService.equals(action.substring(0, action.indexOf(':') + 1) + "ViaService")) {
throw new IllegalStateException(RESOURCE_NAME + " forwards " + use + " for " + operation
+ ", no recorded action on a member of the record of a type it acts on");
}
return new Forwarded(action, type, of, member, endpoint, viaService);
}
private static Set<String> names(JsonNode list) {
@@ -16,6 +16,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -136,6 +137,64 @@ public final class RequestResources {
return named(operation, resources, formats(table, operation), Map.of(), body, partition, region, accountId, stored);
}
/**
* A request an operation's service makes to another service as the caller, which the caller needs permission for
* too: {@code action} on {@code resource}, sent from {@code endpoint}, the operation's endpoint prefix, which the
* condition key {@code viaService} names where the action takes one (null otherwise). Not {@code held} when the
* action's service holds no resource of that name (a deleted key), {@code resource} then being the value the
* record holds: that service refuses the request, so the operation fails.
*/
public record Forwarded(String action, String resource, String viaService, String endpoint, boolean held) {
}
/**
* The requests the operation's service makes to another as the caller (the table's {@code forwarded}), for the
* 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
* 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.
*/
public static List<Forwarded> forwarded(String operation, List<String> resources, String accountId,
StoredResourceArns held, Function<String, StoredResourceArns> services) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
List<RequestResourceMembers.Forwarded> uses = operation == null ? List.of()
: table.forwarded().getOrDefault(operation, List.of());
if (uses.isEmpty() || held == null) {
return List.of();
}
Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
List<Forwarded> found = new ArrayList<>();
for (RequestResourceMembers.Forwarded use : uses) {
StoredResourceArns service = services.apply(use.action().substring(0, use.action().indexOf(':')));
RequestResourceMembers.ArnFormat of = formats.get(use.of());
if (service == null || of == null) {
continue;
}
for (String resource : resources) {
if (!of.pattern().matcher(resource).matches()) {
continue;
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(resource);
Optional<String> named = held.recorded(resource, use.member());
if (named.isEmpty()) {
continue;
}
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()) {
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));
}
}
}
return List.copyOf(found);
}
/** Whether the table holds the operation as one with no resource of its own, which is checked on {@code *}. */
public static boolean actsOnNoResource(String operation) {
return reads(operation) && !hasIndividualTargets(operation)
@@ -10,7 +10,9 @@ import java.util.Optional;
* ({@code scalable-target/<id>}, named by its service namespace, resource id and scalable dimension;
* {@code workgroup/<id>}, named by its name). Also the ARNs of the resources a request names through another of its
* service's own (the cluster or workgroup a Data API session runs on, the cluster an EMR instance group is in, the
* accounts an IAM Identity Center permission set is provisioned to).
* accounts an IAM Identity Center permission set is provisioned to). Also what a resource's record holds that a
* request the operation's service forwards as the caller acts on (the key a Redshift snapshot is encrypted with), and
* the ARN of that resource in the service that owns it (the key, in KMS).
*
* <p>The reader asks for every type of the namespace, not only for the ones whose ARN carries an id the service
* mints, so a service may answer for a type whose ARN it does not mint: a key an alias names is the key the alias
@@ -25,8 +27,8 @@ import java.util.Optional;
* for the namespace a request is of, so IAM never depends on that service directly.</p>
*
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
* {@code through}, a default): never a fact about what an operation acts on, which the table alone says, from
* botocore and the Service Reference, or from AWS behaviour measured where neither carries it.</p>
* {@code through}, a default, {@code forwarded}): never a fact about what an operation acts on, which the table alone
* says, from botocore and the Service Reference, or from what AWS says where neither carries it.</p>
*/
public interface StoredResourceArns {
@@ -52,6 +54,26 @@ public interface StoredResourceArns {
return List.of();
}
/**
* What the resource stored under {@code arn}, in the account and Region the ARN names, records in {@code member},
* as botocore names that member of the type's record (a Redshift Serverless snapshot's {@code kmsKeyId}, the key
* it is encrypted with); empty when the service holds no such resource, it records nothing there, or the member
* is not one it reads. A variable the ARN leaves open ({@code *}) matches whatever the handler would act on in
* its place (a provisioned snapshot of any cluster, for a restore naming none).
*/
default Optional<String> recorded(String arn, String member) {
return Optional.empty();
}
/**
* 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
* another service forwards as the caller then needs no permission of the caller's on it. False for any other.
*/
default boolean grantsItsAccountThroughServices(String arn) {
return false;
}
/**
* As {@link #findByMembers}, for a resource another account owns that the request names by that account, which its
* service lets the caller reach when the resource's policy allows it (a Redshift Serverless snapshot shared by its
@@ -254,6 +254,19 @@ public class ResourceArnBuilder {
return named.isEmpty() ? List.of("*") : named;
}
/**
* The requests the service of {@code operation}, the one the request is dispatched as, makes to another service as
* the caller on what the resources it is checked on hold (see {@link RequestResources#forwarded}), each resource
* looked up in its own service's stored state; none when the table gives the operation none.
*/
public List<RequestResources.Forwarded> forwarded(String operation, List<String> resources, String accountId) {
if (operation == null || operation.indexOf(':') < 0) {
return List.of();
}
return RequestResources.forwarded(operation, resources, accountId,
storedResourceArns(operation.substring(0, operation.indexOf(':'))), this::storedResourceArns);
}
/** The registered finder of the namespace's stored ARNs; null when there is none. */
private StoredResourceArns storedResourceArns(String namespace) {
if (storedResourceArns == null || storedResourceArns.isUnsatisfied()) {
@@ -0,0 +1,41 @@
package io.floci.aws.services.kms;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.iam.ResourcePolicyProvider;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
/**
* Supplies a KMS key's key policy to IAM policy evaluation, together with the account that owns the key: the one in
* its ARN, also when the key does not exist or has no policy, so a call on another account's key is judged as
* cross-account, needing the key policy as well as the caller's own. An alias has no policy of its own, and an ARN
* with its id open names no one key.
*/
@ApplicationScoped
public class KmsResourcePolicyProvider implements ResourcePolicyProvider {
private static final String KEY_PREFIX = "key/";
private final KmsService kms;
@Inject
public KmsResourcePolicyProvider(KmsService kms) {
this.kms = kms;
}
@Override
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
Optional<AwsArnUtils.Arn> parsed = ResourcePolicyProvider.regionalArn(resourceArn, "kms");
if (parsed.isEmpty()) {
return List.of();
}
String target = parsed.get().resource();
if (!target.startsWith(KEY_PREFIX) || target.length() == KEY_PREFIX.length() || target.contains("*")) {
return List.of();
}
return List.of(new ResourcePolicy(kms.findKeyPolicy(resourceArn).orElse(null), parsed.get().accountId()));
}
}
@@ -13,6 +13,7 @@ import io.floci.aws.core.common.StripedLocks;
import io.floci.aws.core.resource.ExplorerResource;
import io.floci.aws.core.resource.ResourceProvider;
import io.floci.aws.core.resource.SupportedResourceType;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.kms.keytype.KmsKeyType;
@@ -2342,6 +2343,89 @@ public class KmsService implements ResourceProvider {
}
}
/**
* The stored ARN of the key {@code keyIdOrArn} names in {@code accountId}'s {@code region}, whoever is calling: a
* key id or an alias name resolved in that account, or a key or alias ARN read in the account and Region it names.
* The enforcement filter reads this for a key another service's resource records, which may be another account's
* (a shared snapshot's). A reserved {@code alias/aws/<service>} of the caller's account names AWS's managed key
* of that service, which every account has whether anything read it before or not. Empty when that account holds
* no such key.
*/
public Optional<String> findKeyArnOfAccount(String keyIdOrArn, String accountId, String region) {
if (keyIdOrArn == null || keyIdOrArn.isBlank() || accountId == null || region == null) {
return Optional.empty();
}
String account = accountId;
String inRegion = region;
String id = keyIdOrArn;
if (AwsArnUtils.isArnFor(keyIdOrArn, "kms")) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(keyIdOrArn);
account = arn.accountId();
inRegion = arn.region();
id = arn.resource();
}
if (id.startsWith("alias/")) {
if (AwsManagedKeys.isReservedAlias(id) && account.equals(regionResolver.getAccountId())) {
// AWS's own key under alias/aws/<service> is in every account, read or not, as listKeys finds it.
ensureAwsManagedKeys(inRegion);
}
Optional<String> target = ofAccount(aliasStore, account, inRegion + "::" + id).map(KmsAlias::getTargetKeyId);
if (target.isEmpty()) {
return Optional.empty();
}
id = target.get();
} else if (id.startsWith("key/")) {
id = id.substring("key/".length());
}
return ofAccount(keyStore, account, inRegion + "::" + id).map(KmsKey::getArn).filter(arn -> !arn.isBlank());
}
/**
* Whether the key {@code keyArn} names, read in the account and Region of the ARN, is one AWS manages, whose key
* policy AWS writes to let every principal of the account use it through the service it belongs to.
*/
public boolean isAwsManagedKey(String keyArn) {
return keyAt(keyArn).map(key -> AWS_KEY_MANAGER.equals(key.getKeyManager())).orElse(false);
}
/**
* Whether the key {@code keyArn} names, read in the account and Region of the ARN, is one KMS uses for a
* cryptographic request: enabled, neither disabled nor pending deletion, which KMS refuses one with.
*/
public boolean isEnabledKey(String keyArn) {
return keyAt(keyArn).map(key -> "Enabled".equals(key.getKeyState())).orElse(false);
}
/** The key a key ARN names, read in the account and Region of the ARN, whoever is calling. */
private Optional<KmsKey> keyAt(String keyArn) {
if (!AwsArnUtils.isArnFor(keyArn, "kms")) {
return Optional.empty();
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(keyArn);
return arn.resource().startsWith("key/")
? ofAccount(keyStore, arn.accountId(), arn.region() + "::" + arn.resource().substring("key/".length()))
: Optional.empty();
}
/**
* 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.
*/
public Optional<String> findKeyPolicy(String keyArn) {
return keyAt(keyArn).map(KmsKey::getPolicy).filter(policy -> !policy.isBlank());
}
/**
* What {@code accountId} stores under {@code key}, an entry written before accounts were kept apart included; a
* store that keeps no accounts apart holds the caller's alone.
*/
private <V> Optional<V> ofAccount(StorageBackend<String, V> store, String accountId, String key) {
if (store instanceof AccountAwareStorageBackend<V> accounts) {
return accounts.getForAccount(accountId, key).or(() -> accounts.getLegacyForAccount(accountId, key));
}
return accountId.equals(regionResolver.getAccountId()) ? store.get(key) : 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
@@ -2388,7 +2472,7 @@ public class KmsService implements ResourceProvider {
if (!region.equals(arn.region())) {
throw new AwsException("NotFoundException", "Invalid arn " + arn.region(), 400);
}
// Floci does not evaluate key policies, so another account's key is never usable here;
// KMS serves the caller's own keys only, so another account's key is never usable here;
// without this the store would answer with the caller's own key or alias of that name.
if (!arn.accountId().equals(regionResolver.getAccountId())) {
throw new AwsException("NotFoundException", arn.resource().startsWith("alias/")
@@ -0,0 +1,51 @@
package io.floci.aws.services.kms;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
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.
*/
@ApplicationScoped
public class KmsStoredResourceArns implements StoredResourceArns {
private final KmsService kms;
private final RegionResolver regionResolver;
@Inject
public KmsStoredResourceArns(KmsService kms, RegionResolver regionResolver) {
this.kms = kms;
this.regionResolver = regionResolver;
}
@Override
public String namespace() {
return "kms";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return findInAccount(type, names, regionResolver.getAccountId(), region);
}
@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)
: Optional.empty();
}
/** 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);
}
}
@@ -74,6 +74,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
@@ -2161,6 +2162,33 @@ public class RedshiftService implements ManagedSecretRotator {
return named;
}
/**
* The snapshot an ARN names in its account, as a restore finds it, a cluster the ARN leaves open ({@code *})
* matching any: in the caller's account the copy kept in the ARN's Region before the snapshot itself, and in
* another account the snapshot itself alone, taken in the ARN's Region, as a shared one is restored.
*/
public Optional<Snapshot> findSnapshotAt(String snapshotArn) {
if (!AwsArnUtils.isArnFor(snapshotArn, "redshift")) {
return Optional.empty();
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(snapshotArn);
String resource = arn.resource();
int slash = resource.indexOf('/');
if (!resource.startsWith("snapshot:") || slash < 0) {
return Optional.empty();
}
String cluster = resource.substring("snapshot:".length(), slash);
String identifier = resource.substring(slash + 1);
Predicate<Snapshot> ofCluster = snapshot -> "*".equals(cluster) || cluster.equals(snapshot.getClusterIdentifier());
if (!arn.accountId().equals(clusters.accountId())) {
return snapshots.getForAccount(arn.accountId(), identifier).filter(ofCluster)
.filter(snapshot -> snapshot.getSnapshotArn() == null
|| AwsArnUtils.parse(snapshot.getSnapshotArn()).region().equals(arn.region()));
}
return snapshotCopies.getForAccount(arn.accountId(), copyKey(arn.region(), identifier)).filter(ofCluster)
.or(() -> snapshots.getForAccount(arn.accountId(), identifier).filter(ofCluster));
}
private boolean isInRequestRegion(Snapshot snapshot) {
if (snapshot.getSnapshotArn() == null) {
return true;
@@ -0,0 +1,43 @@
package io.floci.aws.services.redshift;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.redshift.model.Snapshot;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
/**
* What IAM asks Redshift of the resources a request names: what a snapshot records as its {@code KmsKeyId}, the key a
* restore asks KMS to decrypt with as the caller.
*/
@ApplicationScoped
public class RedshiftStoredResourceArns implements StoredResourceArns {
private final RedshiftService redshift;
@Inject
public RedshiftStoredResourceArns(RedshiftService redshift) {
this.redshift = redshift;
}
@Override
public String namespace() {
return "redshift";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
/** The key the snapshot an ARN names, in any account, records as its {@code KmsKeyId}. */
@Override
public Optional<String> recorded(String arn, String member) {
if (!"KmsKeyId".equals(member)) {
return Optional.empty();
}
return redshift.findSnapshotAt(arn).map(Snapshot::getKmsKeyId).filter(key -> !key.isBlank());
}
}
@@ -1006,6 +1006,23 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns
return findSnapshotOfAccount(account, names.getFirst(), region).map(RedshiftServerlessSnapshot::getSnapshotArn);
}
/**
* What the snapshot stored under {@code arn}, in any account, records as its {@code kmsKeyId}: its key, none for
* one under AWS's own key ({@value #AWS_OWNED_KMS_KEY}), which is no key of the account's.
*/
@Override
public Optional<String> recorded(String arn, String member) {
if (!"kmsKeyId".equals(member) || !AwsArnUtils.isArnFor(arn, "redshift-serverless")) {
return Optional.empty();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
return snapshots.scanForAccount(parsed.accountId(), key -> key.startsWith(parsed.region() + "::")).stream()
.filter(snapshot -> arn.equals(snapshot.getSnapshotArn()))
.map(RedshiftServerlessSnapshot::getKmsKeyId)
.filter(key -> key != null && !key.isBlank() && !AWS_OWNED_KMS_KEY.equals(key))
.findFirst();
}
/** The snapshot {@code snapshotName} of {@code accountId} in {@code region}, whoever is calling. */
public Optional<RedshiftServerlessSnapshot> findSnapshotOfAccount(String accountId, String snapshotName,
String region) {