feat(redshift): support more COPY and UNLOAD options (#5204)

* feat(redshift): support more COPY and UNLOAD options

COPY now accepts REGION, CREDENTIALS, key-based credentials, EMPTYASNULL,
BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS and TRUNCATECOLUMNS. UNLOAD now
accepts REGION, CREDENTIALS, key-based credentials and EXTENSION. Field
content options run in a new CopyRecordTransformer; TRUNCATECOLUMNS reads
column lengths from the catalog and so needs the Simple Query protocol.
Clauses that cannot be honoured still fail open to PostgreSQL.

* feat(redshift): support UNLOAD ESCAPE, CLEANPATH and server-side encryption options

UNLOAD now accepts ESCAPE (text framing only), CLEANPATH, ENCRYPTED AUTO and
ENCRYPTED with KMS_KEY_ID, which is stored as aws:kms server-side encryption
on the data and manifest objects. CLEANPATH lists and authorizes every delete
up front but removes the objects only when the first output arrives, so a
query that PostgreSQL rejects keeps the previous export. An empty prefix,
ALLOWOVERWRITE and client-side encryption still fail open to PostgreSQL.

* fix(redshift): address review findings on COPY and UNLOAD options

- Reject blank access key, secret, session token and IAM role so an empty
  pair cannot enable unsigned S3 access.
- CLEANPATH lists and authorizes the prefix again when the first output
  arrives, so an object uploaded since preparation does not survive.
- REMOVEQUOTES no longer closes a text-mode field on an escaped quote.
- TRUNCATECOLUMNS counts characters, as PostgreSQL does for varchar(n),
  and cuts decoded text so escape sequences are never split.
- Bound the heap used by field-level COPY options with a per-object size
  limit and a budget shared across connections.

* fix(redshift): delete the CLEANPATH prefix under one bucket lock

S3Service.deleteObjectsWithPrefix lists the prefix, authorizes every key
and deletes them while holding the bucket monitor that PutObject and
DeleteObject already use, so an upload cannot land between the listing
and the deletes and survive next to the new export.

* fix(redshift): measure TRUNCATECOLUMNS in bytes and tighten review follow-ups

Redshift counts CHAR(n) and VARCHAR(n) in bytes, so TRUNCATECOLUMNS now
measures decoded bytes and cuts on a character boundary instead of
counting characters. The UNLOAD docs described bare ENCRYPTED as
client-side; client-side is the MASTER_SYMMETRIC_KEY form. The
concurrent-put lock test now waits for the put thread to be BLOCKED
instead of a fixed 300 ms timeout.

* style(redshift): fix import order in S3CopySimulatorTest
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-08 23:19:40 -04:00
1 parent 52985a2f19
commit 38ce99ba54
10 files changed
+1889 -66

No files matched your search

@@ -186,6 +186,115 @@ class RedshiftInterceptorIntegrationTest {
}
}
@Test
void copyAcceptsRegionKeyCredentialsAndNullHandlingOptions() throws Exception {
String bucket = "redshift-copy-options";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "people/p1.txt",
"1|alice\n2|\n3| \n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection connection = waitForConnection(sharedCluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE copy_opts_people (id int, name text)");
statement.execute("COPY copy_opts_people FROM 's3://" + bucket + "/people/p1.txt' "
+ "ACCESS_KEY_ID 'test' SECRET_ACCESS_KEY 'test' REGION 'us-east-1' "
+ "EMPTYASNULL BLANKSASNULL");
try (ResultSet rows = statement.executeQuery(
"SELECT count(*) FROM copy_opts_people WHERE name IS NULL")) {
assertTrue(rows.next());
assertEquals(2, rows.getInt(1));
}
}
}
@Test
void copyTruncateColumnsCutsOverlongValuesOverSimpleQuery() throws Exception {
String bucket = "redshift-copy-truncate";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "t.txt",
"1|abcdef\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection connection = waitForConnection(
simpleQueryJdbcUrl(sharedCluster), "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE copy_trunc (id int, name varchar(3))");
statement.execute("COPY copy_trunc FROM 's3://" + bucket + "/t.txt' TRUNCATECOLUMNS");
try (ResultSet rows = statement.executeQuery("SELECT name FROM copy_trunc")) {
assertTrue(rows.next());
assertEquals("abc", rows.getString(1));
}
}
}
@Test
void copyTruncateColumnsOverExtendedQueryExplainsTheSimpleQueryRequirement() throws Exception {
String bucket = "redshift-copy-truncate-ext";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "t.txt",
"1|abcdef\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection connection = waitForConnection(sharedCluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE copy_trunc_ext (id int, name varchar(3))");
SQLException failure = assertThrows(SQLException.class, () -> statement.execute(
"COPY copy_trunc_ext FROM 's3://" + bucket + "/t.txt' TRUNCATECOLUMNS"));
assertTrue(failure.getMessage().contains("preferQueryMode=simple"), failure.getMessage());
}
}
@Test
void unloadAppliesExtensionAndAcceptsRegion() throws Exception {
String bucket = "redshift-unload-extension";
s3.createBucket(bucket, "us-east-1");
try (Connection connection = waitForConnection(sharedCluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("UNLOAD ('select 1') TO 's3://" + bucket + "/ext/' "
+ "REGION 'us-east-1' EXTENSION '.csv' ALLOWOVERWRITE");
}
List<S3Object> objects = s3.listObjects(bucket, "ext/", null, 100);
assertEquals(1, objects.size());
assertEquals("ext/0000_part_00.csv", objects.get(0).getKey());
}
@Test
void unloadCleanPathRemovesOnlyObjectsUnderThePrefix() throws Exception {
String bucket = "redshift-unload-cleanpath";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "clean/old.txt", "old\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
s3.putObject(bucket, "clean2/keep.txt", "keep\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection connection = waitForConnection(sharedCluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("UNLOAD ('select 1') TO 's3://" + bucket + "/clean/' CLEANPATH");
}
List<S3Object> cleaned = s3.listObjects(bucket, "clean/", null, 100);
assertEquals(1, cleaned.size());
assertEquals("clean/0000_part_00", cleaned.get(0).getKey());
assertTrue(s3.objectExists(bucket, "clean2/keep.txt"));
}
@Test
void unloadEscapeEscapesTheDelimiterInData() throws Exception {
String bucket = "redshift-unload-escape";
s3.createBucket(bucket, "us-east-1");
try (Connection connection = waitForConnection(sharedCluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE unload_escape (v text)");
statement.execute("INSERT INTO unload_escape VALUES ('a|b')");
statement.execute("UNLOAD ('select v from unload_escape') TO 's3://" + bucket
+ "/esc/' ESCAPE ALLOWOVERWRITE");
}
List<S3Object> objects = s3.listObjects(bucket, "esc/", null, 100);
assertEquals(1, objects.size());
assertEquals("a\\|b\n", new String(
s3.getObject(bucket, objects.get(0).getKey()).getData(), StandardCharsets.UTF_8));
}
@Test
void namedPreparedCopyAndUnloadCanBeExecutedTwice() throws Exception {
Cluster cluster = sharedCluster;
@@ -0,0 +1,178 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class CopyRecordTransformerTest {
private static CopyStatementParser.CopyTransforms transforms(
boolean blanks, boolean empty, boolean removeQuotes, boolean truncate, Character invalid) {
return new CopyStatementParser.CopyTransforms(blanks, empty, removeQuotes, truncate, invalid);
}
private static String apply(String delimiter, boolean csv, String nullAs,
CopyStatementParser.CopyTransforms transforms, String input) {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", delimiter, 0, false, csv, nullAs, null,
false, false, false, transforms);
byte[] out = new CopyRecordTransformer(spec, null)
.apply(input.getBytes(StandardCharsets.UTF_8));
return new String(out, StandardCharsets.UTF_8);
}
@Test
void emptyAsNullReplacesEmptyTextFields() {
assertEquals("1|\\N|x\n2|b|\\N\n",
apply("|", false, null, transforms(false, true, false, false, null), "1||x\n2|b|\n"));
}
@Test
void blanksAsNullOnlyTouchesWhitespaceFields() {
assertEquals("1|\\N|x\n2||y\n",
apply("|", false, null, transforms(true, false, false, false, null), "1| |x\n2||y\n"));
}
@Test
void customNullStringIsUsedAsMarker() {
assertEquals("1|NULL|x\n",
apply("|", false, "NULL", transforms(false, true, false, false, null), "1||x\n"));
}
@Test
void removeQuotesKeepsDelimiterInsideQuotesAndEscapesItForPostgres() {
assertEquals("1|a\\|b|c\n",
apply("|", false, null, transforms(false, false, true, false, null), "1|\"a|b\"|c\n"));
assertEquals("x\n",
apply("|", false, null, transforms(false, false, true, false, null), "'x'\n"));
}
@Test
void removeQuotesWithoutClosingQuoteFails() {
assertThrows(S3CopySimulator.S3TransferException.class,
() -> apply("|", false, null, transforms(false, false, true, false, null), "1|\"abc\n"));
}
@Test
void csvQuotedEmptyFieldBecomesNullAndQuotedCommaSurvives() {
assertEquals("1,,x\n",
apply(",", true, null, transforms(false, true, false, false, null), "1,\"\",x\n"));
assertEquals("1,\"a,b\",\n",
apply(",", true, null, transforms(true, false, false, false, null), "1,\"a,b\", \n"));
}
@Test
void crlfLineEndingsAreNormalisedAndLastFieldIsNotPolluted() {
assertEquals("a|b\n1|\\N\n",
apply("|", false, null, transforms(false, true, false, false, null), "a|b\r\n1|\r\n"));
}
@Test
void lastRecordWithoutNewlineOrWithTrailingDelimiterIsTerminated() {
assertEquals("1|\\N\n",
apply("|", false, null, transforms(false, true, false, false, null), "1|"));
assertEquals("1|b\n",
apply("|", false, null, transforms(false, true, false, false, null), "1|b"));
}
@Test
void backslashEscapedDelimiterStaysInsideItsField() {
assertEquals("a\\|b|c\n",
apply("|", false, null, transforms(false, true, false, false, null), "a\\|b|c\n"));
}
@Test
void sanitizeUtf8ReplacesEachInvalidByteAndKeepsValidCharacters() {
byte[] input = {'a', (byte) 0xFF, 'b', (byte) 0xC3, (byte) 0x28, (byte) 0xC3, (byte) 0xA9};
assertEquals("a?b?(é",
new String(CopyRecordTransformer.sanitizeUtf8(input, (byte) '?'), StandardCharsets.UTF_8));
}
private static String applyWithLimits(String delimiter, boolean csv, List<Integer> limits, String input) {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", delimiter, 0, false, csv, null, null,
false, false, false, transforms(false, false, false, true, null));
byte[] out = new CopyRecordTransformer(spec, limits).apply(input.getBytes(StandardCharsets.UTF_8));
return new String(out, StandardCharsets.UTF_8);
}
@Test
void truncateColumnsCutsOnlyLimitedColumns() {
assertEquals("1|abc|xyzxyz\n",
applyWithLimits("|", false, Arrays.asList(null, 3, null), "1|abcdef|xyzxyz\n"));
}
@Test
void truncateColumnsNeverSplitsAMultiByteCharacter() {
// The limit counts bytes, so the 2-byte e-acute does not fit twice into 3 bytes.
assertEquals("a\n", applyWithLimits("|", false, List.of(2), "aébc\n"));
assertEquals("é\n", applyWithLimits("|", false, List.of(3), "éééé\n"));
assertEquals("éé\n", applyWithLimits("|", false, List.of(4), "ééé\n"));
}
@Test
void truncateColumnsLeavesAValueThatFitsItsByteLimit() {
assertEquals("éé\n", applyWithLimits("|", false, List.of(4), "éé\n"));
}
@Test
void truncateColumnsKeepsCsvQuoting() {
assertEquals("\"abc\",x\n", applyWithLimits(",", true, Arrays.asList(3, null), "\"abcdef\",x\n"));
}
@Test
void truncateColumnsLeavesTheNullMarkerIntact() {
assertEquals("\\N|x|y\n",
applyWithLimits("|", false, Arrays.asList(1, 10, 10), "\\N|x|y\n"));
}
@Test
void truncateColumnsKeepsAnEscapedBackslashWhole() {
// Decoded value is ab, backslash, c. The 3-byte cut keeps the backslash, re-escaped.
assertEquals("ab\\\\|hello\n",
applyWithLimits("|", false, Arrays.asList(3, null), "ab\\\\c|hello\n"));
}
@Test
void truncateColumnsCountsAnEscapedDelimiterAsOneByte() {
assertEquals("a\\|b|x\n", applyWithLimits("|", false, Arrays.asList(3, null), "a\\|b|x\n"));
}
@Test
void truncateColumnsNeverSplitsAnOctalEscape() {
// Backslash 101, 102 and 103 decode to A, B and C.
assertEquals("AB\n", applyWithLimits("|", false, List.of(2), "\\101\\102\\103\n"));
}
@Test
void removeQuotesDoesNotCloseOnAnEscapedQuoteBeforeTheDelimiter() {
assertEquals("a\\\"\\|b|x\n",
apply("|", false, null, transforms(false, false, true, false, null), "\"a\\\"|b\"|x\n"));
}
@Test
void removeQuotesRecognisesTheClosingQuoteBeforeCrlf() {
assertEquals("a\nb\n",
apply("|", false, null, transforms(false, false, true, false, null), "'a'\r\n'b'\n"));
}
@Test
void csvQuotedLastFieldBeforeCrlfIsAccepted() {
assertEquals("1,\"x\"\n",
apply(",", true, null, transforms(false, true, false, false, null), "1,\"x\"\r\n"));
}
@Test
void acceptInvalidCharsAloneDoesNotNeedFieldParsing() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", "|", 0, false, false, null, null, false, false, false,
transforms(false, false, false, false, '#'));
byte[] out = new CopyRecordTransformer(spec, null).apply(new byte[]{'a', (byte) 0xFF, '\n'});
assertEquals("a#\n", new String(out, StandardCharsets.UTF_8));
}
}
@@ -307,8 +307,8 @@ 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/' 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/' MASTER_SYMMETRIC_KEY 'k'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' KMS_KEY_ID 'k'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' ZSTD"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' PARTITION BY (dt)"));
}
@@ -327,6 +327,185 @@ class CopyStatementParserTest {
assertEquals("csv", u.nullAs());
}
@Test
void copyAcceptsAndIgnoresRegion() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' REGION 'eu-west-1'");
assertNotNull(c);
assertNull(c.iamRoleArn());
}
@Test
void copyMapsCredentialsIamRoleToIamRoleArn() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' CREDENTIALS 'aws_iam_role=arn:aws:iam::000000000000:role/r'");
assertEquals("arn:aws:iam::000000000000:role/r", c.iamRoleArn());
}
@Test
void copyAcceptsKeyCredentialsWithoutRole() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' ACCESS_KEY_ID 'test' SECRET_ACCESS_KEY 'test' SESSION_TOKEN 'test'");
assertNotNull(c);
assertNull(c.iamRoleArn());
}
@Test
void copyAcceptsKeyCredentialsInsideCredentialsString() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' CREDENTIALS 'aws_access_key_id=test;aws_secret_access_key=test'");
assertNotNull(c);
assertNull(c.iamRoleArn());
}
@Test
void copyRejectsConflictingOrIncompleteAuthorization() {
assertNull(CopyStatementParser.parse(
"COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::000000000000:role/r' "
+ "CREDENTIALS 'aws_iam_role=arn:aws:iam::000000000000:role/r2'"));
assertNull(CopyStatementParser.parse(
"COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::000000000000:role/r' "
+ "ACCESS_KEY_ID 'test' SECRET_ACCESS_KEY 'test'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ACCESS_KEY_ID 'test'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ACCESS_KEY_ID '' SECRET_ACCESS_KEY ''"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ACCESS_KEY_ID 'test' SECRET_ACCESS_KEY ' '"));
assertNull(CopyStatementParser.parse(
"COPY t FROM 's3://b/k' ACCESS_KEY_ID 'test' SECRET_ACCESS_KEY 'test' SESSION_TOKEN ''"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' IAM_ROLE ''"));
assertNull(CopyStatementParser.parse(
"UNLOAD ('select 1') TO 's3://b/out/' ACCESS_KEY_ID '' SECRET_ACCESS_KEY ''"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' SESSION_TOKEN 'test'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' REGION 'a' REGION 'b'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' CREDENTIALS 'aws_access_key_id=test'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' CREDENTIALS 'something_else=1'"));
}
@Test
void copyStillRejectsEncryptionClauses() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ENCRYPTED"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MASTER_SYMMETRIC_KEY 'k'"));
}
@Test
void unloadAcceptsRegionAndCredentials() {
CopyStatementParser.S3Unload u = unload(
"UNLOAD ('select 1') TO 's3://b/out/' REGION 'us-east-1' "
+ "CREDENTIALS 'aws_iam_role=arn:aws:iam::000000000000:role/r'");
assertEquals("arn:aws:iam::000000000000:role/r", u.iamRoleArn());
assertNotNull(unload("UNLOAD ('select 1') TO 's3://b/out/' ACCESS_KEY_ID 'test' SECRET_ACCESS_KEY 'test'"));
}
@Test
void unloadParsesExtensionVerbatim() {
CopyStatementParser.S3Unload u = unload(
"UNLOAD ('select 1') TO 's3://b/out/' EXTENSION '.csv'");
assertEquals(".csv", u.extension());
assertNull(unload("UNLOAD ('select 1') TO 's3://b/out/'").extension());
}
@Test
void unloadRejectsUnsafeOrRepeatedExtension() {
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' EXTENSION ''"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' EXTENSION 'a/b'"));
assertNull(CopyStatementParser.parse(
"UNLOAD ('select 1') TO 's3://b/out/' EXTENSION '.a' EXTENSION '.b'"));
}
@Test
void copyParsesFieldContentOptions() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' EMPTYASNULL BLANKSASNULL REMOVEQUOTES ACCEPTINVCHARS AS '#'");
assertTrue(c.transforms().emptyAsNull());
assertTrue(c.transforms().blanksAsNull());
assertTrue(c.transforms().removeQuotes());
assertEquals('#', c.transforms().invalidCharReplacement());
}
@Test
void copyParsesTruncateColumns() {
assertTrue(copyFrom("COPY t FROM 's3://b/k' TRUNCATECOLUMNS").transforms().truncateColumns());
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' TRUNCATECOLUMNS TRUNCATECOLUMNS"));
assertNull(CopyStatementParser.parse(
"COPY t FROM 's3://b/k' FORMAT AS JSON 'auto' TRUNCATECOLUMNS"));
}
@Test
void acceptInvCharsDefaultsToQuestionMark() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' ACCEPTINVCHARS");
assertEquals('?', c.transforms().invalidCharReplacement());
assertEquals(CopyStatementParser.CopyTransforms.NONE, copyFrom("COPY t FROM 's3://b/k'").transforms());
}
@Test
void acceptInvCharsReplacementCannotBeFramingSyntax() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ACCEPTINVCHARS AS '|'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ACCEPTINVCHARS AS '\\'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' CSV ACCEPTINVCHARS AS '\"'"));
assertNotNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ACCEPTINVCHARS AS '#'"));
}
@Test
void copyRejectsInvalidTransformCombinations() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' CSV REMOVEQUOTES"));
assertNull(CopyStatementParser.parse(
"COPY t FROM 's3://b/k' FORMAT AS JSON 'auto' EMPTYASNULL"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DELIMITER 'é' EMPTYASNULL"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' EMPTYASNULL EMPTYASNULL"));
}
@Test
void unloadParsesEscapeOnlyWhenFramingStaysText() {
assertTrue(unload("UNLOAD ('select 1') TO 's3://b/out/' ESCAPE").escape());
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' CSV ESCAPE"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' ADDQUOTES ESCAPE"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' HEADER ESCAPE"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' ESCAPE ESCAPE"));
}
@Test
void unloadParsesCleanPathAndFailsOpenWhenItCouldBeUnsafe() {
assertTrue(unload("UNLOAD ('select 1') TO 's3://b/out/' CLEANPATH").cleanPath());
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' CLEANPATH ALLOWOVERWRITE"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/' CLEANPATH"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' CLEANPATH CLEANPATH"));
}
@Test
void unloadParsesServerSideEncryptionOptions() {
CopyStatementParser.S3Unload kms = unload(
"UNLOAD ('select 1') TO 's3://b/out/' ENCRYPTED KMS_KEY_ID 'key-1'");
assertTrue(kms.encrypted());
assertEquals("key-1", kms.sseKmsKeyId());
CopyStatementParser.S3Unload reversed = unload(
"UNLOAD ('select 1') TO 's3://b/out/' KMS_KEY_ID 'key-2' ENCRYPTED");
assertEquals("key-2", reversed.sseKmsKeyId());
CopyStatementParser.S3Unload auto = unload("UNLOAD ('select 1') TO 's3://b/out/' ENCRYPTED AUTO");
assertTrue(auto.encrypted());
assertNull(auto.sseKmsKeyId());
assertFalse(unload("UNLOAD ('select 1') TO 's3://b/out/'").encrypted());
}
@Test
void unloadEncryptionFailsOpenWhenItWouldNeedClientSideKeys() {
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' ENCRYPTED"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' KMS_KEY_ID 'k'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' ENCRYPTED KMS_KEY_ID ' '"));
assertNull(CopyStatementParser.parse(
"UNLOAD ('select 1') TO 's3://b/out/' ENCRYPTED AUTO KMS_KEY_ID 'k'"));
assertNull(CopyStatementParser.parse(
"UNLOAD ('select 1') TO 's3://b/out/' ENCRYPTED MASTER_SYMMETRIC_KEY 'k'"));
}
@Test
void unloadRejectsConflictingAuthorization() {
assertNull(CopyStatementParser.parse(
"UNLOAD ('select 1') TO 's3://b/out/' IAM_ROLE 'arn:aws:iam::000000000000:role/r' "
+ "ACCESS_KEY_ID 'test' SECRET_ACCESS_KEY 'test'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/out/' REGION 'a' REGION 'b'"));
}
@Test
void parseCopy_jsonAuto_explicitColumns() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY users (id, name) FROM 's3://mybucket/users.json' "
@@ -4,10 +4,13 @@ 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.PutObjectOptions;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -18,11 +21,13 @@ import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
@@ -36,7 +41,9 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -326,6 +333,152 @@ class S3CopySimulatorTest {
S3CopySimulator.unloadBackendSql(spec));
}
private CopyStatementParser.S3Unload unloadSpecWithExtension(boolean gzip, boolean manifest, String extension) {
return new CopyStatementParser.S3Unload("select a,b from t", "wh", "out/",
"|", false, gzip, false, false, null, manifest, true, true, 0, null, extension);
}
private CopyStatementParser.S3Unload unloadSpecWithOptions(
boolean manifest, boolean cleanPath, boolean encrypted, String kmsKeyId) {
return new CopyStatementParser.S3Unload("select a,b from t", "wh", "out/", "|", false, false, false,
false, null, manifest, false, true, 0, null, null, false, cleanPath, encrypted, kmsKeyId);
}
@Test
void cleanPathDeletesOnlyObjectsUnderThePrefixBeforeWriting() throws Exception {
S3Object old1 = new S3Object("wh", "out/old1", new byte[0], "text/plain");
S3Object old2 = new S3Object("wh", "out/old2", new byte[0], "text/plain");
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(old1, old2), List.of(), false, null));
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n"));
S3CopySimulator.runUnload(simClient, simBackend, unloadSpecWithOptions(false, true, false, null),
s3, null, 'I');
joinBackend(backend);
verify(s3).deleteObjectsWithPrefix(eq("wh"), eq("out/"), any());
assertTrue(written.containsKey("out/0000_part_00"), written.keySet().toString());
}
@Test
void cleanPathDeletesNothingUntilOutputArrivesAndDeletesBeforeTheFirstWrite() throws Exception {
S3Object old1 = new S3Object("wh", "out/old1", new byte[0], "text/plain");
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(old1), List.of(), false, null));
try (S3CopySimulator.UnloadCollector collector =
S3CopySimulator.prepareUnload(unloadSpecWithOptions(false, true, false, null), s3, null)) {
verify(s3, never()).deleteObjectsWithPrefix(any(), any(), any());
collector.complete();
}
InOrder order = inOrder(s3);
order.verify(s3).deleteObjectsWithPrefix(eq("wh"), eq("out/"), any());
order.verify(s3).putObject(eq("wh"), eq("out/0000_part_00"), any(), any(), any());
}
@Test
void cleanPathAuthorizesEachDeleteThroughTheCallbackItHandsToS3() throws Exception {
doAnswer(inv -> {
Consumer<String> authorize = inv.getArgument(2);
authorize.accept("out/late");
return 1;
}).when(s3).deleteObjectsWithPrefix(eq("wh"), eq("out/"), any());
try (S3CopySimulator.UnloadCollector collector =
S3CopySimulator.prepareUnload(unloadSpecWithOptions(false, true, false, null), s3, null)) {
collector.complete();
}
verify(s3).authorizeAnonymousDeleteObject("wh", "out/late");
}
@Test
void cleanPathKeepsObjectsWhenTheQueryNeverProducesOutput() throws Exception {
S3Object old1 = new S3Object("wh", "out/old1", new byte[0], "text/plain");
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(old1), List.of(), false, null));
// Closed without complete(): the backend rejected the query, e.g. an unknown column.
try (S3CopySimulator.UnloadCollector collector =
S3CopySimulator.prepareUnload(unloadSpecWithOptions(false, true, false, null), s3, null)) {
assertNotNull(collector);
}
verify(s3, never()).deleteObjectsWithPrefix(any(), any(), any());
}
@Test
void cleanPathDeniedDeleteFailsBeforeAnythingIsWritten() {
S3Object old1 = new S3Object("wh", "out/old1", new byte[0], "text/plain");
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(old1), List.of(), false, null));
doThrow(new AwsException("AccessDenied", "denied", 403))
.when(s3).authorizeAnonymousDeleteObject("wh", "out/old1");
assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareUnload(unloadSpecWithOptions(false, true, false, null), s3, null));
verify(s3, never()).deleteObjectsWithPrefix(any(), any(), any());
verify(s3, never()).putObject(any(), any(), any(), any(), any());
}
@Test
void kmsKeyIdIsStoredOnDataAndManifestObjects() throws Exception {
ArgumentCaptor<PutObjectOptions> options = ArgumentCaptor.forClass(PutObjectOptions.class);
when(s3.putObject(eq("wh"), any(), any(), any(), any(), options.capture())).thenReturn(null);
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n"));
S3CopySimulator.runUnload(simClient, simBackend, unloadSpecWithOptions(true, false, true, "key-1"),
s3, null, 'I');
joinBackend(backend);
assertEquals(2, options.getAllValues().size());
for (PutObjectOptions captured : options.getAllValues()) {
assertEquals("aws:kms", captured.getServerSideEncryption());
assertEquals("key-1", captured.getSseKmsKeyId());
}
}
@Test
void unloadAppendsExtensionToDataKeys() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n"));
S3CopySimulator.runUnload(simClient, simBackend, unloadSpecWithExtension(false, false, ".csv"),
s3, null, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/0000_part_00.csv"), written.keySet().toString());
}
@Test
void unloadWithExtensionDoesNotAddAGzipSuffixAndListsTheNameInManifest() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n"));
S3CopySimulator.runUnload(simClient, simBackend, unloadSpecWithExtension(true, true, "txt.gz"),
s3, null, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/0000_part_00.txt.gz"), written.keySet().toString());
String manifest = new String(written.get("out/manifest"), StandardCharsets.UTF_8);
assertTrue(manifest.contains("s3://wh/out/0000_part_00.txt.gz"), manifest);
}
@Test
void unloadWritesSingleObjectAndForwardsCommandComplete() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
@@ -1364,6 +1517,107 @@ class S3CopySimulatorTest {
assertEquals('d', rawBytes[0]);
}
private static String copyDataPayload(byte[] frames) {
ByteArrayOutputStream payload = new ByteArrayOutputStream();
int i = 0;
while (i < frames.length) {
int length = ((frames[i + 1] & 0xFF) << 24) | ((frames[i + 2] & 0xFF) << 16)
| ((frames[i + 3] & 0xFF) << 8) | (frames[i + 4] & 0xFF);
payload.write(frames, i + 5, length - 4);
i += 1 + length;
}
return payload.toString(StandardCharsets.UTF_8);
}
@Test
void streamCopyInput_appliesFieldTransforms() throws Exception {
CopyStatementParser.CopyTransforms transforms =
new CopyStatementParser.CopyTransforms(true, true, false, false, null);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"people", List.of(), "wh", "p.txt", "|", 0, false, false, null, null,
false, false, false, transforms);
S3Object dataObj = new S3Object("wh", "p.txt",
"1| \n2||x\n".getBytes(StandardCharsets.UTF_8), "text/plain");
when(s3.getObject("wh", "p.txt")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
assertEquals("1|\\N\n2|\\N|x\n", copyDataPayload(out.toByteArray()));
}
@Test
void streamCopyInput_transformsAfterGzipDecodeAndHeaderSkip() throws Exception {
CopyStatementParser.CopyTransforms transforms =
new CopyStatementParser.CopyTransforms(false, true, false, false, null);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"people", List.of(), "wh", "p.gz", "|", 1, true, false, null, null,
false, false, false, transforms);
ByteArrayOutputStream gz = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(gz)) {
gzip.write("id|name\n1|\n".getBytes(StandardCharsets.UTF_8));
}
when(s3.getObject("wh", "p.gz")).thenReturn(new S3Object("wh", "p.gz", gz.toByteArray(), "application/gzip"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.gz"), s3, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
assertEquals("1|\\N\n", copyDataPayload(out.toByteArray()));
}
@Test
void alignMaxBytes_followsExplicitColumnListAndFoldsUnquotedNames() {
List<S3CopySimulator.ColumnInfo> catalog = List.of(
new S3CopySimulator.ColumnInfo("id", null),
new S3CopySimulator.ColumnInfo("name", 3),
new S3CopySimulator.ColumnInfo("Note", 5));
CopyStatementParser.S3CopyFrom explicit = new CopyStatementParser.S3CopyFrom(
"t", List.of("NAME", "\"Note\""), "wh", "k", "|", 0, false, false, null, null);
assertEquals(Arrays.asList(3, 5), S3CopySimulator.alignMaxBytes(explicit, catalog));
CopyStatementParser.S3CopyFrom all = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null);
assertEquals(Arrays.asList(null, 3, 5), S3CopySimulator.alignMaxBytes(all, catalog));
}
@Test
void streamCopyInput_withTruncateColumnsAndNoCatalogFailsAndNamesSimpleQueryMode() {
CopyStatementParser.CopyTransforms transforms =
new CopyStatementParser.CopyTransforms(false, false, false, true, null);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream()));
assertTrue(failure.getMessage().contains("preferQueryMode=simple"), failure.getMessage());
}
@Test
void streamCopyInput_withFieldTransformOverTheObjectLimitFailsTheStatementAndReleasesTheBudget() {
CopyStatementParser.CopyTransforms transforms =
new CopyStatementParser.CopyTransforms(true, false, false, false, null);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "1||x\n1||x\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
long saved = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES;
int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = 8;
try {
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream()));
assertTrue(failure.getMessage().contains("8-byte limit"), failure.getMessage());
assertEquals(availableBefore, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
} finally {
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = saved;
}
}
@Test
void copyBackendSql_quotesDiscoveredColumnIdentifiers() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
@@ -35,6 +35,10 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
@@ -1634,4 +1638,72 @@ class S3ServiceTest {
void authorizeSignedDeleteObjectIsANoOpWhenEnforceAuthIsOff() {
assertDoesNotThrow(() -> s3Service.authorizeSignedDeleteObject("ASIAFAKEKEY00000001", "sessiontoken", "signed-del-bucket", "some/key"));
}
@Test
void deleteObjectsWithPrefixRemovesOnlyTheMatchingKeys() {
s3Service.createBucket("prefix-del", "us-east-1");
s3Service.putObject("prefix-del", "out/a", new byte[]{1}, "text/plain", Map.of());
s3Service.putObject("prefix-del", "out/b", new byte[]{2}, "text/plain", Map.of());
s3Service.putObject("prefix-del", "keep/c", new byte[]{3}, "text/plain", Map.of());
int deleted = s3Service.deleteObjectsWithPrefix("prefix-del", "out/", key -> { });
assertEquals(2, deleted);
assertFalse(s3Service.objectExists("prefix-del", "out/a"));
assertFalse(s3Service.objectExists("prefix-del", "out/b"));
assertTrue(s3Service.objectExists("prefix-del", "keep/c"));
}
@Test
void deleteObjectsWithPrefixRemovesNothingWhenAnyKeyIsDenied() {
s3Service.createBucket("prefix-deny", "us-east-1");
s3Service.putObject("prefix-deny", "out/a", new byte[]{1}, "text/plain", Map.of());
s3Service.putObject("prefix-deny", "out/b", new byte[]{2}, "text/plain", Map.of());
assertThrows(AwsException.class, () -> s3Service.deleteObjectsWithPrefix("prefix-deny", "out/", key -> {
if (key.equals("out/b")) {
throw new AwsException("AccessDenied", "denied", 403);
}
}));
assertTrue(s3Service.objectExists("prefix-deny", "out/a"));
assertTrue(s3Service.objectExists("prefix-deny", "out/b"));
}
@Test
void deleteObjectsWithPrefixHoldsOffAConcurrentPutUntilItIsDone() throws Exception {
s3Service.createBucket("prefix-lock", "us-east-1");
s3Service.putObject("prefix-lock", "out/old", new byte[]{1}, "text/plain", Map.of());
CountDownLatch authorizing = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
CompletableFuture<Integer> delete = CompletableFuture.supplyAsync(() ->
s3Service.deleteObjectsWithPrefix("prefix-lock", "out/", key -> {
authorizing.countDown();
try {
assertTrue(release.await(10, TimeUnit.SECONDS));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}));
assertTrue(authorizing.await(10, TimeUnit.SECONDS));
FutureTask<S3Object> put = new FutureTask<>(() ->
s3Service.putObject("prefix-lock", "out/late", new byte[]{2}, "text/plain", Map.of()));
Thread putThread = new Thread(put);
putThread.start();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (putThread.getState() != Thread.State.BLOCKED && System.nanoTime() < deadline) {
Thread.onSpinWait();
}
assertEquals(Thread.State.BLOCKED, putThread.getState());
assertFalse(put.isDone());
release.countDown();
assertEquals(1, delete.get(10, TimeUnit.SECONDS));
put.get(10, TimeUnit.SECONDS);
assertFalse(s3Service.objectExists("prefix-lock", "out/old"));
assertTrue(s3Service.objectExists("prefix-lock", "out/late"));
}
}