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

+3 -3
View File
@@ -27,7 +27,7 @@ For the upstream API shape, see the [Amazon Redshift Serverless API Reference](h
| `ListSnapshots` | Page through the snapshots in the Region, filtered by `namespaceName`, `namespaceArn`, `ownerAccount` and a `startTime`/`endTime` window |
| `UpdateSnapshot` | Change a snapshot's `retentionPeriod` (-1 for indefinite); an omitted period leaves it unchanged |
| `DeleteSnapshot` | Remove a snapshot and return it |
| `RestoreFromSnapshot` | Restore into an existing namespace and workgroup, replaying the snapshot's dump into the workgroup's database; neither is created |
| `RestoreFromSnapshot` | Restore into an existing namespace and workgroup, replaying the snapshot's dump into the workgroup's database; neither is created. With `ownerAccount` set to another account, the snapshot is restored from that account. With IAM enforcement on, the snapshot's resource policy must allow the caller `redshift-serverless:RestoreFromSnapshot` and the caller's own policies must too, or the call is refused with `AccessDeniedException` |
| `CreateUsageLimit` | Set a usage limit on a workgroup, defaulting `period` to `monthly` and `breachAction` to `log` |
| `GetUsageLimit` | Return a usage limit by `usageLimitId` |
| `ListUsageLimits` | Page through the usage limits in the Region, filtered by `resourceArn` and `usageType` |
@@ -37,7 +37,7 @@ For the upstream API shape, see the [Amazon Redshift Serverless API Reference](h
| `ListTagsForResource` | Return the tags on the namespace or workgroup named by `resourceArn` |
| `TagResource` | Merge tags into the namespace or workgroup named by `resourceArn` |
| `UntagResource` | Remove tags by key from the namespace or workgroup named by `resourceArn` |
| `PutResourcePolicy` | Replace the resource policy of a snapshot; the policy must be a JSON object and is stored, not evaluated |
| `PutResourcePolicy` | Replace the resource policy of a snapshot; the policy must be a JSON object and is evaluated, under IAM enforcement, when another account restores the snapshot with `RestoreFromSnapshot` |
| `GetResourcePolicy` | Return the resource policy of a snapshot |
| `DeleteResourcePolicy` | Remove the resource policy of a snapshot |
| `GetTrack` | Return one of the release tracks `current` and `trailing`; a track carries no `workgroupVersion` |
@@ -143,7 +143,7 @@ aws redshift-serverless delete-namespace --namespace-name analytics
```
- **Snapshots dump the database.** While the namespace's workgroup is running, `CreateSnapshot` runs `pg_dump` on its container and stores the dump under `<persistent-path>/redshift-serverless-dumps/<account>/<region>/`. `RestoreFromSnapshot` drops every user schema (the catalog bootstrap schema excepted) and replays the dump with `psql`, stopping at the first failing statement, so rows written after the snapshot are gone. The current contents are dumped first and put back if replay or credential changes fail, and a restore whose recorded dump file has gone missing fails instead of reporting success. A snapshot taken with no running workgroup is metadata only, and restoring it leaves the database untouched. `DeleteSnapshot` removes the dump. Snapshot ARNs use the snapshot name as their id, snapshot names are 3-255 lowercase letters, digits and hyphens, and `retentionPeriod` is `-1` (indefinite, the default) or 1 to 3653 days. Snapshots are taggable by ARN. `snapshotName` and `snapshotArn` cannot be sent together. Floci's own `floci_internal` bootstrap schema, which feeds the `svv_external_*` views from the Glue catalog, is left out of both the dump and the reset, matching AWS where the Glue catalog is outside a namespace snapshot, so a client schema with that exact name is not captured. Snapshots with finite retention expire at their creation time plus the retention period. A dedicated background worker removes expired metadata, dumps and resource policies across all accounts and Regions. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_ENABLED=false`. Indefinite snapshots are preserved. Cleanup serializes with restore and retention updates. A failed cleanup remains `DELETED`, rejects restore and retention updates, and is retried on later sweeps, including after restart. Persistent and WAL storage commit the deletion marker synchronously; hybrid storage retains its periodic-flush durability. Missing dump files are treated as already removed; untrusted paths are preserved and logged. Cross-Region copies are described under snapshot copy configurations below, and an expired copy is removed like any other snapshot.
- **`UpdateSnapshot` changes only `retentionPeriod`.** It is validated like `CreateSnapshot` (`-1` or 1 to 3653 days), `-1` makes the snapshot indefinite, and an omitted period leaves the snapshot unchanged. `snapshotRemainingDays` keeps counting from the creation time, because Floci stores no separate retention start.
- **Resource policies are recorded, not acted on.** A policy is stored per account and Region, echoed in the shape of the API model, and dropped on read once the snapshot it belongs to is gone. A snapshot recreated under the same name is a different snapshot: the record keeps the snapshot's creation time, so the policy is not inherited. `PutResourcePolicy` accepts a JSON object for a snapshot ARN of this account and Region; no principal in it gains access. A foreign or non-snapshot ARN is a `ValidationException`.
- **Resource policies grant cross-account restore only.** A policy is stored per account and Region, echoed in the shape of the API model, and dropped on read once the snapshot it belongs to is gone. A snapshot recreated under the same name is a different snapshot: the record keeps the snapshot's creation time, so the policy is not inherited. `PutResourcePolicy` accepts a JSON object for a snapshot ARN of this account and Region. Under IAM enforcement the policy is read like the resource policy of an SQS queue: a request naming a snapshot of another account (`snapshotName` with `ownerAccount`, or `snapshotArn`) is checked on that account's snapshot ARN, so the policy must allow the caller (or the caller's account) `redshift-serverless:RestoreFromSnapshot`, an explicit `Deny` wins, a snapshot with no policy is not shared, and the caller's own identity policies must allow the call as well. A statement with no `Resource`, as in AWS's own `PutResourcePolicy` example, applies to the snapshot the policy is on. With enforcement off nothing evaluates the policy. The dump is read from the owner's directory and the workgroup and namespace restored into are the caller's. No other action reads the policy yet. A foreign or non-snapshot ARN is a `ValidationException`.
- **Endpoint access is recorded, not acted on.** An endpoint is stored per account and Region, echoed in the shape of the API model, and dropped on read once its workgroup is gone; a workgroup recreated under the same name is a different workgroup and does not inherit it. `CreateEndpointAccess` creates no VPC endpoint. `address` and `port` are the workgroup's own, so a client can connect; `vpcEndpoint` carries a generated id and one network interface per subnet, without a `vpcId`, and `ListEndpointAccess` with a `vpcId` returns nothing. `vpcSecurityGroupIds` is optional. Endpoint names are 1 to 30 letters, digits or hyphens, start with a letter, and contain no consecutive or trailing hyphens. Security groups are the only member `UpdateEndpointAccess` changes.
- **Custom domain associations are recorded, not acted on.** An association is stored per account and Region and dropped on read once its workgroup is gone; a workgroup recreated under the same name does not inherit it. A workgroup has at most one custom domain association. The certificate expiry time comes from ACM when the certificate exists in the emulator.
- **Snapshot copy configurations copy snapshots.** A background sweep copies every `AVAILABLE` snapshot of the namespace that was taken at or after the configuration's creation into the destination Region, with its dump and metadata. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_ENABLED=false`. The copy is a snapshot of its own: it keeps the name, namespace name, owner, tags and admin user of the source, gets an ARN in the destination Region, uses `destinationKmsKeyId` as its key, and counts its `snapshotRetentionPeriod` (indefinite when omitted or `-1`) from the moment it is copied. Describe, restore, delete and expiration treat it like any other snapshot, and restoring it needs an existing namespace and workgroup in the destination Region. A copy is never copied on. The source records where it has been copied, so deleting or expiring the copy does not bring it back, and a retry or restart after a crash makes no second copy. If a snapshot of the same name that is not a copy of this source already exists in the destination Region, Floci keeps it, logs a warning and does not copy. A snapshot deleted and taken again under the same name is copied again and replaces the earlier copy of that name; each copy has its own dump file, and the earlier one is removed only after the replacement is saved, so a failed replacement leaves the earlier copy restorable. A failed copy, such as a missing dump file, leaves the source untouched and is retried by the next sweep. A crash in the middle of a copy can leave an unreferenced dump file in the destination directory, which a reset removes. `UpdateSnapshotCopyConfiguration` changes the retention of copies made afterwards, not of existing ones. Deleting the configuration stops further copies and keeps the copies already made. These are Floci choices where AWS does not say otherwise. A configuration is stored per account and Region and dropped on read once its namespace is gone; a namespace recreated under the same name does not inherit it. The destination must be a known Region in the same partition as the namespace's and must differ from it, and a namespace has only one configuration at a time (`ConflictException`). Delete the existing configuration before choosing another destination Region.
@@ -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(),
@@ -1,11 +1,11 @@
{
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-11", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "macie2": ["macie2"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "rekognition": ["rekognition"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
"namespaces": {"access-analyzer": ["accessanalyzer"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalyticsv2"], "logs": ["logs"], "macie2": ["macie2"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
"clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"},
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"],
"notCovered": {"account": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its Line truncated
"notCovered": {"account": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its Line truncated
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web"],
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "controltower": {"Baseline": "arn:${Partition}:controltower:${Region}::baseline/${BaselineId}", "EnabledBaseline": "arn:${Partition}:controltower:${Region}:${Account}:enabledbaseline/${EnabledBaselineId}", "EnabledControl": "arn:${Partition}:controltower:${Region}:${Account}:enabledcontrol/${EnabledControlId}", "LandingZone": "arn:${Partition}:controltower:${Region}:${Account}:landingzone/${LandingZoneId}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "datasync": {"agent": "arn:${Partition}:datasync:${Region}:${Account}:agent/${AgenLine truncated
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "controltower": {"Baseline": "arn:${Partition}:controltower:${Region}::baseline/${BaselineId}", "EnabledBaseline": "arn:${Partition}:controltower:${Region}:${Account}:enabledbaseline/${EnabledBaselineId}", "EnabledControl": "arn:${Partition}:controltower:${Region}:${Account}:enabledcontrol/${EnabledControlId}", "LandingZone": "arn:${Partition}:controltower:${Region}:${Account}:landingzone/${LandingZoneId}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "datasync": {"agent": "arn:${Partition}:datasync:${Region}:${Account}:agent/${AgenLine truncated
"unqualified": {"states": ["statemachine"]},
"mintedIds": {"events": ["api-destination", "connection"]},
"operations": {
@@ -2545,6 +2545,71 @@
"redshift-data:ListSessions": {"action": "redshift-data:ListSessions", "types": [], "resources": []},
"redshift-data:ListStatements": {"action": "redshift-data:ListStatements", "types": [], "resources": []},
"redshift-data:ListTables": {"action": "redshift-data:ListTables", "types": ["cluster", "workgroup"], "resources": [{"types": ["cluster", "workgroup"], "arn": "SecretArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]}]},
"redshift-serverless:ConvertRecoveryPointToSnapshot": {"action": "redshift-serverless:ConvertRecoveryPointToSnapshot", "types": ["recoveryPoint", "snapshot"], "resources": [{"type": "recoveryPoint", "fill": {"RecoveryPointId": "recoveryPointId"}}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"]}]},
"redshift-serverless:CreateCustomDomainAssociation": {"action": "redshift-serverless:CreateCustomDomainAssociation", "types": ["workgroup"], "resources": [{"types": ["workgroup"], "arn": "customDomainCertificateArn"}, {"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:CreateEndpointAccess": {"action": "redshift-serverless:CreateEndpointAccess", "types": ["endpointAccess"], "resources": [{"type": "endpointAccess", "fill": {}, "find": ["endpointName"]}]},
"redshift-serverless:CreateNamespace": {"action": "redshift-serverless:CreateNamespace", "types": ["namespace"], "resources": [{"types": ["namespace"], "arn": "defaultIamRoleArn"}, {"types": ["namespace"], "arn": "redshiftIdcApplicationArn"}, {"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:CreateReservation": {"action": "redshift-serverless:CreateReservation", "types": [], "resources": []},
"redshift-serverless:CreateScheduledAction": {"action": "redshift-serverless:CreateScheduledAction", "types": ["namespace"], "resources": [{"types": ["namespace"], "arn": "roleArn"}, {"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:CreateSnapshot": {"action": "redshift-serverless:CreateSnapshot", "types": ["namespace", "snapshot"], "resources": [{"type": "namespace", "fill": {}, "find": ["namespaceName"]}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"], "made": true}]},
"redshift-serverless:CreateSnapshotCopyConfiguration": {"action": "redshift-serverless:CreateSnapshotCopyConfiguration", "types": ["namespace"], "resources": [{"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:CreateUsageLimit": {"action": "redshift-serverless:CreateUsageLimit", "types": [], "resources": []},
"redshift-serverless:CreateWorkgroup": {"action": "redshift-serverless:CreateWorkgroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:DeleteCustomDomainAssociation": {"action": "redshift-serverless:DeleteCustomDomainAssociation", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:DeleteEndpointAccess": {"action": "redshift-serverless:DeleteEndpointAccess", "types": ["endpointAccess"], "resources": [{"type": "endpointAccess", "fill": {}, "find": ["endpointName"]}]},
"redshift-serverless:DeleteNamespace": {"action": "redshift-serverless:DeleteNamespace", "types": ["namespace"], "resources": [{"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:DeleteResourcePolicy": {"action": "redshift-serverless:DeleteResourcePolicy", "types": [], "resources": []},
"redshift-serverless:DeleteScheduledAction": {"action": "redshift-serverless:DeleteScheduledAction", "types": [], "resources": []},
"redshift-serverless:DeleteSnapshot": {"action": "redshift-serverless:DeleteSnapshot", "types": ["snapshot"], "resources": [{"type": "snapshot", "fill": {}, "find": ["snapshotName"]}]},
"redshift-serverless:DeleteSnapshotCopyConfiguration": {"action": "redshift-serverless:DeleteSnapshotCopyConfiguration", "types": [], "resources": []},
"redshift-serverless:DeleteUsageLimit": {"action": "redshift-serverless:DeleteUsageLimit", "types": [], "resources": []},
"redshift-serverless:DeleteWorkgroup": {"action": "redshift-serverless:DeleteWorkgroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:GetCredentials": {"action": "redshift-serverless:GetCredentials", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:GetCustomDomainAssociation": {"action": "redshift-serverless:GetCustomDomainAssociation", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:GetEndpointAccess": {"action": "redshift-serverless:GetEndpointAccess", "types": ["endpointAccess"], "resources": [{"type": "endpointAccess", "fill": {}, "find": ["endpointName"]}]},
"redshift-serverless:GetIdentityCenterAuthToken": {"action": "redshift-serverless:GetIdentityCenterAuthToken", "types": ["workgroup"], "resources": []},
"redshift-serverless:GetNamespace": {"action": "redshift-serverless:GetNamespace", "types": ["namespace"], "resources": [{"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:GetRecoveryPoint": {"action": "redshift-serverless:GetRecoveryPoint", "types": ["recoveryPoint"], "resources": [{"type": "recoveryPoint", "fill": {"RecoveryPointId": "recoveryPointId"}}]},
"redshift-serverless:GetReservation": {"action": "redshift-serverless:GetReservation", "types": [], "resources": []},
"redshift-serverless:GetReservationOffering": {"action": "redshift-serverless:GetReservationOffering", "types": [], "resources": []},
"redshift-serverless:GetResourcePolicy": {"action": "redshift-serverless:GetResourcePolicy", "types": [], "resources": []},
"redshift-serverless:GetScheduledAction": {"action": "redshift-serverless:GetScheduledAction", "types": [], "resources": []},
"redshift-serverless:GetSnapshot": {"action": "redshift-serverless:GetSnapshot", "types": ["snapshot"], "resources": [{"types": ["snapshot"], "arn": "snapshotArn"}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"], "account": "ownerAccount"}]},
"redshift-serverless:GetTableRestoreStatus": {"action": "redshift-serverless:GetTableRestoreStatus", "types": [], "resources": []},
"redshift-serverless:GetTrack": {"action": "redshift-serverless:GetTrack", "types": [], "resources": []},
"redshift-serverless:GetUsageLimit": {"action": "redshift-serverless:GetUsageLimit", "types": [], "resources": []},
"redshift-serverless:GetWorkgroup": {"action": "redshift-serverless:GetWorkgroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:ListCustomDomainAssociations": {"action": "redshift-serverless:ListCustomDomainAssociations", "types": [], "resources": []},
"redshift-serverless:ListEndpointAccess": {"action": "redshift-serverless:ListEndpointAccess", "types": ["endpointAccess"], "resources": []},
"redshift-serverless:ListManagedWorkgroups": {"action": "redshift-serverless:ListManagedWorkgroups", "types": [], "resources": []},
"redshift-serverless:ListNamespaces": {"action": "redshift-serverless:ListNamespaces", "types": [], "resources": []},
"redshift-serverless:ListRecoveryPoints": {"action": "redshift-serverless:ListRecoveryPoints", "types": ["recoveryPoint"], "resources": [{"types": ["recoveryPoint"], "arn": "namespaceArn"}]},
"redshift-serverless:ListReservationOfferings": {"action": "redshift-serverless:ListReservationOfferings", "types": [], "resources": []},
"redshift-serverless:ListReservations": {"action": "redshift-serverless:ListReservations", "types": [], "resources": []},
"redshift-serverless:ListScheduledActions": {"action": "redshift-serverless:ListScheduledActions", "types": [], "resources": []},
"redshift-serverless:ListSnapshotCopyConfigurations": {"action": "redshift-serverless:ListSnapshotCopyConfigurations", "types": ["namespace"], "resources": [{"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:ListSnapshots": {"action": "redshift-serverless:ListSnapshots", "types": ["snapshot"], "resources": [{"types": ["snapshot"], "arn": "namespaceArn"}]},
"redshift-serverless:ListTableRestoreStatus": {"action": "redshift-serverless:ListTableRestoreStatus", "types": [], "resources": []},
"redshift-serverless:ListTagsForResource": {"action": "redshift-serverless:ListTagsForResource", "types": ["namespace", "workgroup"], "resources": [{"types": ["namespace", "workgroup"], "arn": "resourceArn"}]},
"redshift-serverless:ListTracks": {"action": "redshift-serverless:ListTracks", "types": [], "resources": []},
"redshift-serverless:ListUsageLimits": {"action": "redshift-serverless:ListUsageLimits", "types": [], "resources": []},
"redshift-serverless:ListWorkgroups": {"action": "redshift-serverless:ListWorkgroups", "types": [], "resources": []},
"redshift-serverless:PutResourcePolicy": {"action": "redshift-serverless:PutResourcePolicy", "types": [], "resources": []},
"redshift-serverless:RestoreFromRecoveryPoint": {"action": "redshift-serverless:RestoreFromRecoveryPoint", "types": ["recoveryPoint"], "resources": [{"type": "recoveryPoint", "fill": {"RecoveryPointId": "recoveryPointId"}}]},
"redshift-serverless:RestoreFromSnapshot": {"action": "redshift-serverless:RestoreFromSnapshot", "types": ["snapshot"], "resources": [{"types": ["snapshot"], "arn": "snapshotArn"}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"], "account": "ownerAccount"}]},
"redshift-serverless:RestoreTableFromRecoveryPoint": {"action": "redshift-serverless:RestoreTableFromRecoveryPoint", "types": ["namespace", "recoveryPoint"], "resources": [{"type": "recoveryPoint", "fill": {"RecoveryPointId": "recoveryPointId"}}, {"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:RestoreTableFromSnapshot": {"action": "redshift-serverless:RestoreTableFromSnapshot", "types": ["namespace", "snapshot"], "resources": [{"type": "namespace", "fill": {}, "find": ["namespaceName"]}, {"type": "snapshot", "fill": {}, "find": ["snapshotName"]}]},
"redshift-serverless:TagResource": {"action": "redshift-serverless:TagResource", "types": ["namespace", "recoveryPoint", "snapshot", "workgroup"], "resources": [{"types": ["namespace", "recoveryPoint", "snapshot", "workgroup"], "arn": "resourceArn"}]},
"redshift-serverless:UntagResource": {"action": "redshift-serverless:UntagResource", "types": ["namespace", "recoveryPoint", "snapshot", "workgroup"], "resources": [{"types": ["namespace", "recoveryPoint", "snapshot", "workgroup"], "arn": "resourceArn"}]},
"redshift-serverless:UpdateCustomDomainAssociation": {"action": "redshift-serverless:UpdateCustomDomainAssociation", "types": ["workgroup"], "resources": [{"types": ["workgroup"], "arn": "customDomainCertificateArn"}, {"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift-serverless:UpdateEndpointAccess": {"action": "redshift-serverless:UpdateEndpointAccess", "types": ["endpointAccess"], "resources": [{"type": "endpointAccess", "fill": {}, "find": ["endpointName"]}]},
"redshift-serverless:UpdateLakehouseConfiguration": {"action": "redshift-serverless:UpdateLakehouseConfiguration", "types": ["namespace"], "resources": [{"types": ["namespace"], "arn": "lakehouseIdcApplicationArn"}, {"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:UpdateNamespace": {"action": "redshift-serverless:UpdateNamespace", "types": ["namespace"], "resources": [{"types": ["namespace"], "arn": "defaultIamRoleArn"}, {"type": "namespace", "fill": {}, "find": ["namespaceName"]}]},
"redshift-serverless:UpdateScheduledAction": {"action": "redshift-serverless:UpdateScheduledAction", "types": [], "resources": []},
"redshift-serverless:UpdateSnapshot": {"action": "redshift-serverless:UpdateSnapshot", "types": ["snapshot"], "resources": [{"type": "snapshot", "fill": {}, "find": ["snapshotName"]}]},
"redshift-serverless:UpdateSnapshotCopyConfiguration": {"action": "redshift-serverless:UpdateSnapshotCopyConfiguration", "types": [], "resources": []},
"redshift-serverless:UpdateUsageLimit": {"action": "redshift-serverless:UpdateUsageLimit", "types": [], "resources": []},
"redshift-serverless:UpdateWorkgroup": {"action": "redshift-serverless:UpdateWorkgroup", "types": ["workgroup"], "resources": [{"type": "workgroup", "fill": {}, "find": ["workgroupName"]}]},
"redshift:AcceptReservedNodeExchange": {"action": "redshift:AcceptReservedNodeExchange", "types": [], "resources": []},
"redshift:AddPartner": {"action": "redshift:AddPartner", "types": [], "resources": []},
"redshift:AssociateDataShareConsumer": {"action": "redshift:AssociateDataShareConsumer", "types": ["datashare"], "resources": [{"types": ["datashare"], "arn": "ConsumerArn"}, {"types": ["datashare"], "arn": "DataShareArn"}]},
@@ -140,11 +140,14 @@ class RequestResourceMembersTest {
for (String bad : List.of("\"fill\":{},\"find\":[]", "\"fill\":{},\"find\":[\"Ids[]\"]",
"\"fill\":{\"Id\":\"Id\"},\"find\":[\"Namespace\"]", "\"fill\":{},\"find\":\"Namespace\"",
"\"fill\":{},\"find\":{\"a\":\"Namespace\"}",
"\"fill\":{},\"find\":[\"Namespace\"],\"account\":\"registryId\"",
"\"fill\":{},\"find\":[\"Namespace\"],\"absent\":{\"Namespace\":\"ecs\"}")) {
assertThrows(IllegalStateException.class,
() -> parse(document(formats, "{\"type\":\"target\"," + bad + "}")), bad);
}
// The account its member gives is the one it is found in.
assertEquals(new Member("registryId", false), parseUnchecked(document(formats,
"{\"type\":\"target\",\"fill\":{},\"find\":[\"Namespace\"],\"account\":\"registryId\"}"))
.operations().get("a:Op").getFirst().account());
// Nor beside an ARN member, which names the resource itself.
assertThrows(IllegalStateException.class, () -> parse(document(formats,
"{\"types\":[\"target\"],\"arn\":\"TargetArn\",\"find\":[\"Namespace\"]}")));
@@ -631,6 +631,48 @@ class RequestResourcesTest {
json("{\"ResourceArn\":\"" + key + "\"}"), "aws", "us-east-1", "000000000000", stored));
}
/**
* A snapshot another account shares is named by its name and the {@code ownerAccount} of that account: it is that
* account's snapshot the request acts on, the one {@code findInAccount} gives or else the owner's ARN with its id
* open, and a request naming no owner acts on the caller's own.
*/
@Test
void aResourceFoundByMembersIsInTheAccountItsAccountMemberGives() {
String own = "arn:aws:redshift-serverless:us-east-1:000000000000:snapshot/own-id";
String theirs = "arn:aws:redshift-serverless:us-east-1:111111111111:snapshot/their-id";
StoredResourceArns stored = new StoredResourceArns() {
@Override
public String namespace() {
return "redshift-serverless";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return List.of("snap").equals(names) ? Optional.of(own) : Optional.empty();
}
@Override
public Optional<String> findInAccount(String type, List<String> names, String account, String region) {
return "111111111111".equals(account) && List.of("snap").equals(names)
? Optional.of(theirs) : Optional.empty();
}
};
assertEquals(List.of(own), RequestResources.of("redshift-serverless:GetSnapshot",
json("{\"snapshotName\":\"snap\"}"), "aws", "us-east-1", "000000000000", stored));
assertEquals(List.of(theirs), RequestResources.of("redshift-serverless:GetSnapshot",
json("{\"snapshotName\":\"snap\",\"ownerAccount\":\"111111111111\"}"), "aws", "us-east-1",
"000000000000", stored));
// A snapshot the owner has none of by that name has its id open in the owner's account.
assertEquals(List.of("arn:aws:redshift-serverless:us-east-1:222222222222:snapshot/*"),
RequestResources.of("redshift-serverless:GetSnapshot",
json("{\"snapshotName\":\"other\",\"ownerAccount\":\"222222222222\"}"), "aws",
"us-east-1", "000000000000", stored));
// An owner that is no account id names no resource.
assertEquals(List.of(), RequestResources.of("redshift-serverless:GetSnapshot",
json("{\"snapshotName\":\"snap\",\"ownerAccount\":\"nope\"}"), "aws", "us-east-1",
"000000000000", stored));
}
/**
* A scalable target's ARN is all the id Application Auto Scaling mints, while its requests name it by its service
* namespace, resource id and scalable dimension: it is the one stored under those, or else has its id open, as a
@@ -62,6 +62,11 @@ class RedshiftServerlessAdministrationHandlerTest {
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
+ invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"
+ invocation.getArgument(2, String.class));
when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class),
any(String.class)))
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
+ invocation.getArgument(1, String.class) + ":" + invocation.getArgument(2, String.class)
+ ":" + invocation.getArgument(3, String.class));
RedshiftServerlessEndpoints endpoints = mock(RedshiftServerlessEndpoints.class);
when(endpoints.allocate()).thenReturn(new Endpoint("localhost", 7100));
RedshiftServerlessRuntime runtime = mock(RedshiftServerlessRuntime.class);
@@ -618,6 +618,46 @@ class RedshiftServerlessIntegrationTest {
.body("message", equalTo("resourceArn does not identify a snapshot in this account and Region."));
}
@Test
void aSnapshotAnotherAccountOwnsIsRestoredFromItsOwnersAccount() {
String owner = "111122223333";
String caller = "444455556666";
String stranger = "777788889999";
callAs(owner, "CreateNamespace", "{\"namespaceName\":\"share-src\",\"adminUsername\":\"admin\"}").statusCode(200);
String snapshotArn = callAs(owner, "CreateSnapshot",
"{\"snapshotName\":\"share-snap\",\"namespaceName\":\"share-src\"}")
.statusCode(200).extract().path("snapshot.snapshotArn");
callAs(caller, "CreateNamespace", "{\"namespaceName\":\"share-dst\",\"adminUsername\":\"admin\"}").statusCode(200);
callAs(caller, "CreateWorkgroup", "{\"workgroupName\":\"share-wg\",\"namespaceName\":\"share-dst\"}")
.statusCode(200);
String restore = "{\"namespaceName\":\"share-dst\",\"workgroupName\":\"share-wg\","
+ "\"snapshotName\":\"share-snap\",\"ownerAccount\":\"" + owner + "\"}";
// Whether the snapshot's policy shares it is IAM enforcement's to decide, which this class leaves off.
callAs(caller, "RestoreFromSnapshot", restore)
.statusCode(200)
.body("ownerAccount", equalTo(owner))
.body("snapshotName", equalTo("share-snap"))
.body("namespace.namespaceName", equalTo("share-dst"));
// A snapshot that is not the owner's is not found, however it is named.
callAs(caller, "RestoreFromSnapshot", restore.replace("share-snap", "no-such-snap")).statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
callAs(caller, "RestoreFromSnapshot", restore.replace(owner, stranger)).statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
// The owner's snapshot ARN names the snapshot as well as its name does; one of another account does not.
String byArn = "{\"namespaceName\":\"share-dst\",\"workgroupName\":\"share-wg\","
+ "\"snapshotArn\":\"" + snapshotArn + "\",\"ownerAccount\":\"" + owner + "\"}";
callAs(caller, "RestoreFromSnapshot", byArn).statusCode(200)
.body("ownerAccount", equalTo(owner))
.body("snapshotName", equalTo("share-snap"));
callAs(caller, "RestoreFromSnapshot", byArn.replace("\"ownerAccount\":\"" + owner, "\"ownerAccount\":\"" + stranger))
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void resourcePolicyIsIsolatedPerAccount() {
String accountA = "111122223333";
@@ -14,7 +14,9 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -95,4 +97,31 @@ class RedshiftServerlessResourcePolicyExpirationTest {
service.deleteExpiredSnapshotPolicy(entry);
assertTrue(store.getForAccount(account, key).isPresent());
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void policyOfSnapshotIsReadFromTheOwnersAccountForTheSameSnapshotGeneration() {
String owner = "999999999999";
String region = "us-east-1";
String arn = "arn:aws:redshift-serverless:us-east-1:" + owner + ":snapshot/shared-snap";
Instant created = Instant.parse("2030-01-01T00:00:00Z");
AccountAwareStorageBackend<ResourcePolicy> store = AccountAwareStorageBackend.inMemory("123456789012");
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-resourcepolicies.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
RedshiftServerlessResourcePolicyService service = new RedshiftServerlessResourcePolicyService(
factory, mock(RedshiftServerlessService.class), new ObjectMapper());
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
snapshot.setSnapshotArn(arn);
snapshot.setSnapshotCreateTime(created);
ResourcePolicy policy = new ResourcePolicy(arn, "{\"Version\":\"2012-10-17\"}");
policy.setSnapshotCreateTime(created);
store.putForAccount(owner, region + "::" + arn, policy);
assertEquals(Optional.of("{\"Version\":\"2012-10-17\"}"), service.policyOfSnapshot(owner, snapshot, region));
assertTrue(service.policyOfSnapshot("123456789012", snapshot, region).isEmpty());
snapshot.setSnapshotCreateTime(created.plusSeconds(1));
assertTrue(service.policyOfSnapshot(owner, snapshot, region).isEmpty());
}
}
@@ -0,0 +1,115 @@
package io.floci.aws.services.redshiftserverless;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy;
import io.floci.aws.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftServerlessResourcePolicyProviderTest {
private static final String OWNER = "111122223333";
private static final String REGION = "us-east-1";
private static final String SNAPSHOT_ARN = "arn:aws:redshift-serverless:" + REGION + ":" + OWNER
+ ":snapshot/shared";
private static final String WITH_RESOURCE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":\"444455556666\"},\"Action\":\"redshift-serverless:RestoreFromSnapshot\","
+ "\"Resource\":\"*\"}]}";
private static final String WITHOUT_RESOURCE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":\"444455556666\"},\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}]}";
private final ObjectMapper objectMapper = new ObjectMapper();
private RedshiftServerlessService serverless;
private RedshiftServerlessResourcePolicyService policies;
private RedshiftServerlessResourcePolicyProvider provider;
private RedshiftServerlessSnapshot snapshot;
@BeforeEach
void setUp() {
serverless = mock(RedshiftServerlessService.class);
policies = mock(RedshiftServerlessResourcePolicyService.class);
provider = new RedshiftServerlessResourcePolicyProvider(serverless, policies, objectMapper);
snapshot = new RedshiftServerlessSnapshot();
snapshot.setSnapshotName("shared");
snapshot.setSnapshotArn(SNAPSHOT_ARN);
when(serverless.findSnapshotOfAccount(OWNER, "shared", REGION)).thenReturn(Optional.of(snapshot));
when(policies.policyOfSnapshot(any(), any(), any())).thenReturn(Optional.empty());
}
@Test
void aSnapshotComesWithItsPolicyAndTheAccountInItsArn() {
when(policies.policyOfSnapshot(eq(OWNER), eq(snapshot), eq(REGION))).thenReturn(Optional.of(WITH_RESOURCE));
assertEquals(List.of(new ResourcePolicy(WITH_RESOURCE, OWNER)),
provider.getResourcePolicies("redshift-serverless", SNAPSHOT_ARN));
}
@Test
void aSnapshotWithNoPolicyStillHasItsOwner() {
assertEquals(List.of(new ResourcePolicy(null, OWNER)),
provider.getResourcePolicies("redshift-serverless", SNAPSHOT_ARN));
}
@Test
void aSnapshotThatIsNotThereStillHasItsOwner() {
String missing = "arn:aws:redshift-serverless:" + REGION + ":" + OWNER + ":snapshot/missing";
when(serverless.findSnapshotOfAccount(OWNER, "missing", REGION)).thenReturn(Optional.empty());
assertEquals(List.of(new ResourcePolicy(null, OWNER)),
provider.getResourcePolicies("redshift-serverless", missing));
}
@Test
void aStatementWithNoResourceIsAttachedToTheSnapshot() throws Exception {
when(policies.policyOfSnapshot(eq(OWNER), eq(snapshot), eq(REGION))).thenReturn(Optional.of(WITHOUT_RESOURCE));
String policy = provider.getResourcePolicies("redshift-serverless", SNAPSHOT_ARN).getFirst().policyDocument();
JsonNode statement = objectMapper.readTree(policy).path("Statement").get(0);
assertEquals(SNAPSHOT_ARN, statement.path("Resource").asText());
assertEquals("redshift-serverless:RestoreFromSnapshot", statement.path("Action").asText());
}
@Test
void aStatementThatNamesItsResourceIsKept() {
assertEquals(WITH_RESOURCE, provider.withResource(WITH_RESOURCE, SNAPSHOT_ARN));
String notResource = WITHOUT_RESOURCE.replace("\"Action\"", "\"NotResource\":\"*\",\"Action\"");
assertEquals(notResource, provider.withResource(notResource, SNAPSHOT_ARN));
}
@Test
void aSingleStatementObjectIsAttachedToTheSnapshotToo() throws Exception {
String single = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":\"444455556666\"},\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}}";
JsonNode statement = objectMapper.readTree(provider.withResource(single, SNAPSHOT_ARN)).path("Statement");
assertEquals(SNAPSHOT_ARN, statement.path("Resource").asText());
}
@Test
void aPolicyThatCannotBeReadIsPassedOnAsItIs() {
assertEquals("{not json", provider.withResource("{not json", SNAPSHOT_ARN));
}
@Test
void anythingThatIsNotOneSnapshotIsLeftToOtherProviders() {
assertTrue(provider.getResourcePolicies("redshift-serverless", "*").isEmpty());
assertTrue(provider.getResourcePolicies("redshift-serverless",
"arn:aws:redshift-serverless:" + REGION + ":" + OWNER + ":snapshot/*").isEmpty());
assertTrue(provider.getResourcePolicies("redshift-serverless",
"arn:aws:redshift-serverless:" + REGION + ":" + OWNER + ":namespace/abc").isEmpty());
assertTrue(provider.getResourcePolicies("sqs", "arn:aws:sqs:" + REGION + ":" + OWNER + ":orders").isEmpty());
}
}
@@ -14,6 +14,7 @@ import io.floci.aws.services.redshiftserverless.model.Namespace;
import io.floci.aws.services.redshiftserverless.model.PricePerformanceTarget;
import io.floci.aws.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import io.floci.aws.services.redshiftserverless.model.Workgroup;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -96,6 +97,11 @@ class RedshiftServerlessServiceTest {
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
+ invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"
+ invocation.getArgument(2, String.class));
when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class),
any(String.class)))
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
+ invocation.getArgument(1, String.class) + ":" + invocation.getArgument(2, String.class)
+ ":" + invocation.getArgument(3, String.class));
nextPort = 7100;
endpoints = mock(RedshiftServerlessEndpoints.class);
when(endpoints.allocate()).thenAnswer(invocation -> new Endpoint("localhost", nextPort++));
@@ -1057,6 +1063,132 @@ class RedshiftServerlessServiceTest {
assertEquals("ResourceNotFoundException", noSnapshot.getErrorCode());
}
@Test
void restoreFromSharedSnapshotReadsTheSnapshotOfAnotherAccount() throws Exception {
String owner = "999999999999";
create("shared-ns");
createWorkgroup("shared-wg", "shared-ns");
RedshiftServerlessSnapshot own = service.createSnapshot("own-snap", "shared-ns", null, null, REGION);
Path ownerDump = dumpDir.resolve("redshift-serverless-dumps").resolve(owner).resolve(REGION)
.resolve("their-snap.sql").toAbsolutePath().normalize();
Files.createDirectories(ownerDump.getParent());
Files.writeString(ownerDump, "select 1;");
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(own);
theirs.setSnapshotName("their-snap");
theirs.setOwnerAccount(owner);
theirs.setSqlDump(ownerDump.toString());
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
assertTrue(service.findSnapshotOfAccount(owner, "their-snap", REGION).isPresent());
assertTrue(service.findSnapshotOfAccount(ACCOUNT_ID, "their-snap", REGION).isEmpty());
assertTrue(service.findSnapshotOfAccount(owner, "own-snap", REGION).isEmpty());
RedshiftServerlessService.RestoreResult restored = service.restoreFromSharedSnapshot(
"shared-ns", "shared-wg", "their-snap", owner, null, null, REGION);
assertEquals("AVAILABLE", restored.namespace().getStatus());
assertEquals("their-snap", restored.snapshot().getSnapshotName());
assertEquals(owner, restored.snapshot().getOwnerAccount());
verify(runtime).restoreSnapshot(eq(ACCOUNT_ID), eq(REGION), eq("shared-wg"), any(), any(), eq(ownerDump),
any());
}
@Test
@SuppressWarnings("unchecked")
void findNamesTheArnOfTheSnapshotOfTheAccountThatOwnsIt() {
String owner = "999999999999";
create("find-ns");
RedshiftServerlessSnapshot own = service.createSnapshot("own-snap", "find-ns", null, null, REGION);
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(own);
theirs.setSnapshotName("their-snap");
theirs.setSnapshotArn("arn:aws:redshift-serverless:" + REGION + ":" + owner + ":snapshot/their-snap");
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
assertEquals(Optional.of(own.getSnapshotArn()), service.find("snapshot", List.of("own-snap"), REGION));
assertEquals(Optional.of(theirs.getSnapshotArn()),
service.findInAccount("snapshot", List.of("their-snap"), owner, REGION));
assertEquals(Optional.empty(), service.find("snapshot", List.of("their-snap"), REGION));
assertEquals(Optional.empty(), service.findInAccount("snapshot", List.of("own-snap"), owner, REGION));
assertEquals(Optional.empty(), service.findInAccount("namespace", List.of("find-ns"), owner, REGION));
assertEquals(Optional.of(service.getNamespace("find-ns", REGION).getNamespaceArn()),
service.find("namespace", List.of("find-ns"), REGION));
assertEquals(Optional.empty(), service.find("workgroup", List.of("missing"), REGION));
assertEquals(Optional.empty(), service.find("endpointAccess", List.of("any"), REGION));
RedshiftServerlessEndpointAccessService endpointService = mock(RedshiftServerlessEndpointAccessService.class);
Instance<RedshiftServerlessEndpointAccessService> endpointInstance = mock(Instance.class);
when(endpointInstance.isUnsatisfied()).thenReturn(false);
when(endpointInstance.get()).thenReturn(endpointService);
when(endpointService.findEndpointArn("my-endpoint", REGION)).thenReturn(Optional.of("arn:endpoint"));
service.endpointAccess = endpointInstance;
assertEquals(Optional.of("arn:endpoint"), service.find("endpointAccess", List.of("my-endpoint"), REGION));
assertEquals(Optional.empty(), service.find("snapshot", List.of(), REGION));
}
@Test
void anOwnerAccountIsOtherOnlyWhenItDiffersFromTheCallers() {
assertTrue(service.isOtherAccount("999999999999"));
assertFalse(service.isOtherAccount(ACCOUNT_ID));
assertFalse(service.isOtherAccount(null));
assertFalse(service.isOtherAccount(" "));
}
@Test
void snapshotNameFromArnOfAnotherOwnerNeedsThatOwnersAccount() {
String owner = "999999999999";
String ownerArn = "arn:aws:redshift-serverless:" + REGION + ":" + owner + ":snapshot/their-snap";
assertEquals("their-snap", service.snapshotNameFromArn(ownerArn, REGION, owner, "snapshotArn"));
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> service.snapshotNameFromArn(ownerArn, REGION, ACCOUNT_ID, "snapshotArn")).getErrorCode());
}
@Test
void restoreFromSharedSnapshotDoesNotTrustADumpOutsideTheOwnersDirectory() throws Exception {
String owner = "999999999999";
create("shared-ns");
createWorkgroup("shared-wg", "shared-ns");
Path callerDump = dumpDir.resolve("redshift-serverless-dumps").resolve(ACCOUNT_ID).resolve(REGION)
.resolve("elsewhere.sql").toAbsolutePath().normalize();
Files.createDirectories(callerDump.getParent());
Files.writeString(callerDump, "select 1;");
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(
service.createSnapshot("own-snap", "shared-ns", null, null, REGION));
theirs.setSnapshotName("their-snap");
theirs.setOwnerAccount(owner);
theirs.setSqlDump(callerDump.toString());
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
AwsException untrusted = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
"shared-ns", "shared-wg", "their-snap", owner, null, null, REGION));
assertEquals("InternalServerException", untrusted.getErrorCode());
}
@Test
void restoreFromSharedSnapshotStillNeedsAnAvailableSnapshotAndAWorkgroup() {
String owner = "999999999999";
create("shared-ns");
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(
service.createSnapshot("own-snap", "shared-ns", null, null, REGION));
theirs.setSnapshotName("their-snap");
theirs.setOwnerAccount(owner);
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
AwsException noWorkgroup = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
"shared-ns", "missing-wg", "their-snap", owner, null, null, REGION));
assertEquals("ResourceNotFoundException", noWorkgroup.getErrorCode());
AwsException noSnapshot = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
"shared-ns", "missing-wg", "no-such-snap", owner, null, null, REGION));
assertEquals("ResourceNotFoundException", noSnapshot.getErrorCode());
theirs.setStatus("FAILED");
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
AwsException unavailable = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
"shared-ns", "missing-wg", "their-snap", owner, null, null, REGION));
assertEquals("ConflictException", unavailable.getErrorCode());
}
@Test
void restoreRejectsAWorkgroupOfAnotherNamespace() {
create("rest-a");
@@ -0,0 +1,151 @@
package io.floci.aws.services.redshiftserverless;
import io.floci.aws.services.redshift.TempCredential;
import io.floci.aws.services.redshift.model.Endpoint;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
/**
* Under IAM enforcement, a snapshot another account owns is restored only when the snapshot's resource policy
* names the caller, and the caller's own identity policy allows it as well: the request is checked on the
* owner's snapshot ARN, which the policy is attached to.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
private static final String OWNER = "111122223333";
private static final String CALLER = "444455556666";
private static final String STRANGER = "777788889999";
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "RedshiftServerless.";
private static final String ALLOW_RESTORE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\",\"Resource\":\"*\"}]}";
@TestHTTPResource
URI endpoint;
@InjectMock
RedshiftServerlessRuntime runtime;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void stubRuntime() {
when(runtime.generatePassword()).thenReturn("Generated123");
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
when(runtime.issueCredential(any(), any(), any(), any(), anyInt()))
.thenAnswer(invocation -> new TempCredential(invocation.getArgument(3), "temporary-password",
Instant.now().plusSeconds(900), List.of()));
}
@Test
void aSnapshotIsRestorableByAnotherAccountOnlyWhenItsPolicyNamesTheCaller() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String sourceNamespace = "share-src-" + suffix;
String snapshot = "share-snap-" + suffix;
String namespace = "share-dst-" + suffix;
String workgroup = "share-wg-" + suffix;
String callerKey = user(CALLER, ALLOW_RESTORE);
String strangerKey = user(STRANGER, ALLOW_RESTORE);
String unprivilegedKey = user(CALLER, "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"redshift-serverless:GetNamespace\",\"Resource\":\"*\"}]}");
call(OWNER, "CreateNamespace", Map.of("namespaceName", sourceNamespace, "adminUsername", "admin"))
.statusCode(200);
String snapshotArn = call(OWNER, "CreateSnapshot",
Map.of("snapshotName", snapshot, "namespaceName", sourceNamespace))
.statusCode(200).extract().path("snapshot.snapshotArn");
for (String account : List.of(CALLER, STRANGER)) {
call(account, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin"))
.statusCode(200);
call(account, "CreateWorkgroup", Map.of("workgroupName", workgroup, "namespaceName", namespace))
.statusCode(200);
}
Map<String, String> byName = Map.of("namespaceName", namespace, "workgroupName", workgroup,
"snapshotName", snapshot, "ownerAccount", OWNER);
// Not shared until the snapshot's policy says so.
denied(call(callerKey, "RestoreFromSnapshot", byName));
// AWS's own PutResourcePolicy example leaves Resource out: the policy is still on this snapshot.
String sharedWithCaller = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":\"arn:aws:iam::" + CALLER + ":root\"},"
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}]}";
call(OWNER, "PutResourcePolicy", Map.of("resourceArn", snapshotArn, "policy", sharedWithCaller))
.statusCode(200);
call(callerKey, "RestoreFromSnapshot", byName).statusCode(200)
.body("ownerAccount", equalTo(OWNER))
.body("snapshotName", equalTo(snapshot));
call(callerKey, "RestoreFromSnapshot", Map.of("namespaceName", namespace, "workgroupName", workgroup,
"snapshotArn", snapshotArn, "ownerAccount", OWNER)).statusCode(200)
.body("snapshotName", equalTo(snapshot));
// The policy is the resource side only: a caller whose own policy does not allow it is refused, and so is
// an account the policy does not name.
denied(call(unprivilegedKey, "RestoreFromSnapshot", byName));
denied(call(strangerKey, "RestoreFromSnapshot", byName));
// Withdrawing the policy takes the access away at the next restore.
call(OWNER, "DeleteResourcePolicy", Map.of("resourceArn", snapshotArn)).statusCode(200);
denied(call(callerKey, "RestoreFromSnapshot", byName));
}
private static void denied(ValidatableResponse response) {
response.statusCode(400).body("__type", equalTo("AccessDeniedException"))
.body("message", containsString("redshift-serverless:RestoreFromSnapshot"));
}
private String user(String account, String policy) {
String name = "share-" + UUID.randomUUID().toString().substring(0, 8);
String authorization = auth(account, "iam");
String accessKeyId = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, name)
.accessKeyId();
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, name, "p", policy);
return accessKeyId;
}
private ValidatableResponse call(String accessKeyId, String action, Map<String, String> body) {
return given().port(endpoint.getPort())
.header("X-Amz-Target", TARGET_PREFIX + action)
.header("Authorization", auth(accessKeyId, "redshift-serverless"))
.contentType(CONTENT_TYPE)
.body(body)
.when().post("/")
.then();
}
}
+22 -10
View File
@@ -41,7 +41,10 @@ strings, or, for an ARN, a member of a structure or of each element of a list of
A member whose botocore shape is an account id (a string of pattern `[0-9]{12}`) gives the account of
the types the request names by their variables: ECR's `registryId` selects the registry its handler
acts in, so `repository/<name>` is that account's. A member whose shape's pattern takes an ARN before
acts in, so `repository/<name>` is that account's. On a non-create, a bare string member also takes
that role when the same service types that member as an account id in another request. Redshift
Serverless's `ownerAccount` names the snapshot's owner this way, but on a create it names the account
of a resource the new one is made in. A member whose shape's pattern takes an ARN before
the name (`(arn:...:event-bus/)?<name>`) may give the ARN of the type of that name instead, whose one
variable it is then read as, in the ARN's account and Region: EventBridge's `EventBusName`. So may a
field of each element of a list of structures, each element's resource in the account and Region of
@@ -167,8 +170,8 @@ NAMESPACES = ("access-analyzer", "acm", "application-autoscaling", "athena", "bc
"bcm-pricing-calculator", "budgets", "ce", "cloudtrail", "codebuild", "codepipeline", "cognito-identity",
"cognito-idp", "controltower", "cur", "datasync", "ec2", "ecr", "elasticloadbalancing", "elasticmapreduce", "es", "events",
"firehose", "globalaccelerator", "inspector2", "kinesisanalytics", "macie2", "payment-cryptography",
"quicksight", "redshift", "redshift-data", "rekognition", "servicediscovery", "servicequotas", "sso",
"states", "textract", "timestream-influxdb", "translate", "signer", "xray")
"quicksight", "redshift", "redshift-data", "redshift-serverless", "rekognition", "servicediscovery",
"servicequotas", "sso", "states", "textract", "timestream-influxdb", "translate", "signer", "xray")
# SDK clients the reference lists for a namespace's operations whose requests Floci does not serve, and why: their
# members are not read.
@@ -263,10 +266,6 @@ NOT_COVERED: dict[str, str] = {
"ram": _REST,
"rds": _LATER,
"rds-data": _REST,
"redshift-serverless": "not read yet: its namespace, workgroup, snapshot and managed VPC endpoint ARNs end in an "
"id the service mints, `namespace/<id>`, while its requests name them by namespaceName, "
"workgroupName, snapshotName and endpointName, so reading it needs the stored ARNs those "
"find, as Redshift Data's workgroups are found",
"resource-explorer-2": _REST,
"route53": _REST,
"route53resolver": _LATER,
@@ -614,6 +613,13 @@ FOUND_BY: dict[str, tuple[list[str], str]] = {
"target', Application Auto Scaling User Guide), which the reference names ${ResourceId}, while its requests "
"name the target by ServiceNamespace, ResourceId and ScalableDimension; ResourceId is the target's "
"resource (service/<cluster>/<service>), not that id"),
**{f"redshift-serverless:{kind}": ([member], f"a Redshift Serverless {kind}'s ARN ends in the id the service gives "
f"it, {path}/<id> ('The unique identifier' of its {kind}), while its "
f"requests name it by {member}")
for kind, member, path in (("namespace", "namespaceName", "namespace"),
("workgroup", "workgroupName", "workgroup"),
("snapshot", "snapshotName", "snapshot"),
("endpointAccess", "endpointName", "managedvpcendpoint"))},
"redshift-data:workgroup": (
["WorkgroupName"],
"a serverless workgroup's ARN ends in the id Redshift Serverless gives it, workgroup/<id> (its Workgroup's "
@@ -843,10 +849,16 @@ def account_members(models: dict[str, dict], operation: str) -> list[str]:
spec = model["operations"].get(operation)
if spec is None or "input" not in spec or not READ_PROTOCOLS & _protocols(model):
continue
account_names = {name for other in model["operations"].values() if "input" in other
for name, member in model["shapes"][other["input"]["shape"]].get("members", {}).items()
if member.get("location") in BODY_LOCATIONS
and model["shapes"][member["shape"]].get("pattern") in ACCOUNT_ID_PATTERNS | {r"(\d{12})"}
and model["shapes"][member["shape"]]["type"] == "string"}
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
shape = model["shapes"][member["shape"]]
if member.get("location") in BODY_LOCATIONS and shape["type"] == "string" \
and shape.get("pattern") in ACCOUNT_ID_PATTERNS:
and (shape.get("pattern") in ACCOUNT_ID_PATTERNS
or (name in account_names and not CREATING_RE.match(operation))):
found.add(name)
return sorted(found)
@@ -1420,8 +1432,8 @@ ARN_PATH_RE = re.compile(r"^(?:[A-Za-z][A-Za-z0-9_]*(\[])?(\.[A-Za-z][A-Za-z0-9_
r"|[A-Za-z][A-Za-z0-9_]*\{\}(\.[A-Za-z][A-Za-z0-9_]*){1,2})$")
# A format's resource that is a literal and one variable, at its end.
ONE_VARIABLE_RE = re.compile(r"^[^$]*\$\{\w+}$")
# The keys a resource found by members does not take: it is read no other way, in the caller's account.
FOUND_ONLY = {"absent", "arnOf", "account", "fixed", "before"}
# The keys a resource found by members does not take: it is read no other way.
FOUND_ONLY = {"absent", "arnOf", "fixed", "before"}
def validate(document: dict) -> list[str]:
+43 -2
View File
@@ -249,6 +249,49 @@ def test_a_member_holding_an_account_id_gives_the_account_of_the_types_named_by_
assert r.with_account([{"type": "thing", "fill": {}}], FORMATS, ["a", "b"]) == [{"type": "thing", "fill": {}}]
@pytest.mark.parametrize("member", ["ownerAccount", "resourceAccount"])
@pytest.mark.parametrize("pattern", ["[0-9]{12}", r"(\d{12})"])
def test_an_account_member_typed_elsewhere_in_the_service_is_inferred_only_for_non_creates(tmp_path, member, pattern):
service = model({"GetThing": {member: "String"},
"CreateThing": {member: "String"},
"ListThings": {member: "AccountId"},
"CreateOther": {member: "DirectAccountId"}})
service["shapes"]["AccountId"]["pattern"] = pattern
service["shapes"]["DirectAccountId"] = {"type": "string", "pattern": "[0-9]{12}"}
write_models(tmp_path, {"svc": service})
models = r.load_models(tmp_path, {"svc"})
assert r.account_members(models, "GetThing") == [member]
assert r.account_members(models, "CreateThing") == []
assert r.account_members(models, "ListThings") == [member]
assert r.account_members(models, "CreateOther") == [member]
def test_account_member_inference_does_not_cross_service_models(tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ownerAccount": "String"}}),
"other": model({"ListThings": {"ownerAccount": "AccountId"}})})
models = r.load_models(tmp_path, {"svc", "other"})
assert r.account_members(models, "GetThing") == []
def test_redshift_serverless_account_inference_preserves_the_generated_resources():
from regen_partitions import resolve_botocore_data
document = json.loads(r.OUTPUT.read_text())
data, _ = resolve_botocore_data(None)
models = r.load_models(data, set(document["namespaces"]["redshift-serverless"]))
account_operations = set()
for operation, entry in document["operations"].items():
if not operation.startswith("redshift-serverless:"):
continue
derived = r.entry_for(operation, {"action": entry["action"], "types": entry["types"]},
document["arnFormats"]["redshift-serverless"], models)
assert derived == entry, operation
if r.account_members(models, operation.split(":", 1)[1]) == ["ownerAccount"]:
account_operations.add(operation.split(":", 1)[1])
assert account_operations == {"GetSnapshot", "ListEndpointAccess", "ListSnapshots", "ListWorkgroups",
"RestoreFromSnapshot"}
def test_a_format_whose_account_is_an_account_id_variable_takes_the_account_every_other_format_does():
documents = [reference("svc", {}, {"agent": "arn:${Partition}:svc:${Region}:${AccountId}:agent/${AgentId}",
"account": "arn:${Partition}:svc:::account/${AccountId}",
@@ -552,8 +595,6 @@ def with_a_create() -> dict:
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=[]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Ids[]"]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find="Namespace"), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace"], account="registryId"),
"beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace"], absent={"Namespace": "ecs"}),
"beside a fill"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(find=["Namespace"]), "neither an ARN member"),