feat(redshift-serverless): allow cross-account restore of a snapshot its policy shares (#7801) (#7803)

* feat(redshift-serverless): allow cross-account restore of a snapshot its policy shares (#7801)

RestoreFromSnapshot with an ownerAccount other than the caller's now reads the
snapshot from the owner's account and evaluates its resource policy for
redshift-serverless:RestoreFromSnapshot. A policy that allows the caller or the
caller's account grants the restore, an explicit Deny wins, and a snapshot with
no policy is not shared (AccessDeniedException). The dump is read from the
owner's directory and the restore targets the caller's namespace and workgroup.

* fix(redshift-serverless): restore a shared snapshot by the owner's ARN and check its policy under the service lock

A cross-account RestoreFromSnapshot with the owner's snapshotArn failed validation
because only the caller's account was accepted. The snapshot and its policy were also
checked before the service lock was taken, so a deletion, expiry or policy revocation
could land between the check and the restore. The check now runs under the lock.

* fix(redshift-serverless): evaluate a shared snapshot's policy through a ResourcePolicyProvider (#7801)

Move the snapshot policy check out of the service and into IAM enforcement, as SQS, SNS and S3 do:

- RedshiftServerlessResourcePolicyProvider supplies the snapshot's policy and the account in its ARN.
  A statement with no Resource, as in AWS's own PutResourcePolicy example, applies to the snapshot.
- redshift-serverless leaves NOT_COVERED: namespaces, workgroups and snapshots are found by name through
  StoredResourceArns, and RestoreFromSnapshot and GetSnapshot name the owner's snapshot when ownerAccount is set.
- Drop RedshiftServerlessSharedSnapshots and the snapshot-taking restoreFromSharedSnapshot overload.

* fix(redshift-serverless): derive snapshot account from the generator and find endpoint access ARNs (#7801)

Take ownerAccount as an account member in the request-resources generator and honor
account on found resources, replacing the hand-written CORRECTIONS entries and the
two-name branch in find. Answer endpointAccess in find. Share one call in
handleRestoreFromSnapshot.

* fix: derive account members from service models and reuse endpoint lookup
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-11 11:57:28 -04:00
1 parent 013e9b7c2e
commit e37f45f714
20 files changed
+923 -55

No files matched your search

@@ -52,8 +52,8 @@ final class RequestResourceMembers {
private static final Pattern LOCATION = Pattern.compile("\\{[A-Za-z0-9_]+}|\\?[A-Za-z0-9_.-]+");
/** The one id a child type's format appends to its parent's. */
private static final Pattern APPENDED_ID = Pattern.compile("[/:]\\$\\{\\w+}");
/** The keys a resource found by members does not take: it is read no other way, in the caller's account. */
private static final List<String> FOUND_ONLY = List.of("absent", "arnOf", "account", "fixed", "before");
/** The keys a resource found by members does not take: it is read no other way. */
private static final List<String> FOUND_ONLY = List.of("absent", "arnOf", "fixed", "before");
/** The keys of a resource named through a member naming another of its service's own: it is read no other way. */
private static final Set<String> THROUGH_KEYS = Set.of("types", "through", "when", "endpoint");
@@ -467,13 +467,9 @@ public final class RequestResources {
JsonNode body, String partition, String region, String accountId,
StoredResourceArns stored) {
RequestResourceMembers.ArnFormat format = formats.get(resource.types().getFirst());
String account = accountId;
if (resource.account() != null) {
List<String> given = isNull(body, resource.account()) ? List.of() : values(form, body, resource.account());
if (!given.isEmpty() && !ACCOUNT_ID.matcher(given.getFirst()).matches()) {
return;
}
account = given.isEmpty() ? accountId : given.getFirst();
String account = accountOf(resource, form, body, accountId);
if (account == null) {
return;
}
AwsArnUtils.Arn fromRequest = arnGiven(resource, form, body, formats);
List<Filling> fillings = new ArrayList<>(List.of(new Filling(resource.fixed(), fromRequest)));
@@ -526,11 +522,28 @@ public final class RequestResources {
}
}
/**
* The account the resource is in: the one its account member gives, the request's without one or with a JSON null
* for it; null when that member holds no account id, which its handler refuses.
*/
private static String accountOf(RequestResourceMembers.Resource resource, Map<String, String> form, JsonNode body,
String accountId) {
if (resource.account() == null) {
return accountId;
}
List<String> given = isNull(body, resource.account()) ? List.of() : values(form, body, resource.account());
if (given.isEmpty()) {
return accountId;
}
return ACCOUNT_ID.matcher(given.getFirst()).matches() ? given.getFirst() : null;
}
/**
* The resource of a type whose ARN is all an id its service mints, named by the members the table gives it
* ({@code find}), when the request gives each one value: the caller's resource {@code stored} finds under those
* values in the Region, or else its ARN with that id open, as for a create; none when it leaves one out or gives
* it a JSON null, which its handler reads as none.
* values in the Region, or else its ARN with that id open, as for a create; in the account its account member gives
* when it has one, which {@code stored} finds the resource of as {@code findInAccount}; none when it leaves one out
* or gives it a JSON null, which its handler reads as none.
*/
private static void found(Set<String> arns, RequestResourceMembers.Resource resource,
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
@@ -547,9 +560,15 @@ public final class RequestResources {
}
names.add(values.getFirst());
}
String account = accountOf(resource, form, body, accountId);
if (account == null) {
return;
}
String type = resource.types().getFirst();
Optional<String> found = stored == null ? Optional.empty() : stored.findByMembers(type, names, region);
arns.add(found.orElseGet(() -> render(formats.get(type).format(), Map.of(), partition, region, accountId)));
Optional<String> found = stored == null ? Optional.empty()
: account.equals(accountId) ? stored.findByMembers(type, names, region)
: stored.findInAccount(type, names, account, region);
arns.add(found.orElseGet(() -> render(formats.get(type).format(), Map.of(), partition, region, account)));
}
/**
@@ -47,6 +47,16 @@ public interface StoredResourceArns {
return List.of();
}
/**
* 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
* owner): the ARN that account's resource is stored under; empty when there is none, or the service finds none
* of another account.
*/
default Optional<String> findInAccount(String type, List<String> names, String account, String region) {
return Optional.empty();
}
/**
* Resolves an explicit {@code find} selector. An empty list indicates an incomplete selector, which a service
* may reject before IAM evaluation. This is distinct from an ordinary name filling an ARN's variables:
@@ -18,6 +18,7 @@ import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Pattern;
@@ -131,15 +132,23 @@ public class RedshiftServerlessEndpointAccessService implements Resettable {
}
private EndpointAccess require(String endpointName, String region) {
EndpointAccess endpoint = endpoints.get(storageKey(region, endpointName)).orElse(null);
if (endpoint != null && !isOnSameWorkgroup(endpoint, region)) {
return findEndpoint(endpointName, region)
.orElseThrow(() -> ServerlessSupport.notFound("The endpoint " + endpointName + " was not found."));
}
/** The ARN of the caller's endpoint of that name in the Region; empty when there is none. */
public synchronized Optional<String> findEndpointArn(String endpointName, String region) {
return findEndpoint(endpointName, region).map(EndpointAccess::getEndpointArn);
}
private Optional<EndpointAccess> findEndpoint(String endpointName, String region) {
return endpoints.get(storageKey(region, endpointName)).filter(endpoint -> {
if (isOnSameWorkgroup(endpoint, region)) {
return true;
}
endpoints.delete(storageKey(region, endpointName));
endpoint = null;
}
if (endpoint == null) {
throw ServerlessSupport.notFound("The endpoint " + endpointName + " was not found.");
}
return endpoint;
return false;
});
}
/** The region's endpoints whose workgroup is still there; any other is deleted as it is found. */
@@ -253,7 +253,7 @@ public class RedshiftServerlessJsonHandler {
* and Region.
*/
private Response handleGetSnapshot(JsonNode request, String region) {
return snapshotResponse(service.getSnapshot(snapshotNameOf(request, region), region));
return snapshotResponse(service.getSnapshot(snapshotNameOf(request, region, null), region));
}
private Response handleListSnapshots(JsonNode request, String region) {
@@ -281,11 +281,18 @@ public class RedshiftServerlessJsonHandler {
}
private Response handleRestoreFromSnapshot(JsonNode request, String region) {
RedshiftServerlessService.RestoreResult result = service.restoreFromSnapshot(
ServerlessSupport.text(request, "namespaceName"), ServerlessSupport.text(request, "workgroupName"),
snapshotNameOf(request, region), ServerlessSupport.text(request, "ownerAccount"),
ServerlessSupport.bool(request, "manageAdminPassword"),
ServerlessSupport.text(request, "adminPasswordSecretKmsKeyId"), region);
String ownerAccount = ServerlessSupport.text(request, "ownerAccount");
boolean shared = service.isOtherAccount(ownerAccount);
String snapshotName = snapshotNameOf(request, region, shared ? ownerAccount : null);
String namespaceName = ServerlessSupport.text(request, "namespaceName");
String workgroupName = ServerlessSupport.text(request, "workgroupName");
Boolean manageAdminPassword = ServerlessSupport.bool(request, "manageAdminPassword");
String kmsKeyId = ServerlessSupport.text(request, "adminPasswordSecretKmsKeyId");
RedshiftServerlessService.RestoreResult result = shared
? service.restoreFromSharedSnapshot(namespaceName, workgroupName, snapshotName, ownerAccount,
manageAdminPassword, kmsKeyId, region)
: service.restoreFromSnapshot(namespaceName, workgroupName, snapshotName, ownerAccount,
manageAdminPassword, kmsKeyId, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("namespace", namespaceNode(result.namespace()));
response.put("ownerAccount", result.snapshot().getOwnerAccount());
@@ -293,14 +300,21 @@ public class RedshiftServerlessJsonHandler {
return Response.ok(response).build();
}
/** The snapshot name from {@code snapshotName}, or recovered from {@code snapshotArn} when absent. */
private String snapshotNameOf(JsonNode request, String region) {
/**
* The snapshot name from {@code snapshotName}, or recovered from {@code snapshotArn} when absent.
* {@code ownerAccount} is the account the ARN must name, or null for the caller's own.
*/
private String snapshotNameOf(JsonNode request, String region, String ownerAccount) {
String snapshotName = ServerlessSupport.text(request, "snapshotName");
String snapshotArn = ServerlessSupport.text(request, "snapshotArn");
if (snapshotName != null && snapshotArn != null) {
throw ServerlessSupport.validation("snapshotName and snapshotArn cannot both be specified.");
}
return snapshotArn == null ? snapshotName : service.snapshotNameFromArn(snapshotArn, region);
if (snapshotArn == null) {
return snapshotName;
}
return ownerAccount == null ? service.snapshotNameFromArn(snapshotArn, region)
: service.snapshotNameFromArn(snapshotArn, region, ownerAccount, "snapshotArn");
}
private Response handleCreateUsageLimit(JsonNode request, String region) {
@@ -0,0 +1,84 @@
package io.floci.aws.services.redshiftserverless;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.iam.ResourcePolicyProvider;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.Optional;
/**
* Supplies the resource policy of a Redshift Serverless snapshot to IAM policy evaluation, together with the
* account that owns the snapshot: the one in its ARN, also when the snapshot does not exist or has no policy,
* so a call on another account's snapshot is judged as cross-account.
*/
@ApplicationScoped
public class RedshiftServerlessResourcePolicyProvider implements ResourcePolicyProvider {
private static final Logger LOG = Logger.getLogger(RedshiftServerlessResourcePolicyProvider.class);
private static final String SNAPSHOT_PREFIX = "snapshot/";
private final RedshiftServerlessService serverless;
private final RedshiftServerlessResourcePolicyService policies;
private final ObjectMapper objectMapper;
@Inject
public RedshiftServerlessResourcePolicyProvider(RedshiftServerlessService serverless,
RedshiftServerlessResourcePolicyService policies,
ObjectMapper objectMapper) {
this.serverless = serverless;
this.policies = policies;
this.objectMapper = objectMapper;
}
@Override
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
Optional<AwsArnUtils.Arn> parsed = ResourcePolicyProvider.regionalArn(resourceArn, "redshift-serverless");
if (parsed.isEmpty()) {
return List.of();
}
AwsArnUtils.Arn arn = parsed.get();
String target = arn.resource();
// An ARN with an id open (a create, or a snapshot that does not exist) names no one snapshot.
if (!target.startsWith(SNAPSHOT_PREFIX) || target.length() == SNAPSHOT_PREFIX.length()
|| target.contains("*")) {
return List.of();
}
String policy = serverless.findSnapshotOfAccount(arn.accountId(), target.substring(SNAPSHOT_PREFIX.length()),
arn.region())
.flatMap(snapshot -> policies.policyOfSnapshot(arn.accountId(), snapshot, arn.region()))
.map(document -> withResource(document, resourceArn))
.orElse(null);
return List.of(new ResourcePolicy(policy, arn.accountId()));
}
/**
* The policy with the snapshot's ARN as the {@code Resource} of each statement that names none. A resource
* policy is attached to its one resource, and AWS's own {@code PutResourcePolicy} example leaves {@code Resource}
* out, which the evaluator would read as a statement that matches nothing.
*/
String withResource(String document, String resourceArn) {
try {
JsonNode root = objectMapper.readTree(document);
JsonNode statements = root.path("Statement");
boolean changed = false;
for (JsonNode statement : statements.isArray() ? statements : List.of(statements)) {
if (statement instanceof ObjectNode object && !object.has("Resource") && !object.has("NotResource")) {
object.put("Resource", resourceArn);
changed = true;
}
}
return changed ? objectMapper.writeValueAsString(root) : document;
} catch (JsonProcessingException e) {
// The policy was a JSON object when it was stored, so this is not expected; the evaluator reads it as is.
LOG.warnv(e, "Could not read the resource policy of {0}", resourceArn);
return document;
}
}
}
@@ -20,8 +20,8 @@ import java.util.Optional;
import java.util.Set;
/**
* Resource policies for Redshift Serverless snapshots. A policy is stored and echoed, not
* evaluated: no principal named in it gains access.
* Resource policies for Redshift Serverless snapshots. A policy is stored and echoed here; IAM
* enforcement evaluates it through {@link RedshiftServerlessResourcePolicyProvider}.
*
* <p>A policy belongs to a snapshot but lives in its own store, so deleting the snapshot needs no
* hook here. Each read checks that the snapshot is still there and drops the policy otherwise.
@@ -67,6 +67,17 @@ public class RedshiftServerlessResourcePolicyService implements Resettable {
policies.delete(storageKey(region, resourceArn));
}
/**
* The policy on a snapshot of {@code ownerAccount}, read for whoever is calling. A policy left by a
* snapshot since replaced under the same name is not this snapshot's, so it is not returned.
*/
public synchronized Optional<String> policyOfSnapshot(String ownerAccount, RedshiftServerlessSnapshot snapshot,
String region) {
return policies.getForAccount(ownerAccount, storageKey(region, snapshot.getSnapshotArn()))
.filter(stored -> Objects.equals(stored.getSnapshotCreateTime(), snapshot.getSnapshotCreateTime()))
.map(ResourcePolicy::getPolicy);
}
synchronized void deleteExpiredSnapshotPolicy(
AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot> entry) {
RedshiftServerlessSnapshot snapshot = entry.value();
@@ -8,6 +8,7 @@ import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.redshift.SnapshotDumpCopier;
@@ -25,6 +26,7 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.interceptor.Interceptor;
import org.jboss.logging.Logger;
@@ -51,7 +53,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class RedshiftServerlessService implements Resettable {
public class RedshiftServerlessService implements Resettable, StoredResourceArns {
private static final Logger LOG = Logger.getLogger(RedshiftServerlessService.class);
public static final String DEFAULT_DB_NAME = "dev";
@@ -119,6 +121,9 @@ public class RedshiftServerlessService implements Resettable {
private final RedshiftServerlessRuntime runtime;
private final EmulatorConfig config;
private final RedshiftServerlessAdminSecrets adminSecrets;
/** Looked up lazily: the endpoint service is built on this one. */
@Inject
Instance<RedshiftServerlessEndpointAccessService> endpointAccess;
public RedshiftServerlessService(StorageFactory storageFactory, RegionResolver regionResolver,
RedshiftServerlessEndpoints endpoints, RedshiftServerlessRuntime runtime,
@@ -593,12 +598,17 @@ public class RedshiftServerlessService implements Resettable {
/** A stored dump path is trusted only while it still resolves inside this account's dump directory. */
private Optional<Path> trustedDump(RedshiftServerlessSnapshot snapshot, String region) {
return trustedDump(snapshot, workgroups.accountId(), region);
}
/** A stored dump path is trusted only while it still resolves inside the owning account's dump directory. */
private Optional<Path> trustedDump(RedshiftServerlessSnapshot snapshot, String accountId, String region) {
String stored = snapshot.getSqlDump();
if (stored == null || stored.isBlank()) {
return Optional.empty();
}
Path file = Paths.get(stored).toAbsolutePath().normalize();
return file.startsWith(dumpDir(region)) ? Optional.of(file) : Optional.empty();
return file.startsWith(dumpDir(accountId, region)) ? Optional.of(file) : Optional.empty();
}
private static void deleteDumpQuietly(Path dumpFile) {
@@ -624,7 +634,12 @@ public class RedshiftServerlessService implements Resettable {
}
public String snapshotNameFromArn(String snapshotArn, String region, String memberName) {
String prefix = regionResolver.buildArn("redshift-serverless", region, "snapshot/");
return snapshotNameFromArn(snapshotArn, region, workgroups.accountId(), memberName);
}
/** Same as above for a snapshot {@code ownerAccount} owns, as a cross-account restore names it. */
public String snapshotNameFromArn(String snapshotArn, String region, String ownerAccount, String memberName) {
String prefix = regionResolver.buildArn("redshift-serverless", region, ownerAccount, "snapshot/");
if (snapshotArn == null || !snapshotArn.startsWith(prefix) || snapshotArn.length() == prefix.length()) {
throw ServerlessSupport.validation(memberName + " does not identify a snapshot in this account and Region.");
}
@@ -908,6 +923,77 @@ public class RedshiftServerlessService implements Resettable {
if (ownerAccount != null && !ownerAccount.isBlank() && !ownerAccount.equals(snapshot.getOwnerAccount())) {
throw snapshotNotFound(snapshotName);
}
return restoreFrom(namespaceName, workgroupName, snapshot, workgroups.accountId(), manageAdminPassword,
adminPasswordSecretKmsKeyId, region);
}
/**
* Restores a snapshot another account owns. Whether the caller may is decided before this runs, by the
* snapshot's resource policy under IAM enforcement; the dump is read from the owner's directory.
*/
public synchronized RestoreResult restoreFromSharedSnapshot(String namespaceName, String workgroupName,
String snapshotName, String snapshotAccountId,
Boolean manageAdminPassword,
String adminPasswordSecretKmsKeyId, String region) {
validateManagedPassword(manageAdminPassword, null, adminPasswordSecretKmsKeyId);
validateNamespaceName(namespaceName);
RedshiftServerlessSnapshot snapshot = findSnapshotOfAccount(snapshotAccountId, snapshotName, region)
.orElseThrow(() -> snapshotNotFound(snapshotName));
requireAvailableSnapshot(snapshot);
return restoreFrom(namespaceName, workgroupName, snapshot, snapshotAccountId, manageAdminPassword,
adminPasswordSecretKmsKeyId, region);
}
/** Whether {@code ownerAccount} names an account other than the caller's. */
public boolean isOtherAccount(String ownerAccount) {
return ownerAccount != null && !ownerAccount.isBlank() && !ownerAccount.equals(workgroups.accountId());
}
@Override
public String namespace() {
return "redshift-serverless";
}
/**
* The ARN of the caller's resource the request names by its name. These ARNs end in an id Redshift Serverless
* gives them, which IAM policies are matched against.
*/
@Override
public Optional<String> find(String type, List<String> names, String region) {
if (names.isEmpty()) {
return Optional.empty();
}
String name = names.getFirst();
return switch (type) {
case "namespace" -> findNamespace(name, region).map(Namespace::getNamespaceArn);
case "workgroup" -> findWorkgroup(name, region).map(Workgroup::getWorkgroupArn);
case "snapshot" -> findSnapshot(name, region).map(RedshiftServerlessSnapshot::getSnapshotArn);
case "endpointAccess" -> endpointAccess == null || endpointAccess.isUnsatisfied() ? Optional.empty()
: endpointAccess.get().findEndpointArn(name, region);
default -> Optional.empty();
};
}
/** The ARN of the snapshot {@code account} owns under the name the request gives, which its policy may share. */
@Override
public Optional<String> findInAccount(String type, List<String> names, String account, String region) {
if (names.isEmpty() || !"snapshot".equals(type)) {
return Optional.empty();
}
return findSnapshotOfAccount(account, names.getFirst(), region).map(RedshiftServerlessSnapshot::getSnapshotArn);
}
/** The snapshot {@code snapshotName} of {@code accountId} in {@code region}, whoever is calling. */
public Optional<RedshiftServerlessSnapshot> findSnapshotOfAccount(String accountId, String snapshotName,
String region) {
return snapshotName == null ? Optional.empty()
: snapshots.getForAccount(accountId, storageKey(region, snapshotName));
}
private RestoreResult restoreFrom(String namespaceName, String workgroupName, RedshiftServerlessSnapshot snapshot,
String snapshotAccountId, Boolean manageAdminPassword,
String adminPasswordSecretKmsKeyId, String region) {
String snapshotName = snapshot.getSnapshotName();
Workgroup workgroup = getWorkgroup(workgroupName, region);
if (!namespaceName.equals(workgroup.getNamespaceName())) {
throw ServerlessSupport.validation("The workgroup " + workgroupName + " does not belong to the namespace "
@@ -917,7 +1003,7 @@ public class RedshiftServerlessService implements Resettable {
Runnable restoreCredentials = () -> restoreSnapshotCredentials(namespace, snapshot, manageAdminPassword,
adminPasswordSecretKmsKeyId, region);
if (snapshot.getSqlDump() != null && hasLiveRuntime(workgroup)) {
Path dump = trustedDump(snapshot, region).filter(Files::exists).orElseThrow(() -> new AwsException(
Path dump = trustedDump(snapshot, snapshotAccountId, region).filter(Files::exists).orElseThrow(() -> new AwsException(
"InternalServerException", "The data of snapshot " + snapshotName + " is no longer available.",
500));
runtime.restoreSnapshot(workgroups.accountId(), region, workgroupName, workgroup.getMasterUsername(),