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

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

No files matched your search

+10 -5
View File
@@ -797,9 +797,13 @@ order) through its own S3 service and streams the rows into the backing PostgreS
request. `IAM_ROLE default` uses the cluster's default role with the same permission checks.
- `REGION '<region>'` is accepted and ignored: Floci has one S3.
- `CREDENTIALS 'aws_iam_role=<arn>'` behaves like `IAM_ROLE`. `ACCESS_KEY_ID` with `SECRET_ACCESS_KEY`
(and an optional `SESSION_TOKEN`), or `CREDENTIALS 'aws_access_key_id=...;aws_secret_access_key=...'`,
are accepted but never verified or stored: S3 is read as an unsigned request, the same as with no
authorization clause. Combining key credentials with `IAM_ROLE`, or giving only one of the pair, is
(and an optional `SESSION_TOKEN`), or `CREDENTIALS 'aws_access_key_id=...;aws_secret_access_key=...[;token=...]'`,
make S3 be read as that principal when S3 authorization is enforced. IAM must know the access key (a temporary
key also needs its session token) and the secret must match, otherwise the `COPY` fails with SQLSTATE `XX000`.
The key's identity policy must allow `s3:ListBucket` and `s3:GetObject`, and any bucket policy must not deny
the request (`42501` otherwise). With S3 authorization off the keys are ignored, so placeholder keys keep
working, and a statement with no authorization clause reads S3 as an unsigned request. The keys are not
stored. Combining key credentials with `IAM_ROLE`, or giving only one of the pair, is
not intercepted, and neither is a blank key, secret, token or role.
- `EMPTYASNULL`, `BLANKSASNULL`, `REMOVEQUOTES` (not with `CSV` or `JSON`), `ACCEPTINVCHARS [AS 'c']`
(default `?`, one ASCII character) and `TRUNCATECOLUMNS` rewrite field content before loading. Field
@@ -906,8 +910,9 @@ the result to S3 as one or more objects under `<prefix>`.
AWS, the compression suffix is added only when no extension is given, so `EXTENSION 'txt.gz' GZIP`
gives `<prefix>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` and the credential clauses (`CREDENTIALS`, `ACCESS_KEY_ID`, `SECRET_ACCESS_KEY`,
`SESSION_TOKEN`) behave as described for COPY.
- `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.
- `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
@@ -20,6 +20,15 @@ public final class CopyStatementParser {
boolean defaultIamRoleRequested();
}
/** Access keys a COPY names, as {@code CREDENTIALS 'aws_access_key_id=...'} or {@code ACCESS_KEY_ID}. */
public record AccessKeys(String accessKeyId, String secretAccessKey, String sessionToken) {
// Keeps the secret and token out of logs and error messages that print the statement
@Override
public String toString() {
return "AccessKeys[accessKeyId=" + accessKeyId + "]";
}
}
/** COPY options that change field content; {@link #NONE} keeps the plain byte-copy path. */
public record CopyTransforms(
boolean blanksAsNull,
@@ -99,7 +108,8 @@ public final class CopyStatementParser {
boolean jsonAutoIgnoreCase,
boolean manifest,
CopyTransforms transforms,
boolean defaultIamRoleRequested) implements S3Statement {
boolean defaultIamRoleRequested,
AccessKeys accessKeys) implements S3Statement {
public S3CopyFrom {
if (transforms == null) {
@@ -107,6 +117,27 @@ public final class CopyStatementParser {
}
}
public S3CopyFrom(
String targetTable,
List<String> columns,
String bucket,
String keyOrPrefix,
String delimiter,
int headerLines,
boolean gzip,
boolean csv,
String nullAs,
String iamRoleArn,
boolean jsonAuto,
boolean jsonAutoIgnoreCase,
boolean manifest,
CopyTransforms transforms,
boolean defaultIamRoleRequested) {
this(targetTable, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest, transforms,
defaultIamRoleRequested, null);
}
public S3CopyFrom(
String targetTable,
List<String> columns,
@@ -333,9 +364,11 @@ public final class CopyStatementParser {
private static final Pattern CREDENTIALS_ROLE = Pattern.compile(
"(?i)(?:^|;)\\s*aws_iam_role\\s*=\\s*([^;\\s]+)");
private static final Pattern CREDENTIALS_KEY_ID = Pattern.compile(
"(?i)(?:^|;)\\s*aws_access_key_id\\s*=\\s*[^;\\s]+");
"(?i)(?:^|;)\\s*aws_access_key_id\\s*=\\s*([^;\\s]+)");
private static final Pattern CREDENTIALS_SECRET = Pattern.compile(
"(?i)(?:^|;)\\s*aws_secret_access_key\\s*=\\s*[^;\\s]+");
"(?i)(?:^|;)\\s*aws_secret_access_key\\s*=\\s*([^;\\s]+)");
private static final Pattern CREDENTIALS_TOKEN = Pattern.compile(
"(?i)(?:^|;)\\s*token\\s*=\\s*([^;\\s]+)");
private static final Pattern IGNOREHEADER_PATTERN = Pattern.compile(
"(?i)\\bIGNOREHEADER\\s+(?:AS\\s+)?(\\d+)\\b");
private static final Pattern HEADER_PATTERN = Pattern.compile("(?i)\\bHEADER\\b");
@@ -895,13 +928,14 @@ public final class CopyStatementParser {
}
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv,
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest, transforms, auth.defaultIamRoleRequested);
nullAs, iamRoleArn, jsonAuto, jsonAutoIgnoreCase, manifest, transforms, auth.defaultIamRoleRequested,
auth.accessKeys());
}
/**
* Collects the S3 authorization and region clauses shared by COPY and UNLOAD. Key material is
* checked for shape only and never stored: the simulator reads S3 as the cluster role or as an
* unsigned request.
* Collects the S3 authorization and region clauses shared by COPY and UNLOAD. COPY keeps the
* keys it names so the simulator reads S3 as that principal; UNLOAD ignores them and writes as
* the cluster role or as an unsigned request.
*/
private static final class AuthClauses {
static final int NO_MATCH = -1;
@@ -926,6 +960,9 @@ public final class CopyStatementParser {
private boolean seenRegion;
private boolean credentialsHaveKeys;
private boolean credentialsMalformed;
private String clauseAccessKeyId;
private String clauseSecretAccessKey;
private String clauseSessionToken;
AuthClauses(String options, String defaultIamRoleArn) {
this.defaultIamRoleArn = defaultIamRoleArn;
@@ -960,21 +997,24 @@ public final class CopyStatementParser {
return REJECT;
}
seenAccessKeyId = true;
return isBlank(extractNullValue(accessKeyId)) ? REJECT : accessKeyId.end();
clauseAccessKeyId = extractNullValue(accessKeyId);
return isBlank(clauseAccessKeyId) ? REJECT : accessKeyId.end();
}
if (matchClause(secretAccessKey, offset, end)) {
if (seenSecretAccessKey) {
return REJECT;
}
seenSecretAccessKey = true;
return isBlank(extractNullValue(secretAccessKey)) ? REJECT : secretAccessKey.end();
clauseSecretAccessKey = extractNullValue(secretAccessKey);
return isBlank(clauseSecretAccessKey) ? REJECT : secretAccessKey.end();
}
if (matchClause(sessionToken, offset, end)) {
if (seenSessionToken) {
return REJECT;
}
seenSessionToken = true;
return isBlank(extractNullValue(sessionToken)) ? REJECT : sessionToken.end();
clauseSessionToken = extractNullValue(sessionToken);
return isBlank(clauseSessionToken) ? REJECT : sessionToken.end();
}
if (matchClause(region, offset, end)) {
if (seenRegion) {
@@ -991,10 +1031,25 @@ public final class CopyStatementParser {
if (role.find()) {
credentialsRoleArn = role.group(1);
}
boolean hasId = CREDENTIALS_KEY_ID.matcher(value).find();
boolean hasSecret = CREDENTIALS_SECRET.matcher(value).find();
Matcher id = CREDENTIALS_KEY_ID.matcher(value);
Matcher secret = CREDENTIALS_SECRET.matcher(value);
Matcher token = CREDENTIALS_TOKEN.matcher(value);
boolean hasId = id.find();
boolean hasSecret = secret.find();
credentialsHaveKeys = hasId && hasSecret;
credentialsMalformed = hasId != hasSecret;
if (credentialsHaveKeys) {
clauseAccessKeyId = id.group(1);
clauseSecretAccessKey = secret.group(1);
clauseSessionToken = token.find() ? token.group(1) : null;
}
}
AccessKeys accessKeys() {
if (clauseAccessKeyId == null || clauseSecretAccessKey == null) {
return null;
}
return new AccessKeys(clauseAccessKeyId, clauseSecretAccessKey, clauseSessionToken);
}
boolean consistent() {
@@ -11,9 +11,12 @@ import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -121,8 +124,72 @@ public final class RedshiftRoleAccess {
return new RoleSession(accessKeyId, secretAccessKey, sessionToken);
}
/**
* Accepts the keys a {@code COPY} names only when IAM knows them: the secret must match and a
* temporary key must come with its issued token, so an expired or invented key fails here
* instead of reading S3 anonymously. The session is not registered, so there is nothing to release.
*/
public static RoleSession resolveKeySession(CopyStatementParser.AccessKeys keys, IamService iamService) {
Optional<String> secret = iamService.findSecretKey(keys.accessKeyId(), keys.sessionToken());
if (secret.isEmpty()) {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
"S3ServiceException: The AWS Access Key Id you provided does not exist in our records, "
+ "or the session has expired", null);
}
boolean secretMatches = MessageDigest.isEqual(
secret.get().getBytes(StandardCharsets.UTF_8), keys.secretAccessKey().getBytes(StandardCharsets.UTF_8));
if (!secretMatches) {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL,
"S3ServiceException: The request signature we calculated does not match the signature "
+ "you provided", null);
}
return new RoleSession(keys.accessKeyId(), keys.secretAccessKey(), keys.sessionToken());
}
/**
* Evaluates the identity policy of whoever {@code session} belongs to: the role when COPY named
* one, otherwise the principal behind the access key.
*/
public static void authorizeSessionAction(S3Service s3, IamService iamService, RoleSession session,
String roleArn, String action, String resourceArn) {
authorizeSessionAction(s3, iamService, session, roleArn, action, resourceArn, Map.of());
}
/**
* @param conditionContext the condition keys the request itself offers, such as {@code s3:prefix}; for an
* access key the keys that say who is calling are added, so a policy that matches
* on {@code aws:PrincipalArn} sees the same principal as on a signed request
*/
public static void authorizeSessionAction(S3Service s3, IamService iamService, RoleSession session,
String roleArn, String action, String resourceArn,
Map<String, List<String>> conditionContext) {
if (roleArn != null) {
authorizeRoleAction(s3, iamService, roleArn, action, resourceArn, conditionContext);
return;
}
if (!s3.isAuthEnforced()) {
return;
}
CallerContext caller = iamService.resolveCallerContext(session.accessKeyId());
if (caller == null) {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for access key '" + session.accessKeyId() + "': " + action + " on "
+ resourceArn, null);
}
Map<String, List<String>> context = new HashMap<>(conditionContext);
iamService.resolveCallerArns(session.accessKeyId())
.ifPresent(callerArns -> callerArns.putPrincipalKeys(context));
IamPolicyEvaluator.SimulationDecision decision =
ROLE_POLICY_EVALUATOR.simulatePrincipalPolicy(caller, action, resourceArn, context);
if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for access key '" + session.accessKeyId() + "': " + action + " on "
+ resourceArn, null);
}
}
public static void releaseRoleSession(RoleSession roleSession, String iamRoleArn, IamService iamService) {
if (roleSession == null) {
if (roleSession == null || iamRoleArn == null) {
return;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(iamRoleArn);
@@ -169,7 +236,7 @@ public final class RedshiftRoleAccess {
authorizeRoleAction(s3, iamService, roleArn, "s3:ListBucket", bucketArn(roleArn, bucket),
Map.of("s3:prefix", List.of(prefix == null ? "" : prefix)));
try {
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), bucket);
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), bucket, prefix);
} catch (AwsException e) {
throw signedAccessFailure(e, "s3://" + bucket);
}
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
@@ -22,6 +24,7 @@ import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
@@ -115,25 +118,32 @@ public final class S3CopySimulator {
static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
return asKeyAccount(spec, s3, iamService,
() -> prepareCopyScoped(spec, s3, iamService, clusterAccountId, associatedRoleArns));
}
private static CopyInput prepareCopyScoped(CopyStatementParser.S3CopyFrom spec, S3Service s3,
IamService iamService, String clusterAccountId,
List<String> associatedRoleArns) {
requireDefaultIamRole(spec);
RedshiftRoleAccess.RoleSession roleSession = spec.iamRoleArn() != null
? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
: null;
RedshiftRoleAccess.RoleSession roleSession = resolveCopySession(spec, s3, iamService, clusterAccountId,
associatedRoleArns);
try {
try {
if (spec.manifest()) {
if (roleSession != null) {
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject",
RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), spec.keyOrPrefix()));
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
"s3:GetObject", copyObjectArn(spec, s3, spec.keyOrPrefix()));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), spec.keyOrPrefix());
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), spec.keyOrPrefix());
}
} else {
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", copyBucketArn(spec, s3), Map.of("s3:prefix", List.of(spec.keyOrPrefix())));
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(),
spec.keyOrPrefix());
} else {
s3.authorizeAnonymousListBucket(spec.bucket());
}
@@ -158,8 +168,8 @@ public final class S3CopySimulator {
try {
for (String key : keys) {
if (roleSession != null) {
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject",
RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key));
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
"s3:GetObject", copyObjectArn(spec, s3, key));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), key);
@@ -176,6 +186,55 @@ 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
* statement may carry placeholder keys.
*/
private static RedshiftRoleAccess.RoleSession resolveCopySession(
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
if (spec.iamRoleArn() != null) {
return RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId,
associatedRoleArns);
}
if (spec.accessKeys() != null && s3.isAuthEnforced()) {
return RedshiftRoleAccess.resolveKeySession(spec.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());
}
return AwsArnUtils.Arn.global(s3.bucketPartition(spec.bucket()), "s3", "",
spec.bucket()).toString();
}
private static String copyObjectArn(CopyStatementParser.S3CopyFrom spec, S3Service s3, String key) {
return copyBucketArn(spec, s3) + "/" + key;
}
/**
* Runs {@code body} in the account that owns the statement's access key, since IAM and S3 look a key up in
* the current account and the proxy's connection thread carries none. A role-based or keyless COPY, or one
* whose keys are ignored because S3 authorization is off, runs as is.
*/
private static <T> T asKeyAccount(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
Supplier<T> body) {
return RequestScopes.callAs(keyAccount(spec, s3, iamService), body);
}
/** Null when no key is in play, which {@link RequestScopes} reads as "stay in the current account". */
private static String keyAccount(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService) {
if (spec.iamRoleArn() != null || spec.accessKeys() == null || !s3.isAuthEnforced()) {
return null;
}
return iamService.findAccountForAccessKeyId(spec.accessKeys().accessKeyId()).orElse(null);
}
static String copyBackendSql(CopyStatementParser.S3CopyFrom spec) {
return fabricateCopy(spec, null);
}
@@ -200,8 +259,19 @@ public final class S3CopySimulator {
static void streamCopyInput(CopyInput input, List<String> discoveredColumns,
List<Integer> columnMaxBytes, List<CopyRecordTransformer.ColumnKind> columnKinds,
OutputStream backendOut) throws IOException {
streamObjects(input.spec(), discoveredColumns, columnMaxBytes, columnKinds, input.s3(), input.iamService(),
input.roleSession(), input.keys(), backendOut);
String account = keyAccount(input.spec(), input.s3(), input.iamService());
try {
RequestScopes.callAsChecked(account, () -> {
streamObjects(input.spec(), discoveredColumns, columnMaxBytes, columnKinds, input.s3(),
input.iamService(), input.roleSession(), input.keys(), backendOut);
return null;
});
} catch (IOException | RuntimeException e) {
throw e;
} catch (Exception e) {
// The body throws only IOException and unchecked exceptions, so this is unreachable.
throw new IllegalStateException(e);
}
}
static void releaseCopySession(CopyInput input) {
@@ -504,8 +574,8 @@ public final class S3CopySimulator {
byte[] buffer = new byte[CHUNK];
for (int i = 0; i < keys.size(); i++) {
if (roleSession != null) {
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject",
RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), keys.get(i)));
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
"s3:GetObject", copyObjectArn(spec, s3, keys.get(i)));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), keys.get(i));
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), keys.get(i));
@@ -1236,6 +1236,16 @@ public class S3Service implements Resettable, ResourceProvider {
authorizeListBucket(bucketName, new RequestAuthorization(true, accessKeyId, sessionToken));
}
/**
* Authorize a signed {@code s3:ListBucket} that lists under {@code prefix}. The bucket policy sees
* {@code s3:prefix} as a real listing offers it, so a statement conditioned on the prefix matches
* instead of failing on the absent key.
*/
public void authorizeSignedListBucket(String accessKeyId, String sessionToken, String bucketName, String prefix) {
authorizeBucketRead(bucketName, "s3:ListBucket", new RequestAuthorization(true, accessKeyId, sessionToken),
Map.of("s3:prefix", List.of(prefix == null ? "" : prefix)));
}
/** Authorize a signed {@code s3:DeleteObject}; see {@link #authorizeSignedGetObject}. */
public void authorizeSignedDeleteObject(String accessKeyId, String sessionToken, String bucketName, String key) {
authorizeDeleteObject(bucketName, key, null, new RequestAuthorization(true, accessKeyId, sessionToken));
@@ -1307,8 +1317,13 @@ public class S3Service implements Resettable, ResourceProvider {
}
void authorizeBucketRead(String bucketName, String action, RequestAuthorization authorization) {
authorizeBucketRead(bucketName, action, authorization, null);
}
void authorizeBucketRead(String bucketName, String action, RequestAuthorization authorization,
Map<String, List<String>> requestConditions) {
String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketPartition(bucketName), bucketName);
authorizeS3Read(bucketName, null, null, action, bucketArn, authorization);
authorizeS3Read(bucketName, null, null, action, bucketArn, authorization, requestConditions);
}
/**
@@ -1369,7 +1384,7 @@ public class S3Service implements Resettable, ResourceProvider {
void authorizeObjectRead(String bucketName, String key, String versionId, String action, RequestAuthorization authorization) {
String objectArn = S3PublicAccessEvaluator.objectArn(bucketPartition(bucketName), bucketName, key);
authorizeS3Read(bucketName, key, versionId, S3ObjectActions.forVersion(action, versionId), objectArn,
authorization);
authorization, null);
}
void authorizePutObject(String bucketName, String key, RequestAuthorization authorization) {
@@ -1488,7 +1503,8 @@ public class S3Service implements Resettable, ResourceProvider {
return enforceAuth;
}
private void authorizeS3Read(String bucketName, String key, String versionId, String action, String resourceArn, RequestAuthorization authorization) {
private void authorizeS3Read(String bucketName, String key, String versionId, String action, String resourceArn,
RequestAuthorization authorization, Map<String, List<String>> requestConditions) {
if (!enforceAuth) {
return;
}
@@ -1498,7 +1514,7 @@ public class S3Service implements Resettable, ResourceProvider {
: RequestAuthorization.unsigned();
if (requestAuthorization.signed()) {
authorizeSignedBucketPolicy(bucketName, key, action, resourceArn, requestAuthorization, null);
authorizeSignedBucketPolicy(bucketName, key, action, resourceArn, requestAuthorization, requestConditions);
return;
}
@@ -7505,7 +7521,7 @@ public class S3Service implements Resettable, ResourceProvider {
* partition can still reach the bucket, and a policy naming it must match as written. A
* bucket that does not exist yet takes the request's partition, where it would be created.
*/
String bucketPartition(String bucketName) {
public String bucketPartition(String bucketName) {
return resolveBucket(bucketName)
.map(Bucket::getRegion)
.map(AwsRegions::partitionFor)
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
@@ -200,4 +201,93 @@ class RedshiftInterceptorIamRoleEnforcedIntegrationTest {
}
}
}
@Test
void copyWithAnIamUsersOwnAccessKeyIsAuthorizedAsThatUser() throws Exception {
clusterId = "it-copy-access-key";
String bucket = "redshift-copy-access-key";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "p1.txt", "1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
iamService.createUser("CopyKeyReader", "/");
iamService.putUserPolicy("CopyKeyReader", "ReadBucket", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::redshift-copy-access-key"},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::redshift-copy-access-key/*"}
]}
""");
iamService.createUser("CopyKeyStranger", "/");
AccessKey reader = iamService.createAccessKey("CopyKeyReader");
AccessKey stranger = iamService.createAccessKey("CopyKeyStranger");
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123", null, List.of(),
List.of());
try (Connection connection = waitForConnection(cluster, "simple");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE people (id int, name text)");
statement.execute("COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID '"
+ reader.getAccessKeyId() + "' SECRET_ACCESS_KEY '" + reader.getSecretAccessKey() + "'");
try (ResultSet rows = statement.executeQuery("SELECT name FROM people")) {
assertTrue(rows.next());
assertEquals("alice", rows.getString(1));
}
SQLException wrongSecret = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID '" + reader.getAccessKeyId()
+ "' SECRET_ACCESS_KEY 'not-the-secret'"));
assertEquals("XX000", wrongSecret.getSQLState());
SQLException unknownKey = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID 'AKIAUNKNOWNKEY00000' "
+ "SECRET_ACCESS_KEY 'whatever'"));
assertEquals("XX000", unknownKey.getSQLState());
SQLException noPolicy = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/p1.txt' ACCESS_KEY_ID '" + stranger.getAccessKeyId()
+ "' SECRET_ACCESS_KEY '" + stranger.getSecretAccessKey() + "'"));
assertEquals("42501", noPolicy.getSQLState());
}
}
@Test
void copyHonorsABucketPolicyDenyConditionedOnTheRequestedPrefix() throws Exception {
clusterId = "it-copy-bucket-prefix";
String bucket = "redshift-copy-bucket-prefix";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "private/p1.txt", "1|alice\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
s3.putObject(bucket, "public/p1.txt", "2|bob\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
// the user's own policy allows everything, so only the bucket policy can refuse the private prefix
iamService.createUser("CopyPrefixReader", "/");
iamService.putUserPolicy("CopyPrefixReader", "ReadAll", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
]}
""");
s3.putBucketPolicy(bucket, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Principal":"*","Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::redshift-copy-bucket-prefix",
"Condition":{"StringLike":{"s3:prefix":"private/*"}}}
]}
""");
AccessKey reader = iamService.createAccessKey("CopyPrefixReader");
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123", null, List.of(),
List.of());
try (Connection connection = waitForConnection(cluster, "simple");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE people (id int, name text)");
String credentials = " ACCESS_KEY_ID '" + reader.getAccessKeyId() + "' SECRET_ACCESS_KEY '"
+ reader.getSecretAccessKey() + "'";
SQLException denied = assertThrows(SQLException.class, () -> statement.execute(
"COPY people FROM 's3://" + bucket + "/private/p1.txt'" + credentials));
assertEquals("42501", denied.getSQLState());
statement.execute("COPY people FROM 's3://" + bucket + "/public/p1.txt'" + credentials);
try (ResultSet rows = statement.executeQuery("SELECT name FROM people")) {
assertTrue(rows.next());
assertEquals("bob", rows.getString(1));
}
}
}
}
@@ -419,6 +419,42 @@ class CopyStatementParserTest {
assertNull(c.iamRoleArn());
}
@Test
void copyKeepsTheKeysAndTokenOfACredentialsString() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' CREDENTIALS "
+ "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=s3cr3t/+x;token=tok/+en=='");
assertEquals("ASIAEXAMPLE", c.accessKeys().accessKeyId());
assertEquals("s3cr3t/+x", c.accessKeys().secretAccessKey());
assertEquals("tok/+en==", c.accessKeys().sessionToken());
}
@Test
void copyKeepsTheKeysOfSeparateClauses() {
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' ACCESS_KEY_ID 'AKIAEXAMPLE' SECRET_ACCESS_KEY 'secret'");
assertEquals("AKIAEXAMPLE", c.accessKeys().accessKeyId());
assertEquals("secret", c.accessKeys().secretAccessKey());
assertNull(c.accessKeys().sessionToken());
}
@Test
void copyWithoutKeysHasNoAccessKeys() {
assertNull(copyFrom("COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::000000000000:role/r'").accessKeys());
}
@Test
void accessKeysStringFormHidesTheSecretAndToken() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' CREDENTIALS "
+ "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=s3cr3t;token=tok'");
String text = c.toString();
assertTrue(text.contains("ASIAEXAMPLE"));
assertFalse(text.contains("s3cr3t"));
assertFalse(text.contains("tok'") || text.contains("token=tok"));
}
@Test
void copyRejectsConflictingOrIncompleteAuthorization() {
assertNull(CopyStatementParser.parse(
@@ -188,7 +188,7 @@ class RedshiftRoleAccessTest {
IamService iamService = mock(IamService.class);
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token");
doThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist", 404)).when(s3)
.authorizeSignedListBucket("ASIAX", "token", "bucket");
.authorizeSignedListBucket("ASIAX", "token", "bucket", "");
S3CopySimulator.S3TransferException missing = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", ""));
@@ -204,7 +204,7 @@ class RedshiftRoleAccessTest {
IamService iamService = mock(IamService.class);
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token");
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket("ASIAX", "token", "bucket");
.authorizeSignedListBucket("ASIAX", "token", "bucket", "");
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedGetObject("ASIAX", "token", "bucket", "key");
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
@@ -39,6 +40,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
@@ -93,6 +95,159 @@ class S3CopySimulatorTest {
verifyNoInteractions(s3);
}
private static final String KEY_COPY = "COPY people FROM 's3://bucket/data.csv' CREDENTIALS "
+ "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=secret;token=tok'";
private static CopyStatementParser.S3CopyFrom keyCopy() {
return (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(KEY_COPY);
}
@Test
void copyWithKnownKeysReadsS3AsThoseKeys() {
IamService iamService = mock(IamService.class);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("secret"));
when(s3.isAuthEnforced()).thenReturn(true);
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}")));
when(s3.objectExists("bucket", "data.csv")).thenReturn(true);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
assertEquals(List.of("data.csv"), input.keys());
verify(s3).authorizeSignedListBucket("ASIAEXAMPLE", "tok", "bucket", "data.csv");
verify(s3).authorizeSignedGetObject("ASIAEXAMPLE", "tok", "bucket", "data.csv");
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
}
@Test
void copyWithAnUnknownOrExpiredKeyFailsInsteadOfReadingAnonymously() {
IamService iamService = mock(IamService.class);
when(s3.isAuthEnforced()).thenReturn(true);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.empty());
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("XX000", error.sqlState());
assertTrue(error.getMessage().contains("does not exist in our records"), error.getMessage());
assertFalse(error.getMessage().contains("secret"), error.getMessage());
verify(s3, never()).authorizeAnonymousListBucket(any());
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
}
@Test
void copyWithAWrongSecretFails() {
IamService iamService = mock(IamService.class);
when(s3.isAuthEnforced()).thenReturn(true);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("another-secret"));
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("XX000", error.sqlState());
assertTrue(error.getMessage().contains("signature"), error.getMessage());
}
@Test
void copyWithKeysDeniedByTheirIdentityPolicyFails() {
IamService iamService = mock(IamService.class);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("secret"));
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of()));
when(s3.isAuthEnforced()).thenReturn(true);
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("42501", error.sqlState());
assertTrue(error.getMessage().contains("ASIAEXAMPLE"), error.getMessage());
assertFalse(error.getMessage().contains("tok"), error.getMessage());
verify(s3, never()).authorizeSignedListBucket(any(), any(), any());
}
private static String policy(String statements) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}";
}
private IamService knownKey() {
IamService iamService = mock(IamService.class);
when(iamService.findSecretKey("ASIAEXAMPLE", "tok")).thenReturn(Optional.of("secret"));
when(s3.isAuthEnforced()).thenReturn(true);
when(s3.objectExists("bucket", "data.csv")).thenReturn(true);
return iamService;
}
@Test
void aConditionalDenyOnThePrincipalArnStillAppliesToTheKeysCopy() {
IamService iamService = knownKey();
String arn = "arn:aws:iam::111111111111:user/alice";
when(iamService.resolveCallerArns("ASIAEXAMPLE")).thenReturn(Optional.of(
new IamService.CallerArns(arn, arn)));
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"},"
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\","
+ "\"Condition\":{\"ArnEquals\":{\"aws:PrincipalArn\":\"" + arn + "\"}}}"))));
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertEquals("42501", error.sqlState());
}
@Test
void anAllowThatRequiresTheListedPrefixMatchesTheCopyPrefix() {
IamService iamService = knownKey();
when(s3.objectExists("bucket", "data.csv")).thenReturn(false);
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("data.csv"), any(), anyInt(), any(), any()))
.thenReturn(null);
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:ListBucket\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringLike\":{\"s3:prefix\":\"data*\"}}},"
+ "{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}"))));
// The listing is authorized (no 42501); the empty prefix then finds no object.
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
assertTrue(error.getMessage().contains("not found"), error.getMessage());
}
@Test
void keysAuthorizeAgainstTheArnsOfTheBucketsPartition() {
IamService iamService = knownKey();
when(s3.bucketPartition("bucket")).thenReturn("aws-cn");
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:*\","
+ "\"Resource\":[\"arn:aws-cn:s3:::bucket\",\"arn:aws-cn:s3:::bucket/*\"]}"))));
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
assertEquals(List.of("data.csv"), input.keys());
}
@Test
void theOwnerOfTheKeyIsLookedUpAcrossAccounts() {
IamService iamService = knownKey();
when(iamService.findAccountForAccessKeyId("ASIAEXAMPLE")).thenReturn(Optional.of("222222222222"));
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
"{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}"))));
S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
verify(iamService).findAccountForAccessKeyId("ASIAEXAMPLE");
}
@Test
void copyIgnoresPlaceholderKeysWhenS3AuthorizationIsOff() {
IamService iamService = mock(IamService.class);
when(s3.isAuthEnforced()).thenReturn(false);
when(s3.objectExists("bucket", "data.csv")).thenReturn(true);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
assertEquals(List.of("data.csv"), input.keys());
verifyNoInteractions(iamService);
}
private ServerSocket listener;
private Socket simClient; // simulator's "client" end
private Socket simBackend; // simulator's "backend" end
@@ -114,6 +269,7 @@ class S3CopySimulatorTest {
backendListener.close();
s3 = mock(S3Service.class);
when(s3.bucketPartition(anyString())).thenReturn("aws");
}
@AfterEach
@@ -336,7 +492,7 @@ class S3CopySimulatorTest {
verify(s3, never()).authorizeAnonymousGetObject(any(), any());
verify(s3, never()).authorizeAnonymousListBucket(any());
verify(s3).authorizeSignedListBucket(any(), any(), eq("b"));
verify(s3).authorizeSignedListBucket(any(), any(), eq("b"), any());
verify(s3).authorizeSignedGetObject(any(), any(), eq("b"), eq("k"));
verify(iamService).registerSessionForAccount(
eq("000000000000"), any(), any(), any(), eq(ROLE_ARN), any(), isNull());
@@ -1049,7 +1049,7 @@ class ExternalTableMaterializerTest {
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("bucket"));
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("bucket"), any());
verify(s3).authorizeSignedGetObject(anyString(), anyString(), eq("bucket"), eq("events/p1.csv"));
verify(iam).unregisterSession(eq(ACCOUNT), anyString());
}
@@ -1058,7 +1058,7 @@ class ExternalTableMaterializerTest {
void releasesTheRoleSessionWhenAuthorizationFails() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket(anyString(), anyString(), eq("bucket"));
.authorizeSignedListBucket(anyString(), anyString(), eq("bucket"), any());
assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
@@ -17,6 +17,7 @@ import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -259,7 +260,7 @@ class SpectrumS3ReaderTest {
assertEquals(1, rows.count());
}
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"));
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"), any());
verify(s3).authorizeSignedGetObject(anyString(), anyString(), eq("warehouse"), eq("events/data.csv"));
verify(iam).unregisterSession(eq("000000000000"), anyString());
}
@@ -270,7 +271,7 @@ class SpectrumS3ReaderTest {
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"));
.authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"), any());
assertThrows(SpectrumReadException.class, () -> new SpectrumS3Reader(s3, iam)
.read(session(role), schema(role), table(SpectrumColumn.Type.VARCHAR)).toList());