From 2e707b4b4b0838c10aa78b22e84fb11d09871318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:46:02 +0700 Subject: [PATCH] feat(redshift): enforce UNLOAD access-key credentials (#9713) --- docs/services/redshift.md | 6 +- .../redshift/proxy/CopyEtlLoader.java | 2 +- .../redshift/proxy/CopyStatementParser.java | 32 +++- .../redshift/proxy/S3CopySimulator.java | 163 ++++++++++-------- .../proxy/CopyStatementParserTest.java | 20 +++ .../redshift/proxy/S3CopySimulatorTest.java | 92 ++++++++++ 6 files changed, 239 insertions(+), 76 deletions(-) diff --git a/docs/services/redshift.md b/docs/services/redshift.md index a7e61f1475..baba446021 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -1442,9 +1442,9 @@ the result to S3 as one or more objects under ``. AWS, the compression suffix is added only when no extension is given, so `EXTENSION 'txt.gz' GZIP` gives `0000_part_00.txt.gz`. The value is not validated; an empty value or one containing `/` is not intercepted. AWS does not document whether it inserts the dot itself. -- `REGION` behaves as described for COPY. The key credential clauses (`CREDENTIALS 'aws_access_key_id=...'`, - `ACCESS_KEY_ID`, `SECRET_ACCESS_KEY`, `SESSION_TOKEN`) are accepted but ignored by UNLOAD, which writes - as the role or as an unsigned request. Only COPY reads S3 as the principal those clauses name. +- `REGION` and key credential clauses (`CREDENTIALS 'aws_access_key_id=...'`, `ACCESS_KEY_ID`, + `SECRET_ACCESS_KEY`, `SESSION_TOKEN`) behave as described for COPY: when S3 authorization is enforced, + UNLOAD writes as the principal those keys name. - `ESCAPE` is accepted and relies on PostgreSQL text framing, which already escapes the backslash, newline, carriage return and the delimiter. It is only valid with text framing: combined with `CSV`, `ADDQUOTES` or `HEADER` (which switch the framing to CSV here) the statement is not diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java index f65b054d85..5f33a2804a 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyEtlLoader.java @@ -158,7 +158,7 @@ final class CopyEtlLoader { : S3CopySimulator.prepareCopy(spec, s3, iam, account, roles); try { try { - String keyAccount = S3CopySimulator.keyAccount(spec, s3, iam); + String keyAccount = S3CopySimulator.keyAccount(spec.iamRoleArn(), spec.accessKeys(), s3, iam); String effectiveAccount = keyAccount != null ? keyAccount : account; return RequestScopes.callAsChecked(keyAccount, () -> { if (spec.parquet()) { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java index 746ff85210..2d4c6e1800 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java @@ -285,7 +285,35 @@ public final class CopyStatementParser { boolean encrypted, String sseKmsKeyId, boolean defaultIamRoleRequested, - boolean parquet) implements S3Statement { + boolean parquet, + AccessKeys accessKeys) implements S3Statement { + + public S3Unload( + String selectQuery, + String bucket, + String prefix, + String delimiter, + boolean header, + boolean gzip, + boolean csv, + boolean addQuotes, + String nullAs, + boolean manifest, + boolean allowOverwrite, + boolean parallel, + long maxFileSizeBytes, + String iamRoleArn, + String extension, + boolean escape, + boolean cleanPath, + boolean encrypted, + String sseKmsKeyId, + boolean defaultIamRoleRequested, + boolean parquet) { + this(selectQuery, bucket, prefix, delimiter, header, gzip, csv, addQuotes, nullAs, manifest, + allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension, + escape, cleanPath, encrypted, sseKmsKeyId, defaultIamRoleRequested, parquet, null); + } public S3Unload( String selectQuery, @@ -728,7 +756,7 @@ public final class CopyStatementParser { } return new S3Unload(select, bucket, prefix, delimiter, header, gzip, csv, addQuotes, nullAs, manifest, allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn, extension, - escape, cleanPath, encrypted, kmsKeyId, auth.defaultIamRoleRequested, parquet); + escape, cleanPath, encrypted, kmsKeyId, auth.defaultIamRoleRequested, parquet, auth.accessKeys()); } private static S3CopyFrom parseCopy(String cleaned, String defaultIamRoleArn) { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java index 9d3b891c1c..64471ba0dc 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java @@ -170,8 +170,8 @@ public final class S3CopySimulator { List associatedRoleArns, boolean exactObject, String expectedETag, String versionId) { requireDefaultIamRole(spec); - RedshiftRoleAccess.RoleSession roleSession = resolveCopySession(spec, s3, iamService, clusterAccountId, - associatedRoleArns); + RedshiftRoleAccess.RoleSession roleSession = resolveS3Session(spec.iamRoleArn(), spec.accessKeys(), s3, + iamService, clusterAccountId, associatedRoleArns); try { try { if (spec.manifest()) { @@ -179,7 +179,8 @@ public final class S3CopySimulator { } else if (!exactObject) { if (roleSession != null) { RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), - "s3:ListBucket", copyBucketArn(spec, s3), S3ConditionKeys.listing(spec.keyOrPrefix())); + "s3:ListBucket", s3BucketArn(spec.iamRoleArn(), spec.bucket(), s3), + S3ConditionKeys.listing(spec.keyOrPrefix())); s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), spec.keyOrPrefix()); } else { @@ -219,33 +220,32 @@ public final class S3CopySimulator { } /** - * The session COPY reads S3 as: the role's, or the one the statement's own access keys name. Keys - * are only checked when S3 authorization is on, since with it off every read is allowed and a + * The session a COPY or UNLOAD reaches S3 as: the role's, or the one the statement's own access keys name. + * Keys are only checked when S3 authorization is on, since with it off every request is allowed and a * statement may carry placeholder keys. */ - private static RedshiftRoleAccess.RoleSession resolveCopySession( - CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService, + private static RedshiftRoleAccess.RoleSession resolveS3Session( + String iamRoleArn, CopyStatementParser.AccessKeys accessKeys, S3Service s3, IamService iamService, String clusterAccountId, List associatedRoleArns) { - if (spec.iamRoleArn() != null) { - return RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, - associatedRoleArns); + if (iamRoleArn != null) { + return RedshiftRoleAccess.resolveRoleSession(iamRoleArn, iamService, clusterAccountId, associatedRoleArns); } - if (spec.accessKeys() != null && s3.isAuthEnforced()) { - return RedshiftRoleAccess.resolveKeySession(spec.accessKeys(), iamService); + if (accessKeys != null && s3.isAuthEnforced()) { + return RedshiftRoleAccess.resolveKeySession(accessKeys, iamService); } return null; } /** A role's ARNs live in its partition; an access key has none, so the bucket's own region decides. */ - private static String copyBucketArn(CopyStatementParser.S3CopyFrom spec, S3Service s3) { - if (spec.iamRoleArn() != null) { - return RedshiftRoleAccess.bucketArn(spec.iamRoleArn(), spec.bucket()); + private static String s3BucketArn(String iamRoleArn, String bucket, S3Service s3) { + if (iamRoleArn != null) { + return RedshiftRoleAccess.bucketArn(iamRoleArn, bucket); } - return S3ResourceArns.bucket(s3.bucketPartition(spec.bucket()), spec.bucket()); + return S3ResourceArns.bucket(s3.bucketPartition(bucket), bucket); } - private static String copyObjectArn(CopyStatementParser.S3CopyFrom spec, S3Service s3, String key) { - return copyBucketArn(spec, s3) + "/" + key; + private static String s3ObjectArn(String iamRoleArn, String bucket, S3Service s3, String key) { + return s3BucketArn(iamRoleArn, bucket, s3) + "/" + key; } /** @@ -255,15 +255,16 @@ public final class S3CopySimulator { */ private static T asKeyAccount(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService, Supplier body) { - return RequestScopes.callAs(keyAccount(spec, s3, iamService), body); + return RequestScopes.callAs(keyAccount(spec.iamRoleArn(), spec.accessKeys(), s3, iamService), body); } /** Null when no key is in play, which {@link RequestScopes} reads as "stay in the current account". */ - static String keyAccount(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService) { - if (spec.iamRoleArn() != null || spec.accessKeys() == null || !s3.isAuthEnforced()) { + static String keyAccount(String iamRoleArn, CopyStatementParser.AccessKeys accessKeys, S3Service s3, + IamService iamService) { + if (iamRoleArn != null || accessKeys == null || !s3.isAuthEnforced()) { return null; } - return iamService.findAccountForAccessKeyId(spec.accessKeys().accessKeyId()).orElse(null); + return iamService.findAccountForAccessKeyId(accessKeys.accessKeyId()).orElse(null); } static String copyBackendSql(CopyStatementParser.S3CopyFrom spec) { @@ -297,7 +298,8 @@ public final class S3CopySimulator { List columnMaxBytes, List columnKinds, OutputStream backendOut, RedshiftParquetWriter parquetWriter, String clusterAccountId) throws IOException { - String keyAccount = keyAccount(input.spec(), input.s3(), input.iamService()); + String keyAccount = keyAccount(input.spec().iamRoleArn(), input.spec().accessKeys(), input.s3(), + input.iamService()); String effectiveAccount = keyAccount != null ? keyAccount : clusterAccountId; try { RequestScopes.callAsChecked(keyAccount, () -> { @@ -329,28 +331,37 @@ public final class S3CopySimulator { static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, String clusterAccountId, List associatedRoleArns, RedshiftParquetWriter parquetWriter) { + String keyAccount = keyAccount(spec.iamRoleArn(), spec.accessKeys(), s3, iamService); + return RequestScopes.callAs(keyAccount, () -> prepareUnloadScoped(spec, s3, iamService, clusterAccountId, + associatedRoleArns, parquetWriter, keyAccount)); + } + + private static UnloadCollector prepareUnloadScoped(CopyStatementParser.S3Unload spec, S3Service s3, + IamService iamService, String clusterAccountId, + List associatedRoleArns, + RedshiftParquetWriter parquetWriter, String keyAccount) { requireDefaultIamRole(spec); - RedshiftRoleAccess.RoleSession roleSession = spec.iamRoleArn() != null - ? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, - associatedRoleArns) - : null; + RedshiftRoleAccess.RoleSession roleSession = resolveS3Session(spec.iamRoleArn(), spec.accessKeys(), s3, + iamService, clusterAccountId, associatedRoleArns); String probeKey = unloadDataKey(spec, 0); boolean cleanPath = false; try { if (roleSession != null) { - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", - RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), probeKey)); + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:PutObject", s3ObjectArn(spec.iamRoleArn(), spec.bucket(), s3, probeKey)); s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), probeKey); if (spec.manifest()) { String manifestKey = spec.prefix() + "manifest"; - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", - RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), manifestKey)); + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:PutObject", s3ObjectArn(spec.iamRoleArn(), spec.bucket(), s3, manifestKey)); s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), manifestKey); } if (!spec.allowOverwrite() && !spec.cleanPath()) { - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", - RedshiftRoleAccess.bucketArn(spec.iamRoleArn(), spec.bucket())); - s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket()); + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:ListBucket", s3BucketArn(spec.iamRoleArn(), spec.bucket(), s3), + S3ConditionKeys.listing(spec.prefix())); + s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), + spec.prefix()); if (targetPrefixHasObjects(spec, s3)) { throw new S3TransferException(SQLSTATE_INTERNAL, "S3 prefix s3://" + spec.bucket() + "/" + spec.prefix() @@ -389,7 +400,9 @@ public final class S3CopySimulator { "UNLOAD memory budget exhausted; retry shortly", null); } try { - return new S3UnloadCollector(spec, s3, iamService, roleSession, cleanPath, parquetWriter, clusterAccountId); + String effectiveAccount = keyAccount != null ? keyAccount : clusterAccountId; + return new S3UnloadCollector(spec, s3, iamService, roleSession, cleanPath, parquetWriter, + effectiveAccount, keyAccount); } catch (IOException e) { UNLOAD_HEAP_MIB.release(UNLOAD_INITIAL_MIB); RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService); @@ -609,7 +622,7 @@ public final class S3CopySimulator { RedshiftRoleAccess.RoleSession roleSession, String key) { if (roleSession != null) { RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), - "s3:GetObject", copyObjectArn(spec, s3, key)); + "s3:GetObject", s3ObjectArn(spec.iamRoleArn(), spec.bucket(), s3, key)); s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key); } else { s3.authorizeAnonymousGetObject(spec.bucket(), key); @@ -1309,9 +1322,11 @@ public final class S3CopySimulator { IamService iamService, RedshiftRoleAccess.RoleSession roleSession) { if (roleSession != null) { - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", - RedshiftRoleAccess.bucketArn(spec.iamRoleArn(), spec.bucket())); - s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket()); + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:ListBucket", s3BucketArn(spec.iamRoleArn(), spec.bucket(), s3), + S3ConditionKeys.listing(spec.prefix())); + s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), + spec.prefix()); } else { s3.authorizeAnonymousListBucket(spec.bucket()); } @@ -1321,8 +1336,8 @@ public final class S3CopySimulator { IamService iamService, RedshiftRoleAccess.RoleSession roleSession, String key) { if (roleSession != null) { - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject", - RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key)); + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:DeleteObject", s3ObjectArn(spec.iamRoleArn(), spec.bucket(), s3, key)); s3.authorizeSignedDeleteObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key); } else { @@ -1382,6 +1397,7 @@ public final class S3CopySimulator { private final CopyStatementParser.S3Unload spec; private final RedshiftParquetWriter parquetWriter; private final String accountId; + private final String keyAccount; private List columns = List.of(); private boolean quotedCsv; private final S3Service s3; @@ -1413,10 +1429,11 @@ public final class S3CopySimulator { private S3UnloadCollector(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession, boolean cleanPath, RedshiftParquetWriter parquetWriter, - String accountId) throws IOException { + String accountId, String keyAccount) throws IOException { this.spec = spec; this.parquetWriter = parquetWriter; this.accountId = accountId; + this.keyAccount = keyAccount; this.cleanPathPending = cleanPath; this.s3 = s3; this.iamService = iamService; @@ -1501,19 +1518,21 @@ public final class S3CopySimulator { } if (spec.manifest()) { try { - String key = spec.prefix() + "manifest"; - if (roleSession != null) { - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", - RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key)); - s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), - spec.bucket(), key); - } else { - s3.authorizeAnonymousPutObject(spec.bucket(), key); - } - putUnloadObject(s3, spec, key, - manifestJson(spec.bucket(), writtenKeys, writtenLengths) - .getBytes(StandardCharsets.UTF_8), - "application/json"); + RequestScopes.runAs(keyAccount, () -> { + String key = spec.prefix() + "manifest"; + if (roleSession != null) { + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:PutObject", s3ObjectArn(spec.iamRoleArn(), spec.bucket(), s3, key)); + s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), + spec.bucket(), key); + } else { + s3.authorizeAnonymousPutObject(spec.bucket(), key); + } + putUnloadObject(s3, spec, key, + manifestJson(spec.bucket(), writtenKeys, writtenLengths) + .getBytes(StandardCharsets.UTF_8), + "application/json"); + }); } catch (RuntimeException e) { fail(SQLSTATE_INTERNAL, "UNLOAD manifest write failed", e); } @@ -1528,7 +1547,7 @@ public final class S3CopySimulator { } closeAcc(acc, sink); if (spec.manifest()) { - deleteWritten(s3, iamService, spec, writtenKeys, roleSession); + RequestScopes.runAs(keyAccount, () -> deleteWritten(s3, iamService, spec, writtenKeys, roleSession)); } aborted = true; } @@ -1558,9 +1577,11 @@ public final class S3CopySimulator { } cleanPathDone = true; try { - authorizeCleanPathList(spec, s3, iamService, roleSession); - s3.deleteObjectsWithPrefix(spec.bucket(), spec.prefix(), - key -> authorizeCleanPathDelete(spec, s3, iamService, roleSession, key)); + RequestScopes.runAs(keyAccount, () -> { + authorizeCleanPathList(spec, s3, iamService, roleSession); + s3.deleteObjectsWithPrefix(spec.bucket(), spec.prefix(), + key -> authorizeCleanPathDelete(spec, s3, iamService, roleSession, key)); + }); } catch (RuntimeException e) { fail(SQLSTATE_INTERNAL, "UNLOAD CLEANPATH failed", e); } @@ -1604,15 +1625,17 @@ public final class S3CopySimulator { private void writePayload(byte[] payload, int index) { String key = unloadDataKey(spec, index); try { - if (roleSession != null) { - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", - RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key)); - s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), - spec.bucket(), key); - } else { - s3.authorizeAnonymousPutObject(spec.bucket(), key); - } - putUnloadObject(s3, spec, key, payload, contentType); + RequestScopes.runAs(keyAccount, () -> { + if (roleSession != null) { + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:PutObject", s3ObjectArn(spec.iamRoleArn(), spec.bucket(), s3, key)); + s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), + spec.bucket(), key); + } else { + s3.authorizeAnonymousPutObject(spec.bucket(), key); + } + putUnloadObject(s3, spec, key, payload, contentType); + }); } catch (AwsException e) { fail(unloadWriteSqlState(e), unloadWriteMessage(e, spec), e); } catch (RuntimeException e) { @@ -1736,8 +1759,8 @@ public final class S3CopySimulator { for (String k : keys) { try { if (roleSession != null) { - RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject", - RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), k)); + RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(), + "s3:DeleteObject", s3ObjectArn(spec.iamRoleArn(), spec.bucket(), s3, k)); s3.authorizeSignedDeleteObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), k); } else { s3.authorizeAnonymousDeleteObject(spec.bucket(), k); diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java index 27ab3f6d38..42af5af6ee 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java @@ -815,6 +815,26 @@ class CopyStatementParserTest { } } + @Test + void parseUnload_capturesAccessKeyCredentials() { + CopyStatementParser.S3Unload inline = unload( + "UNLOAD ('select 1') TO 's3://b/p/' CREDENTIALS " + + "'aws_access_key_id=AKIAEXAMPLE;aws_secret_access_key=secret;token=tok' FORMAT PARQUET"); + assertNotNull(inline.accessKeys()); + assertEquals("AKIAEXAMPLE", inline.accessKeys().accessKeyId()); + assertEquals("secret", inline.accessKeys().secretAccessKey()); + assertEquals("tok", inline.accessKeys().sessionToken()); + assertTrue(inline.parquet()); + + CopyStatementParser.S3Unload separate = unload( + "UNLOAD ('select 1') TO 's3://b/p/' ACCESS_KEY_ID 'AKIA2' SECRET_ACCESS_KEY 'sec2' " + + "SESSION_TOKEN 'tok2'"); + assertNotNull(separate.accessKeys()); + assertEquals("AKIA2", separate.accessKeys().accessKeyId()); + assertEquals("sec2", separate.accessKeys().secretAccessKey()); + assertEquals("tok2", separate.accessKeys().sessionToken()); + } + @Test void parsesCompupdateAndStatupdateOptions() { for (String comp : List.of("COMPUPDATE", "COMPUPDATE PRESET", "COMPUPDATE ON", "COMPUPDATE OFF", "COMPUPDATE TRUE", "COMPUPDATE FALSE")) { diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java index d7d8b24c2a..3598fcd335 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/S3CopySimulatorTest.java @@ -1333,6 +1333,98 @@ class S3CopySimulatorTest { assertEquals('Z', in.nextMessage().type()); } + @Test + void unloadWithAccessKeysEnforcesKeySessionWhenAuthIsOn() throws Exception { + IamService iam = mock(IamService.class); + when(s3.isAuthEnforced()).thenReturn(true); + when(s3.bucketPartition("b")).thenReturn("aws"); + when(iam.findAccountForAccessKeyId("AKIATEST")).thenReturn(Optional.of("111122223333")); + when(iam.findSecretKey("AKIATEST", "tok")).thenReturn(Optional.of("secret")); + when(iam.resolveCallerContext("AKIATEST")).thenReturn(CallerContext.of(List.of( + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":\"*\"}]}"))); + when(iam.resolveCallerArns("AKIATEST")).thenReturn(Optional.empty()); + when(iam.effectiveScpLevels("111122223333")).thenReturn(null); + + CopyStatementParser.S3Unload spec = (CopyStatementParser.S3Unload) CopyStatementParser.parse( + "UNLOAD ('select 1') TO 's3://b/out/' CREDENTIALS " + + "'aws_access_key_id=AKIATEST;aws_secret_access_key=secret;token=tok' ALLOWOVERWRITE"); + try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload( + spec, s3, iam, "000000000000", null, null)) { + collector.accept("1\n".getBytes(StandardCharsets.UTF_8)); + collector.complete(); + } + verify(s3, atLeastOnce()).authorizeSignedPutObject("AKIATEST", "tok", "b", "out/0000_part_00"); + verify(s3).putObject(eq("b"), eq("out/0000_part_00"), any(byte[].class), eq("text/plain"), any()); + + when(iam.findSecretKey("AKIABAD", null)).thenReturn(Optional.empty()); + CopyStatementParser.S3Unload badKey = (CopyStatementParser.S3Unload) CopyStatementParser.parse( + "UNLOAD ('select 1') TO 's3://b/out/' CREDENTIALS " + + "'aws_access_key_id=AKIABAD;aws_secret_access_key=wrong' ALLOWOVERWRITE"); + assertThrows(S3CopySimulator.S3TransferException.class, + () -> S3CopySimulator.prepareUnload(badKey, s3, iam, "000000000000", null, null)); + } + + @Test + void unloadEmptyPrefixCheckScopesListBucketToPrefix() throws Exception { + IamService iam = mock(IamService.class); + when(s3.isAuthEnforced()).thenReturn(true); + IamRole role = heldRole(ROLE_ARN); + when(role.getAssumeRolePolicyDocument()).thenReturn( + "{\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"redshift.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"); + when(iam.findRole("000000000000", "CopyRole")).thenReturn(Optional.of(role)); + when(iam.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of(policy( + "{\"Effect\":\"Allow\",\"Action\":\"s3:PutObject\",\"Resource\":\"*\"}," + + "{\"Effect\":\"Allow\",\"Action\":\"s3:ListBucket\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringLike\":{\"s3:prefix\":\"out/*\"}}}")))); + + CopyStatementParser.S3Unload allowed = (CopyStatementParser.S3Unload) CopyStatementParser.parse( + "UNLOAD ('select 1') TO 's3://b/out/' IAM_ROLE '" + ROLE_ARN + "'"); + try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload( + allowed, s3, iam, "000000000000", List.of(ROLE_ARN), null)) { + verify(s3).authorizeSignedListBucket(any(), any(), eq("b"), eq("out/")); + } + + CopyStatementParser.S3Unload denied = (CopyStatementParser.S3Unload) CopyStatementParser.parse( + "UNLOAD ('select 1') TO 's3://b/other/' IAM_ROLE '" + ROLE_ARN + "'"); + S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class, + () -> S3CopySimulator.prepareUnload(denied, s3, iam, "000000000000", List.of(ROLE_ARN), null)); + assertEquals("42501", error.sqlState()); + } + + @Test + void unloadCleanPathScopesListBucketToPrefix() throws Exception { + IamService iam = mock(IamService.class); + when(s3.isAuthEnforced()).thenReturn(true); + IamRole role = heldRole(ROLE_ARN); + when(role.getAssumeRolePolicyDocument()).thenReturn( + "{\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"redshift.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"); + when(iam.findRole("000000000000", "CopyRole")).thenReturn(Optional.of(role)); + when(iam.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of(policy( + "{\"Effect\":\"Allow\",\"Action\":[\"s3:PutObject\",\"s3:DeleteObject\"],\"Resource\":\"*\"}," + + "{\"Effect\":\"Allow\",\"Action\":\"s3:ListBucket\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringLike\":{\"s3:prefix\":\"out/*\"}}}")))); + + CopyStatementParser.S3Unload allowed = (CopyStatementParser.S3Unload) CopyStatementParser.parse( + "UNLOAD ('select 1') TO 's3://b/out/' IAM_ROLE '" + ROLE_ARN + "' CLEANPATH"); + try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload( + allowed, s3, iam, "000000000000", List.of(ROLE_ARN), null)) { + verify(s3).authorizeSignedListBucket(any(), any(), eq("b"), eq("out/")); + collector.accept("1\n".getBytes(StandardCharsets.UTF_8)); + collector.complete(); + } + verify(s3, times(2)).authorizeSignedListBucket(any(), any(), eq("b"), eq("out/")); + + CopyStatementParser.S3Unload denied = (CopyStatementParser.S3Unload) CopyStatementParser.parse( + "UNLOAD ('select 1') TO 's3://b/other/' IAM_ROLE '" + ROLE_ARN + "' CLEANPATH"); + S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class, + () -> S3CopySimulator.prepareUnload(denied, s3, iam, "000000000000", List.of(ROLE_ARN), null)); + assertEquals("42501", error.sqlState()); + } + @Test void unloadBackendEofMidStreamWithManifestCleansUpWrittenDataObjects() throws Exception { long saved = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;