mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift-serverless): allow cross-account restore of a snapshot its policy shares (#7801) (#7803)
* feat(redshift-serverless): allow cross-account restore of a snapshot its policy shares (#7801) RestoreFromSnapshot with an ownerAccount other than the caller's now reads the snapshot from the owner's account and evaluates its resource policy for redshift-serverless:RestoreFromSnapshot. A policy that allows the caller or the caller's account grants the restore, an explicit Deny wins, and a snapshot with no policy is not shared (AccessDeniedException). The dump is read from the owner's directory and the restore targets the caller's namespace and workgroup. * fix(redshift-serverless): restore a shared snapshot by the owner's ARN and check its policy under the service lock A cross-account RestoreFromSnapshot with the owner's snapshotArn failed validation because only the caller's account was accepted. The snapshot and its policy were also checked before the service lock was taken, so a deletion, expiry or policy revocation could land between the check and the restore. The check now runs under the lock. * fix(redshift-serverless): evaluate a shared snapshot's policy through a ResourcePolicyProvider (#7801) Move the snapshot policy check out of the service and into IAM enforcement, as SQS, SNS and S3 do: - RedshiftServerlessResourcePolicyProvider supplies the snapshot's policy and the account in its ARN. A statement with no Resource, as in AWS's own PutResourcePolicy example, applies to the snapshot. - redshift-serverless leaves NOT_COVERED: namespaces, workgroups and snapshots are found by name through StoredResourceArns, and RestoreFromSnapshot and GetSnapshot name the owner's snapshot when ownerAccount is set. - Drop RedshiftServerlessSharedSnapshots and the snapshot-taking restoreFromSharedSnapshot overload. * fix(redshift-serverless): derive snapshot account from the generator and find endpoint access ARNs (#7801) Take ownerAccount as an account member in the request-resources generator and honor account on found resources, replacing the hand-written CORRECTIONS entries and the two-name branch in find. Answer endpointAccess in find. Share one call in handleRestoreFromSnapshot. * fix: derive account members from service models and reuse endpoint lookup
This commit is contained in:
1 parent
013e9b7c2e
commit
e37f45f714
20 files changed
+923
-55
No files matched your search
@@ -140,11 +140,14 @@ class RequestResourceMembersTest {
|
||||
for (String bad : List.of("\"fill\":{},\"find\":[]", "\"fill\":{},\"find\":[\"Ids[]\"]",
|
||||
"\"fill\":{\"Id\":\"Id\"},\"find\":[\"Namespace\"]", "\"fill\":{},\"find\":\"Namespace\"",
|
||||
"\"fill\":{},\"find\":{\"a\":\"Namespace\"}",
|
||||
"\"fill\":{},\"find\":[\"Namespace\"],\"account\":\"registryId\"",
|
||||
"\"fill\":{},\"find\":[\"Namespace\"],\"absent\":{\"Namespace\":\"ecs\"}")) {
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> parse(document(formats, "{\"type\":\"target\"," + bad + "}")), bad);
|
||||
}
|
||||
// The account its member gives is the one it is found in.
|
||||
assertEquals(new Member("registryId", false), parseUnchecked(document(formats,
|
||||
"{\"type\":\"target\",\"fill\":{},\"find\":[\"Namespace\"],\"account\":\"registryId\"}"))
|
||||
.operations().get("a:Op").getFirst().account());
|
||||
// Nor beside an ARN member, which names the resource itself.
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"types\":[\"target\"],\"arn\":\"TargetArn\",\"find\":[\"Namespace\"]}")));
|
||||
|
||||
@@ -631,6 +631,48 @@ class RequestResourcesTest {
|
||||
json("{\"ResourceArn\":\"" + key + "\"}"), "aws", "us-east-1", "000000000000", stored));
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot another account shares is named by its name and the {@code ownerAccount} of that account: it is that
|
||||
* account's snapshot the request acts on, the one {@code findInAccount} gives or else the owner's ARN with its id
|
||||
* open, and a request naming no owner acts on the caller's own.
|
||||
*/
|
||||
@Test
|
||||
void aResourceFoundByMembersIsInTheAccountItsAccountMemberGives() {
|
||||
String own = "arn:aws:redshift-serverless:us-east-1:000000000000:snapshot/own-id";
|
||||
String theirs = "arn:aws:redshift-serverless:us-east-1:111111111111:snapshot/their-id";
|
||||
StoredResourceArns stored = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "redshift-serverless";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return List.of("snap").equals(names) ? Optional.of(own) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findInAccount(String type, List<String> names, String account, String region) {
|
||||
return "111111111111".equals(account) && List.of("snap").equals(names)
|
||||
? Optional.of(theirs) : Optional.empty();
|
||||
}
|
||||
};
|
||||
assertEquals(List.of(own), RequestResources.of("redshift-serverless:GetSnapshot",
|
||||
json("{\"snapshotName\":\"snap\"}"), "aws", "us-east-1", "000000000000", stored));
|
||||
assertEquals(List.of(theirs), RequestResources.of("redshift-serverless:GetSnapshot",
|
||||
json("{\"snapshotName\":\"snap\",\"ownerAccount\":\"111111111111\"}"), "aws", "us-east-1",
|
||||
"000000000000", stored));
|
||||
// A snapshot the owner has none of by that name has its id open in the owner's account.
|
||||
assertEquals(List.of("arn:aws:redshift-serverless:us-east-1:222222222222:snapshot/*"),
|
||||
RequestResources.of("redshift-serverless:GetSnapshot",
|
||||
json("{\"snapshotName\":\"other\",\"ownerAccount\":\"222222222222\"}"), "aws",
|
||||
"us-east-1", "000000000000", stored));
|
||||
// An owner that is no account id names no resource.
|
||||
assertEquals(List.of(), RequestResources.of("redshift-serverless:GetSnapshot",
|
||||
json("{\"snapshotName\":\"snap\",\"ownerAccount\":\"nope\"}"), "aws", "us-east-1",
|
||||
"000000000000", stored));
|
||||
}
|
||||
|
||||
/**
|
||||
* A scalable target's ARN is all the id Application Auto Scaling mints, while its requests name it by its service
|
||||
* namespace, resource id and scalable dimension: it is the one stored under those, or else has its id open, as a
|
||||
|
||||
+5
@@ -62,6 +62,11 @@ class RedshiftServerlessAdministrationHandlerTest {
|
||||
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
|
||||
+ invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"
|
||||
+ invocation.getArgument(2, String.class));
|
||||
when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class),
|
||||
any(String.class)))
|
||||
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
|
||||
+ invocation.getArgument(1, String.class) + ":" + invocation.getArgument(2, String.class)
|
||||
+ ":" + invocation.getArgument(3, String.class));
|
||||
RedshiftServerlessEndpoints endpoints = mock(RedshiftServerlessEndpoints.class);
|
||||
when(endpoints.allocate()).thenReturn(new Endpoint("localhost", 7100));
|
||||
RedshiftServerlessRuntime runtime = mock(RedshiftServerlessRuntime.class);
|
||||
|
||||
+40
@@ -618,6 +618,46 @@ class RedshiftServerlessIntegrationTest {
|
||||
.body("message", equalTo("resourceArn does not identify a snapshot in this account and Region."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotAnotherAccountOwnsIsRestoredFromItsOwnersAccount() {
|
||||
String owner = "111122223333";
|
||||
String caller = "444455556666";
|
||||
String stranger = "777788889999";
|
||||
|
||||
callAs(owner, "CreateNamespace", "{\"namespaceName\":\"share-src\",\"adminUsername\":\"admin\"}").statusCode(200);
|
||||
String snapshotArn = callAs(owner, "CreateSnapshot",
|
||||
"{\"snapshotName\":\"share-snap\",\"namespaceName\":\"share-src\"}")
|
||||
.statusCode(200).extract().path("snapshot.snapshotArn");
|
||||
callAs(caller, "CreateNamespace", "{\"namespaceName\":\"share-dst\",\"adminUsername\":\"admin\"}").statusCode(200);
|
||||
callAs(caller, "CreateWorkgroup", "{\"workgroupName\":\"share-wg\",\"namespaceName\":\"share-dst\"}")
|
||||
.statusCode(200);
|
||||
String restore = "{\"namespaceName\":\"share-dst\",\"workgroupName\":\"share-wg\","
|
||||
+ "\"snapshotName\":\"share-snap\",\"ownerAccount\":\"" + owner + "\"}";
|
||||
|
||||
// Whether the snapshot's policy shares it is IAM enforcement's to decide, which this class leaves off.
|
||||
callAs(caller, "RestoreFromSnapshot", restore)
|
||||
.statusCode(200)
|
||||
.body("ownerAccount", equalTo(owner))
|
||||
.body("snapshotName", equalTo("share-snap"))
|
||||
.body("namespace.namespaceName", equalTo("share-dst"));
|
||||
|
||||
// A snapshot that is not the owner's is not found, however it is named.
|
||||
callAs(caller, "RestoreFromSnapshot", restore.replace("share-snap", "no-such-snap")).statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
callAs(caller, "RestoreFromSnapshot", restore.replace(owner, stranger)).statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
// The owner's snapshot ARN names the snapshot as well as its name does; one of another account does not.
|
||||
String byArn = "{\"namespaceName\":\"share-dst\",\"workgroupName\":\"share-wg\","
|
||||
+ "\"snapshotArn\":\"" + snapshotArn + "\",\"ownerAccount\":\"" + owner + "\"}";
|
||||
callAs(caller, "RestoreFromSnapshot", byArn).statusCode(200)
|
||||
.body("ownerAccount", equalTo(owner))
|
||||
.body("snapshotName", equalTo("share-snap"));
|
||||
callAs(caller, "RestoreFromSnapshot", byArn.replace("\"ownerAccount\":\"" + owner, "\"ownerAccount\":\"" + stranger))
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourcePolicyIsIsolatedPerAccount() {
|
||||
String accountA = "111122223333";
|
||||
|
||||
+29
@@ -14,7 +14,9 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -95,4 +97,31 @@ class RedshiftServerlessResourcePolicyExpirationTest {
|
||||
service.deleteExpiredSnapshotPolicy(entry);
|
||||
assertTrue(store.getForAccount(account, key).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void policyOfSnapshotIsReadFromTheOwnersAccountForTheSameSnapshotGeneration() {
|
||||
String owner = "999999999999";
|
||||
String region = "us-east-1";
|
||||
String arn = "arn:aws:redshift-serverless:us-east-1:" + owner + ":snapshot/shared-snap";
|
||||
Instant created = Instant.parse("2030-01-01T00:00:00Z");
|
||||
AccountAwareStorageBackend<ResourcePolicy> store = AccountAwareStorageBackend.inMemory("123456789012");
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-resourcepolicies.json"),
|
||||
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
|
||||
RedshiftServerlessResourcePolicyService service = new RedshiftServerlessResourcePolicyService(
|
||||
factory, mock(RedshiftServerlessService.class), new ObjectMapper());
|
||||
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
|
||||
snapshot.setSnapshotArn(arn);
|
||||
snapshot.setSnapshotCreateTime(created);
|
||||
ResourcePolicy policy = new ResourcePolicy(arn, "{\"Version\":\"2012-10-17\"}");
|
||||
policy.setSnapshotCreateTime(created);
|
||||
store.putForAccount(owner, region + "::" + arn, policy);
|
||||
|
||||
assertEquals(Optional.of("{\"Version\":\"2012-10-17\"}"), service.policyOfSnapshot(owner, snapshot, region));
|
||||
assertTrue(service.policyOfSnapshot("123456789012", snapshot, region).isEmpty());
|
||||
|
||||
snapshot.setSnapshotCreateTime(created.plusSeconds(1));
|
||||
assertTrue(service.policyOfSnapshot(owner, snapshot, region).isEmpty());
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package io.floci.aws.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy;
|
||||
import io.floci.aws.services.redshiftserverless.model.RedshiftServerlessSnapshot;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftServerlessResourcePolicyProviderTest {
|
||||
|
||||
private static final String OWNER = "111122223333";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SNAPSHOT_ARN = "arn:aws:redshift-serverless:" + REGION + ":" + OWNER
|
||||
+ ":snapshot/shared";
|
||||
private static final String WITH_RESOURCE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"444455556666\"},\"Action\":\"redshift-serverless:RestoreFromSnapshot\","
|
||||
+ "\"Resource\":\"*\"}]}";
|
||||
private static final String WITHOUT_RESOURCE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"444455556666\"},\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}]}";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private RedshiftServerlessService serverless;
|
||||
private RedshiftServerlessResourcePolicyService policies;
|
||||
private RedshiftServerlessResourcePolicyProvider provider;
|
||||
private RedshiftServerlessSnapshot snapshot;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
serverless = mock(RedshiftServerlessService.class);
|
||||
policies = mock(RedshiftServerlessResourcePolicyService.class);
|
||||
provider = new RedshiftServerlessResourcePolicyProvider(serverless, policies, objectMapper);
|
||||
snapshot = new RedshiftServerlessSnapshot();
|
||||
snapshot.setSnapshotName("shared");
|
||||
snapshot.setSnapshotArn(SNAPSHOT_ARN);
|
||||
when(serverless.findSnapshotOfAccount(OWNER, "shared", REGION)).thenReturn(Optional.of(snapshot));
|
||||
when(policies.policyOfSnapshot(any(), any(), any())).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotComesWithItsPolicyAndTheAccountInItsArn() {
|
||||
when(policies.policyOfSnapshot(eq(OWNER), eq(snapshot), eq(REGION))).thenReturn(Optional.of(WITH_RESOURCE));
|
||||
|
||||
assertEquals(List.of(new ResourcePolicy(WITH_RESOURCE, OWNER)),
|
||||
provider.getResourcePolicies("redshift-serverless", SNAPSHOT_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotWithNoPolicyStillHasItsOwner() {
|
||||
assertEquals(List.of(new ResourcePolicy(null, OWNER)),
|
||||
provider.getResourcePolicies("redshift-serverless", SNAPSHOT_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotThatIsNotThereStillHasItsOwner() {
|
||||
String missing = "arn:aws:redshift-serverless:" + REGION + ":" + OWNER + ":snapshot/missing";
|
||||
when(serverless.findSnapshotOfAccount(OWNER, "missing", REGION)).thenReturn(Optional.empty());
|
||||
|
||||
assertEquals(List.of(new ResourcePolicy(null, OWNER)),
|
||||
provider.getResourcePolicies("redshift-serverless", missing));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStatementWithNoResourceIsAttachedToTheSnapshot() throws Exception {
|
||||
when(policies.policyOfSnapshot(eq(OWNER), eq(snapshot), eq(REGION))).thenReturn(Optional.of(WITHOUT_RESOURCE));
|
||||
|
||||
String policy = provider.getResourcePolicies("redshift-serverless", SNAPSHOT_ARN).getFirst().policyDocument();
|
||||
|
||||
JsonNode statement = objectMapper.readTree(policy).path("Statement").get(0);
|
||||
assertEquals(SNAPSHOT_ARN, statement.path("Resource").asText());
|
||||
assertEquals("redshift-serverless:RestoreFromSnapshot", statement.path("Action").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStatementThatNamesItsResourceIsKept() {
|
||||
assertEquals(WITH_RESOURCE, provider.withResource(WITH_RESOURCE, SNAPSHOT_ARN));
|
||||
String notResource = WITHOUT_RESOURCE.replace("\"Action\"", "\"NotResource\":\"*\",\"Action\"");
|
||||
assertEquals(notResource, provider.withResource(notResource, SNAPSHOT_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSingleStatementObjectIsAttachedToTheSnapshotToo() throws Exception {
|
||||
String single = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"444455556666\"},\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}}";
|
||||
|
||||
JsonNode statement = objectMapper.readTree(provider.withResource(single, SNAPSHOT_ARN)).path("Statement");
|
||||
|
||||
assertEquals(SNAPSHOT_ARN, statement.path("Resource").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyThatCannotBeReadIsPassedOnAsItIs() {
|
||||
assertEquals("{not json", provider.withResource("{not json", SNAPSHOT_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anythingThatIsNotOneSnapshotIsLeftToOtherProviders() {
|
||||
assertTrue(provider.getResourcePolicies("redshift-serverless", "*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("redshift-serverless",
|
||||
"arn:aws:redshift-serverless:" + REGION + ":" + OWNER + ":snapshot/*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("redshift-serverless",
|
||||
"arn:aws:redshift-serverless:" + REGION + ":" + OWNER + ":namespace/abc").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sqs", "arn:aws:sqs:" + REGION + ":" + OWNER + ":orders").isEmpty());
|
||||
}
|
||||
}
|
||||
+132
@@ -14,6 +14,7 @@ import io.floci.aws.services.redshiftserverless.model.Namespace;
|
||||
import io.floci.aws.services.redshiftserverless.model.PricePerformanceTarget;
|
||||
import io.floci.aws.services.redshiftserverless.model.RedshiftServerlessSnapshot;
|
||||
import io.floci.aws.services.redshiftserverless.model.Workgroup;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -96,6 +97,11 @@ class RedshiftServerlessServiceTest {
|
||||
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
|
||||
+ invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"
|
||||
+ invocation.getArgument(2, String.class));
|
||||
when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class),
|
||||
any(String.class)))
|
||||
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
|
||||
+ invocation.getArgument(1, String.class) + ":" + invocation.getArgument(2, String.class)
|
||||
+ ":" + invocation.getArgument(3, String.class));
|
||||
nextPort = 7100;
|
||||
endpoints = mock(RedshiftServerlessEndpoints.class);
|
||||
when(endpoints.allocate()).thenAnswer(invocation -> new Endpoint("localhost", nextPort++));
|
||||
@@ -1057,6 +1063,132 @@ class RedshiftServerlessServiceTest {
|
||||
assertEquals("ResourceNotFoundException", noSnapshot.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromSharedSnapshotReadsTheSnapshotOfAnotherAccount() throws Exception {
|
||||
String owner = "999999999999";
|
||||
create("shared-ns");
|
||||
createWorkgroup("shared-wg", "shared-ns");
|
||||
RedshiftServerlessSnapshot own = service.createSnapshot("own-snap", "shared-ns", null, null, REGION);
|
||||
Path ownerDump = dumpDir.resolve("redshift-serverless-dumps").resolve(owner).resolve(REGION)
|
||||
.resolve("their-snap.sql").toAbsolutePath().normalize();
|
||||
Files.createDirectories(ownerDump.getParent());
|
||||
Files.writeString(ownerDump, "select 1;");
|
||||
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(own);
|
||||
theirs.setSnapshotName("their-snap");
|
||||
theirs.setOwnerAccount(owner);
|
||||
theirs.setSqlDump(ownerDump.toString());
|
||||
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
|
||||
|
||||
assertTrue(service.findSnapshotOfAccount(owner, "their-snap", REGION).isPresent());
|
||||
assertTrue(service.findSnapshotOfAccount(ACCOUNT_ID, "their-snap", REGION).isEmpty());
|
||||
assertTrue(service.findSnapshotOfAccount(owner, "own-snap", REGION).isEmpty());
|
||||
|
||||
RedshiftServerlessService.RestoreResult restored = service.restoreFromSharedSnapshot(
|
||||
"shared-ns", "shared-wg", "their-snap", owner, null, null, REGION);
|
||||
|
||||
assertEquals("AVAILABLE", restored.namespace().getStatus());
|
||||
assertEquals("their-snap", restored.snapshot().getSnapshotName());
|
||||
assertEquals(owner, restored.snapshot().getOwnerAccount());
|
||||
verify(runtime).restoreSnapshot(eq(ACCOUNT_ID), eq(REGION), eq("shared-wg"), any(), any(), eq(ownerDump),
|
||||
any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void findNamesTheArnOfTheSnapshotOfTheAccountThatOwnsIt() {
|
||||
String owner = "999999999999";
|
||||
create("find-ns");
|
||||
RedshiftServerlessSnapshot own = service.createSnapshot("own-snap", "find-ns", null, null, REGION);
|
||||
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(own);
|
||||
theirs.setSnapshotName("their-snap");
|
||||
theirs.setSnapshotArn("arn:aws:redshift-serverless:" + REGION + ":" + owner + ":snapshot/their-snap");
|
||||
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
|
||||
|
||||
assertEquals(Optional.of(own.getSnapshotArn()), service.find("snapshot", List.of("own-snap"), REGION));
|
||||
assertEquals(Optional.of(theirs.getSnapshotArn()),
|
||||
service.findInAccount("snapshot", List.of("their-snap"), owner, REGION));
|
||||
assertEquals(Optional.empty(), service.find("snapshot", List.of("their-snap"), REGION));
|
||||
assertEquals(Optional.empty(), service.findInAccount("snapshot", List.of("own-snap"), owner, REGION));
|
||||
assertEquals(Optional.empty(), service.findInAccount("namespace", List.of("find-ns"), owner, REGION));
|
||||
assertEquals(Optional.of(service.getNamespace("find-ns", REGION).getNamespaceArn()),
|
||||
service.find("namespace", List.of("find-ns"), REGION));
|
||||
assertEquals(Optional.empty(), service.find("workgroup", List.of("missing"), REGION));
|
||||
assertEquals(Optional.empty(), service.find("endpointAccess", List.of("any"), REGION));
|
||||
RedshiftServerlessEndpointAccessService endpointService = mock(RedshiftServerlessEndpointAccessService.class);
|
||||
Instance<RedshiftServerlessEndpointAccessService> endpointInstance = mock(Instance.class);
|
||||
when(endpointInstance.isUnsatisfied()).thenReturn(false);
|
||||
when(endpointInstance.get()).thenReturn(endpointService);
|
||||
when(endpointService.findEndpointArn("my-endpoint", REGION)).thenReturn(Optional.of("arn:endpoint"));
|
||||
service.endpointAccess = endpointInstance;
|
||||
assertEquals(Optional.of("arn:endpoint"), service.find("endpointAccess", List.of("my-endpoint"), REGION));
|
||||
assertEquals(Optional.empty(), service.find("snapshot", List.of(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOwnerAccountIsOtherOnlyWhenItDiffersFromTheCallers() {
|
||||
assertTrue(service.isOtherAccount("999999999999"));
|
||||
assertFalse(service.isOtherAccount(ACCOUNT_ID));
|
||||
assertFalse(service.isOtherAccount(null));
|
||||
assertFalse(service.isOtherAccount(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void snapshotNameFromArnOfAnotherOwnerNeedsThatOwnersAccount() {
|
||||
String owner = "999999999999";
|
||||
String ownerArn = "arn:aws:redshift-serverless:" + REGION + ":" + owner + ":snapshot/their-snap";
|
||||
|
||||
assertEquals("their-snap", service.snapshotNameFromArn(ownerArn, REGION, owner, "snapshotArn"));
|
||||
assertEquals("ValidationException", assertThrows(AwsException.class,
|
||||
() -> service.snapshotNameFromArn(ownerArn, REGION, ACCOUNT_ID, "snapshotArn")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromSharedSnapshotDoesNotTrustADumpOutsideTheOwnersDirectory() throws Exception {
|
||||
String owner = "999999999999";
|
||||
create("shared-ns");
|
||||
createWorkgroup("shared-wg", "shared-ns");
|
||||
Path callerDump = dumpDir.resolve("redshift-serverless-dumps").resolve(ACCOUNT_ID).resolve(REGION)
|
||||
.resolve("elsewhere.sql").toAbsolutePath().normalize();
|
||||
Files.createDirectories(callerDump.getParent());
|
||||
Files.writeString(callerDump, "select 1;");
|
||||
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(
|
||||
service.createSnapshot("own-snap", "shared-ns", null, null, REGION));
|
||||
theirs.setSnapshotName("their-snap");
|
||||
theirs.setOwnerAccount(owner);
|
||||
theirs.setSqlDump(callerDump.toString());
|
||||
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
|
||||
|
||||
AwsException untrusted = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
|
||||
"shared-ns", "shared-wg", "their-snap", owner, null, null, REGION));
|
||||
|
||||
assertEquals("InternalServerException", untrusted.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreFromSharedSnapshotStillNeedsAnAvailableSnapshotAndAWorkgroup() {
|
||||
String owner = "999999999999";
|
||||
create("shared-ns");
|
||||
RedshiftServerlessSnapshot theirs = new RedshiftServerlessSnapshot(
|
||||
service.createSnapshot("own-snap", "shared-ns", null, null, REGION));
|
||||
theirs.setSnapshotName("their-snap");
|
||||
theirs.setOwnerAccount(owner);
|
||||
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
|
||||
|
||||
AwsException noWorkgroup = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
|
||||
"shared-ns", "missing-wg", "their-snap", owner, null, null, REGION));
|
||||
assertEquals("ResourceNotFoundException", noWorkgroup.getErrorCode());
|
||||
|
||||
AwsException noSnapshot = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
|
||||
"shared-ns", "missing-wg", "no-such-snap", owner, null, null, REGION));
|
||||
assertEquals("ResourceNotFoundException", noSnapshot.getErrorCode());
|
||||
|
||||
theirs.setStatus("FAILED");
|
||||
snapshotStore.putForAccount(owner, REGION + "::their-snap", theirs);
|
||||
AwsException unavailable = assertThrows(AwsException.class, () -> service.restoreFromSharedSnapshot(
|
||||
"shared-ns", "missing-wg", "their-snap", owner, null, null, REGION));
|
||||
assertEquals("ConflictException", unavailable.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreRejectsAWorkgroupOfAnotherNamespace() {
|
||||
create("rest-a");
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package io.floci.aws.services.redshiftserverless;
|
||||
|
||||
import io.floci.aws.services.redshift.TempCredential;
|
||||
import io.floci.aws.services.redshift.model.Endpoint;
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Under IAM enforcement, a snapshot another account owns is restored only when the snapshot's resource policy
|
||||
* names the caller, and the caller's own identity policy allows it as well: the request is checked on the
|
||||
* owner's snapshot ARN, which the policy is attached to.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
|
||||
private static final String OWNER = "111122223333";
|
||||
private static final String CALLER = "444455556666";
|
||||
private static final String STRANGER = "777788889999";
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String TARGET_PREFIX = "RedshiftServerless.";
|
||||
private static final String ALLOW_RESTORE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\",\"Resource\":\"*\"}]}";
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@InjectMock
|
||||
RedshiftServerlessRuntime runtime;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void stubRuntime() {
|
||||
when(runtime.generatePassword()).thenReturn("Generated123");
|
||||
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
|
||||
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
|
||||
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
|
||||
when(runtime.issueCredential(any(), any(), any(), any(), anyInt()))
|
||||
.thenAnswer(invocation -> new TempCredential(invocation.getArgument(3), "temporary-password",
|
||||
Instant.now().plusSeconds(900), List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSnapshotIsRestorableByAnotherAccountOnlyWhenItsPolicyNamesTheCaller() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceNamespace = "share-src-" + suffix;
|
||||
String snapshot = "share-snap-" + suffix;
|
||||
String namespace = "share-dst-" + suffix;
|
||||
String workgroup = "share-wg-" + suffix;
|
||||
String callerKey = user(CALLER, ALLOW_RESTORE);
|
||||
String strangerKey = user(STRANGER, ALLOW_RESTORE);
|
||||
String unprivilegedKey = user(CALLER, "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"redshift-serverless:GetNamespace\",\"Resource\":\"*\"}]}");
|
||||
|
||||
call(OWNER, "CreateNamespace", Map.of("namespaceName", sourceNamespace, "adminUsername", "admin"))
|
||||
.statusCode(200);
|
||||
String snapshotArn = call(OWNER, "CreateSnapshot",
|
||||
Map.of("snapshotName", snapshot, "namespaceName", sourceNamespace))
|
||||
.statusCode(200).extract().path("snapshot.snapshotArn");
|
||||
for (String account : List.of(CALLER, STRANGER)) {
|
||||
call(account, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin"))
|
||||
.statusCode(200);
|
||||
call(account, "CreateWorkgroup", Map.of("workgroupName", workgroup, "namespaceName", namespace))
|
||||
.statusCode(200);
|
||||
}
|
||||
Map<String, String> byName = Map.of("namespaceName", namespace, "workgroupName", workgroup,
|
||||
"snapshotName", snapshot, "ownerAccount", OWNER);
|
||||
|
||||
// Not shared until the snapshot's policy says so.
|
||||
denied(call(callerKey, "RestoreFromSnapshot", byName));
|
||||
|
||||
// AWS's own PutResourcePolicy example leaves Resource out: the policy is still on this snapshot.
|
||||
String sharedWithCaller = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"arn:aws:iam::" + CALLER + ":root\"},"
|
||||
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}]}";
|
||||
call(OWNER, "PutResourcePolicy", Map.of("resourceArn", snapshotArn, "policy", sharedWithCaller))
|
||||
.statusCode(200);
|
||||
call(callerKey, "RestoreFromSnapshot", byName).statusCode(200)
|
||||
.body("ownerAccount", equalTo(OWNER))
|
||||
.body("snapshotName", equalTo(snapshot));
|
||||
call(callerKey, "RestoreFromSnapshot", Map.of("namespaceName", namespace, "workgroupName", workgroup,
|
||||
"snapshotArn", snapshotArn, "ownerAccount", OWNER)).statusCode(200)
|
||||
.body("snapshotName", equalTo(snapshot));
|
||||
|
||||
// The policy is the resource side only: a caller whose own policy does not allow it is refused, and so is
|
||||
// an account the policy does not name.
|
||||
denied(call(unprivilegedKey, "RestoreFromSnapshot", byName));
|
||||
denied(call(strangerKey, "RestoreFromSnapshot", byName));
|
||||
|
||||
// Withdrawing the policy takes the access away at the next restore.
|
||||
call(OWNER, "DeleteResourcePolicy", Map.of("resourceArn", snapshotArn)).statusCode(200);
|
||||
denied(call(callerKey, "RestoreFromSnapshot", byName));
|
||||
}
|
||||
|
||||
private static void denied(ValidatableResponse response) {
|
||||
response.statusCode(400).body("__type", equalTo("AccessDeniedException"))
|
||||
.body("message", containsString("redshift-serverless:RestoreFromSnapshot"));
|
||||
}
|
||||
|
||||
private String user(String account, String policy) {
|
||||
String name = "share-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String authorization = auth(account, "iam");
|
||||
String accessKeyId = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, name)
|
||||
.accessKeyId();
|
||||
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, name, "p", policy);
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
private ValidatableResponse call(String accessKeyId, String action, Map<String, String> body) {
|
||||
return given().port(endpoint.getPort())
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
.header("Authorization", auth(accessKeyId, "redshift-serverless"))
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user