mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(redshift): share a cluster snapshot with another account (#8077)
AuthorizeSnapshotAccess and RevokeSnapshotAccess record the accounts that may restore a manual, available snapshot. The snapshot reports OwnerAccount and AccountsWithRestoreAccess, DescribeClusterSnapshots takes an OwnerAccount filter that lists only what the owner shared with the caller, and RestoreFromClusterSnapshot takes an OwnerAccount (or a SnapshotArn of another account) and restores a shared snapshot from the owner's dump. A snapshot that is not shared is refused with AccessToSnapshotDenied, and the grant does not outlive the snapshot. IAM takes generated data only, so the RestoreFromClusterSnapshot correction is replaced by two rules in regen_iam_request_resources.py. A top-level request member whose name ends in Account gives the account of each type whose botocore structure has that same member: Snapshot has OwnerAccount and Cluster does not, so the snapshot moves to the owner's account and the restored cluster stays the caller's. Of several members that could fill a variable, one naming the type before the variable wins over a bare one, so the snapshot's ClusterName comes from SnapshotClusterIdentifier rather than ClusterIdentifier. Across every operation the rules change only that entry, which also gains DefaultIamRoleArn and RedshiftIdcApplicationArn as ARN rows that never match a cluster or snapshot, and CloudFront's GetInvalidationForDistributionTenant, whose tenant is now filled from DistributionTenantId rather than the invalidation's Id. The handler's SnapshotArn check now resolves the partition through RegionResolver, as the service's Region check does, so a Region outside the known partitions cannot make the two disagree.
This commit is contained in:
1 parent
9c0f644038
commit
315367f21f
15 files changed
+805
-45
No files matched your search
+97
@@ -0,0 +1,97 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.services.redshift.RedshiftClient;
|
||||
import software.amazon.awssdk.services.redshift.model.AccountWithRestoreAccess;
|
||||
import software.amazon.awssdk.services.redshift.model.RedshiftException;
|
||||
import software.amazon.awssdk.services.redshift.model.Snapshot;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/** Sharing a manual Redshift cluster snapshot with another account, through the AWS SDK for Java v2. */
|
||||
@DisplayName("Redshift snapshot sharing")
|
||||
class RedshiftSnapshotSharingTest {
|
||||
|
||||
private static final String OWNER = "111111111111";
|
||||
private static final String CALLER = "222222222222";
|
||||
private static final String SUFFIX = UUID.randomUUID().toString().substring(0, 8);
|
||||
private static final String CLUSTER = "share-c-" + SUFFIX;
|
||||
private static final String SNAPSHOT = "share-s-" + SUFFIX;
|
||||
private static final String RESTORED = "share-r-" + SUFFIX;
|
||||
|
||||
private static RedshiftClient owner;
|
||||
private static RedshiftClient caller;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
String endpoint = System.getenv("FLOCI_ENDPOINT");
|
||||
if (endpoint == null || endpoint.isBlank()) {
|
||||
endpoint = "http://localhost:4566";
|
||||
}
|
||||
if (!endpoint.startsWith("http")) {
|
||||
endpoint = "http://" + endpoint;
|
||||
}
|
||||
owner = client(endpoint, OWNER);
|
||||
caller = client(endpoint, CALLER);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
for (Runnable step : new Runnable[] {
|
||||
() -> caller.deleteCluster(r -> r.clusterIdentifier(RESTORED).skipFinalClusterSnapshot(true)),
|
||||
() -> owner.deleteClusterSnapshot(r -> r.snapshotIdentifier(SNAPSHOT)),
|
||||
() -> owner.deleteCluster(r -> r.clusterIdentifier(CLUSTER).skipFinalClusterSnapshot(true))}) {
|
||||
try {
|
||||
step.run();
|
||||
} catch (Exception ignored) {
|
||||
// Best effort: the test may have failed before creating the resource.
|
||||
}
|
||||
}
|
||||
owner.close();
|
||||
caller.close();
|
||||
}
|
||||
|
||||
private static RedshiftClient client(String endpoint, String account) {
|
||||
return RedshiftClient.builder().endpointOverride(URI.create(endpoint)).region(TestFixtures.region())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an authorized account restores the snapshot and a revoked one cannot")
|
||||
void authorizedAccountRestoresUntilRevoked() {
|
||||
owner.createCluster(r -> r.clusterIdentifier(CLUSTER).nodeType("dc2.large")
|
||||
.masterUsername("admin").masterUserPassword("Secret123"));
|
||||
Snapshot created = owner.createClusterSnapshot(r -> r.snapshotIdentifier(SNAPSHOT)
|
||||
.clusterIdentifier(CLUSTER)).snapshot();
|
||||
assertThat(created.ownerAccount()).isEqualTo(OWNER);
|
||||
|
||||
assertThatThrownBy(() -> caller.restoreFromClusterSnapshot(r -> r.clusterIdentifier(RESTORED)
|
||||
.snapshotIdentifier(SNAPSHOT).ownerAccount(OWNER)))
|
||||
.isInstanceOfSatisfying(RedshiftException.class,
|
||||
e -> assertThat(e.awsErrorDetails().errorCode()).isEqualTo("AccessToSnapshotDenied"));
|
||||
|
||||
Snapshot authorized = owner.authorizeSnapshotAccess(r -> r.snapshotIdentifier(SNAPSHOT)
|
||||
.accountWithRestoreAccess(CALLER)).snapshot();
|
||||
assertThat(authorized.accountsWithRestoreAccess()).extracting(AccountWithRestoreAccess::accountId)
|
||||
.containsExactly(CALLER);
|
||||
assertThat(caller.describeClusterSnapshots(r -> r.ownerAccount(OWNER)).snapshots())
|
||||
.extracting(Snapshot::snapshotIdentifier).containsExactly(SNAPSHOT);
|
||||
|
||||
caller.restoreFromClusterSnapshot(r -> r.clusterIdentifier(RESTORED)
|
||||
.snapshotIdentifier(SNAPSHOT).ownerAccount(OWNER));
|
||||
assertThat(caller.describeClusters(r -> r.clusterIdentifier(RESTORED)).clusters()).hasSize(1);
|
||||
|
||||
owner.revokeSnapshotAccess(r -> r.snapshotIdentifier(SNAPSHOT).accountWithRestoreAccess(CALLER));
|
||||
assertThat(caller.describeClusterSnapshots(r -> r.ownerAccount(OWNER)).snapshots()).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 |
|
||||
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 |
|
||||
| [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 16 |
|
||||
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 57 |
|
||||
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 59 |
|
||||
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
|
||||
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 |
|
||||
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 |
|
||||
|
||||
@@ -127,11 +127,13 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz
|
||||
| `DescribeClusters` | List clusters and their connection details |
|
||||
| `DeleteCluster` | Create the requested final snapshot, then remove the cluster; accepts `SkipFinalClusterSnapshot` to delete without a backup |
|
||||
| `CreateClusterSnapshot` | Back up a cluster to a SQL dump via `pg_dump` |
|
||||
| `DescribeClusterSnapshots` | List snapshots, optionally filtered by snapshot or cluster identifier and SnapshotType (manual or automated) |
|
||||
| `DescribeClusterSnapshots` | List snapshots, optionally filtered by snapshot or cluster identifier and SnapshotType (manual or automated). Every snapshot reports `OwnerAccount` and `AccountsWithRestoreAccess`. With `OwnerAccount` set to another account, only the snapshots that account has authorized the caller to restore are listed, and naming one that is not shared is `ClusterSnapshotNotFound` |
|
||||
| `AuthorizeSnapshotAccess` | Let another account restore a manual, available snapshot (`AccountWithRestoreAccess`, a 12 digit account id). Authorizing an account twice is `AuthorizationAlreadyExists` |
|
||||
| `RevokeSnapshotAccess` | Take the restore access of an account away; the next restore by it is refused. An account that was not authorized is `AuthorizationNotFound` |
|
||||
| `DeleteClusterSnapshot` | Remove a snapshot and its stored dump |
|
||||
| `ModifyClusterSnapshot` | Update the retention period of a manual cluster snapshot |
|
||||
| `CopyClusterSnapshot` | Copy an automated cluster snapshot to a manual snapshot with a new identifier and retention period |
|
||||
| `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql`; accepts `SnapshotIdentifier` or a same-account, same-region `SnapshotArn` |
|
||||
| `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql`; accepts `SnapshotIdentifier` or a same-region `SnapshotArn`. `OwnerAccount`, or a `SnapshotArn` of another account, restores a snapshot that account has authorized the caller to restore, and is refused with `AccessToSnapshotDenied` otherwise; the dump is read from the owner's directory and the cluster is created in the caller's account |
|
||||
| `CreateClusterParameterGroup` | Register a parameter group (metadata only) |
|
||||
| `DescribeClusterParameterGroups` | List parameter groups, optionally filtered by name |
|
||||
| `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` |
|
||||
@@ -616,7 +618,13 @@ For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyC
|
||||
update both the cluster's master password and its secret value; rotation requires an available
|
||||
cluster and does not use a Lambda function.
|
||||
- Snapshot restoration has the same limitations as `RestoreFromClusterSnapshot`: snapshots are
|
||||
local SQL dumps, not cross-account backups or a full Redshift engine image.
|
||||
local SQL dumps, not a full Redshift engine image.
|
||||
- Snapshot sharing is recorded on the snapshot. `AuthorizeSnapshotAccess` adds the account to
|
||||
`AccountsWithRestoreAccess` and `RevokeSnapshotAccess` removes it, so a snapshot deleted and taken again under
|
||||
the same name starts with no grant. Only a manual, available snapshot can be shared. A shared snapshot can be
|
||||
described and restored by the account it is shared with, and by no other action. The caller's own identity
|
||||
policies are the IAM filter's to check when IAM enforcement is on. KMS key grants are not checked, and a
|
||||
snapshot copied to another Region is shared only through the Region it was taken in.
|
||||
- `AWS::Redshift::ClusterSecurityGroup` is accepted as metadata: Floci does not emulate the legacy EC2-Classic security group model.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -201,7 +201,12 @@ public class RedshiftQueryHandler {
|
||||
case "DescribeClusterSnapshots" -> {
|
||||
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
|
||||
String clusterIdentifier = params.getFirst("ClusterIdentifier");
|
||||
List<Snapshot> snapshots = service.describeSnapshots(snapshotIdentifier, clusterIdentifier);
|
||||
String ownerAccount = params.getFirst("OwnerAccount");
|
||||
boolean shared = service.isOtherAccount(ownerAccount);
|
||||
List<Snapshot> snapshots = shared
|
||||
? service.describeSharedSnapshots(ownerAccount, snapshotIdentifier, clusterIdentifier)
|
||||
: service.describeSnapshots(snapshotIdentifier, clusterIdentifier);
|
||||
String owner = shared ? ownerAccount : regionResolver.getAccountId();
|
||||
String snapshotType = params.getFirst("SnapshotType");
|
||||
if (snapshotType != null) {
|
||||
if (!List.of("manual", "automated").contains(snapshotType)) {
|
||||
@@ -214,7 +219,7 @@ public class RedshiftQueryHandler {
|
||||
.start("DescribeClusterSnapshotsResult")
|
||||
.start("Snapshots");
|
||||
for (Snapshot snapshot : snapshots) {
|
||||
xmlBuilder.raw(buildSnapshotXml(snapshot));
|
||||
xmlBuilder.raw(buildSnapshotXml(snapshot, owner));
|
||||
}
|
||||
String xml = xmlBuilder
|
||||
.end("Snapshots")
|
||||
@@ -226,6 +231,31 @@ public class RedshiftQueryHandler {
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "AuthorizeSnapshotAccess", "RevokeSnapshotAccess" -> {
|
||||
boolean authorize = "AuthorizeSnapshotAccess".equals(action);
|
||||
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
|
||||
String snapshotClusterIdentifier = params.getFirst("SnapshotClusterIdentifier");
|
||||
RestoredSnapshot named = resolveSnapshot(snapshotIdentifier, snapshotClusterIdentifier,
|
||||
params.getFirst("SnapshotArn"), authorizationHeader);
|
||||
if (named.owner() != null) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + named.name() + " not found", 404);
|
||||
}
|
||||
String accountId = requireParam(params, "AccountWithRestoreAccess");
|
||||
Snapshot snapshot = authorize
|
||||
? service.authorizeSnapshotAccess(named.name(), named.cluster(), accountId)
|
||||
: service.revokeSnapshotAccess(named.name(), named.cluster(), accountId);
|
||||
String xml = new XmlBuilder()
|
||||
.start(action + "Response")
|
||||
.start(action + "Result")
|
||||
.raw(buildSnapshotXml(snapshot))
|
||||
.end(action + "Result")
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", "test-req-id")
|
||||
.end("ResponseMetadata")
|
||||
.end(action + "Response")
|
||||
.build();
|
||||
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
case "DeleteClusterSnapshot" -> {
|
||||
String snapshotIdentifier = params.getFirst("SnapshotIdentifier");
|
||||
Snapshot snapshot = service.deleteSnapshot(snapshotIdentifier, params.getFirst("SnapshotClusterIdentifier"));
|
||||
@@ -286,8 +316,9 @@ public class RedshiftQueryHandler {
|
||||
String nodeType = params.getFirst("NodeType");
|
||||
RestoredSnapshot snapshot = resolveSnapshot(snapshotIdentifier,
|
||||
params.getFirst("SnapshotClusterIdentifier"), snapshotArn, authorizationHeader);
|
||||
String ownerAccount = snapshot.owner() != null ? snapshot.owner() : params.getFirst("OwnerAccount");
|
||||
Cluster cluster = service.restoreFromClusterSnapshot(clusterIdentifier, snapshot.name(),
|
||||
snapshot.cluster(), nodeType);
|
||||
snapshot.cluster(), nodeType, ownerAccount);
|
||||
String xml = new XmlBuilder()
|
||||
.start("RestoreFromClusterSnapshotResponse")
|
||||
.start("RestoreFromClusterSnapshotResult")
|
||||
@@ -1253,8 +1284,14 @@ public class RedshiftQueryHandler {
|
||||
};
|
||||
}
|
||||
|
||||
/** The snapshot a restore names: its name, and the cluster it was taken from, which the request is checked on. */
|
||||
private record RestoredSnapshot(String cluster, String name) {
|
||||
/**
|
||||
* The snapshot a restore names: its name, and the cluster it was taken from, which the request is checked on.
|
||||
* {@code owner} is the account an ARN names when it is not the caller's, otherwise null.
|
||||
*/
|
||||
private record RestoredSnapshot(String cluster, String name, String owner) {
|
||||
RestoredSnapshot(String cluster, String name) {
|
||||
this(cluster, name, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1288,20 +1325,27 @@ public class RedshiftQueryHandler {
|
||||
|| slash < 0 || slash == resource.length() - 1) {
|
||||
throw new AwsException("InvalidParameterValue", "Invalid SnapshotArn: " + snapshotArn, 400);
|
||||
}
|
||||
// An ARN from another account or region must not match a local snapshot by name.
|
||||
if (!arn.accountId().equals(regionResolver.getAccountId())
|
||||
|| !arn.region().equals(regionResolver.resolveRegionFromAuth(authorizationHeader))) {
|
||||
// An ARN from another region must not match a local snapshot by name. One from another account names that
|
||||
// account's snapshot, which the service checks was shared with the caller.
|
||||
String requestRegion = regionResolver.resolveRegionFromAuth(authorizationHeader);
|
||||
if (!arn.region().equals(requestRegion)
|
||||
|| !arn.partition().equals(regionResolver.partitionForRegion(requestRegion))) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotArn + " not found", 404);
|
||||
}
|
||||
String owner = arn.accountId().equals(regionResolver.getAccountId()) ? null : arn.accountId();
|
||||
String cluster = resource.substring("snapshot:".length(), slash);
|
||||
if (cluster.isBlank() || snapshotClusterIdentifier != null && !snapshotClusterIdentifier.isBlank()
|
||||
&& !snapshotClusterIdentifier.equals(cluster)) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotArn + " not found", 404);
|
||||
}
|
||||
return new RestoredSnapshot(cluster, resource.substring(slash + 1));
|
||||
return new RestoredSnapshot(cluster, resource.substring(slash + 1), owner);
|
||||
}
|
||||
|
||||
private String buildSnapshotXml(Snapshot snapshot) {
|
||||
return buildSnapshotXml(snapshot, regionResolver.getAccountId());
|
||||
}
|
||||
|
||||
private String buildSnapshotXml(Snapshot snapshot, String ownerAccount) {
|
||||
// Both are absent on snapshots persisted before these fields existed; omit them.
|
||||
String createTime = snapshot.getSnapshotCreateTime() != null
|
||||
? DateTimeFormatter.ISO_INSTANT.format(snapshot.getSnapshotCreateTime())
|
||||
@@ -1317,7 +1361,13 @@ public class RedshiftQueryHandler {
|
||||
.elem("Status", snapshot.getStatus())
|
||||
.elem("Port", String.valueOf(snapshot.getPort()))
|
||||
.elem("MasterUsername", snapshot.getMasterUsername())
|
||||
.elem("SourceRegion", snapshot.getSourceRegion());
|
||||
.elem("SourceRegion", snapshot.getSourceRegion())
|
||||
.elem("OwnerAccount", ownerAccount)
|
||||
.start("AccountsWithRestoreAccess");
|
||||
for (String account : snapshot.getAccountsWithRestoreAccess()) {
|
||||
builder.start("AccountWithRestoreAccess").elem("AccountId", account).end("AccountWithRestoreAccess");
|
||||
}
|
||||
builder.end("AccountsWithRestoreAccess");
|
||||
if (snapshot.getKmsKeyId() != null) {
|
||||
builder.elem("Encrypted", "true").elem("KmsKeyId", snapshot.getKmsKeyId());
|
||||
}
|
||||
|
||||
@@ -1942,10 +1942,14 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
* createSnapshot (or by a different account).
|
||||
*/
|
||||
private boolean isTrustedDumpPath(String storedPath) {
|
||||
return isTrustedDumpPath(storedPath, clusters.accountId());
|
||||
}
|
||||
|
||||
private boolean isTrustedDumpPath(String storedPath, String ownerAccount) {
|
||||
if (storedPath == null || storedPath.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
Path dir = accountDumpDir();
|
||||
Path dir = accountDumpDir(ownerAccount);
|
||||
return Paths.get(storedPath).toAbsolutePath().normalize().startsWith(dir);
|
||||
}
|
||||
|
||||
@@ -2103,6 +2107,113 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
return describeSnapshots(snapshotIdentifier, null);
|
||||
}
|
||||
|
||||
/** Whether {@code ownerAccount} names an account other than the caller's. */
|
||||
public boolean isOtherAccount(String ownerAccount) {
|
||||
return ownerAccount != null && !ownerAccount.isBlank() && !ownerAccount.equals(clusters.accountId());
|
||||
}
|
||||
|
||||
/**
|
||||
* The snapshots {@code ownerAccount} has authorized the caller to restore, narrowed as
|
||||
* {@link #describeSnapshots(String, String)} is. One the owner has not shared is left out of a listing, and
|
||||
* reported as not found when named.
|
||||
*/
|
||||
public List<Snapshot> describeSharedSnapshots(String ownerAccount, String snapshotIdentifier,
|
||||
String clusterIdentifier) {
|
||||
List<Snapshot> shared = snapshots.scanForAccount(ownerAccount, key -> true).stream()
|
||||
.filter(this::isSharedWithCaller)
|
||||
.filter(this::isInRequestRegion)
|
||||
.filter(snapshot -> takenFrom(snapshot, clusterIdentifier))
|
||||
.toList();
|
||||
if (snapshotIdentifier == null || snapshotIdentifier.isBlank()) {
|
||||
return shared;
|
||||
}
|
||||
List<Snapshot> named = shared.stream()
|
||||
.filter(snapshot -> snapshotIdentifier.equals(snapshot.getSnapshotIdentifier())).toList();
|
||||
if (named.isEmpty()) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404);
|
||||
}
|
||||
return named;
|
||||
}
|
||||
|
||||
private boolean isInRequestRegion(Snapshot snapshot) {
|
||||
if (snapshot.getSnapshotArn() == null) {
|
||||
return true;
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(snapshot.getSnapshotArn());
|
||||
return arn.region().equals(regionResolver.getRegion())
|
||||
&& arn.partition().equals(regionResolver.getPartition());
|
||||
}
|
||||
|
||||
private boolean isSharedWithCaller(Snapshot snapshot) {
|
||||
return snapshot.getAccountsWithRestoreAccess().contains(clusters.accountId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets {@code accountId} restore the manual snapshot, as AuthorizeSnapshotAccess does. The grant lives on the
|
||||
* snapshot record, so a snapshot deleted and taken again under the same name starts with none.
|
||||
*/
|
||||
public Snapshot authorizeSnapshotAccess(String snapshotIdentifier, String snapshotClusterIdentifier,
|
||||
String accountId) {
|
||||
requireAccountId(accountId);
|
||||
return withResourceLock("snapshot", snapshotIdentifier, () -> {
|
||||
Snapshot snapshot = shareableSnapshot(snapshotIdentifier, snapshotClusterIdentifier);
|
||||
if (!snapshot.getAccountsWithRestoreAccess().add(accountId)) {
|
||||
throw new AwsException("AuthorizationAlreadyExists",
|
||||
"The specified AccountId is already authorized to restore " + snapshotIdentifier, 400);
|
||||
}
|
||||
saveSnapshot(snapshot);
|
||||
return snapshot;
|
||||
});
|
||||
}
|
||||
|
||||
/** Takes the restore access of {@code accountId} away, as RevokeSnapshotAccess does. */
|
||||
public Snapshot revokeSnapshotAccess(String snapshotIdentifier, String snapshotClusterIdentifier,
|
||||
String accountId) {
|
||||
requireAccountId(accountId);
|
||||
return withResourceLock("snapshot", snapshotIdentifier, () -> {
|
||||
Snapshot snapshot = shareableSnapshot(snapshotIdentifier, snapshotClusterIdentifier);
|
||||
if (!snapshot.getAccountsWithRestoreAccess().remove(accountId)) {
|
||||
throw new AwsException("AuthorizationNotFound",
|
||||
"The specified AccountId is not authorized to restore " + snapshotIdentifier, 404);
|
||||
}
|
||||
saveSnapshot(snapshot);
|
||||
return snapshot;
|
||||
});
|
||||
}
|
||||
|
||||
private static void requireAccountId(String accountId) {
|
||||
if (accountId == null || !accountId.matches("[0-9]{12}")) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"AccountWithRestoreAccess must be a 12 digit account id", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private Snapshot shareableSnapshot(String snapshotIdentifier, String snapshotClusterIdentifier) {
|
||||
String copyKey = copyKey(regionResolver.getRegion(), snapshotIdentifier);
|
||||
if (snapshotCopies.get(copyKey).isPresent()) {
|
||||
throw new AwsException("InvalidClusterSnapshotState",
|
||||
"Snapshot " + snapshotIdentifier + " is not an available manual snapshot, which is the only kind"
|
||||
+ " that can be shared", 400);
|
||||
}
|
||||
Snapshot snapshot = snapshots.get(snapshotIdentifier)
|
||||
.filter(this::isInRequestRegion)
|
||||
.filter(found -> takenFrom(found, snapshotClusterIdentifier))
|
||||
.orElseThrow(() -> new AwsException("ClusterSnapshotNotFound",
|
||||
"Snapshot " + snapshotIdentifier + " not found", 404));
|
||||
if (!"available".equals(snapshot.getStatus()) || !"manual".equals(snapshot.getSnapshotType())) {
|
||||
throw new AwsException("InvalidClusterSnapshotState",
|
||||
"Snapshot " + snapshotIdentifier + " is not an available manual snapshot, which is the only kind"
|
||||
+ " that can be shared", 400);
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private void saveSnapshot(Snapshot snapshot) {
|
||||
String identifier = snapshot.getSnapshotIdentifier();
|
||||
snapshots.putAllAtomically(Map.of(identifier, snapshot));
|
||||
snapshots.flush();
|
||||
}
|
||||
|
||||
public Optional<Snapshot> getSnapshot(String snapshotIdentifier) {
|
||||
return findSnapshot(snapshotIdentifier);
|
||||
}
|
||||
@@ -2207,6 +2318,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
copy.setScheduledTime(null);
|
||||
copy.setSnapshotArn(snapshotArn(source.getClusterIdentifier(), targetSnapshotIdentifier));
|
||||
copy.setCopiedToRegions(new LinkedHashSet<>());
|
||||
copy.setAccountsWithRestoreAccess(new LinkedHashSet<>());
|
||||
copy.setSqlDump(null);
|
||||
|
||||
Path copiedDump = null;
|
||||
@@ -2303,10 +2415,26 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
/** Restores the snapshot, which must have been taken from {@code snapshotClusterIdentifier} when one is given. */
|
||||
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier,
|
||||
String snapshotClusterIdentifier, String nodeType) {
|
||||
return restoreFromClusterSnapshot(clusterIdentifier, snapshotIdentifier, snapshotClusterIdentifier, nodeType,
|
||||
null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores the snapshot {@code ownerAccount} owns, when it has authorized the caller to restore it. Without an
|
||||
* owner, or with the caller's own account, the snapshot is the caller's.
|
||||
*/
|
||||
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier,
|
||||
String snapshotClusterIdentifier, String nodeType,
|
||||
String ownerAccount) {
|
||||
if (ownerAccount != null && !ownerAccount.isBlank() && !ownerAccount.matches("[0-9]{12}")) {
|
||||
throw new AwsException("InvalidParameterValue", "OwnerAccount must be a 12 digit account id", 400);
|
||||
}
|
||||
String snapshotOwner = isOtherAccount(ownerAccount) ? ownerAccount : clusters.accountId();
|
||||
return withResourceLock("cluster", clusterIdentifier, () -> {
|
||||
ensureNoManagedRotation(clusters.accountId(), clusterIdentifier);
|
||||
return withResourceLock("snapshot", snapshotIdentifier, () -> mutate(
|
||||
() -> restoreSnapshot(clusterIdentifier, snapshotIdentifier, snapshotClusterIdentifier, nodeType)));
|
||||
return withResourceLock(snapshotOwner, "snapshot", snapshotIdentifier, () -> mutate(
|
||||
() -> restoreSnapshot(clusterIdentifier, snapshotIdentifier, snapshotClusterIdentifier, nodeType,
|
||||
snapshotOwner)));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2319,7 +2447,8 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
return withResourceLock("cluster", clusterIdentifier, () -> withResourceLock("snapshot", snapshotIdentifier,
|
||||
() -> {
|
||||
ensureNoManagedRotation(clusters.accountId(), clusterIdentifier);
|
||||
Cluster cluster = restoreSnapshot(clusterIdentifier, snapshotIdentifier, null, nodeType);
|
||||
Cluster cluster = restoreSnapshot(clusterIdentifier, snapshotIdentifier, null, nodeType,
|
||||
clusters.accountId());
|
||||
try {
|
||||
cluster.setClusterSubnetGroupName(clusterSubnetGroupName);
|
||||
if (manageMasterPassword) {
|
||||
@@ -2362,18 +2491,25 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
}
|
||||
|
||||
private Cluster restoreSnapshot(String clusterIdentifier, String snapshotIdentifier,
|
||||
String snapshotClusterIdentifier, String nodeType) {
|
||||
String snapshotClusterIdentifier, String nodeType, String snapshotOwner) {
|
||||
if (clusters.get(clusterIdentifier).isPresent()) {
|
||||
throw new AwsException("ClusterAlreadyExists", "Cluster " + clusterIdentifier + " already exists", 400);
|
||||
}
|
||||
|
||||
Optional<Snapshot> snapshotOpt = findSnapshot(snapshotIdentifier)
|
||||
.filter(found -> takenFrom(found, snapshotClusterIdentifier));
|
||||
boolean shared = !snapshotOwner.equals(clusters.accountId());
|
||||
Optional<Snapshot> snapshotOpt = (shared ? snapshots.getForAccount(snapshotOwner, snapshotIdentifier)
|
||||
: findSnapshot(snapshotIdentifier))
|
||||
.filter(found -> takenFrom(found, snapshotClusterIdentifier))
|
||||
.filter(found -> !shared || isInRequestRegion(found));
|
||||
if (snapshotOpt.isEmpty()) {
|
||||
throw new AwsException("ClusterSnapshotNotFound", "Snapshot " + snapshotIdentifier + " not found", 404);
|
||||
}
|
||||
|
||||
Snapshot snapshot = snapshotOpt.get();
|
||||
if (shared && !isSharedWithCaller(snapshot)) {
|
||||
throw new AwsException("AccessToSnapshotDenied", "The owner of snapshot " + snapshotIdentifier
|
||||
+ " has not authorized your account to restore it", 400);
|
||||
}
|
||||
|
||||
// Validate the stored dump location up front, before any provisioning. A snapshot whose
|
||||
// sqlDump was written by pre-validation code could point outside this account's dump dir;
|
||||
@@ -2381,7 +2517,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
// and an orphaned container behind.
|
||||
String sqlDump = snapshot.getSqlDump();
|
||||
boolean hasDump = sqlDump != null && !sqlDump.isBlank();
|
||||
if (hasDump && !isTrustedDumpPath(sqlDump)) {
|
||||
if (hasDump && !isTrustedDumpPath(sqlDump, snapshotOwner)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Snapshot " + snapshotIdentifier + " has an unusable dump location", 400);
|
||||
}
|
||||
@@ -2391,7 +2527,8 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
String sourceCluster = snapshot.getClusterIdentifier();
|
||||
String password = Optional.ofNullable(snapshot.getMasterPassword())
|
||||
.filter(p -> !p.isBlank())
|
||||
.or(() -> clusters.get(sourceCluster).map(Cluster::getMasterPassword))
|
||||
.or(() -> (shared ? clusters.getForAccount(snapshotOwner, sourceCluster) : clusters.get(sourceCluster))
|
||||
.map(Cluster::getMasterPassword))
|
||||
.filter(p -> p != null && !p.isBlank())
|
||||
.orElse("admin");
|
||||
|
||||
@@ -3379,6 +3516,7 @@ public class RedshiftService implements ManagedSecretRotator {
|
||||
copy.setSqlDump(dump == null ? null : dump.toString());
|
||||
copy.setCopiedToRegions(new LinkedHashSet<>());
|
||||
copy.setTags(new LinkedHashMap<>());
|
||||
copy.setAccountsWithRestoreAccess(new LinkedHashSet<>());
|
||||
copy.setKmsKeyId(Optional.ofNullable(cluster.getSnapshotCopyGrantName())
|
||||
.flatMap(name -> snapshotCopyGrants.getForAccount(accountId, name))
|
||||
.map(SnapshotCopyGrant::getKmsKeyId).orElse(null));
|
||||
|
||||
@@ -29,6 +29,7 @@ public class Snapshot {
|
||||
private Instant sourceSnapshotCreateTime;
|
||||
private String kmsKeyId;
|
||||
private Set<String> copiedToRegions = new LinkedHashSet<>();
|
||||
private Set<String> accountsWithRestoreAccess = new LinkedHashSet<>();
|
||||
|
||||
public String getSourceRegion() { return sourceRegion; }
|
||||
public void setSourceRegion(String value) { sourceRegion = value; }
|
||||
@@ -76,6 +77,7 @@ public class Snapshot {
|
||||
this.sourceSnapshotCreateTime = other.sourceSnapshotCreateTime;
|
||||
this.kmsKeyId = other.kmsKeyId;
|
||||
this.copiedToRegions = new LinkedHashSet<>(other.copiedToRegions);
|
||||
this.accountsWithRestoreAccess = new LinkedHashSet<>(other.accountsWithRestoreAccess);
|
||||
this.tags = new LinkedHashMap<>(other.tags);
|
||||
}
|
||||
|
||||
@@ -178,6 +180,11 @@ public class Snapshot {
|
||||
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public Set<String> getAccountsWithRestoreAccess() { return accountsWithRestoreAccess; }
|
||||
public void setAccountsWithRestoreAccess(Set<String> value) {
|
||||
accountsWithRestoreAccess = value == null ? new LinkedHashSet<>() : new LinkedHashSet<>(value);
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
@@ -401,7 +401,7 @@
|
||||
"cloudfront:GetFieldLevelEncryptionProfileConfig": {"action": "cloudfront:GetFieldLevelEncryptionProfileConfig", "types": ["field-level-encryption-profile"], "resources": [{"type": "field-level-encryption-profile", "fill": {"Id": "Id"}}], "located": {"Id": "{Id}"}},
|
||||
"cloudfront:GetFunction": {"action": "cloudfront:GetFunction", "types": ["function"], "resources": [{"type": "function", "fill": {"Name": "Name"}}], "located": {"Name": "{Name}"}},
|
||||
"cloudfront:GetInvalidation": {"action": "cloudfront:GetInvalidation", "types": ["distribution"], "resources": [{"type": "distribution", "fill": {"DistributionId": "DistributionId"}}], "located": {"DistributionId": "{DistributionId}"}},
|
||||
"cloudfront:GetInvalidationForDistributionTenant": {"action": "cloudfront:GetInvalidationForDistributionTenant", "types": ["distribution-tenant"], "resources": [{"type": "distribution-tenant", "fill": {"Id": "Id"}}], "located": {"Id": "{Id}"}},
|
||||
"cloudfront:GetInvalidationForDistributionTenant": {"action": "cloudfront:GetInvalidationForDistributionTenant", "types": ["distribution-tenant"], "resources": [{"type": "distribution-tenant", "fill": {"Id": "DistributionTenantId"}}], "located": {"DistributionTenantId": "{DistributionTenantId}", "Id": "{Id}"}},
|
||||
"cloudfront:GetKeyGroup": {"action": "cloudfront:GetKeyGroup", "types": [], "resources": []},
|
||||
"cloudfront:GetKeyGroupConfig": {"action": "cloudfront:GetKeyGroupConfig", "types": [], "resources": []},
|
||||
"cloudfront:GetManagedCertificateDetails": {"action": "cloudfront:GetManagedCertificateDetails", "types": ["distribution-tenant"], "resources": []},
|
||||
@@ -3168,7 +3168,7 @@
|
||||
"redshift:RejectDataShare": {"action": "redshift:RejectDataShare", "types": ["datashare"], "resources": [{"types": ["datashare"], "arn": "DataShareArn"}]},
|
||||
"redshift:ResetClusterParameterGroup": {"action": "redshift:ResetClusterParameterGroup", "types": ["parametergroup"], "resources": [{"type": "parametergroup", "fill": {"ParameterGroupName": "ParameterGroupName"}}]},
|
||||
"redshift:ResizeCluster": {"action": "redshift:ResizeCluster", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}]},
|
||||
"redshift:RestoreFromClusterSnapshot": {"action": "redshift:RestoreFromClusterSnapshot", "types": ["cluster", "snapshot"], "resources": [{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "snapshot", "fill": {"ClusterName": "SnapshotClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}}, {"types": ["snapshot"], "arn": "SnapshotArn"}]},
|
||||
"redshift:RestoreFromClusterSnapshot": {"action": "redshift:RestoreFromClusterSnapshot", "types": ["cluster", "snapshot"], "resources": [{"types": ["cluster", "snapshot"], "arn": "DefaultIamRoleArn"}, {"types": ["cluster", "snapshot"], "arn": "RedshiftIdcApplicationArn"}, {"types": ["cluster", "snapshot"], "arn": "SnapshotArn"}, {"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "snapshot", "fill": {"ClusterName": "SnapshotClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}, "account": "OwnerAccount"}]},
|
||||
"redshift:RestoreTableFromClusterSnapshot": {"action": "redshift:RestoreTableFromClusterSnapshot", "types": ["cluster", "snapshot"], "resources": [{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}, {"type": "snapshot", "fill": {"ClusterName": "ClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}}]},
|
||||
"redshift:ResumeCluster": {"action": "redshift:ResumeCluster", "types": ["cluster"], "resources": [{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}}]},
|
||||
"redshift:RevokeClusterSecurityGroupIngress": {"action": "redshift:RevokeClusterSecurityGroupIngress", "types": ["securitygroup", "securitygroupingress-ec2securitygroup"], "resources": []},
|
||||
|
||||
@@ -1114,6 +1114,20 @@ class RequestResourcesTest {
|
||||
form("Action=GetClusterCredentials&ClusterIdentifier=prod&DbUser=analyst&DbName=dev")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void redshiftRestoreFromClusterSnapshotUsesOwnerAccountForSourceSnapshot() {
|
||||
String own = "arn:aws:redshift:us-east-1:000000000000:";
|
||||
String owner = "arn:aws:redshift:us-east-1:111122223333:";
|
||||
assertEquals(List.of(own + "cluster:restored", owner + "snapshot:source/snap"),
|
||||
of("redshift:RestoreFromClusterSnapshot",
|
||||
form("Action=RestoreFromClusterSnapshot&ClusterIdentifier=restored&SnapshotIdentifier=snap"
|
||||
+ "&SnapshotClusterIdentifier=source&OwnerAccount=111122223333")));
|
||||
assertEquals(List.of(own + "cluster:restored", own + "snapshot:source/snap"),
|
||||
of("redshift:RestoreFromClusterSnapshot",
|
||||
form("Action=RestoreFromClusterSnapshot&ClusterIdentifier=restored&SnapshotIdentifier=snap"
|
||||
+ "&SnapshotClusterIdentifier=source")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestNamingNoResourceOrOfANamespaceTheTableDoesNotReadIsCheckedOnStar() {
|
||||
assertEquals(List.of(), of("ecr:DescribeRepositories", json("{}")));
|
||||
|
||||
+32
@@ -1734,6 +1734,38 @@ class IamRequestResourceEnforcementIntegrationTest {
|
||||
refused(restore(user, restored, source), "redshift:RestoreFromClusterSnapshot");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRedshiftRestoreWithOwnerAccountIsCheckedOnTheOwnerSnapshot() {
|
||||
String source = "res-source-" + suffix();
|
||||
String restored = "res-restored-" + suffix();
|
||||
String ownerAccount = "111122223333";
|
||||
String ownerSnapshotArn = "arn:aws:redshift:us-east-1:" + ownerAccount + ":snapshot:" + source + "/snap";
|
||||
User user = user("res-redshift-restore-owner");
|
||||
|
||||
user.policy(allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "cluster:" + restored) + ","
|
||||
+ allowOn("redshift:RestoreFromClusterSnapshot", ownerSnapshotArn));
|
||||
restoreWithOwner(user, restored, source, ownerAccount)
|
||||
.statusCode(404).body(containsString("ClusterSnapshotNotFound"));
|
||||
|
||||
user.policy(allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "cluster:" + restored) + ","
|
||||
+ allowOn("redshift:RestoreFromClusterSnapshot", "*") + ","
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"redshift:RestoreFromClusterSnapshot\",\"Resource\":\""
|
||||
+ ownerSnapshotArn + "\"}");
|
||||
refused(restoreWithOwner(user, restored, source, ownerAccount), "redshift:RestoreFromClusterSnapshot");
|
||||
|
||||
user.policy(allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "cluster:" + restored) + ","
|
||||
+ allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "snapshot:" + source + "/snap"));
|
||||
refused(restoreWithOwner(user, restored, source, ownerAccount), "redshift:RestoreFromClusterSnapshot");
|
||||
}
|
||||
|
||||
private static ValidatableResponse restoreWithOwner(User user, String cluster, String snapshotCluster,
|
||||
String ownerAccount) {
|
||||
return user.query("redshift", "RestoreFromClusterSnapshot").formParam("Version", "2012-12-01")
|
||||
.formParam("ClusterIdentifier", cluster).formParam("SnapshotIdentifier", "snap")
|
||||
.formParam("SnapshotClusterIdentifier", snapshotCluster)
|
||||
.formParam("OwnerAccount", ownerAccount).post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse redshiftTag(User user, String arn) {
|
||||
return user.query("redshift", "CreateTags").formParam("Version", "2012-12-01").formParam("ResourceName", arn)
|
||||
.formParam("Tags.Tag.1.Key", "team").formParam("Tags.Tag.1.Value", "data").post("/").then();
|
||||
|
||||
@@ -364,6 +364,7 @@ class RedshiftQueryHandlerTest {
|
||||
regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("acc");
|
||||
when(regionResolver.resolveRegionFromAuth(anyString())).thenReturn("us-east-1");
|
||||
when(regionResolver.partitionForRegion(anyString())).thenReturn("aws");
|
||||
handler = new RedshiftQueryHandler(service, credentialBroker, config, iamDbUserResolver, regionResolver);
|
||||
}
|
||||
|
||||
@@ -621,7 +622,7 @@ class RedshiftQueryHandlerTest {
|
||||
cluster.setMasterUsername("admin");
|
||||
cluster.setClusterStatus("available");
|
||||
cluster.setEndpoint(new Endpoint("localhost", 5439));
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", null, "dc2.large")).thenReturn(cluster);
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", null, "dc2.large", null)).thenReturn(cluster);
|
||||
|
||||
Response response = handler.handle("RestoreFromClusterSnapshot", params);
|
||||
assertEquals(200, response.getStatus());
|
||||
@@ -638,11 +639,11 @@ class RedshiftQueryHandlerTest {
|
||||
params.putSingle("ClusterIdentifier", "restored-cluster");
|
||||
params.putSingle("SnapshotArn", "arn:aws:redshift:us-east-1:acc:snapshot:src/my-snap");
|
||||
Cluster cluster = availableCluster("restored-cluster");
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null)).thenReturn(cluster);
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null, null)).thenReturn(cluster);
|
||||
|
||||
Response response = handler.handle("RestoreFromClusterSnapshot", params, "auth");
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(service).restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null);
|
||||
verify(service).restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -668,15 +669,53 @@ class RedshiftQueryHandlerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromClusterSnapshotForeignAccountArnNotFound() {
|
||||
void restoreFromClusterSnapshotForeignAccountArnNamesTheOwner() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "restored-cluster");
|
||||
params.putSingle("SnapshotArn", "arn:aws:redshift:us-east-1:999999999999:snapshot:src/my-snap");
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null, "999999999999"))
|
||||
.thenReturn(availableCluster("restored-cluster"));
|
||||
|
||||
Response response = handler.handle("RestoreFromClusterSnapshot", params, "auth");
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(service).restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null, "999999999999");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromClusterSnapshotOfAnotherRegionArnIsNotFound() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "restored-cluster");
|
||||
params.putSingle("SnapshotArn", "arn:aws:redshift:eu-west-1:999999999999:snapshot:src/my-snap");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
|
||||
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromClusterSnapshotOfAnotherPartitionArnIsNotFound() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "restored-cluster");
|
||||
params.putSingle("SnapshotArn", "arn:aws-cn:redshift:us-east-1:999999999999:snapshot:src/my-snap");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
|
||||
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromClusterSnapshotPassesTheOwnerAccountItNames() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ClusterIdentifier", "restored-cluster");
|
||||
params.putSingle("SnapshotIdentifier", "my-snap");
|
||||
params.putSingle("OwnerAccount", "999999999999");
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "my-snap", null, null, "999999999999"))
|
||||
.thenReturn(availableCluster("restored-cluster"));
|
||||
|
||||
assertEquals(200, handler.handle("RestoreFromClusterSnapshot", params, "auth").getStatus());
|
||||
verify(service).restoreFromClusterSnapshot("restored-cluster", "my-snap", null, null, "999999999999");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -690,7 +729,7 @@ class RedshiftQueryHandlerTest {
|
||||
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
|
||||
assertEquals("InvalidParameterCombination", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
/** The cluster a request is authorized on, snapshot:<cluster>/<name>, is the one its snapshot must be of. */
|
||||
@@ -712,11 +751,11 @@ class RedshiftQueryHandlerTest {
|
||||
params.putSingle("ClusterIdentifier", "restored-cluster");
|
||||
params.putSingle("SnapshotIdentifier", "test-snapshot");
|
||||
params.putSingle("SnapshotClusterIdentifier", "prod");
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "prod", null))
|
||||
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "prod", null, null))
|
||||
.thenReturn(availableCluster("restored-cluster"));
|
||||
|
||||
assertEquals(200, handler.handle("RestoreFromClusterSnapshot", params, "auth").getStatus());
|
||||
verify(service).restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "prod", null);
|
||||
verify(service).restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "prod", null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -730,7 +769,7 @@ class RedshiftQueryHandlerTest {
|
||||
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
|
||||
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
|
||||
assertEquals(404, ex.getHttpStatus());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -742,7 +781,7 @@ class RedshiftQueryHandlerTest {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
|
||||
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
|
||||
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -2053,6 +2053,89 @@ class RedshiftServiceTest {
|
||||
verifyNoInteractions(cm);
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeSnapshotAccessRecordsTheAccountOnceAndRevokeRemovesIt() {
|
||||
Snapshot snapshot = snapshotOf("snap-1", "c1");
|
||||
snapshot.setStatus("available");
|
||||
snapshot.setSnapshotType("manual");
|
||||
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshot));
|
||||
|
||||
assertTrue(service.authorizeSnapshotAccess("snap-1", null, "222222222222")
|
||||
.getAccountsWithRestoreAccess().contains("222222222222"));
|
||||
assertEquals("AuthorizationAlreadyExists", assertThrows(AwsException.class,
|
||||
() -> service.authorizeSnapshotAccess("snap-1", null, "222222222222")).getErrorCode());
|
||||
assertTrue(service.revokeSnapshotAccess("snap-1", null, "222222222222")
|
||||
.getAccountsWithRestoreAccess().isEmpty());
|
||||
assertEquals("AuthorizationNotFound", assertThrows(AwsException.class,
|
||||
() -> service.revokeSnapshotAccess("snap-1", null, "222222222222")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAutomatedSnapshotCannotBeShared() {
|
||||
Snapshot snapshot = snapshotOf("snap-auto", "c1");
|
||||
snapshot.setStatus("available");
|
||||
snapshot.setSnapshotType("automated");
|
||||
when(snapshotBackend.get("snap-auto")).thenReturn(Optional.of(snapshot));
|
||||
|
||||
assertEquals("InvalidClusterSnapshotState", assertThrows(AwsException.class,
|
||||
() -> service.authorizeSnapshotAccess("snap-auto", null, "222222222222")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccountIdThatIsNotTwelveDigitsIsRefused() {
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> service.authorizeSnapshotAccess("snap-1", null, "not-an-account")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeSharedSnapshotsListsOnlyWhatTheOwnerAuthorizedTheCallerToRestore() {
|
||||
Snapshot shared = snapshotOf("shared", "c1");
|
||||
shared.getAccountsWithRestoreAccess().add("111111111111");
|
||||
Snapshot hidden = snapshotOf("hidden", "c1");
|
||||
when(snapshotBackend.scanForAccount(eq("999999999999"), any())).thenReturn(List.of(shared, hidden));
|
||||
|
||||
assertEquals(List.of(shared), service.describeSharedSnapshots("999999999999", null, null));
|
||||
assertEquals(List.of(shared), service.describeSharedSnapshots("999999999999", "shared", "c1"));
|
||||
assertEquals("ClusterSnapshotNotFound", assertThrows(AwsException.class,
|
||||
() -> service.describeSharedSnapshots("999999999999", "hidden", null)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreOfASnapshotTheOwnerHasNotSharedIsDenied() {
|
||||
when(snapshotBackend.getForAccount("999999999999", "snap-1")).thenReturn(Optional.of(snapshotOf("snap-1", "c1")));
|
||||
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.restoreFromClusterSnapshot("c1", "snap-1", null, null, "999999999999"));
|
||||
assertEquals("AccessToSnapshotDenied", ex.getErrorCode());
|
||||
verifyNoInteractions(cm);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeSharedSnapshotsAndRestoreDenyCrossRegionSnapshotByName() {
|
||||
Snapshot foreignRegionSnap = snapshotOf("shared-foreign", "c1");
|
||||
foreignRegionSnap.setSnapshotArn("arn:aws:redshift:eu-west-1:999999999999:snapshot:c1/shared-foreign");
|
||||
foreignRegionSnap.getAccountsWithRestoreAccess().add("111111111111");
|
||||
|
||||
when(snapshotBackend.scanForAccount(eq("999999999999"), any())).thenReturn(List.of(foreignRegionSnap));
|
||||
assertTrue(service.describeSharedSnapshots("999999999999", null, null).isEmpty());
|
||||
assertEquals("ClusterSnapshotNotFound", assertThrows(AwsException.class,
|
||||
() -> service.describeSharedSnapshots("999999999999", "shared-foreign", null)).getErrorCode());
|
||||
|
||||
when(snapshotBackend.getForAccount("999999999999", "shared-foreign")).thenReturn(Optional.of(foreignRegionSnap));
|
||||
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
|
||||
assertEquals("ClusterSnapshotNotFound", assertThrows(AwsException.class,
|
||||
() -> service.restoreFromClusterSnapshot("c1", "shared-foreign", null, null, "999999999999")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromClusterSnapshotWithInvalidOwnerAccountThrowsInvalidParameterValue() {
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> service.restoreFromClusterSnapshot("c1", "snap-1", null, null, "not-an-account")).getErrorCode());
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
() -> service.restoreFromClusterSnapshot("c1", "snap-1", null, null, "12345")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSnapshotOfAnotherClusterIsNotFoundAndKept() {
|
||||
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshotOf("snap-1", "protected")));
|
||||
@@ -2450,6 +2533,7 @@ class RedshiftServiceTest {
|
||||
source.setKmsKeyId("orig-key");
|
||||
source.setTags(Map.of("Env", "Test"));
|
||||
source.setCopiedToRegions(new HashSet<>(Set.of("us-west-2")));
|
||||
source.getAccountsWithRestoreAccess().add("222222222222");
|
||||
targetSnapshotIsFree("manual-copy-1");
|
||||
|
||||
Snapshot copy = service.copyClusterSnapshot("auto-snap-1", "manual-copy-1", null, 30);
|
||||
@@ -2463,6 +2547,7 @@ class RedshiftServiceTest {
|
||||
assertEquals("orig-key", copy.getKmsKeyId());
|
||||
assertEquals(Map.of("Env", "Test"), copy.getTags());
|
||||
assertTrue(copy.getCopiedToRegions().isEmpty());
|
||||
assertTrue(copy.getAccountsWithRestoreAccess().isEmpty());
|
||||
verify(snapshotBackend).putAllAtomically(any());
|
||||
verify(snapshotBackend).flush();
|
||||
}
|
||||
|
||||
@@ -286,6 +286,31 @@ class RedshiftSnapshotCopyServiceTest {
|
||||
assertEquals(List.of(new RedshiftService.TaggedResource(copyArn, "snapshot", "env", "test")), tags);
|
||||
}
|
||||
|
||||
@Test
|
||||
void regionalCopyDoesNotInheritRestoreAccessGrants() throws Exception {
|
||||
Fixture fixture = fixture();
|
||||
seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60));
|
||||
fixture.service(SOURCE).createSnapshot("nightly", "warehouse");
|
||||
fixture.service(SOURCE).authorizeSnapshotAccess("nightly", "warehouse", "222222222222");
|
||||
|
||||
fixture.service(SOURCE).runSnapshotCopies(Instant.now());
|
||||
|
||||
Snapshot copy = fixture.copies().getForAccount(ACCOUNT, DESTINATION + "::nightly").orElseThrow();
|
||||
assertTrue(copy.getAccountsWithRestoreAccess().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizingAccessToACopyIsRefused() throws Exception {
|
||||
Fixture fixture = fixture();
|
||||
seedCluster(fixture, "warehouse", Instant.now().minusSeconds(60));
|
||||
fixture.service(SOURCE).createSnapshot("nightly", "warehouse");
|
||||
fixture.service(SOURCE).runSnapshotCopies(Instant.now());
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> fixture.service(DESTINATION).authorizeSnapshotAccess("nightly", "warehouse", "222222222222"));
|
||||
assertEquals("InvalidClusterSnapshotState", ex.getErrorCode());
|
||||
}
|
||||
|
||||
private long dumpFilesUnderCopies() {
|
||||
Path root = directory.resolve("redshift-dumps").resolve(ACCOUNT).resolve("copies");
|
||||
if (!Files.isDirectory(root)) {
|
||||
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.floci.aws.services.redshift.container.RedshiftContainerManager;
|
||||
import io.floci.aws.services.redshift.proxy.RedshiftProxyManager;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.redshift.RedshiftClient;
|
||||
import software.amazon.awssdk.services.redshift.model.AccountWithRestoreAccess;
|
||||
import software.amazon.awssdk.services.redshift.model.RedshiftException;
|
||||
import software.amazon.awssdk.services.redshift.model.Snapshot;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftSnapshotSharingIntegrationTest {
|
||||
private static final String OWNER = "111111111111";
|
||||
private static final String CALLER = "222222222222";
|
||||
private static final String DUMP = "CREATE TABLE shared (id integer); INSERT INTO shared VALUES (7);";
|
||||
|
||||
@InjectMock
|
||||
RedshiftContainerManager containerManager;
|
||||
|
||||
@InjectMock
|
||||
RedshiftProxyManager proxyManager;
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@BeforeEach
|
||||
void prepareRuntime() {
|
||||
when(containerManager.start(anyString(), anyString(), anyString(), anyString(), any(), any()))
|
||||
.thenReturn(new RedshiftContainerHandle("mock-container", "cluster", "localhost", 5432));
|
||||
doAnswer(invocation -> {
|
||||
Files.writeString(invocation.getArgument(3, Path.class), DUMP);
|
||||
return null;
|
||||
}).when(containerManager).takeSnapshot(anyString(), anyString(), anyString(), any(Path.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkAuthorizedAccountRestoresAnotherAccountSnapshotUntilRevoked() {
|
||||
String source = "share-source";
|
||||
String snapshotName = "share-snap";
|
||||
String restored = "share-restored";
|
||||
String refused = "share-refused";
|
||||
AtomicReference<String> restoredDump = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
restoredDump.set(Files.readString(invocation.getArgument(3, Path.class)));
|
||||
return null;
|
||||
}).when(containerManager).restoreSnapshot(eq(CALLER), eq(restored), eq("admin"), any(Path.class));
|
||||
try (RedshiftClient owner = client(OWNER); RedshiftClient caller = client(CALLER)) {
|
||||
createCluster(owner, source);
|
||||
try {
|
||||
Snapshot created = owner.createClusterSnapshot(request -> request.snapshotIdentifier(snapshotName)
|
||||
.clusterIdentifier(source)).snapshot();
|
||||
assertEquals(OWNER, created.ownerAccount());
|
||||
assertTrue(created.accountsWithRestoreAccess().isEmpty());
|
||||
|
||||
// Nothing is shared yet: the caller cannot see the snapshot, and cannot restore it.
|
||||
assertTrue(caller.describeClusterSnapshots(request -> request.ownerAccount(OWNER)).snapshots().isEmpty());
|
||||
assertEquals("ClusterSnapshotNotFound", assertThrows(RedshiftException.class,
|
||||
() -> caller.describeClusterSnapshots(request -> request.ownerAccount(OWNER)
|
||||
.snapshotIdentifier(snapshotName))).awsErrorDetails().errorCode());
|
||||
assertEquals("AccessToSnapshotDenied", assertThrows(RedshiftException.class,
|
||||
() -> caller.restoreFromClusterSnapshot(request -> request.clusterIdentifier(refused)
|
||||
.snapshotIdentifier(snapshotName).ownerAccount(OWNER))).awsErrorDetails().errorCode());
|
||||
|
||||
Snapshot authorized = owner.authorizeSnapshotAccess(request -> request.snapshotIdentifier(snapshotName)
|
||||
.accountWithRestoreAccess(CALLER)).snapshot();
|
||||
assertEquals(List.of(CALLER), accounts(authorized));
|
||||
assertEquals("AuthorizationAlreadyExists", assertThrows(RedshiftException.class,
|
||||
() -> owner.authorizeSnapshotAccess(request -> request.snapshotIdentifier(snapshotName)
|
||||
.accountWithRestoreAccess(CALLER))).awsErrorDetails().errorCode());
|
||||
assertEquals(List.of(CALLER), accounts(owner.describeClusterSnapshots(request -> request
|
||||
.snapshotIdentifier(snapshotName)).snapshots().getFirst()));
|
||||
|
||||
List<Snapshot> shared = caller.describeClusterSnapshots(request -> request.ownerAccount(OWNER)).snapshots();
|
||||
assertEquals(1, shared.size());
|
||||
assertEquals(OWNER, shared.getFirst().ownerAccount());
|
||||
assertEquals(snapshotName, shared.getFirst().snapshotIdentifier());
|
||||
|
||||
caller.restoreFromClusterSnapshot(request -> request.clusterIdentifier(restored)
|
||||
.snapshotIdentifier(snapshotName).ownerAccount(OWNER));
|
||||
assertEquals(DUMP, restoredDump.get());
|
||||
assertEquals(restored, caller.describeClusters(request -> request.clusterIdentifier(restored))
|
||||
.clusters().getFirst().clusterIdentifier());
|
||||
|
||||
owner.revokeSnapshotAccess(request -> request.snapshotIdentifier(snapshotName)
|
||||
.accountWithRestoreAccess(CALLER));
|
||||
assertEquals("AuthorizationNotFound", assertThrows(RedshiftException.class,
|
||||
() -> owner.revokeSnapshotAccess(request -> request.snapshotIdentifier(snapshotName)
|
||||
.accountWithRestoreAccess(CALLER))).awsErrorDetails().errorCode());
|
||||
assertEquals("AccessToSnapshotDenied", assertThrows(RedshiftException.class,
|
||||
() -> caller.restoreFromClusterSnapshot(request -> request.clusterIdentifier(refused)
|
||||
.snapshotIdentifier(snapshotName).ownerAccount(OWNER))).awsErrorDetails().errorCode());
|
||||
|
||||
// A snapshot deleted and taken again under the same name does not inherit the grant.
|
||||
owner.authorizeSnapshotAccess(request -> request.snapshotIdentifier(snapshotName)
|
||||
.accountWithRestoreAccess(CALLER));
|
||||
owner.deleteClusterSnapshot(request -> request.snapshotIdentifier(snapshotName));
|
||||
owner.createClusterSnapshot(request -> request.snapshotIdentifier(snapshotName).clusterIdentifier(source));
|
||||
assertTrue(caller.describeClusterSnapshots(request -> request.ownerAccount(OWNER)).snapshots().isEmpty());
|
||||
} finally {
|
||||
deleteClusterIfPresent(owner, source);
|
||||
deleteClusterIfPresent(caller, restored);
|
||||
deleteSnapshotIfPresent(owner, snapshotName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkSharedSnapshotIsRestorableByItsArnAndOnlyTheOwnerGrantsAccess() {
|
||||
String source = "share-arn-source";
|
||||
String snapshotName = "share-arn-snap";
|
||||
String restored = "share-arn-restored";
|
||||
try (RedshiftClient owner = client(OWNER); RedshiftClient caller = client(CALLER)) {
|
||||
createCluster(owner, source);
|
||||
try {
|
||||
String arn = owner.createClusterSnapshot(request -> request.snapshotIdentifier(snapshotName)
|
||||
.clusterIdentifier(source)).snapshot().snapshotArn();
|
||||
owner.authorizeSnapshotAccess(request -> request.snapshotArn(arn).accountWithRestoreAccess(CALLER));
|
||||
|
||||
caller.restoreFromClusterSnapshot(request -> request.clusterIdentifier(restored).snapshotArn(arn));
|
||||
assertEquals(restored, caller.describeClusters(request -> request.clusterIdentifier(restored))
|
||||
.clusters().getFirst().clusterIdentifier());
|
||||
|
||||
// A caller cannot grant itself access to a snapshot it does not own.
|
||||
assertEquals("ClusterSnapshotNotFound", assertThrows(RedshiftException.class,
|
||||
() -> caller.authorizeSnapshotAccess(request -> request.snapshotArn(arn)
|
||||
.accountWithRestoreAccess(CALLER))).awsErrorDetails().errorCode());
|
||||
assertEquals("InvalidParameterValue", assertThrows(RedshiftException.class,
|
||||
() -> owner.authorizeSnapshotAccess(request -> request.snapshotIdentifier(snapshotName)
|
||||
.accountWithRestoreAccess("not-an-account"))).awsErrorDetails().errorCode());
|
||||
} finally {
|
||||
deleteClusterIfPresent(owner, source);
|
||||
deleteClusterIfPresent(caller, restored);
|
||||
deleteSnapshotIfPresent(owner, snapshotName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> accounts(Snapshot snapshot) {
|
||||
return snapshot.accountsWithRestoreAccess().stream().map(AccountWithRestoreAccess::accountId).toList();
|
||||
}
|
||||
|
||||
private RedshiftClient client(String account) {
|
||||
return RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"))).build();
|
||||
}
|
||||
|
||||
private static void createCluster(RedshiftClient client, String name) {
|
||||
client.createCluster(request -> request.clusterIdentifier(name).nodeType("dc2.large")
|
||||
.masterUsername("admin").masterUserPassword("Secret123"));
|
||||
}
|
||||
|
||||
private static void deleteClusterIfPresent(RedshiftClient client, String name) {
|
||||
try {
|
||||
client.deleteCluster(request -> request.clusterIdentifier(name).skipFinalClusterSnapshot(true));
|
||||
} catch (RedshiftException expected) {
|
||||
if (!"ClusterNotFound".equals(expected.awsErrorDetails().errorCode())) {
|
||||
throw expected;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteSnapshotIfPresent(RedshiftClient client, String name) {
|
||||
try {
|
||||
client.deleteClusterSnapshot(request -> request.snapshotIdentifier(name));
|
||||
} catch (RedshiftException expected) {
|
||||
if (!"ClusterSnapshotNotFound".equals(expected.awsErrorDetails().errorCode())) {
|
||||
throw expected;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,11 @@ strings, or, for an ARN, a member of a structure or of each element of a list of
|
||||
or the member is a bare `Name`, `Id` or `Identifier`, the variable is named after the type and the
|
||||
operation is about the type, its name past the verb the type's (`DescribeTargetGroups`, but not
|
||||
`StartExecution` for a state machine, whose `name` is the execution's), and no member holds its ARN.
|
||||
Of several members that could fill a variable, one naming the type before the variable wins over a
|
||||
bare one: the snapshot `RestoreFromClusterSnapshot` restores has the cluster its
|
||||
`SnapshotClusterIdentifier` names, not the `ClusterIdentifier` of the cluster it creates, and the
|
||||
tenant `GetInvalidationForDistributionTenant` reads has its `DistributionTenantId`, not the
|
||||
invalidation's `Id`.
|
||||
The variables nothing fills are left open as `*`: a resource the request creates has the id its
|
||||
service mints, so `CreateTargetGroup` names `targetgroup/<Name>/*`.
|
||||
- names neither, but the type is the one the operation is named after (`CreateCapacityReservation`
|
||||
@@ -44,7 +49,10 @@ the types the request names by their variables: ECR's `registryId` selects the r
|
||||
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
|
||||
of a resource the new one is made in. A top-level member whose name ends in `Account` gives the account
|
||||
of each type whose botocore structure has a member of that same name: Redshift's `Snapshot` has an
|
||||
`OwnerAccount` and its `Cluster` has none, so `RestoreFromClusterSnapshot`'s names the snapshot's
|
||||
owner, while the restored cluster stays the caller's. 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
|
||||
@@ -559,14 +567,6 @@ CORRECTIONS: dict[str, tuple[list[dict], str]] = {
|
||||
"policy must allow access to the resource dbname for the specified database name'), and the Management "
|
||||
"Guide's policy granting the action on a dbuser alone allows it; the rule names the database by "
|
||||
"ClusterIdentifier alone when DbName is absent"),
|
||||
"redshift:RestoreFromClusterSnapshot": ([
|
||||
{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}},
|
||||
{"type": "snapshot", "fill": {"ClusterName": "SnapshotClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}},
|
||||
{"types": ["snapshot"], "arn": "SnapshotArn"},
|
||||
], "the snapshot's cluster is SnapshotClusterIdentifier ('The name of the cluster the source snapshot was created "
|
||||
"from'), not ClusterIdentifier, the cluster 'that will be created from restoring the snapshot'; its "
|
||||
"DefaultIamRoleArn is an IAM role's ARN and its RedshiftIdcApplicationArn an IAM Identity Center "
|
||||
"application's, never a cluster's or a snapshot's"),
|
||||
**{f"redshift:{operation}": ([{"types": ["cluster", "eventsubscription", "hsmclientcertificate", "hsmconfiguration",
|
||||
"integration", "parametergroup", "securitygroup",
|
||||
"securitygroupingress-cidr", "securitygroupingress-ec2securitygroup",
|
||||
@@ -1131,6 +1131,34 @@ def with_account(resources: list[dict], formats: dict[str, str], accounts: list[
|
||||
and resource.get("when", {}).get(accounts[0]) != [None] else resource for resource in resources]
|
||||
|
||||
|
||||
def structure_account_members(models: dict[str, dict], operation: str, types: list[str]) -> dict[str, str]:
|
||||
"""The top-level members of the operation's request whose name ends in `Account`, by the type whose botocore
|
||||
structure (the one named after the type, `Snapshot` for `snapshot`) has a member of that same name; a type
|
||||
whose structure has two of them, or none, is left out."""
|
||||
found: dict[str, set[str]] = {}
|
||||
for model in models.values():
|
||||
spec = model["operations"].get(operation)
|
||||
if spec is None or "input" not in spec or not READ_PROTOCOLS & _protocols(model):
|
||||
continue
|
||||
accounts = [name for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items()
|
||||
if member.get("location") in BODY_LOCATIONS and re.search(r"account$", name, re.IGNORECASE)
|
||||
and model["shapes"][member["shape"]]["type"] == "string"]
|
||||
for kind in types:
|
||||
structures = [shape for name, shape in model["shapes"].items()
|
||||
if shape.get("type") == "structure" and stem(name) == stem(kind)]
|
||||
for shape in structures:
|
||||
found.setdefault(kind, set()).update(name for name in accounts if name in shape.get("members", {}))
|
||||
return {kind: next(iter(names)) for kind, names in sorted(found.items()) if len(names) == 1}
|
||||
|
||||
|
||||
def with_structure_account(resources: list[dict], formats: dict[str, str], accounts: dict[str, str]) -> list[dict]:
|
||||
"""The resources, each a type named by its variables and given no account yet taking the one the request's
|
||||
member of its structure's name gives, when the type's format has an account."""
|
||||
return [dict(resource, account=accounts[resource["type"]]) if "fill" in resource and "account" not in resource
|
||||
and resource["type"] in accounts and "${Account}" in formats.get(resource["type"], "") else resource
|
||||
for resource in resources]
|
||||
|
||||
|
||||
def _kinds(resource: dict) -> list[str]:
|
||||
"""The resource types a resource names, as the strings they are: the types it acts on, or the one it names."""
|
||||
named: list = list(resource.get("types") or [resource.get("type")])
|
||||
@@ -1326,7 +1354,10 @@ def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str
|
||||
or (qualified and names_type(member, kind_stem)))))]
|
||||
if not candidates:
|
||||
return None
|
||||
return min(candidates, key=lambda member: (stem(member) != variable_stem, names[member].endswith("[]"), len(member), member))
|
||||
# A member naming the type before the variable (`SnapshotClusterIdentifier` for the snapshot's `ClusterName`,
|
||||
# `DistributionTenantId` for the tenant's `Id`) wins over a bare one, which names something else.
|
||||
return min(candidates, key=lambda member: (stem(member) != kind_stem + variable_stem, stem(member) != variable_stem,
|
||||
names[member].endswith("[]"), len(member), member))
|
||||
|
||||
|
||||
def also_filled(types: list[str], members: dict[str, str], filled: dict[str, dict[str, str]],
|
||||
@@ -1434,6 +1465,8 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
|
||||
optional)
|
||||
resources = with_map_fields(resources, types, formats, map_fields(models, operation.split(":", 1)[1]))
|
||||
resources = with_account(resources, formats, account_members(models, operation.split(":", 1)[1]))
|
||||
resources = with_structure_account(resources, formats,
|
||||
structure_account_members(models, operation.split(":", 1)[1], types))
|
||||
resources = with_arn_of(resources, formats, name_or_arn_members(models, operation.split(":", 1)[1]))
|
||||
resources = with_made(resources, operation, formats)
|
||||
entry = {"action": upstream["action"], "types": types, "resources": resources}
|
||||
|
||||
@@ -43,6 +43,20 @@ def test_a_member_fills_a_variable_its_stem_relates_to_and_of_its_kind():
|
||||
{"type": "thing", "fill": {"ThingName": "SpecialThingName"}}]
|
||||
|
||||
|
||||
def test_a_member_naming_the_type_before_the_variable_wins_over_a_bare_one():
|
||||
formats = {"snapshot": "arn:${Partition}:svc:${Region}:${Account}:snapshot:${ClusterName}/${SnapshotName}",
|
||||
"cluster": FORMATS["thing"].replace("thing/${ThingName}", "cluster:${ClusterName}")}
|
||||
# The snapshot's cluster is the one its SnapshotClusterIdentifier names; ClusterIdentifier is the cluster's own.
|
||||
assert r.resources_for("svc:RestoreFromClusterSnapshot", ["cluster", "snapshot"], formats,
|
||||
members("ClusterIdentifier", "SnapshotIdentifier", "SnapshotClusterIdentifier")) == [
|
||||
{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}},
|
||||
{"type": "snapshot", "fill": {"ClusterName": "SnapshotClusterIdentifier", "SnapshotName": "SnapshotIdentifier"}}]
|
||||
# The tenant's id is its own, not the bare Id of the invalidation the operation reads.
|
||||
assert r.resources_for("svc:GetInvalidationForTenant", ["tenant"],
|
||||
{"tenant": "arn:${Partition}:svc::${Account}:tenant/${Id}"}, members("TenantId", "Id")) == [
|
||||
{"type": "tenant", "fill": {"Id": "TenantId"}}]
|
||||
|
||||
|
||||
def test_a_bare_name_fills_the_type_the_operation_is_about_and_no_other():
|
||||
assert r.resources_for("svc:CreateThing", ["thing"], FORMATS, members("Name")) == [
|
||||
{"type": "thing", "fill": {"ThingName": "Name"}}]
|
||||
@@ -395,6 +409,30 @@ 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": {}}]
|
||||
|
||||
|
||||
def test_an_account_member_of_a_types_own_structure_gives_that_types_account_alone(tmp_path):
|
||||
service = model({"RestoreThing": {"ThingName": "String", "PoolId": "String", "OwnerAccount": "String"}})
|
||||
service["shapes"]["Thing"] = {"type": "structure", "members": {"OwnerAccount": {"shape": "String"}}}
|
||||
service["shapes"]["Pool"] = {"type": "structure", "members": {"PoolId": {"shape": "String"}}}
|
||||
write_models(tmp_path, {"svc": service})
|
||||
models = r.load_models(tmp_path, {"svc"})
|
||||
assert r.structure_account_members(models, "RestoreThing", ["thing", "pool"]) == {"thing": "OwnerAccount"}
|
||||
resources = [{"type": "thing", "fill": {"ThingName": "ThingName"}}, {"type": "pool", "fill": {"PoolId": "PoolId"}},
|
||||
{"types": ["thing"], "arn": "ThingArn"}]
|
||||
assert r.with_structure_account(resources, FORMATS, {"thing": "OwnerAccount"}) == [
|
||||
{"type": "thing", "fill": {"ThingName": "ThingName"}, "account": "OwnerAccount"},
|
||||
{"type": "pool", "fill": {"PoolId": "PoolId"}}, {"types": ["thing"], "arn": "ThingArn"}]
|
||||
# An account another rule gave stays, and a format without an account takes none.
|
||||
given = [{"type": "thing", "fill": {}, "account": "registryId"}]
|
||||
assert r.with_structure_account(given, FORMATS, {"thing": "OwnerAccount"}) == given
|
||||
assert r.with_structure_account([{"type": "catalog", "fill": {}}], {"catalog": "arn:${Partition}:svc:::catalog"},
|
||||
{"catalog": "OwnerAccount"}) == [{"type": "catalog", "fill": {}}]
|
||||
# A structure with two such members says nothing about which one is its account.
|
||||
service["shapes"]["Thing"]["members"]["SourceAccount"] = {"shape": "String"}
|
||||
service["shapes"]["RestoreThingIn"]["members"]["SourceAccount"] = {"shape": "String"}
|
||||
write_models(tmp_path / "two", {"svc": service})
|
||||
assert r.structure_account_members(r.load_models(tmp_path / "two", {"svc"}), "RestoreThing", ["thing"]) == {}
|
||||
|
||||
|
||||
ACCOUNTS = {"account": "arn:${Partition}:account::${Account}:account",
|
||||
"accountInOrganization":
|
||||
"arn:${Partition}:account::${ManagementAccountId}:account/o-${OrganizationId}/${MemberAccountId}"}
|
||||
|
||||
Reference in new issue
Block a user