From 8a817ec5e9fd9ef24f77f4866b40123428c5de75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:03:53 +0700 Subject: [PATCH] feat(redshift-serverless): read and list snapshots another account shares (#7899) GetSnapshot and ListSnapshots with an ownerAccount other than the caller's now read the owner's snapshots and return only the ones the snapshot resource policy shares with the caller. A snapshot is never shared across partitions. --- docs/services/redshift-serverless.md | 6 +- .../aws/services/dsql/DsqlPrincipals.java | 27 +---- .../services/iam/RequestCallerResolver.java | 51 ++++++++ .../RedshiftServerlessJsonHandler.java | 36 ++++-- .../RedshiftServerlessService.java | 25 +++- .../RedshiftServerlessSharedSnapshots.java | 80 ++++++++++++ ...ftServerlessAdministrationHandlerTest.java | 2 +- .../RedshiftServerlessIntegrationTest.java | 38 ++++++ .../RedshiftServerlessJsonHandlerTest.java | 2 +- ...RedshiftServerlessSharedSnapshotsTest.java | 114 ++++++++++++++++++ ...tSharingIamEnforcementIntegrationTest.java | 63 ++++++++++ 11 files changed, 408 insertions(+), 36 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java create mode 100644 src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshots.java create mode 100644 src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshotsTest.java diff --git a/docs/services/redshift-serverless.md b/docs/services/redshift-serverless.md index 2cec45ebdf..93a46a4f84 100644 --- a/docs/services/redshift-serverless.md +++ b/docs/services/redshift-serverless.md @@ -23,8 +23,8 @@ For the upstream API shape, see the [Amazon Redshift Serverless API Reference](h | `UpdateWorkgroup` | Apply the supplied fields to an existing workgroup and return it | | `DeleteWorkgroup` | Stop a workgroup's container and proxy, release its endpoint, and return it with `status` `DELETING` | | `CreateSnapshot` | Create an `AVAILABLE` snapshot of a namespace, dumping the workgroup's database when it is running; a snapshot created in a standby Region stands in for a cross-Region copy | -| `GetSnapshot` | Return a snapshot by `snapshotName` or `snapshotArn` | -| `ListSnapshots` | Page through the snapshots in the Region, filtered by `namespaceName`, `namespaceArn`, `ownerAccount` and a `startTime`/`endTime` window | +| `GetSnapshot` | Return a snapshot by `snapshotName` or `snapshotArn`. With `ownerAccount` set to another account, the snapshot is read from that account, and under IAM enforcement refused with `AccessDeniedException` unless its resource policy allows the caller `redshift-serverless:GetSnapshot` | +| `ListSnapshots` | Page through the snapshots in the Region, filtered by `namespaceName`, `namespaceArn`, `ownerAccount` and a `startTime`/`endTime` window. With `ownerAccount` set to another account, only the snapshots of that account whose resource policy allows the caller `redshift-serverless:GetSnapshot` are listed, and the others are left out | | `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. 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` | @@ -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 `/redshift-serverless-dumps///`. `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 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`. +- **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. `GetSnapshot` and `ListSnapshots` with another `ownerAccount` read that account's snapshots. `GetSnapshot` is checked by IAM enforcement like the restore, against `redshift-serverless:GetSnapshot`. `ListSnapshots` names no single snapshot, so it lists only the snapshots whose policy allows the caller `redshift-serverless:GetSnapshot` and leaves the others out, with enforcement on or off. A snapshot is never shared across partitions. 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. diff --git a/src/main/java/io/floci/aws/services/dsql/DsqlPrincipals.java b/src/main/java/io/floci/aws/services/dsql/DsqlPrincipals.java index 68feb59b43..760815bc75 100644 --- a/src/main/java/io/floci/aws/services/dsql/DsqlPrincipals.java +++ b/src/main/java/io/floci/aws/services/dsql/DsqlPrincipals.java @@ -2,12 +2,10 @@ package io.floci.aws.services.dsql; import io.floci.aws.core.common.IamConditionContextResolver; import io.floci.aws.core.common.RegionResolver; -import io.floci.aws.core.common.RequestContext; import io.floci.aws.services.iam.IamService; import io.floci.aws.services.iam.IamService.CallerArns; +import io.floci.aws.services.iam.RequestCallerResolver; import jakarta.enterprise.context.ApplicationScoped; -import jakarta.enterprise.context.ContextNotActiveException; -import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import java.util.HashMap; @@ -23,26 +21,22 @@ public class DsqlPrincipals { private final IamService iamService; private final RegionResolver regionResolver; - private final Instance requestContext; + private final RequestCallerResolver callers; @Inject - public DsqlPrincipals(IamService iamService, RegionResolver regionResolver, - Instance requestContext) { + public DsqlPrincipals(IamService iamService, RegionResolver regionResolver, RequestCallerResolver callers) { this.iamService = iamService; this.regionResolver = regionResolver; - this.requestContext = requestContext; + this.callers = callers; } public CallerArns caller() { - return callerOf(accessKeyId()); + return callers.caller(); } /** Who signs with {@code accessKeyId}, as {@link #caller()} names the caller of a request. */ public CallerArns callerOf(String accessKeyId) { - String accountId = regionResolver.getAccountId(); - return iamService.resolveCallerArns(accessKeyId) - .orElseGet(() -> CallerArns.accountRoot(regionResolver.buildGlobalArn("iam", accountId, "root"), - accountId)); + return callers.callerOf(accessKeyId); } /** @@ -65,13 +59,4 @@ public class DsqlPrincipals { public boolean exists(String arn) { return iamService.heldPrincipalArn(arn).isPresent(); } - - private String accessKeyId() { - try { - return requestContext.isResolvable() ? requestContext.get().getAccessKeyId() : null; - } catch (ContextNotActiveException e) { - // A call outside a request, such as CloudFormation's, is the account's own. - return null; - } - } } diff --git a/src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java b/src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java new file mode 100644 index 0000000000..bc2fe06b92 --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/RequestCallerResolver.java @@ -0,0 +1,51 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; +import io.floci.aws.services.iam.IamService.CallerArns; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.context.ContextNotActiveException; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; + +/** + * Who is calling, for a service that checks a resource policy against the caller itself rather than leaving it to + * IAM enforcement. A credential that names no IAM identity is its account's root, as for STS. + */ +@ApplicationScoped +public class RequestCallerResolver { + + private final IamService iamService; + private final RegionResolver regionResolver; + private final Instance requestContext; + + @Inject + public RequestCallerResolver(IamService iamService, RegionResolver regionResolver, + Instance requestContext) { + this.iamService = iamService; + this.regionResolver = regionResolver; + this.requestContext = requestContext; + } + + /** The caller of the current request. */ + public CallerArns caller() { + return callerOf(accessKeyId()); + } + + /** Who signs with {@code accessKeyId}, as {@link #caller()} names the caller of a request. */ + public CallerArns callerOf(String accessKeyId) { + String accountId = regionResolver.getAccountId(); + return iamService.resolveCallerArns(accessKeyId) + .orElseGet(() -> CallerArns.accountRoot(regionResolver.buildGlobalArn("iam", accountId, "root"), + accountId)); + } + + private String accessKeyId() { + try { + return requestContext.isResolvable() ? requestContext.get().getAccessKeyId() : null; + } catch (ContextNotActiveException e) { + // A call outside a request, such as CloudFormation's, is the account's own. + return null; + } + } +} diff --git a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandler.java b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandler.java index 4241140500..f36dfa328d 100644 --- a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandler.java +++ b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandler.java @@ -47,19 +47,22 @@ public class RedshiftServerlessJsonHandler { private final RedshiftServerlessUsageLimitService usageLimits; private final RedshiftServerlessAdminJsonHandler admin; private final RedshiftServerlessCustomDomainService customDomains; + private final RedshiftServerlessSharedSnapshots sharedSnapshots; @Inject public RedshiftServerlessJsonHandler(RedshiftServerlessService service, ObjectMapper objectMapper, RedshiftIamDbUserResolver iamDbUserResolver, RedshiftServerlessUsageLimitService usageLimits, RedshiftServerlessAdminJsonHandler admin, - RedshiftServerlessCustomDomainService customDomains) { + RedshiftServerlessCustomDomainService customDomains, + RedshiftServerlessSharedSnapshots sharedSnapshots) { this.service = service; this.objectMapper = objectMapper; this.iamDbUserResolver = iamDbUserResolver; this.usageLimits = usageLimits; this.admin = admin; this.customDomains = customDomains; + this.sharedSnapshots = sharedSnapshots; } public Response handle(String action, JsonNode request, String region) { @@ -249,19 +252,34 @@ public class RedshiftServerlessJsonHandler { } /** - * GetSnapshot also accepts {@code snapshotArn}, which must name a snapshot of this account - * and Region. + * GetSnapshot also accepts {@code snapshotArn}, which must name a snapshot of {@code ownerAccount}, or of + * this account without one, in this Region. A snapshot of another account is read from that account; whether + * its policy shares it with the caller is for IAM enforcement to decide. */ private Response handleGetSnapshot(JsonNode request, String region) { - return snapshotResponse(service.getSnapshot(snapshotNameOf(request, region, null), region)); + String ownerAccount = ServerlessSupport.text(request, "ownerAccount"); + if (!service.isOtherAccount(ownerAccount)) { + return snapshotResponse(service.getSnapshot(snapshotNameOf(request, region, null), region)); + } + String snapshotName = snapshotNameOf(request, region, ownerAccount); + return snapshotResponse(service.findSnapshotOfAccount(ownerAccount, snapshotName, region) + .orElseThrow(() -> ServerlessSupport.notFound("The snapshot " + snapshotName + " was not found."))); } private Response handleListSnapshots(JsonNode request, String region) { - PaginatedResult page = service.listSnapshots( - ServerlessSupport.text(request, "namespaceName"), ServerlessSupport.text(request, "namespaceArn"), ServerlessSupport.text(request, "ownerAccount"), - AwsJsonTimestamp.epochSeconds(request, "startTime", "ValidationException"), - AwsJsonTimestamp.epochSeconds(request, "endTime", "ValidationException"), region, - ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken")); + String ownerAccount = ServerlessSupport.text(request, "ownerAccount"); + Instant startTime = AwsJsonTimestamp.epochSeconds(request, "startTime", "ValidationException"); + Instant endTime = AwsJsonTimestamp.epochSeconds(request, "endTime", "ValidationException"); + PaginatedResult page = service.isOtherAccount(ownerAccount) + ? service.listSnapshotsOfAccount(ownerAccount, + owned -> sharedSnapshots.readable(ownerAccount, owned, region), + ServerlessSupport.text(request, "namespaceName"), + ServerlessSupport.text(request, "namespaceArn"), startTime, endTime, region, + ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken")) + : service.listSnapshots( + ServerlessSupport.text(request, "namespaceName"), + ServerlessSupport.text(request, "namespaceArn"), ownerAccount, startTime, endTime, region, + ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken")); ObjectNode response = objectMapper.createObjectNode(); ArrayNode items = response.putArray("snapshots"); page.items().forEach(snapshot -> items.add(snapshotNode(snapshot))); diff --git a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java index b2a2eedfa4..94d2684f5e 100644 --- a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java +++ b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessService.java @@ -48,6 +48,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Supplier; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -886,7 +887,29 @@ public class RedshiftServerlessService implements Resettable, StoredResourceArns String ownerAccount, Instant startTime, Instant endTime, String region, Integer maxResults, String nextToken) { - List all = snapshots.scan(key -> key.startsWith(region + "::")).stream() + return pageOfSnapshots(snapshots.scan(key -> key.startsWith(region + "::")), namespaceName, namespaceArn, + ownerAccount, startTime, endTime, maxResults, nextToken); + } + + /** + * Lists the snapshots {@code accountId} owns in {@code region}, narrowed as {@link #listSnapshots} does, to the + * ones {@code visible} keeps. Whether the caller may see a snapshot of another account is for the caller of + * this method to decide. + */ + public PaginatedResult listSnapshotsOfAccount( + String accountId, UnaryOperator> visible, String namespaceName, + String namespaceArn, Instant startTime, Instant endTime, String region, Integer maxResults, + String nextToken) { + List owned = snapshots.scanForAccount(accountId, + key -> key.startsWith(region + "::")); + return pageOfSnapshots(visible.apply(owned), namespaceName, namespaceArn, accountId, startTime, endTime, + maxResults, nextToken); + } + + private PaginatedResult pageOfSnapshots( + List candidates, String namespaceName, String namespaceArn, + String ownerAccount, Instant startTime, Instant endTime, Integer maxResults, String nextToken) { + List all = candidates.stream() .filter(snapshot -> namespaceName == null || namespaceName.isBlank() || namespaceName.equals(snapshot.getNamespaceName())) .filter(snapshot -> namespaceArn == null || namespaceArn.isBlank() diff --git a/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshots.java b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshots.java new file mode 100644 index 0000000000..dff814476f --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshots.java @@ -0,0 +1,80 @@ +package io.floci.aws.services.redshiftserverless; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.IamConditionContextResolver; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.iam.IamPolicyEvaluator; +import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; +import io.floci.aws.services.iam.IamService.CallerArns; +import io.floci.aws.services.iam.RequestCallerResolver; +import io.floci.aws.services.iam.RequestPrincipal; +import io.floci.aws.services.redshiftserverless.model.RedshiftServerlessSnapshot; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Narrows the snapshots another account owns to the ones its resource policy shares with the caller, for + * ListSnapshots, which IAM cannot filter item by item. A snapshot with no policy, or a policy that does not + * allow the caller {@code redshift-serverless:GetSnapshot}, is not shared. GetSnapshot and RestoreFromSnapshot + * name one snapshot, so IAM enforcement checks them through {@link RedshiftServerlessResourcePolicyProvider}. + */ +@ApplicationScoped +public class RedshiftServerlessSharedSnapshots { + + static final String GET_ACTION = "redshift-serverless:GetSnapshot"; + + private final RedshiftServerlessResourcePolicyService policies; + private final IamPolicyEvaluator evaluator; + private final RegionResolver regionResolver; + private final RequestCallerResolver callers; + private final RedshiftServerlessResourcePolicyProvider resourcePolicyProvider; + + @Inject + public RedshiftServerlessSharedSnapshots(RedshiftServerlessResourcePolicyService policies, + IamPolicyEvaluator evaluator, RegionResolver regionResolver, + RequestCallerResolver callers, + RedshiftServerlessResourcePolicyProvider resourcePolicyProvider) { + this.policies = policies; + this.evaluator = evaluator; + this.regionResolver = regionResolver; + this.callers = callers; + this.resourcePolicyProvider = resourcePolicyProvider; + } + + /** + * The snapshots of {@code ownerAccount} that are shared with the caller. One that is not shared is left out, + * as it is for any caller that cannot see it, rather than refused. + */ + public List readable(String ownerAccount, List snapshots, + String region) { + return snapshots.stream().filter(snapshot -> isShared(snapshot, ownerAccount, region)).toList(); + } + + private boolean isShared(RedshiftServerlessSnapshot snapshot, String ownerAccount, String region) { + String policy = policies.policyOfSnapshot(ownerAccount, snapshot, region).orElse(null); + return policy != null && allows(policy, snapshot, ownerAccount, region); + } + + private boolean allows(String policy, RedshiftServerlessSnapshot snapshot, String ownerAccount, String region) { + CallerArns caller = callers.caller(); + // an account in one partition cannot be granted a snapshot of another, whatever the policy names + if (!AwsArnUtils.parse(snapshot.getSnapshotArn()).partition() + .equals(AwsArnUtils.parse(caller.callerArn()).partition())) { + return false; + } + Map> context = new HashMap<>(); + caller.putPrincipalKeys(context); + Map> effective = IamConditionContextResolver.withGlobalContext(context, + snapshot.getSnapshotArn(), region, regionResolver.getAccountId(), ownerAccount, GET_ACTION); + String normalizedPolicy = resourcePolicyProvider.withResource(policy, snapshot.getSnapshotArn()); + ResourcePolicyDecision decision = evaluator.evaluateResourcePolicyFor(List.of(normalizedPolicy), + RequestPrincipal.caller(caller), GET_ACTION, snapshot.getSnapshotArn(), effective); + // ALLOW_ACCOUNT is a grant to the caller's whole account, which a cross-account policy may give. + return decision == ResourcePolicyDecision.ALLOW || decision == ResourcePolicyDecision.ALLOW_ACCOUNT + || decision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER; + } +} diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java index 5c6e739352..2d36cc8864 100644 --- a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessAdministrationHandlerTest.java @@ -100,7 +100,7 @@ class RedshiftServerlessAdministrationHandlerTest { new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, serverlessService), new RedshiftServerlessScheduledActionService(storageFactory, serverlessService, mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)), - customDomains); + customDomains, mock(RedshiftServerlessSharedSnapshots.class)); } @Test diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessIntegrationTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessIntegrationTest.java index bd52de6318..62bf70dc7d 100644 --- a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessIntegrationTest.java @@ -658,6 +658,44 @@ class RedshiftServerlessIntegrationTest { .body("__type", equalTo("ValidationException")); } + @Test + void aSnapshotOfAnotherAccountIsReadAndOnlyTheSharedOnesAreListed() { + String owner = "111122223333"; + String caller = "444455556666"; + String allowCaller = "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\"," + + "\\\"Principal\\\":{\\\"AWS\\\":\\\"arn:aws:iam::" + caller + ":root\\\"}," + + "\\\"Action\\\":\\\"redshift-serverless:GetSnapshot\\\",\\\"Resource\\\":\\\"*\\\"}]}"; + + callAs(owner, "CreateNamespace", "{\"namespaceName\":\"read-src\",\"adminUsername\":\"admin\"}").statusCode(200); + String sharedArn = callAs(owner, "CreateSnapshot", + "{\"snapshotName\":\"read-shared\",\"namespaceName\":\"read-src\"}") + .statusCode(200).extract().path("snapshot.snapshotArn"); + callAs(owner, "CreateSnapshot", "{\"snapshotName\":\"read-private\",\"namespaceName\":\"read-src\"}") + .statusCode(200); + String get = "{\"snapshotName\":\"read-shared\",\"ownerAccount\":\"" + owner + "\"}"; + String list = "{\"ownerAccount\":\"" + owner + "\"}"; + + // GetSnapshot reads the owner's snapshot, and IAM enforcement checks its policy. The list leaves out what + // is not shared rather than refusing. + callAs(caller, "ListSnapshots", list).statusCode(200).body("snapshots", hasSize(0)); + + callAs(owner, "PutResourcePolicy", "{\"resourceArn\":\"" + sharedArn + "\",\"policy\":\"" + allowCaller + "\"}") + .statusCode(200); + callAs(caller, "GetSnapshot", get).statusCode(200) + .body("snapshot.snapshotName", equalTo("read-shared")) + .body("snapshot.ownerAccount", equalTo(owner)); + callAs(caller, "GetSnapshot", "{\"snapshotArn\":\"" + sharedArn + "\",\"ownerAccount\":\"" + owner + "\"}") + .statusCode(200).body("snapshot.snapshotName", equalTo("read-shared")); + callAs(caller, "ListSnapshots", list).statusCode(200) + .body("snapshots", hasSize(1)) + .body("snapshots[0].snapshotName", equalTo("read-shared")); + callAs(caller, "GetSnapshot", get.replace("read-shared", "no-such-snap")).statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + + callAs(owner, "DeleteResourcePolicy", "{\"resourceArn\":\"" + sharedArn + "\"}").statusCode(200); + callAs(caller, "ListSnapshots", list).statusCode(200).body("snapshots", hasSize(0)); + } + @Test void resourcePolicyIsIsolatedPerAccount() { String accountA = "111122223333"; diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java index d344d3fcd8..ec367455f3 100644 --- a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java @@ -134,7 +134,7 @@ class RedshiftServerlessJsonHandlerTest { new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, service), new RedshiftServerlessScheduledActionService(storageFactory, service, mock(RedshiftServerlessScheduledActionAuthorizer.class), regionResolver)), - customDomains); + customDomains, mock(RedshiftServerlessSharedSnapshots.class)); } @SuppressWarnings({"unchecked", "rawtypes"}) diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshotsTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshotsTest.java new file mode 100644 index 0000000000..0549526df4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSharedSnapshotsTest.java @@ -0,0 +1,114 @@ +package io.floci.aws.services.redshiftserverless; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; +import io.floci.aws.services.iam.IamPolicyEvaluator; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.RequestCallerResolver; +import io.floci.aws.services.redshiftserverless.model.RedshiftServerlessSnapshot; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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 RedshiftServerlessSharedSnapshotsTest { + + private static final String OWNER = "111111111111"; + private static final String CALLER = "222222222222"; + private static final String REGION = "us-east-1"; + private static final String SNAPSHOT_ARN = "arn:aws:redshift-serverless:us-east-1:" + OWNER + ":snapshot/shared"; + + private RedshiftServerlessResourcePolicyService policies; + private RedshiftServerlessSharedSnapshots shared; + private RedshiftServerlessSnapshot snapshot; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + policies = mock(RedshiftServerlessResourcePolicyService.class); + IamService iamService = mock(IamService.class); + when(iamService.resolveCallerArns(any())).thenReturn(Optional.empty()); + Instance requestContext = mock(Instance.class); + ObjectMapper objectMapper = new ObjectMapper(); + RegionResolver regionResolver = new RegionResolver(REGION, CALLER); + RedshiftServerlessResourcePolicyProvider resourcePolicyProvider = new RedshiftServerlessResourcePolicyProvider( + mock(RedshiftServerlessService.class), policies, objectMapper); + shared = new RedshiftServerlessSharedSnapshots(policies, + new IamPolicyEvaluator(objectMapper), regionResolver, + new RequestCallerResolver(iamService, regionResolver, requestContext), resourcePolicyProvider); + + snapshot = new RedshiftServerlessSnapshot(); + snapshot.setSnapshotName("shared"); + snapshot.setSnapshotArn(SNAPSHOT_ARN); + snapshot.setSnapshotCreateTime(Instant.parse("2030-01-01T00:00:00Z")); + } + + private void policy(String document) { + when(policies.policyOfSnapshot(eq(OWNER), eq(snapshot), eq(REGION))).thenReturn(Optional.of(document)); + } + + private static String statement(String effect, String principal) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"" + effect + "\",\"Principal\":{\"AWS\":\"" + + principal + "\"},\"Action\":\"redshift-serverless:GetSnapshot\",\"Resource\":\"*\"}]}"; + } + + @Test + void aResourceLessAllowSharesTheSnapshot() { + policy(statement("Allow", CALLER).replace(",\"Resource\":\"*\"", "")); + + assertEquals(List.of(snapshot), shared.readable(OWNER, List.of(snapshot), REGION)); + } + + @Test + void aResourceLessDenyOverridesAnExplicitAllow() { + policy(""" + {"Statement":[ + {"Effect":"Allow","Principal":{"AWS":"222222222222"}, + "Action":"redshift-serverless:GetSnapshot","Resource":"*"}, + {"Effect":"Deny","Principal":{"AWS":"222222222222"}, + "Action":"redshift-serverless:GetSnapshot"} + ]} + """); + + assertEquals(List.of(), shared.readable(OWNER, List.of(snapshot), REGION)); + } + + @Test + void aSingleResourceLessStatementSharesTheSnapshot() { + policy(""" + {"Statement":{"Effect":"Allow","Principal":{"AWS":"222222222222"}, + "Action":"redshift-serverless:GetSnapshot"}} + """); + + assertEquals(List.of(snapshot), shared.readable(OWNER, List.of(snapshot), REGION)); + } + + @Test + void readableKeepsOnlyTheSnapshotsSharedWithTheCaller() { + RedshiftServerlessSnapshot hidden = new RedshiftServerlessSnapshot(snapshot); + hidden.setSnapshotName("hidden"); + hidden.setSnapshotArn("arn:aws:redshift-serverless:us-east-1:" + OWNER + ":snapshot/hidden"); + policy(statement("Allow", "arn:aws:iam::" + CALLER + ":root")); + when(policies.policyOfSnapshot(eq(OWNER), eq(hidden), eq(REGION))).thenReturn(Optional.empty()); + + assertEquals(List.of(snapshot), shared.readable(OWNER, List.of(snapshot, hidden), REGION)); + } + + @Test + void aSnapshotOfAnotherPartitionIsNotSharedWhateverThePolicyNames() { + snapshot.setSnapshotArn("arn:aws-cn:redshift-serverless:cn-north-1:" + OWNER + ":snapshot/shared"); + policy(statement("Allow", CALLER)); + + assertEquals(List.of(), shared.readable(OWNER, List.of(snapshot), REGION)); + } +} diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java index 0da2637e0f..88a98b19d7 100644 --- a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java @@ -26,6 +26,7 @@ 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.hamcrest.Matchers.hasSize; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; @@ -73,6 +74,68 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest { Instant.now().plusSeconds(900), List.of())); } + @Test + void sharedSnapshotReadsAndListsRespectDenialsAndSnapshotRecreation() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String namespace = "read-src-" + suffix; + String snapshot = "read-shared-" + suffix; + String privateSnapshot = "read-private-" + suffix; + String callerKey = user(CALLER, """ + {"Statement":[{"Effect":"Allow","Action":["redshift-serverless:GetSnapshot", + "redshift-serverless:ListSnapshots"],"Resource":"*"}]} + """); + String allow = """ + {"Statement":{"Effect":"Allow","Principal":{"AWS":"%s"}, + "Action":"redshift-serverless:GetSnapshot"}} + """.formatted(CALLER); + String deny = """ + {"Statement":[ + {"Effect":"Allow","Principal":{"AWS":"%s"}, + "Action":"redshift-serverless:GetSnapshot","Resource":"*"}, + {"Effect":"Deny","Principal":{"AWS":"%s"}, + "Action":"redshift-serverless:GetSnapshot"} + ]} + """.formatted(CALLER, CALLER); + call(OWNER, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin")).statusCode(200); + String arn = call(OWNER, "CreateSnapshot", Map.of("snapshotName", snapshot, "namespaceName", namespace)) + .statusCode(200).extract().path("snapshot.snapshotArn"); + call(OWNER, "CreateSnapshot", Map.of("snapshotName", privateSnapshot, "namespaceName", namespace)).statusCode(200); + Map byName = Map.of("snapshotName", snapshot, "ownerAccount", OWNER); + Map byArn = Map.of("snapshotArn", arn, "ownerAccount", OWNER); + Map list = Map.of("ownerAccount", OWNER); + + readDenied(call(callerKey, "GetSnapshot", Map.of("snapshotName", privateSnapshot, "ownerAccount", OWNER))); + readDenied(call(callerKey, "GetSnapshot", byName)); + call(callerKey, "ListSnapshots", list).statusCode(200).body("snapshots", hasSize(0)); + + call(OWNER, "PutResourcePolicy", Map.of("resourceArn", arn, "policy", allow)).statusCode(200); + call(callerKey, "GetSnapshot", byName).statusCode(200).body("snapshot.snapshotName", equalTo(snapshot)); + call(callerKey, "GetSnapshot", byArn).statusCode(200).body("snapshot.snapshotName", equalTo(snapshot)); + call(callerKey, "ListSnapshots", list).statusCode(200) + .body("snapshots", hasSize(1)).body("snapshots[0].snapshotName", equalTo(snapshot)); + + call(OWNER, "PutResourcePolicy", Map.of("resourceArn", arn, "policy", deny)).statusCode(200); + readDenied(call(callerKey, "GetSnapshot", byName)); + call(callerKey, "ListSnapshots", list).statusCode(200).body("snapshots", hasSize(0)); + + call(OWNER, "DeleteResourcePolicy", Map.of("resourceArn", arn)).statusCode(200); + readDenied(call(callerKey, "GetSnapshot", byName)); + call(callerKey, "ListSnapshots", list).statusCode(200).body("snapshots", hasSize(0)); + + call(OWNER, "PutResourcePolicy", Map.of("resourceArn", arn, "policy", allow)).statusCode(200); + call(callerKey, "GetSnapshot", byName).statusCode(200); + call(OWNER, "DeleteSnapshot", Map.of("snapshotName", snapshot)).statusCode(200); + call(OWNER, "CreateSnapshot", Map.of("snapshotName", snapshot, "namespaceName", namespace)).statusCode(200); + readDenied(call(callerKey, "GetSnapshot", byName)); + readDenied(call(callerKey, "GetSnapshot", byArn)); + call(callerKey, "ListSnapshots", list).statusCode(200).body("snapshots", hasSize(0)); + } + + private static void readDenied(ValidatableResponse response) { + response.statusCode(400).body("__type", equalTo("AccessDeniedException")) + .body("message", containsString("redshift-serverless:GetSnapshot")); + } + @Test void aSnapshotIsRestorableByAnotherAccountOnlyWhenItsPolicyNamesTheCaller() { String suffix = UUID.randomUUID().toString().substring(0, 8);