mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): sign the Spectrum floci-duck transfer with the role session when S3 auth is enforced (#7162)
This commit is contained in:
1 parent
6d71c3599d
commit
cedc1073ec
16 files changed
+843
-32
No files matched your search
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.s3.S3Controller;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.scheduler.SchedulerController;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
@@ -1591,6 +1592,133 @@ class IamEnforcementFilterTest {
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
private static final String SCRATCH_OBJECT = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/"
|
||||
+ "spectrum-123e4567-e89b-12d3-a456-426614174000.csv";
|
||||
|
||||
private IamEnforcementFilter newFilterWithRealEvaluator() {
|
||||
return newFilterWithRealEvaluator(null);
|
||||
}
|
||||
|
||||
private IamEnforcementFilter newFilterWithRealEvaluator(Instance<S3Service> s3ServiceProvider) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ScpProvider> scpProvider = mock(Instance.class);
|
||||
when(scpProvider.isResolvable()).thenReturn(false);
|
||||
return new IamEnforcementFilter(
|
||||
config, accountResolver, iamService, new IamPolicyEvaluator(new ObjectMapper()),
|
||||
actionRegistry, arnBuilder, requestContext, conditionContextResolver,
|
||||
mock(CloudTrailService.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup, null, s3ServiceProvider);
|
||||
}
|
||||
|
||||
private void stubSignedS3Request(ContainerRequestContext containerRequest, String action, String resource,
|
||||
IamService.CallerArns callerArns, String identityPolicy) {
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260726/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("222233334444");
|
||||
requestContext.setRegion("us-east-1");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn(action);
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of(identityPolicy)));
|
||||
when(iamService.resolveCallerArns("ASIASESSION")).thenReturn(Optional.of(callerArns));
|
||||
when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.of(SCRATCH_OBJECT));
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString()))
|
||||
.thenReturn(List.of(resource));
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
|
||||
when(containerRequest.getMethod()).thenReturn("PUT");
|
||||
}
|
||||
|
||||
private static IamService.CallerArns assumedRoleArns() {
|
||||
return new IamService.CallerArns("arn:aws:sts::222233334444:assumed-role/SpectrumRole/session",
|
||||
"arn:aws:iam::222233334444:role/SpectrumRole", IamService.CallerArns.TYPE_ASSUMED_ROLE, null, null,
|
||||
false);
|
||||
}
|
||||
|
||||
private static final String NO_STATEMENTS = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
|
||||
|
||||
@Test
|
||||
void anAssumedRoleSessionMayWriteTheSpectrumScratchBucketWithoutAPolicyNamingIt() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void spectrumScratchWriteIsAuthorizedAheadOfRolePoliciesAndDenies() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(),
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"s3:*\","
|
||||
+ "\"Resource\":\"*\"}]}");
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scratchWriteDeniedWhenBucketIsNotInternalScratchBucket() {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<S3Service> s3ServiceProvider = mock(Instance.class);
|
||||
S3Service s3Service = mock(S3Service.class);
|
||||
when(s3ServiceProvider.isResolvable()).thenReturn(true);
|
||||
when(s3ServiceProvider.get()).thenReturn(s3Service);
|
||||
when(s3Service.isSpectrumScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)).thenReturn(false);
|
||||
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
|
||||
|
||||
newFilterWithRealEvaluator(s3ServiceProvider).filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theScratchBucketAllowDoesNotCoverReadsOtherBucketsOrOtherKeys() {
|
||||
String bucket = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/";
|
||||
for (String[] attempt : new String[][] {
|
||||
{"s3:GetObject", SCRATCH_OBJECT},
|
||||
{"s3:PutObject", "arn:aws:s3:::user-bucket/spectrum-123e4567-e89b-12d3-a456-426614174000.csv"},
|
||||
{"s3:PutObject", bucket + "nested/other.csv"}}) {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, attempt[0], attempt[1], assumedRoleArns(), NO_STATEMENTS);
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theScratchBucketAllowDoesNotCoverAnIamUser() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT,
|
||||
new IamService.CallerArns("arn:aws:iam::222233334444:user/alice",
|
||||
"arn:aws:iam::222233334444:user/alice", IamService.CallerArns.TYPE_USER, null, "alice",
|
||||
false), NO_STATEMENTS);
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnrelatedRoleSessionCannotWriteTheSpectrumScratchBucket() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
|
||||
when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.empty());
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
// FullAWSAccess baseline auto-attached to every OU/account when SCP enforcement is on.
|
||||
private static final String FULL_AWS_ACCESS =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
|
||||
|
||||
+80
@@ -17,6 +17,7 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -94,4 +95,83 @@ class FlociDuckClientServiceTest {
|
||||
|
||||
assertEquals("http://172.18.0.2:4566", requestBody.get().path("s3_endpoint").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void executeInjectsSessionTokenDdlAndPassesCredentials() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
AtomicReference<JsonNode> requestBody = new AtomicReference<>();
|
||||
server = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
server.createContext("/execute", exchange -> {
|
||||
requestBody.set(mapper.readTree(exchange.getRequestBody().readAllBytes()));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
|
||||
FlociDuckManager duckManager = mock(FlociDuckManager.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
|
||||
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
|
||||
when(duckManager.ensureReady()).thenReturn("http://localhost:" + server.getAddress().getPort());
|
||||
when(config.baseUrl()).thenReturn("http://localhost:4566");
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class));
|
||||
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
|
||||
when(dockerHostResolver.resolve()).thenReturn("127.0.0.1");
|
||||
|
||||
FlociDuckClient client = new FlociDuckClient(duckManager, config,
|
||||
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, 4566), mapper);
|
||||
client.execute("SELECT 1", "INSTALL iceberg;", "s3://bucket/out.csv",
|
||||
"ASIAEXAMPLE", "secretKey123", "tokenXYZ");
|
||||
|
||||
JsonNode body = requestBody.get();
|
||||
assertEquals("ASIAEXAMPLE", body.path("s3_access_key").asText());
|
||||
assertEquals("secretKey123", body.path("s3_secret_key").asText());
|
||||
assertEquals("s3://bucket/out.csv", body.path("output_s3_path").asText());
|
||||
String setupSql = body.path("setup_sql").asText();
|
||||
assertTrue(setupSql.startsWith("SET s3_session_token = 'tokenXYZ';\n"));
|
||||
assertTrue(setupSql.contains("INSTALL iceberg;"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryInjectsSessionTokenDdlAndPassesCredentials() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
AtomicReference<JsonNode> requestBody = new AtomicReference<>();
|
||||
server = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
server.createContext("/query", exchange -> {
|
||||
requestBody.set(mapper.readTree(exchange.getRequestBody().readAllBytes()));
|
||||
String response = "{\"status\": \"success\", \"rows\": [{\"col\": 1}]}";
|
||||
exchange.sendResponseHeaders(200, response.length());
|
||||
exchange.getResponseBody().write(response.getBytes(StandardCharsets.UTF_8));
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
|
||||
FlociDuckManager duckManager = mock(FlociDuckManager.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
|
||||
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
|
||||
when(duckManager.ensureReady()).thenReturn("http://localhost:" + server.getAddress().getPort());
|
||||
when(config.baseUrl()).thenReturn("http://localhost:4566");
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class));
|
||||
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
|
||||
when(dockerHostResolver.resolve()).thenReturn("127.0.0.1");
|
||||
|
||||
FlociDuckClient client = new FlociDuckClient(duckManager, config,
|
||||
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, 4566), mapper);
|
||||
client.query("SELECT 1 AS col", "", "ASIAEXAMPLE", "secretKey123", "tokenXYZ");
|
||||
|
||||
JsonNode body = requestBody.get();
|
||||
assertEquals("ASIAEXAMPLE", body.path("s3_access_key").asText());
|
||||
assertEquals("secretKey123", body.path("s3_secret_key").asText());
|
||||
String setupSql = body.path("setup_sql").asText();
|
||||
assertEquals("SET s3_session_token = 'tokenXYZ';\n", setupSql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionTokenQuotesAreEscaped() {
|
||||
assertEquals("SET s3_session_token = 'a''b';\nINSTALL x;",
|
||||
FlociDuckClient.injectSessionToken("INSTALL x;", "a'b"));
|
||||
}
|
||||
}
|
||||
@@ -2611,6 +2611,30 @@ class IamServiceTest {
|
||||
assertTrue(sessions.getForAccount("000000000000", "ASIASTSSESSION").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void spectrumScratchResourceRegistrationAndClear() {
|
||||
String accountId = "222233334444";
|
||||
String accessKeyId = "ASIASPECTRUM";
|
||||
AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "000000000000");
|
||||
IamService service = iamService(false, new InMemoryStorage<>(), sessions);
|
||||
|
||||
service.registerSessionForAccount(
|
||||
accountId, accessKeyId, "secret", "token",
|
||||
"arn:aws:iam::222233334444:role/R", Instant.now().plusSeconds(900), null);
|
||||
|
||||
assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty());
|
||||
|
||||
String scratchArn = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-1234.csv";
|
||||
service.registerSpectrumScratchResource(accessKeyId, scratchArn);
|
||||
|
||||
assertEquals(Optional.of(scratchArn), service.spectrumScratchResourceArn(accessKeyId));
|
||||
|
||||
service.clearSpectrumScratchResource(accessKeyId);
|
||||
|
||||
assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Instance Profiles
|
||||
// =========================================================================
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.services.glue.GlueService;
|
||||
import io.github.hectorvent.floci.services.glue.model.Database;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatement;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatementParser;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.GlueTableBuilder;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
|
||||
import io.github.hectorvent.floci.testing.SidecarS3AuthEnforcedProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Cold load, cached read and reload of a Spectrum external table with {@code s3.enforce-auth} on:
|
||||
* the floci-duck transfer runs under the role's signed session, and a bucket policy that denies the
|
||||
* role stops the next query with SQLSTATE 42501 even though the table is already cached.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarS3AuthEnforcedProfile.class)
|
||||
class RedshiftSpectrumS3AuthEnforcedIntegrationTest {
|
||||
|
||||
private static final String ROLE_NAME = "SpectrumAuthItRole";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/" + ROLE_NAME;
|
||||
private static final String TRUST_POLICY = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
|
||||
|
||||
@Inject
|
||||
RedshiftService redshiftService;
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
GlueService glueService;
|
||||
|
||||
private String clusterId;
|
||||
private String bucket;
|
||||
private String glueDatabase;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDocker();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
if (clusterId != null) {
|
||||
redshiftService.deleteCluster(clusterId);
|
||||
}
|
||||
if (bucket != null) {
|
||||
s3Service.deleteBucketPolicy(bucket);
|
||||
s3Service.deleteObject(bucket, "events/part-1.csv");
|
||||
s3Service.deleteBucket(bucket);
|
||||
}
|
||||
if (glueDatabase != null) {
|
||||
glueService.deleteDatabase(glueDatabase);
|
||||
}
|
||||
iamService.deleteRolePolicy(ROLE_NAME, "AllowS3");
|
||||
iamService.deleteRole(ROLE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void coldLoadReloadAndCachedReadUseTheRoleSessionAndHonorABucketPolicyDeny() throws Exception {
|
||||
iamService.createRole(ROLE_NAME, "/", TRUST_POLICY, null, 0, null);
|
||||
iamService.putRolePolicy(ROLE_NAME, "AllowS3", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":["s3:GetObject","s3:ListBucket"],"Resource":"*"}]}""");
|
||||
bucket = "spectrum-auth-" + System.nanoTime();
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
glueDatabase = "spectrum_auth_" + System.nanoTime();
|
||||
Database database = new Database();
|
||||
database.setName(glueDatabase);
|
||||
glueService.createDatabase(database);
|
||||
clusterId = "it-auth-" + System.nanoTime();
|
||||
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123",
|
||||
null, List.of(), List.of(ROLE_ARN));
|
||||
try (Connection connection = waitForConnection(cluster);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE '" + glueDatabase
|
||||
+ "' IAM_ROLE '" + ROLE_ARN + "'");
|
||||
String externalDdl = "CREATE EXTERNAL TABLE lake.events (id INTEGER, amount INTEGER) "
|
||||
+ "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE LOCATION 's3://"
|
||||
+ bucket + "/events/'";
|
||||
ExternalStatement.CreateTable external = (ExternalStatement.CreateTable)
|
||||
new ExternalStatementParser().parse(externalDdl).orElseThrow();
|
||||
glueService.createTable(glueDatabase, GlueTableBuilder.toGlueTable(external));
|
||||
|
||||
assertEquals(17L, sumAmount(statement));
|
||||
assertEquals(17L, sumAmount(statement));
|
||||
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,30\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
assertEquals(40L, sumAmount(statement));
|
||||
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,50\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
String queryId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"ClusterIdentifier":"%s","DbUser":"admin","Database":"dev",
|
||||
"Sql":"SELECT SUM(amount) AS total FROM lake.events","WaitTimeSeconds":30}
|
||||
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
|
||||
assertEquals("FINISHED", RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Status"));
|
||||
Number total = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
|
||||
"{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Records[0][0].longValue");
|
||||
assertEquals(60L, total.longValue());
|
||||
|
||||
s3Service.putBucketPolicy(bucket, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
|
||||
"Principal":{"AWS":"%s"},"Action":["s3:GetObject","s3:ListBucket"],
|
||||
"Resource":["arn:aws:s3:::%s","arn:aws:s3:::%s/*"]}]}""".formatted(ROLE_ARN, bucket, bucket));
|
||||
SQLException denied = assertThrows(SQLException.class, () -> sumAmount(statement));
|
||||
assertEquals("42501", denied.getSQLState());
|
||||
}
|
||||
}
|
||||
|
||||
private static long sumAmount(Statement statement) throws SQLException {
|
||||
try (ResultSet rows = statement.executeQuery("SELECT SUM(amount) FROM lake.events")) {
|
||||
assertTrue(rows.next());
|
||||
return rows.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection waitForConnection(Cluster cluster) {
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev";
|
||||
return Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull);
|
||||
}
|
||||
}
|
||||
+17
-3
@@ -17,6 +17,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -139,6 +140,19 @@ class RedshiftRoleAccessTest {
|
||||
assertThat(expiry.getValue().isBefore(before.plus(Duration.ofMinutes(31))), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveRoleSessionIncludesSecretAccessKeyMatchingIamSession() {
|
||||
IamService iamService = iamServiceWithRole(TRUST_POLICY);
|
||||
|
||||
RedshiftRoleAccess.RoleSession session = RedshiftRoleAccess.resolveRoleSession(
|
||||
ROLE_ARN, iamService, ACCOUNT, List.of(ROLE_ARN));
|
||||
|
||||
assertNotNull(session.secretAccessKey());
|
||||
assertThat(session.secretAccessKey().length(), equalTo(40));
|
||||
verify(iamService).registerSessionForAccount(eq(ACCOUNT), eq(session.accessKeyId()),
|
||||
eq(session.secretAccessKey()), eq(session.sessionToken()), eq(ROLE_ARN), any(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeRoleActionAllowsWhatTheIdentityPolicyGrants() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
@@ -158,7 +172,7 @@ class RedshiftRoleAccessTest {
|
||||
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListBucket",
|
||||
"Resource":"arn:aws:s3:::bucket","Condition":{"StringLike":{"s3:prefix":["events/*"]}}}]}""")));
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token");
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token");
|
||||
|
||||
RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", "events/");
|
||||
S3CopySimulator.S3TransferException denied = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
@@ -172,7 +186,7 @@ class RedshiftRoleAccessTest {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
when(s3.isAuthEnforced()).thenReturn(false);
|
||||
IamService iamService = mock(IamService.class);
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token");
|
||||
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");
|
||||
|
||||
@@ -188,7 +202,7 @@ class RedshiftRoleAccessTest {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
when(s3.isAuthEnforced()).thenReturn(false);
|
||||
IamService iamService = mock(IamService.class);
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token");
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token");
|
||||
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
|
||||
.authorizeSignedListBucket("ASIAX", "token", "bucket");
|
||||
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
|
||||
|
||||
+120
-5
@@ -50,6 +50,8 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.ArgumentMatchers.notNull;
|
||||
import static org.mockito.ArgumentMatchers.startsWith;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -200,7 +202,7 @@ class ExternalTableMaterializerTest {
|
||||
Table table = icebergTable("s3://bucket/events/metadata/v[1].json");
|
||||
when(glue.getTable("lake", "events")).thenReturn(table);
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(duck.query(anyString(), any(), eq(ACCOUNT))).thenAnswer(invocation -> {
|
||||
when(duck.query(anyString(), any(), startsWith("ASIA"), anyString(), anyString())).thenAnswer(invocation -> {
|
||||
String sql = invocation.getArgument(0);
|
||||
if (!sql.contains("status IN ('ADDED', 'EXISTING')") || sql.contains("content = 'DATA'")) {
|
||||
return List.of();
|
||||
@@ -222,16 +224,129 @@ class ExternalTableMaterializerTest {
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("42501"));
|
||||
verify(duck).query(argThat(sql -> sql.contains("iceberg_metadata('s3://bucket/events/metadata/v[[]1].json')")),
|
||||
any(), eq(ACCOUNT));
|
||||
any(), startsWith("ASIA"), anyString(), anyString());
|
||||
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void coldLoadWithAuthEnforcedTransfersWithTheRoleSessionCredentials() {
|
||||
when(glue.getTable("lake", "events")).thenReturn(csvTable());
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
|
||||
]}""")));
|
||||
|
||||
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
|
||||
verify(duck).execute(argThat(sql -> sql.contains("LIMIT 1001")), isNull(), anyString(),
|
||||
startsWith("ASIA"), anyString(), notNull());
|
||||
verify(duck, never()).execute(anyString(), any(), anyString(), eq(ACCOUNT));
|
||||
verify(iam).registerSpectrumScratchResource(startsWith("ASIA"),
|
||||
startsWith("arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void transferDenialDuringColdLoadReturns42501() {
|
||||
when(glue.getTable("lake", "events")).thenReturn(csvTable());
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
|
||||
]}""")));
|
||||
doThrow(new RuntimeException("floci-duck execute returned HTTP 500: HTTP Error: HTTP 403 (Forbidden) while writing scratch"))
|
||||
.when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("42501"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accessDenialDuringIcebergScanReturns42501() {
|
||||
Table table = icebergTable("s3://bucket/events/metadata/v1.json");
|
||||
when(glue.getTable("lake", "events")).thenReturn(table);
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
|
||||
]}""")));
|
||||
when(duck.query(anyString(), any(), startsWith("ASIA"), anyString(), anyString()))
|
||||
.thenThrow(new RuntimeException("floci-duck query error: AccessDenied: Access Denied"));
|
||||
|
||||
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("42501"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrelatedExecutionErrorDuringColdLoadReturns58030() {
|
||||
when(glue.getTable("lake", "events")).thenReturn(csvTable());
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
|
||||
]}""")));
|
||||
doThrow(new RuntimeException("floci-duck execute returned HTTP 500: Parser Error: syntax error"))
|
||||
.when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("58030"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void conversionErrorCarrying403InScratchPathReturns58030() {
|
||||
when(glue.getTable("lake", "events")).thenReturn(csvTable());
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
|
||||
]}""")));
|
||||
doThrow(new RuntimeException("floci-duck execute returned HTTP 500: Failed to write to "
|
||||
+ "'s3://floci-internal-redshift-spectrum-scratch/spectrum-e403d511-1234.csv': "
|
||||
+ "Conversion Error: Could not convert string 'foo' to INT32"))
|
||||
.when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("58030"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void conversionErrorOnFailedValueContaining403Returns58030() {
|
||||
when(glue.getTable("lake", "events")).thenReturn(csvTable());
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
|
||||
]}""")));
|
||||
doThrow(new RuntimeException("floci-duck execute returned HTTP 500: "
|
||||
+ "Conversion Error: Could not convert string '403' to INT32"))
|
||||
.when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString());
|
||||
|
||||
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("58030"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesIcebergManifestBeforeTheMetadataScanReadsIt() {
|
||||
Table table = icebergTable("s3://bucket/events/metadata/v1.json");
|
||||
when(glue.getTable("lake", "events")).thenReturn(table);
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
when(duck.query(anyString(), any(), eq(ACCOUNT))).thenAnswer(invocation -> {
|
||||
when(duck.query(anyString(), any(), startsWith("ASIA"), anyString(), anyString())).thenAnswer(invocation -> {
|
||||
String sql = invocation.getArgument(0);
|
||||
if (sql.contains("read_avro")) {
|
||||
return List.of(Map.of("manifest_path", "s3://bucket/private/manifest.avro"));
|
||||
@@ -249,8 +364,8 @@ class ExternalTableMaterializerTest {
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("42501"));
|
||||
verify(duck).query(argThat(sql -> sql.contains("read_avro('s3://bucket/events/metadata/snap[*].avro')")),
|
||||
any(), eq(ACCOUNT));
|
||||
verify(duck, never()).query(argThat(sql -> sql.contains("iceberg_metadata")), any(), eq(ACCOUNT));
|
||||
any(), startsWith("ASIA"), anyString(), anyString());
|
||||
verify(duck, never()).query(argThat(sql -> sql.contains("iceberg_metadata")), any(), anyString(), anyString(), anyString());
|
||||
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* {@link SidecarContainersProfile} with S3 authorization enforced, so the floci-duck transfer of a
|
||||
* Spectrum cold load has to present a signed role session instead of the account-scoped development
|
||||
* credentials.
|
||||
*/
|
||||
public class SidecarS3AuthEnforcedProfile extends SidecarContainersProfile {
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
Map<String, String> overrides = new HashMap<>(super.getConfigOverrides());
|
||||
overrides.put("floci.services.s3.enforce-auth", "true");
|
||||
return overrides;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user