mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): require kms:Decrypt on an encrypted snapshot's key to restore it (#8309)
AWS requires the customer managed key of an encrypted snapshot to be shared with the account restoring it (Redshift Management Guide, "Sharing a snapshot"). Neither botocore nor the Service Reference says so, so the request-resources generator states it in FORWARDED, an evidence entry under MEASURED's rules: the action and the snapshot type, with the rest read from the metadata (the key type and format kms:Decrypt acts on, the snapshot record's KmsKeyId member, the endpoint prefix, kms:ViaService). Under IAM enforcement a Redshift or Redshift Serverless restore is then also checked as kms:Decrypt on the key the snapshot records, found in the snapshot's account, against the key policy and the caller's own policies, with aws:ViaAWSService and kms:ViaService naming the service's endpoint. KMS key policies are now evaluated as resource policies. A key KMS would not use, disabled, pending deletion or not held, refuses the restore, as KMS refuses the request the service makes with it. A snapshot under AWS's own key records none, and one under an AWS managed key (a copy grant made without a key) needs nothing, as AWS writes that key's policy to let the account use it through the service.
This commit is contained in:
1 parent
ddc844b48e
commit
f09468fb19
22 files changed
+1234
-43
No files matched your search
@@ -86,6 +86,39 @@ class RequestResourceMembersTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardedRequestsJoinTheirActionsRecordedTypeAndViaServiceKeyAndRefuseAnythingElse() throws Exception {
|
||||
assertEquals(List.of(new RequestResourceMembers.Forwarded("kms:Decrypt", "key", "snapshot", "kmsKeyId",
|
||||
"redshift-serverless", "kms:ViaService")),
|
||||
RequestResourceMembers.table().forwarded().get("redshift-serverless:RestoreFromSnapshot"));
|
||||
assertEquals(List.of(new RequestResourceMembers.Forwarded("kms:Decrypt", "key", "snapshot", "KmsKeyId",
|
||||
"redshift", "kms:ViaService")),
|
||||
RequestResourceMembers.table().forwarded().get("redshift:RestoreFromClusterSnapshot"));
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree("""
|
||||
{"namespaces":{"example":["example"]},"arnFormats":{"example":{
|
||||
"thing":"arn:${Partition}:example:${Region}:${Account}:thing/${ThingId}"}},
|
||||
"forwardedActions":{"keys:Decrypt":{"type":"key",
|
||||
"format":"arn:${Partition}:keys:${Region}:${Account}:key/${KeyId}"}},
|
||||
"operations":{"example:Restore":{"types":["thing"],"resources":[],
|
||||
"forwarded":[{"action":"keys:Decrypt","of":"thing","member":"keysKeyId","endpoint":"example"}]}}}
|
||||
""");
|
||||
assertEquals(List.of(new RequestResourceMembers.Forwarded("keys:Decrypt", "key", "thing", "keysKeyId",
|
||||
"example", null)), parse(document.toString()).forwarded().get("example:Restore"));
|
||||
for (String invalid : List.of(
|
||||
"[{\"action\":\"keys:Encrypt\",\"of\":\"thing\",\"member\":\"keysKeyId\",\"endpoint\":\"example\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"gadget\",\"member\":\"keysKeyId\",\"endpoint\":\"example\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"thing\",\"member\":\"Keys[]\",\"endpoint\":\"example\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"thing\",\"member\":\"keysKeyId\",\"endpoint\":\"\"}]",
|
||||
"[{\"action\":\"keys:Decrypt\",\"of\":\"thing\",\"member\":\"keysKeyId\"}]")) {
|
||||
ObjectNode changed = document.deepCopy();
|
||||
((ObjectNode) changed.path("operations").path("example:Restore")).set("forwarded", MAPPER.readTree(invalid));
|
||||
assertThrows(IllegalStateException.class, () -> parse(changed.toString()), invalid);
|
||||
}
|
||||
ObjectNode otherKey = document.deepCopy();
|
||||
((ObjectNode) otherKey.path("forwardedActions").path("keys:Decrypt")).put("viaService", "other:ViaService");
|
||||
assertThrows(IllegalStateException.class, () -> parse(otherKey.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTableReadsItsNamespacesAndGivesEachTypeItNamesAnArnFormat() {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
|
||||
@@ -1110,6 +1110,85 @@ class RequestResourcesTest {
|
||||
assertEquals(List.of(), of("codebuild:StopBuild", json("{\"id\":\"orphan\"}"), codeBuild));
|
||||
}
|
||||
|
||||
/**
|
||||
* A restore whose service asks KMS, as the caller, to decrypt with the key its snapshot records is also checked
|
||||
* as {@code kms:Decrypt} on that key, found in the snapshot's own account and Region, the caller's or another's;
|
||||
* one KMS no longer holds is forwarded as the value the snapshot records, not held, which refuses it; a snapshot
|
||||
* recording no key, or one under a key AWS manages, whose policy lets the account use it through the service,
|
||||
* forwards nothing.
|
||||
*/
|
||||
@Test
|
||||
void aRestoreForwardsDecryptOnTheKeyItsSnapshotRecords() {
|
||||
String caller = "000000000000";
|
||||
String owner = "111122223333";
|
||||
String own = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/mine";
|
||||
String shared = "arn:aws:redshift-serverless:eu-west-1:" + owner + ":snapshot/theirs";
|
||||
String plain = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/plain";
|
||||
String lost = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/lost";
|
||||
String managed = "arn:aws:redshift-serverless:us-east-1:" + caller + ":snapshot/managed";
|
||||
String awsKey = "arn:aws:kms:us-east-1:" + caller + ":key/aws-redshift";
|
||||
Map<String, String> keys = Map.of(own, "k-own", shared, "alias/theirs", lost, "deleted",
|
||||
managed, "alias/aws/redshift");
|
||||
StoredResourceArns serverless = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "redshift-serverless";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> recorded(String arn, String member) {
|
||||
return "kmsKeyId".equals(member) ? Optional.ofNullable(keys.get(arn)) : Optional.empty();
|
||||
}
|
||||
};
|
||||
StoredResourceArns kms = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "kms";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
if (!"key".equals(type)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return names.equals(List.of("k-own")) ? Optional.of("arn:aws:kms:" + region + ":" + caller + ":key/k-own")
|
||||
: names.equals(List.of("alias/aws/redshift")) ? Optional.of(awsKey) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findInAccount(String type, List<String> names, String account, String region) {
|
||||
return "key".equals(type) && names.equals(List.of("alias/theirs"))
|
||||
? Optional.of("arn:aws:kms:" + region + ":" + account + ":key/k-theirs") : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean grantsItsAccountThroughServices(String arn) {
|
||||
return awsKey.equals(arn);
|
||||
}
|
||||
};
|
||||
String operation = "redshift-serverless:RestoreFromSnapshot";
|
||||
assertEquals(List.of(
|
||||
new RequestResources.Forwarded("kms:Decrypt", "arn:aws:kms:us-east-1:" + caller + ":key/k-own",
|
||||
"kms:ViaService", "redshift-serverless", true),
|
||||
new RequestResources.Forwarded("kms:Decrypt", "arn:aws:kms:eu-west-1:" + owner + ":key/k-theirs",
|
||||
"kms:ViaService", "redshift-serverless", true),
|
||||
new RequestResources.Forwarded("kms:Decrypt", "deleted", "kms:ViaService", "redshift-serverless",
|
||||
false)),
|
||||
RequestResources.forwarded(operation, List.of("*", own, shared, plain, lost, managed), caller,
|
||||
serverless, namespace -> "kms".equals(namespace) ? kms : null));
|
||||
// Without the snapshot's or the key's service, or for an operation forwarding nothing, nothing is forwarded.
|
||||
assertEquals(List.of(), RequestResources.forwarded(operation, List.of(own), caller, null, namespace -> kms));
|
||||
assertEquals(List.of(), RequestResources.forwarded(operation, List.of(own), caller, serverless,
|
||||
namespace -> null));
|
||||
assertEquals(List.of(), RequestResources.forwarded("redshift-serverless:GetSnapshot", List.of(own), caller,
|
||||
serverless, namespace -> kms));
|
||||
}
|
||||
|
||||
/**
|
||||
* A Parameter Store parameter is {@code parameter/<name>} whether its name starts with a slash or not, without the
|
||||
* whitespace around it, a name of two leading slashes keeping the second and one beginning {@code /parameter/}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package io.floci.aws.services.kms;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy;
|
||||
import io.floci.aws.services.kms.model.KmsAlias;
|
||||
import io.floci.aws.services.kms.model.KmsKey;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Another service reads a key its resource records, and the key's policy, in the account that resource is in, whoever
|
||||
* is calling: a shared snapshot's key is the owner's.
|
||||
*/
|
||||
class KmsKeyOfAccountTest {
|
||||
|
||||
private static final String OWNER = "111122223333";
|
||||
private static final String CALLER = "444455556666";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private KmsService owners;
|
||||
private KmsService callers;
|
||||
private KmsKey key;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AccountAwareStorageBackend<KmsKey> keys = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, OWNER);
|
||||
AccountAwareStorageBackend<KmsAlias> aliases = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null,
|
||||
OWNER);
|
||||
owners = new KmsService(keys, aliases, new InMemoryStorage<>(), new RegionResolver(REGION, OWNER));
|
||||
callers = new KmsService(keys, aliases, new InMemoryStorage<>(), new RegionResolver(REGION, CALLER));
|
||||
key = owners.createKey("snapshot key", REGION);
|
||||
owners.createAlias("alias/snapshots", key.getKeyId(), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIsFoundByItsIdAliasOrArnInTheAccountItIsIn() {
|
||||
String arn = key.getArn();
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount(key.getKeyId(), OWNER, REGION));
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount("alias/snapshots", OWNER, REGION));
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount(arn, CALLER, REGION));
|
||||
assertEquals(Optional.of(arn), callers.findKeyArnOfAccount(
|
||||
"arn:aws:kms:" + REGION + ":" + OWNER + ":alias/snapshots", CALLER, REGION));
|
||||
// Not the caller's key, nor one in another Region, nor AWS's own key, which no account holds.
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount(key.getKeyId(), CALLER, REGION));
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount(key.getKeyId(), OWNER, "eu-west-1"));
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount("AWS_OWNED_KMS_KEY", OWNER, REGION));
|
||||
assertEquals(Optional.empty(), callers.findKeyArnOfAccount("alias/none", OWNER, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeysPolicyIsReadInTheAccountOfItsArn() {
|
||||
assertThat(callers.findKeyPolicy(key.getArn()).orElseThrow(), containsString(OWNER));
|
||||
assertEquals(Optional.empty(), callers.findKeyPolicy(key.getArn().replace(OWNER, CALLER)));
|
||||
assertEquals(Optional.empty(), callers.findKeyPolicy("arn:aws:kms:" + REGION + ":" + OWNER + ":alias/snapshots"));
|
||||
assertEquals(Optional.empty(), callers.findKeyPolicy("arn:aws:sqs:" + REGION + ":" + OWNER + ":queue"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A key's policy is its resource policy, owned by the account in its ARN even when that account holds no such key,
|
||||
* so another account's key is judged as cross-account; an alias or a key left open has none.
|
||||
*/
|
||||
@Test
|
||||
void theProviderGivesAKeysPolicyAndOwnerAndNothingForAnAliasOrAnOpenKey() {
|
||||
KmsResourcePolicyProvider provider = new KmsResourcePolicyProvider(callers);
|
||||
List<ResourcePolicy> policies = provider.getResourcePolicies("redshift-serverless", key.getArn());
|
||||
assertEquals(1, policies.size());
|
||||
assertEquals(OWNER, policies.getFirst().ownerAccountId());
|
||||
assertThat(policies.getFirst().policyDocument(), containsString("kms:*"));
|
||||
String missing = "arn:aws:kms:" + REGION + ":777788889999:key/" + key.getKeyId();
|
||||
assertEquals(List.of(new ResourcePolicy(null, "777788889999")), provider.getResourcePolicies("kms", missing));
|
||||
assertTrue(provider.getResourcePolicies("kms", "arn:aws:kms:" + REGION + ":" + OWNER + ":alias/snapshots")
|
||||
.isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("kms", "arn:aws:kms:" + REGION + ":" + OWNER + ":key/*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("kms", "*").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStoredResourceArnsFindAKeyInTheCallersAccountOrAnother() {
|
||||
KmsStoredResourceArns stored = new KmsStoredResourceArns(owners, new RegionResolver(REGION, OWNER));
|
||||
assertEquals("kms", stored.namespace());
|
||||
assertEquals(Optional.of(key.getArn()), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
assertEquals(Optional.of(key.getArn()), stored.findInAccount("key", List.of("alias/snapshots"), OWNER, REGION));
|
||||
assertEquals(Optional.empty(), stored.findInAccount("key", List.of(key.getKeyId()), CALLER, REGION));
|
||||
assertEquals(Optional.empty(), stored.find("alias", List.of("alias/snapshots"), REGION));
|
||||
assertFalse(stored.grantsItsAccountThroughServices(key.getArn()));
|
||||
}
|
||||
|
||||
/** A key KMS would refuse a decrypt with, disabled or pending deletion, is none a forwarded request finds. */
|
||||
@Test
|
||||
void theStoredResourceArnsFindNoKeyKmsWouldNotUse() {
|
||||
KmsStoredResourceArns stored = new KmsStoredResourceArns(owners, new RegionResolver(REGION, OWNER));
|
||||
owners.disableKey(key.getKeyId(), REGION);
|
||||
assertEquals(Optional.empty(), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
owners.enableKey(key.getKeyId(), REGION);
|
||||
assertEquals(Optional.of(key.getArn()), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
owners.scheduleKeyDeletion(key.getKeyId(), 7, REGION);
|
||||
assertEquals(Optional.empty(), stored.find("key", List.of(key.getKeyId()), REGION));
|
||||
// Its lookup still finds it: only a request KMS would serve with it is refused.
|
||||
assertEquals(Optional.of(key.getArn()), owners.findKeyArnOfAccount(key.getKeyId(), OWNER, REGION));
|
||||
}
|
||||
|
||||
/**
|
||||
* The reserved {@code alias/aws/redshift}, as a default copy grant records it, names AWS's managed key of the
|
||||
* account, which is there before anything read KMS, and whose policy lets the account use it through Redshift.
|
||||
*/
|
||||
@Test
|
||||
void aReservedAliasNamesTheAccountsAwsManagedKeyWhichGrantsItsAccountThroughServices() {
|
||||
AccountAwareStorageBackend<KmsKey> keys = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, OWNER);
|
||||
AccountAwareStorageBackend<KmsAlias> aliases = new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null,
|
||||
OWNER);
|
||||
KmsService fresh = new KmsService(keys, aliases, new InMemoryStorage<>(), new RegionResolver(REGION, OWNER));
|
||||
KmsStoredResourceArns stored = new KmsStoredResourceArns(fresh, new RegionResolver(REGION, OWNER));
|
||||
String managed = stored.find("key", List.of("arn:aws:kms:" + REGION + ":" + OWNER + ":alias/aws/redshift"),
|
||||
REGION).orElseThrow();
|
||||
assertTrue(fresh.isAwsManagedKey(managed));
|
||||
assertTrue(stored.grantsItsAccountThroughServices(managed));
|
||||
// Another account's reserved alias is not seeded for it, so it names no key here.
|
||||
assertEquals(Optional.empty(), fresh.findKeyArnOfAccount("alias/aws/redshift", CALLER, REGION));
|
||||
}
|
||||
}
|
||||
@@ -4022,6 +4022,52 @@ class RedshiftServiceTest {
|
||||
assertThrows(AwsException.class, () -> service.deleteClusterSubnetGroup("missing"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot ARN of the caller's names the copy kept in its Region before the snapshot itself, a cluster left open
|
||||
* matching any, and what it records as its {@code KmsKeyId} is the key a restore decrypts with. One of another
|
||||
* account names that account's snapshot itself alone, taken in the ARN's Region, as a shared restore reads it.
|
||||
*/
|
||||
@Test
|
||||
void aSnapshotArnNamesTheCopyInItsRegionFirstAndItsKeyIsWhatItRecords() {
|
||||
Snapshot copy = snapshot("c1", "snap", "arn:aws:redshift:eu-west-1:111111111111:snapshot:c1/snap");
|
||||
copy.setKmsKeyId("key-copy");
|
||||
Snapshot original = snapshot("c1", "snap", "arn:aws:redshift:us-east-1:111111111111:snapshot:c1/snap");
|
||||
when(snapshotCopyBackend.getForAccount("111111111111", "eu-west-1::snap")).thenReturn(Optional.of(copy));
|
||||
when(snapshotBackend.getForAccount("111111111111", "snap")).thenReturn(Optional.of(original));
|
||||
String prefix = "arn:aws:redshift:eu-west-1:111111111111:snapshot:";
|
||||
|
||||
assertEquals(Optional.of(copy), service.findSnapshotAt(prefix + "c1/snap"));
|
||||
assertEquals(Optional.of(copy), service.findSnapshotAt(prefix + "*/snap"));
|
||||
assertEquals(Optional.of(original), service.findSnapshotAt("arn:aws:redshift:us-east-1:111111111111:snapshot:c1/snap"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt(prefix + "c2/snap"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt("arn:aws:redshift:eu-west-1:111111111111:cluster:c1"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt("arn:aws:redshift-serverless:eu-west-1:111111111111:snapshot/x"));
|
||||
|
||||
RedshiftStoredResourceArns stored = new RedshiftStoredResourceArns(service);
|
||||
assertEquals("redshift", stored.namespace());
|
||||
assertEquals(Optional.of("key-copy"), stored.recorded(prefix + "*/snap", "KmsKeyId"));
|
||||
assertEquals(Optional.empty(), stored.recorded("arn:aws:redshift:us-east-1:111111111111:snapshot:c1/snap", "KmsKeyId"));
|
||||
assertEquals(Optional.empty(), stored.recorded(prefix + "c1/snap", "kmsKeyId"));
|
||||
|
||||
// Another account's: its snapshot in the ARN's Region, never the copy it keeps there.
|
||||
Snapshot theirs = snapshot("c1", "snap", "arn:aws:redshift:us-east-1:222222222222:snapshot:c1/snap");
|
||||
Snapshot theirCopy = snapshot("c1", "snap", "arn:aws:redshift:eu-west-1:222222222222:snapshot:c1/snap");
|
||||
theirCopy.setKmsKeyId("key-their-copy");
|
||||
when(snapshotCopyBackend.getForAccount("222222222222", "eu-west-1::snap")).thenReturn(Optional.of(theirCopy));
|
||||
when(snapshotBackend.getForAccount("222222222222", "snap")).thenReturn(Optional.of(theirs));
|
||||
assertEquals(Optional.of(theirs), service.findSnapshotAt("arn:aws:redshift:us-east-1:222222222222:snapshot:c1/snap"));
|
||||
assertEquals(Optional.empty(), service.findSnapshotAt("arn:aws:redshift:eu-west-1:222222222222:snapshot:c1/snap"));
|
||||
assertEquals(Optional.empty(), stored.recorded("arn:aws:redshift:eu-west-1:222222222222:snapshot:*/snap", "KmsKeyId"));
|
||||
}
|
||||
|
||||
private static Snapshot snapshot(String cluster, String identifier, String arn) {
|
||||
Snapshot snapshot = new Snapshot();
|
||||
snapshot.setClusterIdentifier(cluster);
|
||||
snapshot.setSnapshotIdentifier(identifier);
|
||||
snapshot.setSnapshotArn(arn);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsSnapshotCopyGrant() {
|
||||
when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty());
|
||||
|
||||
+147
-7
@@ -18,6 +18,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -35,7 +36,8 @@ 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.
|
||||
* owner's snapshot ARN, which the policy is attached to. A snapshot encrypted with a customer managed key also needs
|
||||
* {@code kms:Decrypt} on that key, from the key policy and the caller's own policy.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
@@ -48,6 +50,8 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
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\":\"*\"}]}";
|
||||
private static final String ALLOW_RESTORE_AND_DECRYPT = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":"
|
||||
+ "\"Allow\",\"Action\":[\"redshift-serverless:RestoreFromSnapshot\",\"kms:Decrypt\"],\"Resource\":\"*\"}]}";
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
@@ -166,10 +170,7 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
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))
|
||||
call(OWNER, "PutResourcePolicy", Map.of("resourceArn", snapshotArn, "policy", sharedWith(CALLER)))
|
||||
.statusCode(200);
|
||||
call(callerKey, "RestoreFromSnapshot", byName).statusCode(200)
|
||||
.body("ownerAccount", equalTo(OWNER))
|
||||
@@ -188,6 +189,136 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
denied(call(callerKey, "RestoreFromSnapshot", byName));
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot encrypted with a customer managed key restores in another account only when the key's policy lets
|
||||
* that account decrypt with it and the caller's own policy allows {@code kms:Decrypt} on it, as AWS requires the
|
||||
* key to be shared with the account performing the restore. Redshift Serverless reaches KMS as the caller, from
|
||||
* its endpoint in the request's Region, which a key policy's {@code kms:ViaService} condition names.
|
||||
*/
|
||||
@Test
|
||||
void anEncryptedSnapshotRestoresInAnotherAccountOnlyWhenItsKeyIsSharedWithIt() {
|
||||
EncryptedSnapshot encrypted = encryptedSnapshot("KeyMetadata.KeyId", CALLER);
|
||||
call(OWNER, "PutResourcePolicy", Map.of("resourceArn", encrypted.snapshotArn(), "policy", sharedWith(CALLER)))
|
||||
.statusCode(200);
|
||||
String decrypting = user(CALLER, ALLOW_RESTORE_AND_DECRYPT);
|
||||
String restoringOnly = user(CALLER, ALLOW_RESTORE);
|
||||
Map<String, String> byName = encrypted.restore(Map.of("snapshotName", encrypted.snapshot(),
|
||||
"ownerAccount", OWNER));
|
||||
|
||||
// Shared, but the key is still the owner's alone.
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", byName));
|
||||
|
||||
putKeyPolicy(encrypted.key(), keySharedWith(CALLER, null));
|
||||
call(decrypting, "RestoreFromSnapshot", byName).statusCode(200)
|
||||
.body("snapshotName", equalTo(encrypted.snapshot()));
|
||||
call(decrypting, "RestoreFromSnapshot", encrypted.restore(Map.of("snapshotArn", encrypted.snapshotArn(),
|
||||
"ownerAccount", OWNER))).statusCode(200);
|
||||
// The key policy is the resource side only: the caller's own policy must allow decrypting with the key too.
|
||||
keyDenied(call(restoringOnly, "RestoreFromSnapshot", byName));
|
||||
|
||||
putKeyPolicy(encrypted.key(), keySharedWith(CALLER, "redshift-serverless.us-east-1.amazonaws.com"));
|
||||
call(decrypting, "RestoreFromSnapshot", byName).statusCode(200);
|
||||
putKeyPolicy(encrypted.key(), keySharedWith(CALLER, "ec2.us-east-1.amazonaws.com"));
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", byName));
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner restoring its own encrypted snapshot needs {@code kms:Decrypt} on the key in its own policy, which the
|
||||
* default key policy delegates to; a snapshot under AWS's own key needs none (the test above restores one).
|
||||
*/
|
||||
@Test
|
||||
void theOwnerRestoresItsEncryptedSnapshotOnlyWhenItsPolicyAllowsDecryptingWithTheKey() {
|
||||
EncryptedSnapshot encrypted = encryptedSnapshot("KeyMetadata.Arn", OWNER);
|
||||
Map<String, String> restore = encrypted.restore(Map.of("snapshotName", encrypted.snapshot()));
|
||||
|
||||
keyDenied(call(user(OWNER, ALLOW_RESTORE), "RestoreFromSnapshot", restore));
|
||||
call(user(OWNER, ALLOW_RESTORE_AND_DECRYPT), "RestoreFromSnapshot", restore).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot whose key KMS would refuse to decrypt with, disabled or pending deletion, is not restored whatever
|
||||
* the policies allow, as KMS refuses the request Redshift Serverless makes with it.
|
||||
*/
|
||||
@Test
|
||||
void aSnapshotWhoseKeyKmsWouldNotUseIsNotRestored() {
|
||||
EncryptedSnapshot encrypted = encryptedSnapshot("KeyMetadata.KeyId", OWNER);
|
||||
Map<String, String> restore = encrypted.restore(Map.of("snapshotName", encrypted.snapshot()));
|
||||
String decrypting = user(OWNER, ALLOW_RESTORE_AND_DECRYPT);
|
||||
|
||||
kms(OWNER, "DisableKey", Map.of("KeyId", encrypted.key())).statusCode(200);
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", restore));
|
||||
kms(OWNER, "EnableKey", Map.of("KeyId", encrypted.key())).statusCode(200);
|
||||
call(decrypting, "RestoreFromSnapshot", restore).statusCode(200);
|
||||
kms(OWNER, "ScheduleKeyDeletion", Map.of("KeyId", encrypted.key(), "PendingWindowInDays", "7"))
|
||||
.statusCode(200);
|
||||
keyDenied(call(decrypting, "RestoreFromSnapshot", restore));
|
||||
}
|
||||
|
||||
/**
|
||||
* An owner's snapshot of a namespace encrypted with a new customer managed key, given to the namespace as the
|
||||
* {@code KeyMetadata} field {@code keyField} names (its id or its ARN), and a namespace and workgroup of
|
||||
* {@code restoringAccount} to restore it into.
|
||||
*/
|
||||
private EncryptedSnapshot encryptedSnapshot(String keyField, String restoringAccount) {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceNamespace = "kms-src-" + suffix;
|
||||
String snapshot = "kms-snap-" + suffix;
|
||||
String namespace = "kms-dst-" + suffix;
|
||||
String workgroup = "kms-wg-" + suffix;
|
||||
String key = kms(OWNER, "CreateKey", Map.of("Description", "snapshot key")).statusCode(200)
|
||||
.extract().path(keyField);
|
||||
call(OWNER, "CreateNamespace", Map.of("namespaceName", sourceNamespace, "adminUsername", "admin",
|
||||
"kmsKeyId", key)).statusCode(200);
|
||||
String snapshotArn = call(OWNER, "CreateSnapshot",
|
||||
Map.of("snapshotName", snapshot, "namespaceName", sourceNamespace))
|
||||
.statusCode(200).extract().path("snapshot.snapshotArn");
|
||||
call(restoringAccount, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin"))
|
||||
.statusCode(200);
|
||||
call(restoringAccount, "CreateWorkgroup", Map.of("workgroupName", workgroup, "namespaceName", namespace))
|
||||
.statusCode(200);
|
||||
return new EncryptedSnapshot(key, snapshot, snapshotArn, namespace, workgroup);
|
||||
}
|
||||
|
||||
/** An encrypted snapshot, its key as the namespace was given it, and where it is restored. */
|
||||
private record EncryptedSnapshot(String key, String snapshot, String snapshotArn, String namespace,
|
||||
String workgroup) {
|
||||
|
||||
/** A restore into the namespace and workgroup of the snapshot {@code naming} names. */
|
||||
Map<String, String> restore(Map<String, String> naming) {
|
||||
Map<String, String> request = new HashMap<>(naming);
|
||||
request.put("namespaceName", namespace);
|
||||
request.put("workgroupName", workgroup);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
|
||||
private static String sharedWith(String account) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":\"arn:aws:iam::" + account + ":root\"},"
|
||||
+ "\"Action\":\"redshift-serverless:RestoreFromSnapshot\"}]}";
|
||||
}
|
||||
|
||||
/** The default key policy, and {@code kms:Decrypt} for {@code account}, through {@code viaService} if given. */
|
||||
private static String keySharedWith(String account, String viaService) {
|
||||
String condition = viaService == null ? ""
|
||||
: ",\"Condition\":{\"StringEquals\":{\"kms:ViaService\":\"" + viaService + "\"}}";
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::" + OWNER + ":root\"},"
|
||||
+ "\"Action\":\"kms:*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::" + account + ":root\"},"
|
||||
+ "\"Action\":\"kms:Decrypt\",\"Resource\":\"*\"" + condition + "}]}";
|
||||
}
|
||||
|
||||
private void putKeyPolicy(String keyId, String policy) {
|
||||
kms(OWNER, "PutKeyPolicy", Map.of("KeyId", keyId, "PolicyName", "default", "Policy", policy))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void keyDenied(ValidatableResponse response) {
|
||||
response.statusCode(400).body("__type", equalTo("AccessDeniedException"))
|
||||
.body("message", containsString("kms:Decrypt"));
|
||||
}
|
||||
|
||||
private static void denied(ValidatableResponse response) {
|
||||
response.statusCode(400).body("__type", equalTo("AccessDeniedException"))
|
||||
.body("message", containsString("redshift-serverless:RestoreFromSnapshot"));
|
||||
@@ -202,10 +333,19 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest {
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
private ValidatableResponse kms(String accessKeyId, String action, Map<String, String> body) {
|
||||
return send("TrentService." + action, "kms", accessKeyId, body);
|
||||
}
|
||||
|
||||
private ValidatableResponse call(String accessKeyId, String action, Map<String, String> body) {
|
||||
return send(TARGET_PREFIX + action, "redshift-serverless", accessKeyId, body);
|
||||
}
|
||||
|
||||
/** A JSON request to {@code target}, signed for {@code service} by {@code accessKeyId}. */
|
||||
private ValidatableResponse send(String target, String service, String accessKeyId, Map<String, String> body) {
|
||||
return given().port(endpoint.getPort())
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
.header("Authorization", auth(accessKeyId, "redshift-serverless"))
|
||||
.header("X-Amz-Target", target)
|
||||
.header("Authorization", auth(accessKeyId, service))
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
|
||||
Reference in new issue
Block a user