feat(redshift): authorize COPY and UNLOAD with IAM_ROLE (#3815)

* feat(redshift): parse IAM_ROLE clause on COPY and UNLOAD

* feat(s3): add signed-principal authorization wrappers for role sessions

* feat(redshift): authorize COPY/UNLOAD S3 access through an IAM_ROLE session

* feat(redshift): thread IamService through the Redshift auth proxy chain

* test(redshift): cover IAM_ROLE resolution and signed authorization in prepareCopy

* fix(redshift): complete IAM_ROLE S3 authorization

* test(redshift): cover IAM_ROLE authorization end to end

* docs(redshift): document IAM_ROLE COPY and UNLOAD

* fix(redshift): retain IAM_ROLE session during COPY

* style(test): use Mockito static imports

* fix(native): initialize redshift copy simulator at runtime

* fix(redshift): address IAM role review feedback

* test(redshift): use valid proxy relay keys

* fix(redshift): require IAM roles to be associated

* test(compat): recover CodeArtifact create retries

* fix(redshift): parse IAM role location names

* fix(docs): exclude Redshift IAM role member label

* chore: remove unrelated CodeArtifact test
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-18 10:21:10 -04:00
1 parent c3ec3819ae
commit 677cdbe053
26 files changed
+1142 -250

No files matched your search

@@ -196,6 +196,28 @@ class AssumeRolePolicyEvaluatorTest {
trust("{\"Service\":\"lambda.amazonaws.com\"}"), CALLER_ARN, CALLER_ACCOUNT));
}
@Test
void allowsMatchingServicePrincipal() {
assertTrue(evaluator.allowsService(trust("{\"Service\":\"redshift.amazonaws.com\"}"),
"redshift.amazonaws.com"));
}
@Test
void deniesDifferentServicePrincipal() {
assertFalse(evaluator.allowsService(trust("{\"Service\":\"lambda.amazonaws.com\"}"),
"redshift.amazonaws.com"));
}
@Test
void explicitServiceDenyOverridesAllow() {
String doc = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""";
assertFalse(evaluator.allowsService(doc, "redshift.amazonaws.com"));
}
@Test
void deniesBlankOrMalformedDocument() {
assertFalse(evaluator.allows(null, CALLER_ARN, CALLER_ACCOUNT));
@@ -0,0 +1,141 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
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.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Covers COPY IAM_ROLE authorization when {@code FLOCI_SERVICES_S3_ENFORCE_AUTH} is on, so the
* role's identity-based policy actually gates S3 access. Kept in its own {@code @QuarkusTest}
* class (own {@link EnforceAuthProfile}) because Quarkus restarts the application per distinct
* test profile; {@link RedshiftInterceptorIntegrationTest} runs with enforcement off.
*/
@QuarkusTest
@TestProfile(RedshiftInterceptorIamRoleEnforcedIntegrationTest.EnforceAuthProfile.class)
class RedshiftInterceptorIamRoleEnforcedIntegrationTest {
private static final String REDSHIFT_TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""";
@Inject
RedshiftService service;
@Inject
S3Service s3;
@Inject
IamService iamService;
private String clusterId;
@BeforeAll
static void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for Redshift interceptor integration tests");
}
private static boolean isDockerAvailable() {
try {
Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
.redirectErrorStream(true)
.start();
return process.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
service.deleteCluster(clusterId);
}
}
private static Connection waitForConnection(Cluster cluster) throws SQLException {
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev";
return Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull);
}
@Test
void copyWithAllowingRolePolicySucceeds() throws Exception {
clusterId = "it-copy-iam-role-allow";
String bucket = "redshift-iam-role-allow";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "p1.txt", "1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
iamService.createRole("CopyRoleAllow", "/", REDSHIFT_TRUST_POLICY, null, 0, null);
iamService.putRolePolicy("CopyRoleAllow", "AllowS3", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","s3:ListBucket"],"Resource":"*"}
]}
""");
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123", null, List.of(),
List.of("arn:aws:iam::000000000000:role/CopyRoleAllow"));
try (Connection connection = waitForConnection(cluster);
Statement ddl = connection.createStatement()) {
ddl.execute("CREATE TABLE people (id int, name text)");
try (PreparedStatement copy = connection.prepareStatement(
"COPY people FROM 's3://" + bucket + "/p1.txt' "
+ "IAM_ROLE 'arn:aws:iam::000000000000:role/CopyRoleAllow'")) {
copy.execute();
}
}
}
@Test
void copyWithNoMatchingRolePolicyFails() throws Exception {
clusterId = "it-copy-iam-role-deny";
String bucket = "redshift-iam-role-deny";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "p1.txt", "1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
iamService.createRole("CopyRoleDeny", "/", REDSHIFT_TRUST_POLICY, null, 0, null);
// No policy attached: implicit deny.
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123", null, List.of(),
List.of("arn:aws:iam::000000000000:role/CopyRoleDeny"));
try (Connection connection = waitForConnection(cluster);
Statement ddl = connection.createStatement()) {
ddl.execute("CREATE TABLE people (id int, name text)");
try (PreparedStatement copy = connection.prepareStatement(
"COPY people FROM 's3://" + bucket + "/p1.txt' "
+ "IAM_ROLE 'arn:aws:iam::000000000000:role/CopyRoleDeny'")) {
assertThrows(SQLException.class, copy::execute);
}
}
}
public static final class EnforceAuthProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.s3.enforce-auth", "true");
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
@@ -39,12 +40,20 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class RedshiftInterceptorIntegrationTest {
private static final String REDSHIFT_TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""";
@Inject
RedshiftService service;
@Inject
S3Service s3;
@Inject
IamService iamService;
private String clusterId;
@BeforeAll
@@ -131,6 +140,32 @@ class RedshiftInterceptorIntegrationTest {
s3.getObject(bucket, objects.get(0).getKey()).getData(), StandardCharsets.UTF_8));
}
@Test
void copyWithIamRoleSucceedsWhenEnforceAuthIsOffEvenWithoutAPolicy() throws Exception {
clusterId = "it-copy-iam-role-no-enforce";
String bucket = "redshift-iam-role-no-enforce";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "people/p1.txt",
"1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
iamService.createRole("CopyRoleNoPolicy", "/", REDSHIFT_TRUST_POLICY, null, 0, null);
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123", null, List.of(),
List.of("arn:aws:iam::000000000000:role/CopyRoleNoPolicy"));
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
Statement ddl = connection.createStatement()) {
ddl.execute("CREATE TABLE people (id int, name text)");
try (PreparedStatement copy = connection.prepareStatement(
"COPY people FROM 's3://" + bucket + "/people/p1.txt' "
+ "IAM_ROLE 'arn:aws:iam::000000000000:role/CopyRoleNoPolicy'")) {
copy.execute();
}
try (ResultSet rows = connection.createStatement().executeQuery("SELECT count(*) FROM people")) {
assertTrue(rows.next());
assertEquals(1, rows.getInt(1));
}
}
}
@Test
void namedPreparedCopyAndUnloadCanBeExecutedTwice() throws Exception {
clusterId = "it-extended-named";
@@ -76,6 +76,28 @@ class RedshiftQueryHandlerTest {
assertTrue(xml.contains("<ClusterStatus>available</ClusterStatus>"));
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
}
@Test
void createClusterParsesIamRoleArnLocationName() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "test-cluster");
params.putSingle("NodeType", "dc2.large");
params.putSingle("MasterUsername", "admin");
params.putSingle("MasterUserPassword", "password123");
params.putSingle("IamRoles.IamRoleArn.2", "arn:aws:iam::000000000000:role/second");
params.putSingle("IamRoles.IamRoleArn.1", "arn:aws:iam::000000000000:role/first");
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("test-cluster");
cluster.setClusterStatus("available");
when(service.createCluster(any(), any(), any(), any(), any(), any(), any())).thenReturn(cluster);
handler.handle("CreateCluster", params);
verify(service).createCluster(eq("test-cluster"), eq("dc2.large"), eq("admin"), eq("password123"),
isNull(), eq(List.of()), eq(List.of("arn:aws:iam::000000000000:role/first",
"arn:aws:iam::000000000000:role/second")));
}
@Test
void testDescribeClusters() {
@@ -192,7 +192,7 @@ class RedshiftServiceTest {
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(7108),
eq("172.17.0.12"), eq(32830), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
eq("admin"), eq("Secret123"), eq("dev"), any(), any());
}
@Test
@@ -240,7 +240,7 @@ class RedshiftServiceTest {
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(cluster.getProxyPort()),
eq("172.17.0.9"), eq(32800), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
eq("admin"), eq("Secret123"), eq("dev"), any(), any());
}
@Test
@@ -456,7 +456,7 @@ class RedshiftServiceTest {
verify(proxyManager).stopProxy("111111111111:c1");
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(7107),
eq("172.17.0.11"), eq(32820), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
eq("admin"), eq("Secret123"), eq("dev"), any(), any());
}
@Test
@@ -487,7 +487,7 @@ class RedshiftServiceTest {
// replacement container must be stopped too — once before the restart, once in
// rollback — so it is not left running behind a "failed" cluster.
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(7107), any(), anyInt(),
any(), any(), any(), any(), any());
any(), any(), any(), any(), any(), any());
verify(proxyManager, times(2)).stopProxy("111111111111:c1");
verify(cm, times(2)).stop("111111111111", "c1");
}
@@ -860,7 +860,7 @@ class RedshiftServiceTest {
assertEquals(restored.getEndpoint().getPort(), restored.getProxyPort());
verify(proxyManager).startProxy(eq("111111111111:restored"), anyInt(),
eq("172.17.0.10"), eq(32810), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
eq("admin"), eq("Secret123"), eq("dev"), any(), any());
}
@Test
@@ -78,6 +78,50 @@ class CopyStatementParserTest {
assertEquals("t", c.targetTable());
}
@Test
void parsesIamRoleOnCopy() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::000000000000:role/CopyRole'");
assertEquals("arn:aws:iam::000000000000:role/CopyRole", c.iamRoleArn());
}
@Test
void parsesIamRoleCombinedWithOtherOptions() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::000000000000:role/CopyRole' "
+ "GZIP DELIMITER ','");
assertEquals("arn:aws:iam::000000000000:role/CopyRole", c.iamRoleArn());
assertTrue(c.gzip());
assertEquals(",", c.delimiter());
}
@Test
void copyWithoutIamRoleLeavesItNull() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k'");
assertNull(c.iamRoleArn());
}
@Test
void iamRoleDefaultKeywordIsStillUnsupported() {
// Bare `default` (no quotes) does not match the quoted-ARN clause, so it falls through
// to the existing catch-all and the whole statement is rejected (fail-open), same as today.
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' IAM_ROLE default"));
}
@Test
void parsesIamRoleOnUnload() {
CopyStatementParser.S3Unload u = (CopyStatementParser.S3Unload) CopyStatementParser.parse(
"UNLOAD ('select 1') TO 's3://b/p' IAM_ROLE 'arn:aws:iam::000000000000:role/UnloadRole'");
assertEquals("arn:aws:iam::000000000000:role/UnloadRole", u.iamRoleArn());
}
@Test
void unloadWithoutIamRoleLeavesItNull() {
CopyStatementParser.S3Unload u = (CopyStatementParser.S3Unload) CopyStatementParser.parse(
"UNLOAD ('select 1') TO 's3://b/p'");
assertNull(u.iamRoleArn());
}
@Test
void rejectsInjectionInTableName() {
assertNull(CopyStatementParser.parse("COPY t; DROP TABLE u; FROM 's3://b/k'"));
@@ -122,7 +166,6 @@ class CopyStatementParserTest {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' JSON 'auto'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FIXEDWIDTH 'a:1,b:2'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP MAXERROR 10"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::0:role/r'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'YYYY-MM-DD'"));
}
@@ -263,7 +306,6 @@ class CopyStatementParserTest {
void unloadRejectsUnsupportedOptions() {
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' PARQUET"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' ENCRYPTED"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' IAM_ROLE 'arn:aws:iam::0:role/r'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' REGION 'us-west-2'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' EXTENSION 'csv'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' ZSTD"));
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.AfterEach;
@@ -34,6 +35,7 @@ class ExtendedS3ExchangeTest {
private Socket testClient;
private Socket testBackend;
private S3Service s3;
private IamService iamService;
private final AtomicReference<Throwable> backendFailure = new AtomicReference<>();
@BeforeEach
@@ -48,6 +50,7 @@ class ExtendedS3ExchangeTest {
testBackend = backendListener.accept();
backendListener.close();
s3 = mock(S3Service.class);
iamService = mock(IamService.class);
}
@AfterEach
@@ -65,7 +68,7 @@ class ExtendedS3ExchangeTest {
when(s3.getObject("b", "in/data")).thenReturn(
new S3Object("b", "in/data", "1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom copy = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "in/data", "|", 0, false, false, null);
"t", List.of(), "b", "in/data", "|", 0, false, false, null, null);
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
@@ -73,7 +76,7 @@ class ExtendedS3ExchangeTest {
writeSync();
Thread backend = backendThread(() -> playCopyIn(copied));
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, coordinator, ticket);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, iamService, coordinator, ticket);
joinBackend(backend);
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClient.getInputStream());
@@ -94,14 +97,14 @@ class ExtendedS3ExchangeTest {
});
CopyStatementParser.S3Unload unload = new CopyStatementParser.S3Unload(
"select a from t", "b", "out/", "|", false, false, false,
false, null, false, true, false, 0);
false, null, false, true, false, 0, null);
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
writeSync();
Thread backend = backendThread(this::playCopyOut);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), unload, s3, coordinator, ticket);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), unload, s3, iamService, coordinator, ticket);
joinBackend(backend);
assertEquals("1\n2\n", new String(written.get("out/000"), StandardCharsets.US_ASCII));
@@ -116,7 +119,7 @@ class ExtendedS3ExchangeTest {
@Test
void missingCopyInputSendsCopyFailAndWaitsForSyncRecovery() throws Exception {
CopyStatementParser.S3CopyFrom copy = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "missing", "|", 0, false, false, null);
"t", List.of(), "b", "missing", "|", 0, false, false, null, null);
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
@@ -134,7 +137,7 @@ class ExtendedS3ExchangeTest {
testBackend.getOutputStream().flush();
});
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, coordinator, ticket);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, iamService, coordinator, ticket);
joinBackend(backend);
testClient.setSoTimeout(1_000);
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
@@ -74,7 +75,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 5000, 5000, 100);
mock(S3Service.class), mock(IamService.class), 5000, 5000, 100);
proxy.start(proxyPort);
try (Socket client = new Socket("localhost", proxyPort)) {
@@ -117,7 +118,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 5000, 5000, 100);
mock(S3Service.class), mock(IamService.class), 5000, 5000, 100);
proxy.start(proxyPort);
// Connect, then drop without ever sending a startup packet.
@@ -134,7 +135,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 200, 5000, 100);
mock(S3Service.class), mock(IamService.class), 200, 5000, 100);
proxy.start(proxyPort);
try (Socket client = new Socket("localhost", proxyPort)) {
@@ -153,7 +154,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 5000, 5000, 1);
mock(S3Service.class), mock(IamService.class), 5000, 5000, 1);
proxy.start(proxyPort);
// Hold the proxy's single connection permit from the test thread itself, so the
@@ -192,7 +193,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 5000, 5000, 100);
mock(S3Service.class), mock(IamService.class), 5000, 5000, 100);
proxy.start(proxyPort); // must not throw despite the port being busy at first
assertTrue(portAccepts(proxyPort), "proxy never bound the port after the squatter released it");
@@ -205,7 +206,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "old", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 5000, 5000, 100);
mock(S3Service.class), mock(IamService.class), 5000, 5000, 100);
proxy.start(proxyPort);
proxy.updateMasterPassword("rotated");
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.jboss.logging.Logger;
@@ -47,7 +48,8 @@ class RedshiftInterceptingBridgeTest {
testBackendEnd = backendListener.accept();
s3Stub = Mockito.mock(S3Service.class);
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(bridgeClientEnd, bridgeBackendEnd, s3Stub);
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class));
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
@@ -29,10 +30,13 @@ import static org.mockito.Mockito.when;
class RedshiftProxyManagerTest {
private static final String KEY = "111111111111:c1";
private static final String SECOND_KEY = "111111111111:c2";
private RedshiftProxyManager newManager() {
return new RedshiftProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class),
mock(S3Service.class), testConfig());
mock(S3Service.class), mock(IamService.class), testConfig());
}
private static EmulatorConfig testConfig() {
@@ -57,8 +61,8 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
int port = availablePort();
try {
start(manager, "111111111111:c1", port);
assertTrue(registry(manager).containsKey("111111111111:c1"));
start(manager, KEY, port);
assertTrue(registry(manager).containsKey(KEY));
assertPortUnavailable(port);
} finally {
manager.stopAll();
@@ -69,11 +73,11 @@ class RedshiftProxyManagerTest {
void stopProxyRemovesTheKeyAndReleasesThePort() throws Exception {
RedshiftProxyManager manager = newManager();
int port = availablePort();
start(manager, "k", port);
start(manager, KEY, port);
manager.stopProxy("k");
manager.stopProxy(KEY);
assertFalse(registry(manager).containsKey("k"));
assertFalse(registry(manager).containsKey(KEY));
assertPortAvailable(port);
}
@@ -82,10 +86,10 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
int firstPort = availablePort();
try {
start(manager, "k", firstPort);
start(manager, KEY, firstPort);
int replacementPort = availablePort();
start(manager, "k", replacementPort);
start(manager, KEY, replacementPort);
assertPortAvailable(firstPort);
assertPortUnavailable(replacementPort);
@@ -106,9 +110,9 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
int port = availablePort();
try {
start(manager, "k", port);
manager.updateMasterPassword("k", "rotated");
assertEquals("rotated", masterPassword(registry(manager).get("k")));
start(manager, KEY, port);
manager.updateMasterPassword(KEY, "rotated");
assertEquals("rotated", masterPassword(registry(manager).get(KEY)));
} finally {
manager.stopAll();
}
@@ -118,9 +122,9 @@ class RedshiftProxyManagerTest {
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
RedshiftProxyManager manager = newManager();
int a = availablePort();
start(manager, "a", a);
start(manager, KEY, a);
int b = availablePort();
start(manager, "b", b);
start(manager, SECOND_KEY, b);
manager.stopAll();
@@ -134,8 +138,8 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
try (ServerSocket occupied = new ServerSocket(0)) {
assertThrows(RuntimeException.class,
() -> start(manager, "k", occupied.getLocalPort()));
assertFalse(registry(manager).containsKey("k"));
() -> start(manager, KEY, occupied.getLocalPort()));
assertFalse(registry(manager).containsKey(KEY));
} finally {
manager.stopAll();
}
@@ -146,12 +150,12 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy badProxy = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(badProxy).stop();
registry(manager).put("k", badProxy);
registry(manager).put(KEY, badProxy);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertThrows(RuntimeException.class, () -> manager.stopProxy(KEY));
// Proxy stays registered so a later cleanup attempt can still reach it and retry.
assertSame(badProxy, registry(manager).get("k"));
assertSame(badProxy, registry(manager).get(KEY));
}
@Test
@@ -159,12 +163,12 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy proxy = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).doNothing().when(proxy).stop();
registry(manager).put("k", proxy);
registry(manager).put(KEY, proxy);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertDoesNotThrow(() -> manager.stopProxy("k"));
assertThrows(RuntimeException.class, () -> manager.stopProxy(KEY));
assertDoesNotThrow(() -> manager.stopProxy(KEY));
assertFalse(registry(manager).containsKey("k"));
assertFalse(registry(manager).containsKey(KEY));
verify(proxy, times(2)).stop();
}
@@ -173,12 +177,12 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy stuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stuck).stop();
unclosable(manager).put("k", stuck);
unclosable(manager).put(KEY, stuck);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertThrows(RuntimeException.class, () -> manager.stopProxy(KEY));
// Reference retained so the next attempt can retry the close.
assertSame(stuck, unclosable(manager).get("k"));
assertSame(stuck, unclosable(manager).get(KEY));
}
@Test
@@ -186,13 +190,13 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy stuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stuck).stop();
unclosable(manager).put("k", stuck);
unclosable(manager).put(KEY, stuck);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertThrows(RuntimeException.class, () -> manager.stopProxy(KEY));
assertThrows(RuntimeException.class, () -> manager.stopProxy(KEY));
verify(stuck, times(2)).stop();
assertTrue(unclosable(manager).containsKey("k"));
assertTrue(unclosable(manager).containsKey(KEY));
}
@Test
@@ -200,12 +204,12 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy recovering = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).doNothing().when(recovering).stop();
unclosable(manager).put("k", recovering);
unclosable(manager).put(KEY, recovering);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertDoesNotThrow(() -> manager.stopProxy("k"));
assertThrows(RuntimeException.class, () -> manager.stopProxy(KEY));
assertDoesNotThrow(() -> manager.stopProxy(KEY));
assertFalse(unclosable(manager).containsKey("k"));
assertFalse(unclosable(manager).containsKey(KEY));
}
@Test
@@ -213,12 +217,12 @@ class RedshiftProxyManagerTest {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy stuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stuck).stop();
unclosable(manager).put("k", stuck);
unclosable(manager).put(KEY, stuck);
int port = availablePort();
try {
// A fresh start for the same key must not silently drop the leaked listener.
start(manager, "k", port);
assertSame(stuck, unclosable(manager).get("k"));
start(manager, KEY, port);
assertSame(stuck, unclosable(manager).get(KEY));
} finally {
manager.stopAll();
}
@@ -230,13 +234,13 @@ class RedshiftProxyManagerTest {
RedshiftAuthProxy recovered = mock(RedshiftAuthProxy.class);
RedshiftAuthProxy stillStuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stillStuck).stop();
unclosable(manager).put("a", recovered);
unclosable(manager).put("b", stillStuck);
unclosable(manager).put(KEY, recovered);
unclosable(manager).put(SECOND_KEY, stillStuck);
manager.stopAll();
assertFalse(unclosable(manager).containsKey("a"));
assertTrue(unclosable(manager).containsKey("b"));
assertFalse(unclosable(manager).containsKey(KEY));
assertTrue(unclosable(manager).containsKey(SECOND_KEY));
}
// --- reflection + port helpers copied from RdsProxyManagerTest ---
@@ -1,6 +1,8 @@
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.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.AfterEach;
@@ -35,6 +37,10 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class S3CopySimulatorTest {
@@ -140,7 +146,7 @@ class S3CopySimulatorTest {
private CopyStatementParser.S3Unload unloadSpec(String bucket, String prefix,
boolean gzip, boolean manifest, boolean allowOverwrite, boolean parallel, long maxFileSize) {
return new CopyStatementParser.S3Unload("select a,b from t", bucket, prefix,
"|", false, gzip, false, false, null, manifest, allowOverwrite, parallel, maxFileSize);
"|", false, gzip, false, false, null, manifest, allowOverwrite, parallel, maxFileSize, null);
}
@Test
@@ -154,9 +160,9 @@ class S3CopySimulatorTest {
new S3Object("b", "prefix/a", new byte[0], "text/plain")),
List.of(), false, null));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "prefix/", null, 0, false, true, null);
"t", List.of(), "b", "prefix/", null, 0, false, true, null, null);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3, null);
assertEquals(List.of("prefix/a", "prefix/z"), input.keys());
assertEquals("COPY t FROM STDIN WITH (FORMAT csv, DELIMITER ',')",
@@ -166,16 +172,140 @@ class S3CopySimulatorTest {
@Test
void preparedCopyReportsMissingObject() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "missing", "|", 0, false, false, null);
"t", List.of(), "b", "missing", "|", 0, false, false, null, null);
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(spec, s3));
() -> S3CopySimulator.prepareCopy(spec, s3, null));
assertEquals("XX000", error.sqlState());
assertEquals("S3 object s3://b/missing not found", error.getMessage());
}
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/CopyRole";
@Test
void prepareCopyWithMalformedIamRoleArnFailsBeforeTouchingS3() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, "not-an-arn");
IamService iamService = mock(IamService.class);
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(spec, s3, iamService));
assertEquals("42501", error.sqlState());
verifyNoInteractions(s3);
}
@Test
void prepareCopyWithUnknownRoleFailsBeforeTouchingS3() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, ROLE_ARN);
IamService iamService = mock(IamService.class);
when(iamService.findRole(any(), any())).thenReturn(java.util.Optional.empty());
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(spec, s3, iamService));
assertEquals("42501", error.sqlState());
verifyNoInteractions(s3);
}
@Test
void prepareCopyRejectsCrossAccountRole() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, ROLE_ARN);
IamService iamService = mock(IamService.class);
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(spec, s3, iamService, "111111111111"));
assertEquals("42501", error.sqlState());
assertTrue(error.getMessage().contains("cross-account"));
verifyNoInteractions(s3);
verifyNoInteractions(iamService);
}
@Test
void prepareCopyRejectsRoleNotAssociatedWithCluster() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, ROLE_ARN);
IamService iamService = mock(IamService.class);
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(spec, s3, iamService, "000000000000", List.of()));
assertEquals("42501", error.sqlState());
assertTrue(error.getMessage().contains("not associated"));
verifyNoInteractions(s3);
verifyNoInteractions(iamService);
}
@Test
void prepareCopyRejectsRoleWithoutRedshiftTrust() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, ROLE_ARN);
IamService iamService = mock(IamService.class);
IamRole role = mock(IamRole.class);
when(iamService.findRole("000000000000", "CopyRole"))
.thenReturn(java.util.Optional.of(role));
when(role.getAssumeRolePolicyDocument()).thenReturn(""
+ "{\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},"
+ "\"Action\":\"sts:AssumeRole\"}]}" );
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(spec, s3, iamService, "000000000000"));
assertEquals("42501", error.sqlState());
assertTrue(error.getMessage().contains("trust policy"));
verifyNoInteractions(s3);
}
@Test
void prepareCopyWithValidRoleCallsSignedAuthorization() {
when(s3.objectExists("b", "k")).thenReturn(true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, ROLE_ARN);
IamService iamService = mock(IamService.class);
when(iamService.findRole(any(), any()))
.thenReturn(java.util.Optional.of(mock(io.github.hectorvent.floci.services.iam.model.IamRole.class)));
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3, iamService);
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
verify(s3, never()).authorizeAnonymousListBucket(any());
verify(s3).authorizeSignedListBucket(any(), any(), eq("b"));
verify(s3).authorizeSignedGetObject(any(), any(), eq("b"), eq("k"));
verify(iamService).registerSessionForAccount(
eq("000000000000"), any(), any(), any(), eq(ROLE_ARN), any(), isNull());
verify(iamService, never()).unregisterSession(any(), any());
}
@Test
void copyStreamingUsesRoleSessionForObjectAuthorization() throws Exception {
when(s3.objectExists("b", "k")).thenReturn(true);
when(s3.getObject("b", "k"))
.thenReturn(new S3Object("b", "k", "1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, ROLE_ARN);
IamService iamService = mock(IamService.class);
when(iamService.findRole(any(), any()))
.thenReturn(java.util.Optional.of(mock(io.github.hectorvent.floci.services.iam.model.IamRole.class)));
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3, iamService);
S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream());
verify(s3, times(2))
.authorizeSignedGetObject(any(), any(), eq("b"), eq("k"));
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
}
@Test
void unloadCollectorWritesOneEmptyObjectForZeroRows() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
@@ -185,7 +315,7 @@ class S3CopySimulatorTest {
});
CopyStatementParser.S3Unload spec = unloadSpec("b", "out/", false, false, true, false, 0);
try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload(spec, s3)) {
try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload(spec, s3, null)) {
collector.complete();
}
@@ -208,7 +338,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n", "2|bob\n"));
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
@@ -236,10 +366,10 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = new CopyStatementParser.S3Unload(
"select a,b from t", "wh", "out/", "|", true, false, true, false, null,
false, false, true, 0);
false, false, true, 0, null);
// The fake backend stands in for PostgreSQL: the first CopyData frame is the header row.
Thread backend = backendThread(() -> playUnloadBackend("h1|h2\n", "1|a\n", "2|b\n", "3|c\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertEquals(3, written.size(), written.keySet().toString());
@@ -267,7 +397,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n", "2|bob\n", "3|carol\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/0000_part_00"));
@@ -295,7 +425,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, false, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/000"), written.keySet().toString());
@@ -313,7 +443,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", true, false, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n", "2|b\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/0000_part_00.gz"), written.keySet().toString());
@@ -340,7 +470,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, true, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n", "2|bob\n", "3|carol\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
String manifest = new String(written.get("out/manifest"), StandardCharsets.UTF_8);
@@ -360,7 +490,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
// No backend thread: the select must never run.
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -386,7 +516,7 @@ class S3CopySimulatorTest {
out.flush();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -423,7 +553,7 @@ class S3CopySimulatorTest {
}
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -458,7 +588,7 @@ class S3CopySimulatorTest {
out.flush();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'T');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'T');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -503,7 +633,7 @@ class S3CopySimulatorTest {
out.flush();
});
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
@@ -527,7 +657,7 @@ class S3CopySimulatorTest {
S3CopySimulator.UNLOAD_HEAP_MIB.acquire(192);
try {
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -547,7 +677,7 @@ class S3CopySimulatorTest {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = new CopyStatementParser.S3Unload(
"select a from t", "wh", "out/", "\t", true, false, false, true, "\\N", false, true, true, 0);
"select a from t", "wh", "out/", "\t", true, false, false, true, "\\N", false, true, true, 0, null);
AtomicReference<String> seenSql = new AtomicReference<>();
Thread backend = backendThread(() -> {
@@ -565,7 +695,7 @@ class S3CopySimulatorTest {
out.flush();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
String sql = seenSql.get();
@@ -602,7 +732,7 @@ class S3CopySimulatorTest {
out.flush();
});
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
@@ -617,7 +747,7 @@ class S3CopySimulatorTest {
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -648,7 +778,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, true, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertEquals(1, deleted.size());
@@ -680,7 +810,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, true, true, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n", "2|b\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
// Under ALLOWOVERWRITE a written key may have replaced pre-existing (or another
@@ -701,7 +831,7 @@ class S3CopySimulatorTest {
.when(s3).authorizeAnonymousListBucket(eq("wh"));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -741,7 +871,7 @@ class S3CopySimulatorTest {
testBackend.close();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertEquals(1, deleted.size());
@@ -809,12 +939,12 @@ class S3CopySimulatorTest {
new S3Object("wh", "d/a.txt", "1|alice\n2|bob\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"people", List.of(), "wh", "d/a.txt", "|", 0, false, false, null);
"people", List.of(), "wh", "d/a.txt", "|", 0, false, false, null, null);
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
Thread backend = backendThread(() -> playHappyBackend(copyData));
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
@@ -830,12 +960,12 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "x\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of("a", "b"), "wh", "k", "|", 0, false, false, null);
"t", List.of("a", "b"), "wh", "k", "|", 0, false, false, null, null);
AtomicReference<String> fabricated = new AtomicReference<>();
Thread backend = backendThread(() -> fabricated.set(captureFabricatedThenComplete()));
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
String sql = fabricated.get();
@@ -851,12 +981,12 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "x\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of("a", "b"), "wh", "k", null, 0, false, true, null);
"t", List.of("a", "b"), "wh", "k", null, 0, false, true, null, null);
AtomicReference<String> fabricated = new AtomicReference<>();
Thread backend = backendThread(() -> fabricated.set(captureFabricatedThenComplete()));
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
String sql = fabricated.get();
@@ -871,12 +1001,12 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "x\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, "\\N");
"t", List.of(), "wh", "k", "|", 0, false, false, "\\N", null);
AtomicReference<String> fabricated = new AtomicReference<>();
Thread backend = backendThread(() -> fabricated.set(captureFabricatedThenComplete()));
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
String sql = fabricated.get();
@@ -898,11 +1028,11 @@ class S3CopySimulatorTest {
new S3Object("wh", "p/2", "2|b\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "p/", "|", 1, false, false, null);
"t", List.of(), "wh", "p/", "|", 1, false, false, null, null);
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
Thread backend = backendThread(() -> playHappyBackend(copyData));
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertEquals("1|a\n2|b\n", copyData.toString(StandardCharsets.US_ASCII));
@@ -914,11 +1044,11 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "k.gz")).thenReturn(
new S3Object("wh", "k.gz", gzip("1|a\n2|b\n"), "application/gzip"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k.gz", "|", 0, true, false, null);
"t", List.of(), "wh", "k.gz", "|", 0, true, false, null, null);
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
Thread backend = backendThread(() -> playHappyBackend(copyData));
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertEquals("1|a\n2|b\n", copyData.toString(StandardCharsets.US_ASCII));
@@ -929,9 +1059,9 @@ class S3CopySimulatorTest {
doThrow(new AwsException("AccessDenied", "no", 403))
.when(s3).authorizeAnonymousListBucket("wh");
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null);
"t", List.of(), "wh", "k", "|", 0, false, false, null, null);
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -947,9 +1077,9 @@ class S3CopySimulatorTest {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
"t", List.of(), "wh", "missing", "|", 0, false, false, null, null);
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -965,7 +1095,7 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "1\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"nosuch", List.of(), "wh", "k", "|", 0, false, false, null);
"nosuch", List.of(), "wh", "k", "|", 0, false, false, null, null);
Thread backend = backendThread(() -> {
new PostgresWireDecoder(testBackend.getInputStream()).nextMessage();
@@ -978,7 +1108,7 @@ class S3CopySimulatorTest {
out.flush();
});
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
@@ -992,7 +1122,7 @@ class S3CopySimulatorTest {
when(s3.objectExists("wh", "k")).thenReturn(true);
when(s3.getObject("wh", "k")).thenThrow(new AwsException("InternalError", "boom", 500));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null);
"t", List.of(), "wh", "k", "|", 0, false, false, null, null);
Thread backend = backendThread(() -> {
OutputStream out = testBackend.getOutputStream();
@@ -1014,7 +1144,7 @@ class S3CopySimulatorTest {
out.flush();
});
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -1031,14 +1161,14 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "1\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null);
"t", List.of(), "wh", "k", "|", 0, false, false, null, null);
Thread backend = backendThread(() -> {
new PostgresWireDecoder(testBackend.getInputStream()).nextMessage();
testBackend.close();
});
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
@@ -1053,7 +1183,7 @@ class S3CopySimulatorTest {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
"t", List.of(), "wh", "missing", "|", 0, false, false, null, null);
Thread backend = backendThread(() -> {
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
@@ -1069,7 +1199,7 @@ class S3CopySimulatorTest {
out.flush();
});
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'T');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'T');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
@@ -1097,11 +1227,11 @@ class S3CopySimulatorTest {
new S3Object("wh", "multi/2", "2|b\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "multi/", "|", 0, false, false, null);
"t", List.of(), "wh", "multi/", "|", 0, false, false, null, null);
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
Thread backend = backendThread(() -> playHappyBackend(copyData));
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertEquals("1|a\n2|b\n", copyData.toString(StandardCharsets.US_ASCII));
@@ -1113,7 +1243,7 @@ class S3CopySimulatorTest {
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "1\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null);
"t", List.of(), "wh", "k", "|", 0, false, false, null, null);
simBackend.setSoTimeout(100);
@@ -1126,7 +1256,7 @@ class S3CopySimulatorTest {
}
});
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
@@ -1143,7 +1273,7 @@ class S3CopySimulatorTest {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
"t", List.of(), "wh", "missing", "|", 0, false, false, null, null);
// Backend closes socket when abort query arrives, simulating dropped connection
Thread backend = backendThread(() -> {
@@ -1154,7 +1284,7 @@ class S3CopySimulatorTest {
testBackend.close();
});
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'T');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'T');
joinBackend(backend);
assertTrue(simBackend.isClosed(), "simBackend must be closed upon synchronization failure");
@@ -1172,7 +1302,7 @@ class S3CopySimulatorTest {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
"t", List.of(), "wh", "missing", "|", 0, false, false, null, null);
// Fake backend returns ReadyForQuery with 'T' (e.g. abort query unexpectedly succeeded)
Thread backend = backendThread(() -> {
@@ -1185,7 +1315,7 @@ class S3CopySimulatorTest {
out.flush();
});
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'T');
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'T');
joinBackend(backend);
assertTrue(simBackend.isClosed(), "simBackend must be closed when abort returns non-E status");
@@ -1222,5 +1222,25 @@ class S3ServiceTest {
s3Service.createBucket("anon-del-bucket", "us-east-1");
assertDoesNotThrow(() -> s3Service.authorizeAnonymousDeleteObject("anon-del-bucket", "some/key"));
}
@Test
void authorizeSignedGetObjectIsANoOpWhenEnforceAuthIsOff() {
assertDoesNotThrow(() -> s3Service.authorizeSignedGetObject("ASIAFAKEKEY00000001", "sessiontoken", "signed-get-bucket", "some/key"));
}
@Test
void authorizeSignedPutObjectIsANoOpWhenEnforceAuthIsOff() {
assertDoesNotThrow(() -> s3Service.authorizeSignedPutObject("ASIAFAKEKEY00000001", "sessiontoken", "signed-put-bucket", "some/key"));
}
@Test
void authorizeSignedListBucketIsANoOpWhenEnforceAuthIsOff() {
assertDoesNotThrow(() -> s3Service.authorizeSignedListBucket("ASIAFAKEKEY00000001", "sessiontoken", "signed-list-bucket"));
}
@Test
void authorizeSignedDeleteObjectIsANoOpWhenEnforceAuthIsOff() {
assertDoesNotThrow(() -> s3Service.authorizeSignedDeleteObject("ASIAFAKEKEY00000001", "sessiontoken", "signed-del-bucket", "some/key"));
}
}