feat(redshift): read S3 as the access keys a COPY names (#7334)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-02 21:37:08 -04:00
1 parent b0721f9795
commit a93de121ae
11 files changed
+541 -45

No files matched your search

@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
@@ -200,4 +201,93 @@ class RedshiftInterceptorIamRoleEnforcedIntegrationTest {
}
}
}
@Test
void copyWithAnIamUsersOwnAccessKeyIsAuthorizedAsThatUser() throws Exception {
clusterId = "it-copy-access-key";
String bucket = "redshift-copy-access-key";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "p1.txt", "1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
iamService.createUser("CopyKeyReader", "/");
iamService.putUserPolicy("CopyKeyReader", "ReadBucket", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::redshift-copy-access-key"},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::redshift-copy-access-key/*"}
]}
""");
iamService.createUser("CopyKeyStranger", "/");
AccessKey reader = iamService.createAccessKey("CopyKeyReader");
AccessKey stranger = iamService.createAccessKey("CopyKeyStranger");
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123", null, List.of(),
List.of());
try (Connection connection = waitForConnection(cluster, "simple");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE people (id int, name text)");
statement.execute("COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID '"
+ reader.getAccessKeyId() + "' SECRET_ACCESS_KEY '" + reader.getSecretAccessKey() + "'");
try (ResultSet rows = statement.executeQuery("SELECT name FROM people")) {
assertTrue(rows.next());
assertEquals("alice", rows.getString(1));
}
SQLException wrongSecret = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID '" + reader.getAccessKeyId()
+ "' SECRET_ACCESS_KEY 'not-the-secret'"));
assertEquals("XX000", wrongSecret.getSQLState());
SQLException unknownKey = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID 'AKIAUNKNOWNKEY00000' "
+ "SECRET_ACCESS_KEY 'whatever'"));
assertEquals("XX000", unknownKey.getSQLState());
SQLException noPolicy = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID '" + stranger.getAccessKeyId()
+ "' SECRET_ACCESS_KEY '" + stranger.getSecretAccessKey() + "'"));
assertEquals("42501", noPolicy.getSQLState());
}
}
@Test
void copyHonorsABucketPolicyDenyConditionedOnTheRequestedPrefix() throws Exception {
clusterId = "it-copy-bucket-prefix";
String bucket = "redshift-copy-bucket-prefix";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "private/p1.txt", "1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
s3.putObject(bucket, "public/p1.txt", "2|bob\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
// the user's own policy allows everything, so only the bucket policy can refuse the private prefix
iamService.createUser("CopyPrefixReader", "/");
iamService.putUserPolicy("CopyPrefixReader", "ReadAll", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
]}
""");
s3.putBucketPolicy(bucket, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Principal":"*","Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::redshift-copy-bucket-prefix",
"Condition":{"StringLike":{"s3:prefix":"private/*"}}}
]}
""");
AccessKey reader = iamService.createAccessKey("CopyPrefixReader");
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123", null, List.of(),
List.of());
try (Connection connection = waitForConnection(cluster, "simple");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE people (id int, name text)");
String credentials = " ACCESS_KEY_ID '" + reader.getAccessKeyId() + "' SECRET_ACCESS_KEY '"
+ reader.getSecretAccessKey() + "'";
SQLException denied = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/private/p1.txt'" + credentials));
assertEquals("42501", denied.getSQLState());
statement.execute("COPY people FROM 's3://" + bucket + "/public/p1.txt'" + credentials);
try (ResultSet rows = statement.executeQuery("SELECT name FROM people")) {
assertTrue(rows.next());
assertEquals("bob", rows.getString(1));
}
}
}
}
@@ -419,6 +419,42 @@ class CopyStatementParserTest {
assertNull(c.iamRoleArn());
}
@Test
void copyKeepsTheKeysAndTokenOfACredentialsString() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' CREDENTIALS "
+ "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=s3cr3t/+x;token=tok/+en=='");
assertEquals("ASIAEXAMPLE", c.accessKeys().accessKeyId());
assertEquals("s3cr3t/+x", c.accessKeys().secretAccessKey());
assertEquals("tok/+en==", c.accessKeys().sessionToken());
}
@Test
void copyKeepsTheKeysOfSeparateClauses() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' ACCESS_KEY_ID 'AKIAEXAMPLE' SECRET_ACCESS_KEY 'secret'");
assertEquals("AKIAEXAMPLE", c.accessKeys().accessKeyId());
assertEquals("secret", c.accessKeys().secretAccessKey());
assertNull(c.accessKeys().sessionToken());
}
@Test
void copyWithoutKeysHasNoAccessKeys() {
assertNull(copyFrom("COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::000000000000:role/r'").accessKeys());
}
@Test
void accessKeysStringFormHidesTheSecretAndToken() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' CREDENTIALS "
+ "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=s3cr3t;token=tok'");
String text = c.toString();
assertTrue(text.contains("ASIAEXAMPLE"));
assertFalse(text.contains("s3cr3t"));
assertFalse(text.contains("tok'") || text.contains("token=tok"));
}
@Test
void copyRejectsConflictingOrIncompleteAuthorization() {
assertNull(CopyStatementParser.parse(
@@ -188,7 +188,7 @@ class RedshiftRoleAccessTest {
IamService iamService = mock(IamService.class);
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token");
doThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist", 404)).when(s3)
.authorizeSignedListBucket("ASIAX", "token", "bucket");
.authorizeSignedListBucket("ASIAX", "token", "bucket", "");
S3CopySimulator.S3TransferException missing = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", ""));
@@ -204,7 +204,7 @@ class RedshiftRoleAccessTest {
IamService iamService = mock(IamService.class);
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token");
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket("ASIAX", "token", "bucket");
.authorizeSignedListBucket("ASIAX", "token", "bucket", "");
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedGetObject("ASIAX", "token", "bucket", "key");
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
@@ -39,6 +40,7 @@ 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.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
@@ -93,6 +95,159 @@ class S3CopySimulatorTest {
verifyNoInteractions(s3);
}
private static final String KEY_COPY = "COPY people FROM 's3://bucket/data.csv' CREDENTIALS "
+ "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=secret;token=tok'";
private static CopyStatementParser.S3CopyFrom keyCopy() {
return (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(KEY_COPY);
}
@Test
void copyWithKnownKeysReadsS3AsThoseKeys() {
IamService iamService = mock(IamService.class);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("secret"));
when(s3.isAuthEnforced()).thenReturn(true);
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}")));
when(s3.objectExists("bucket", "data.csv")).thenReturn(true);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
assertEquals(List.of("data.csv"), input.keys());
verify(s3).authorizeSignedListBucket("ASIAEXAMPLE", "tok", "bucket", "data.csv");
verify(s3).authorizeSignedGetObject("ASIAEXAMPLE", "tok", "bucket", "data.csv");
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
}
@Test
void copyWithAnUnknownOrExpiredKeyFailsInsteadOfReadingAnonymously() {
IamService iamService = mock(IamService.class);
when(s3.isAuthEnforced()).thenReturn(true);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.empty());
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("XX000", error.sqlState());
assertTrue(error.getMessage().contains("does not exist in our records"), error.getMessage());
assertFalse(error.getMessage().contains("secret"), error.getMessage());
verify(s3, never()).authorizeAnonymousListBucket(any());
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
}
@Test
void copyWithAWrongSecretFails() {
IamService iamService = mock(IamService.class);
when(s3.isAuthEnforced()).thenReturn(true);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("another-secret"));
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("XX000", error.sqlState());
assertTrue(error.getMessage().contains("signature"), error.getMessage());
}
@Test
void copyWithKeysDeniedByTheirIdentityPolicyFails() {
IamService iamService = mock(IamService.class);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("secret"));
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of()));
when(s3.isAuthEnforced()).thenReturn(true);
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("42501", error.sqlState());
assertTrue(error.getMessage().contains("ASIAEXAMPLE"), error.getMessage());
assertFalse(error.getMessage().contains("tok"), error.getMessage());
verify(s3, never()).authorizeSignedListBucket(any(), any(), any());
}
private static String policy(String statements) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}";
}
private IamService knownKey() {
IamService iamService = mock(IamService.class);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("secret"));
when(s3.isAuthEnforced()).thenReturn(true);
when(s3.objectExists("bucket", "data.csv")).thenReturn(true);
return iamService;
}
@Test
void aConditionalDenyOnThePrincipalArnStillAppliesToTheKeysCopy() {
IamService iamService = knownKey();
String arn = "arn:aws:iam::111111111111:user/alice";
when(iamService.resolveCallerArns("ASIAEXAMPLE")).thenReturn(Optional.of(
new IamService.CallerArns(arn, arn)));
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"},"
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\","
+ "\"Condition\":{\"ArnEquals\":{\"aws:PrincipalArn\":\"" + arn + "\"}}}"))));
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("42501", error.sqlState());
}
@Test
void anAllowThatRequiresTheListedPrefixMatchesTheCopyPrefix() {
IamService iamService = knownKey();
when(s3.objectExists("bucket", "data.csv")).thenReturn(false);
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("data.csv"), any(), anyInt(), any(), any()))
.thenReturn(null);
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:ListBucket\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringLike\":{\"s3:prefix\":\"data*\"}}},"
+ "{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}"))));
// The listing is authorized (no 42501); the empty prefix then finds no object.
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertTrue(error.getMessage().contains("not found"), error.getMessage());
}
@Test
void keysAuthorizeAgainstTheArnsOfTheBucketsPartition() {
IamService iamService = knownKey();
when(s3.bucketPartition("bucket")).thenReturn("aws-cn");
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:*\","
+ "\"Resource\":[\"arn:aws-cn:s3:::bucket\",\"arn:aws-cn:s3:::bucket/*\"]}"))));
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
assertEquals(List.of("data.csv"), input.keys());
}
@Test
void theOwnerOfTheKeyIsLookedUpAcrossAccounts() {
IamService iamService = knownKey();
when(iamService.findAccountForAccessKeyId("ASIAEXAMPLE")).thenReturn(Optional.of("222222222222"));
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}"))));
S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
verify(iamService).findAccountForAccessKeyId("ASIAEXAMPLE");
}
@Test
void copyIgnoresPlaceholderKeysWhenS3AuthorizationIsOff() {
IamService iamService = mock(IamService.class);
when(s3.isAuthEnforced()).thenReturn(false);
when(s3.objectExists("bucket", "data.csv")).thenReturn(true);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
assertEquals(List.of("data.csv"), input.keys());
verifyNoInteractions(iamService);
}
private ServerSocket listener;
private Socket simClient; // simulator's "client" end
private Socket simBackend; // simulator's "backend" end
@@ -114,6 +269,7 @@ class S3CopySimulatorTest {
backendListener.close();
s3 = mock(S3Service.class);
when(s3.bucketPartition(anyString())).thenReturn("aws");
}
@AfterEach
@@ -336,7 +492,7 @@ class S3CopySimulatorTest {
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
verify(s3, never()).authorizeAnonymousListBucket(any());
verify(s3).authorizeSignedListBucket(any(), any(), eq("b"));
verify(s3).authorizeSignedListBucket(any(), any(), eq("b"), any());
verify(s3).authorizeSignedGetObject(any(), any(), eq("b"), eq("k"));
verify(iamService).registerSessionForAccount(
eq("000000000000"), any(), any(), any(), eq(ROLE_ARN), any(), isNull());
@@ -1049,7 +1049,7 @@ class ExternalTableMaterializerTest {
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("bucket"));
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("bucket"), any());
verify(s3).authorizeSignedGetObject(anyString(), anyString(), eq("bucket"), eq("events/p1.csv"));
verify(iam).unregisterSession(eq(ACCOUNT), anyString());
}
@@ -1058,7 +1058,7 @@ class ExternalTableMaterializerTest {
void releasesTheRoleSessionWhenAuthorizationFails() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket(anyString(), anyString(), eq("bucket"));
.authorizeSignedListBucket(anyString(), anyString(), eq("bucket"), any());
assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
@@ -17,6 +17,7 @@ import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -259,7 +260,7 @@ class SpectrumS3ReaderTest {
assertEquals(1, rows.count());
}
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"));
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"), any());
verify(s3).authorizeSignedGetObject(anyString(), anyString(), eq("warehouse"), eq("events/data.csv"));
verify(iam).unregisterSession(eq("000000000000"), anyString());
}
@@ -270,7 +271,7 @@ class SpectrumS3ReaderTest {
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"));
.authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"), any());
assertThrows(SpectrumReadException.class, () -> new SpectrumS3Reader(s3, iam)
.read(session(role), schema(role), table(SpectrumColumn.Type.VARCHAR)).toList());