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

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

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

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

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

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

* fix(redshift): complete IAM_ROLE S3 authorization

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

* docs(redshift): document IAM_ROLE COPY and UNLOAD

* fix(redshift): retain IAM_ROLE session during COPY

* style(test): use Mockito static imports

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

* fix(redshift): address IAM role review feedback

* test(redshift): use valid proxy relay keys

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

* test(compat): recover CodeArtifact create retries

* fix(redshift): parse IAM role location names

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

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

No files matched your search

@@ -7,6 +7,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@@ -74,6 +75,35 @@ public class AssumeRolePolicyEvaluator {
return allow;
}
/**
* Returns true if the trust policy allows the named AWS service principal to assume the role.
*/
public boolean allowsService(String trustPolicyDocument, String servicePrincipal) {
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return false;
}
JsonNode statements;
try {
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
} catch (Exception e) {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return false;
}
boolean allow = false;
if (statements.isArray()) {
for (JsonNode statement : statements) {
switch (evaluateServiceStatement(statement, servicePrincipal)) {
case DENY -> { return false; }
case ALLOW -> allow = true;
case NO_MATCH -> { }
}
}
} else if (statements.isObject()) {
return evaluateServiceStatement(statements, servicePrincipal) == Match.ALLOW;
}
return allow;
}
private enum Match { ALLOW, DENY, NO_MATCH }
private Match evaluateStatement(JsonNode stmt, String callerArn, String callerAccount) {
@@ -86,6 +116,34 @@ public class AssumeRolePolicyEvaluator {
return "Deny".equalsIgnoreCase(stmt.path("Effect").asText("Allow")) ? Match.DENY : Match.ALLOW;
}
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal) {
if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
return Match.NO_MATCH;
}
return "Deny".equalsIgnoreCase(stmt.path("Effect").asText("Allow")) ? Match.DENY : Match.ALLOW;
}
private boolean matchesServicePrincipal(JsonNode principalNode, String servicePrincipal) {
if (principalNode == null || servicePrincipal == null) {
return false;
}
JsonNode service = principalNode.isObject() ? principalNode.get("Service") : null;
if (service == null) {
return false;
}
if (service.isTextual()) {
return IamPolicyEvaluator.globMatches(service.asText(), servicePrincipal);
}
if (service.isArray()) {
for (JsonNode entry : service) {
if (entry.isTextual() && IamPolicyEvaluator.globMatches(entry.asText(), servicePrincipal)) {
return true;
}
}
}
return false;
}
/**
* True if the statement's action element applies to {@code sts:AssumeRole}. An {@code Action}
* element applies when any of its patterns match; a {@code NotAction} element applies when none
@@ -161,7 +219,7 @@ public class AssumeRolePolicyEvaluator {
if (principal.matches("\\d{12}")) {
return principal.equals(callerAccount);
}
var rootMatcher = ACCOUNT_ROOT_ARN.matcher(principal);
Matcher rootMatcher = ACCOUNT_ROOT_ARN.matcher(principal);
if (rootMatcher.matches()) {
return rootMatcher.group(1).equals(callerAccount);
}
@@ -191,7 +249,7 @@ public class AssumeRolePolicyEvaluator {
* be denied a role they are entitled to, with nothing in the response saying why.
*/
private static String assumedRoleToRoleArn(String arn) {
var m = ASSUMED_ROLE_ARN.matcher(arn);
Matcher m = ASSUMED_ROLE_ARN.matcher(arn);
if (!m.matches()) {
return null;
}
@@ -67,9 +67,13 @@ public class RedshiftQueryHandler {
String masterUserPassword = params.getFirst("MasterUserPassword");
String clusterSubnetGroupName = params.getFirst("ClusterSubnetGroupName");
List<String> vpcSecurityGroupIds = memberList(params, "VpcSecurityGroupIds");
List<String> iamRoleArns = memberList(params, "IamRoles");
Cluster cluster = service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
clusterSubnetGroupName, vpcSecurityGroupIds);
Cluster cluster = iamRoleArns.isEmpty()
? service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
clusterSubnetGroupName, vpcSecurityGroupIds)
: service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns);
String xml = new XmlBuilder()
.start("CreateClusterResponse")
.start("CreateClusterResult")
@@ -622,6 +626,14 @@ public class RedshiftQueryHandler {
builder.end("VpcSecurityGroups");
}
if (cluster.getIamRoleArns() != null && !cluster.getIamRoleArns().isEmpty()) {
builder.start("IamRoles");
for (String iamRoleArn : cluster.getIamRoleArns()) {
builder.start("IamRole").elem("IamRoleArn", iamRoleArn).end("IamRole");
}
builder.end("IamRoles");
}
if (cluster.getClusterParameterGroupName() != null) {
builder.start("ClusterParameterGroups")
.start("ClusterParameterGroup")
@@ -848,6 +860,7 @@ public class RedshiftQueryHandler {
return switch (baseName) {
case "SubnetIds" -> quoted + "(\\.member|\\.SubnetIdentifier)?\\.\\d+";
case "VpcSecurityGroupIds" -> quoted + "(\\.member|\\.VpcSecurityGroupId)?\\.\\d+";
case "IamRoles" -> quoted + "(\\.member|\\.IamRoleArn)?\\.\\d+";
case "TagKeys" -> quoted + "(\\.member|\\.TagKey)?\\.\\d+";
case "DbGroups" -> quoted + "(\\.member|\\.DbGroup)?\\.\\d+";
default -> quoted + "(\\.member)?\\.\\d+";
@@ -117,7 +117,8 @@ public class RedshiftService {
relayKey(entry.accountId(), cluster.getClusterIdentifier()), proxyPort,
handle.getHost(), handle.getPort(), endpoint.getAddress(),
cluster.getMasterUsername(), password, CLUSTER_DB_NAME,
passwordValidatorFor(entry.accountId(), cluster.getClusterIdentifier()));
passwordValidatorFor(entry.accountId(), cluster.getClusterIdentifier()),
cluster.getIamRoleArns());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setEndpoint(endpoint);
@@ -143,13 +144,20 @@ public class RedshiftService {
}
public Cluster createCluster(String identifier, String nodeType, String username, String password) {
return createCluster(identifier, nodeType, username, password, null, List.of());
return createCluster(identifier, nodeType, username, password, null, List.of(), List.of());
}
// synchronized like modify/reboot: the container + proxy + port steps must not
// interleave with another admin call on the same cluster.
public synchronized Cluster createCluster(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds) {
return createCluster(identifier, nodeType, username, password, clusterSubnetGroupName,
vpcSecurityGroupIds, List.of());
}
public synchronized Cluster createCluster(String identifier, String nodeType, String username, String password,
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds,
List<String> iamRoleArns) {
if (clusters.get(identifier).isPresent()) {
throw new AwsException("ClusterAlreadyExists", "Cluster " + identifier + " already exists", 400);
}
@@ -164,6 +172,7 @@ public class RedshiftService {
cluster.setMasterPassword(password);
cluster.setClusterSubnetGroupName(clusterSubnetGroupName);
cluster.setVpcSecurityGroupIds(vpcSecurityGroupIds != null ? vpcSecurityGroupIds : List.of());
cluster.setIamRoleArns(iamRoleArns != null ? List.copyOf(iamRoleArns) : List.of());
cluster.setClusterStatus("creating");
clusters.put(identifier, cluster);
clusters.flush();
@@ -181,7 +190,7 @@ public class RedshiftService {
proxyManager.startProxy(relayKey(accountId, identifier), proxyPort,
handle.getHost(), handle.getPort(), endpoint.getAddress(),
username, password, CLUSTER_DB_NAME,
passwordValidatorFor(accountId, identifier));
passwordValidatorFor(accountId, identifier), cluster.getIamRoleArns());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setEndpoint(endpoint);
@@ -497,7 +506,7 @@ public class RedshiftService {
cluster.setProxyPort(proxyPort);
proxyManager.startProxy(key, proxyPort, handle.getHost(), handle.getPort(),
endpoint.getAddress(), cluster.getMasterUsername(), password, CLUSTER_DB_NAME,
passwordValidatorFor(accountId, clusterIdentifier));
passwordValidatorFor(accountId, clusterIdentifier), cluster.getIamRoleArns());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setEndpoint(endpoint);
@@ -727,7 +736,7 @@ public class RedshiftService {
proxyManager.startProxy(relayKey(accountId, clusterIdentifier), proxyPort,
handle.getHost(), handle.getPort(), endpoint.getAddress(),
username, password, CLUSTER_DB_NAME,
passwordValidatorFor(accountId, clusterIdentifier));
passwordValidatorFor(accountId, clusterIdentifier), cluster.getIamRoleArns());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setEndpoint(endpoint);
@@ -17,6 +17,7 @@ public class Cluster {
private String clusterSubnetGroupName;
private String clusterParameterGroupName;
private List<String> vpcSecurityGroupIds = new ArrayList<>();
private List<String> iamRoleArns = new ArrayList<>();
public String getClusterIdentifier() { return clusterIdentifier; }
public void setClusterIdentifier(String clusterIdentifier) { this.clusterIdentifier = clusterIdentifier; }
@@ -36,6 +37,8 @@ public class Cluster {
public void setClusterParameterGroupName(String clusterParameterGroupName) { this.clusterParameterGroupName = clusterParameterGroupName; }
public List<String> getVpcSecurityGroupIds() { return vpcSecurityGroupIds; }
public void setVpcSecurityGroupIds(List<String> vpcSecurityGroupIds) { this.vpcSecurityGroupIds = vpcSecurityGroupIds; }
public List<String> getIamRoleArns() { return iamRoleArns; }
public void setIamRoleArns(List<String> iamRoleArns) { this.iamRoleArns = iamRoleArns; }
// Real backend address of this cluster's PostgreSQL container. `endpoint` now points at the
// auth proxy, not the container, so the container address is kept here for proxy wiring and
@@ -25,7 +25,8 @@ public final class CopyStatementParser {
int headerLines,
boolean gzip,
boolean csv,
String nullAs) implements S3Statement {
String nullAs,
String iamRoleArn) implements S3Statement {
}
public record S3Unload(
@@ -41,7 +42,8 @@ public final class CopyStatementParser {
boolean manifest,
boolean allowOverwrite,
boolean parallel,
long maxFileSizeBytes) implements S3Statement {
long maxFileSizeBytes,
String iamRoleArn) implements S3Statement {
}
private static final Pattern COPY_PATTERN = Pattern.compile(
@@ -67,7 +69,7 @@ public final class CopyStatementParser {
*/
private static final Pattern UNLOAD_UNSUPPORTED_CLAUSE = Pattern.compile(
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD"
+ "|ENCRYPTED|ENCODING|REGION|CREDENTIALS|IAM_ROLE|ACCESS_KEY_ID"
+ "|ENCRYPTED|ENCODING|REGION|CREDENTIALS|ACCESS_KEY_ID"
+ "|SECRET_ACCESS_KEY|SESSION_TOKEN|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
+ "|EXTENSION|CLEANPATH|PARTITION|MAXFILESIZE\\s+\\d+\\s*(?:TB|PB))\\b");
@@ -79,6 +81,8 @@ public final class CopyStatementParser {
"(?i)\\bDELIMITER\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\"|([^\\s;]+))");
private static final Pattern NULL_AS_PATTERN = Pattern.compile(
"(?i)\\bNULL\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
private static final Pattern IAM_ROLE_PATTERN = Pattern.compile(
"(?i)\\bIAM_ROLE\\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");
@@ -92,7 +96,7 @@ public final class CopyStatementParser {
*/
private static final Pattern UNSUPPORTED_CLAUSE = Pattern.compile(
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|JSON|SHAPEFILE|BZIP2|LZOP|ZSTD|MANIFEST|MAXERROR"
+ "|DATEFORMAT|TIMEFORMAT|ENCRYPTED|ENCODING|REGION|CREDENTIALS|IAM_ROLE"
+ "|DATEFORMAT|TIMEFORMAT|ENCRYPTED|ENCODING|REGION|CREDENTIALS"
+ "|ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
+ "|ACCEPTINVCHARS|ACCEPTANYDATE|BLANKSASNULL|EMPTYASNULL|FILLRECORD|TRIMBLANKS"
+ "|TRUNCATECOLUMNS|IGNOREBLANKLINES|ESCAPE|REMOVEQUOTES|EXPLICIT_IDS|COMPUPDATE"
@@ -151,6 +155,7 @@ public final class CopyStatementParser {
String nullAs = null;
String delimiter = null;
long maxFileSizeBytes = 0L;
String iamRoleArn = null;
boolean seenCsv = false;
boolean seenGzip = false;
@@ -162,6 +167,7 @@ public final class CopyStatementParser {
boolean seenNull = false;
boolean seenDelimiter = false;
boolean seenMaxFileSize = false;
boolean seenIamRole = false;
Matcher csvM = CSV_PATTERN.matcher(options);
Matcher gzipM = GZIP_PATTERN.matcher(options);
@@ -173,6 +179,7 @@ public final class CopyStatementParser {
Matcher delimiterM = DELIMITER_PATTERN.matcher(options);
Matcher nullM = NULL_AS_PATTERN.matcher(options);
Matcher maxFileSizeM = MAXFILESIZE_PATTERN.matcher(options);
Matcher iamRoleM = IAM_ROLE_PATTERN.matcher(options);
int offset = 0;
int len = options.length();
@@ -259,6 +266,13 @@ public final class CopyStatementParser {
seenNull = true;
nullAs = extractNullValue(nullM);
offset = nullM.end();
} else if (matchClause(iamRoleM, offset, len)) {
if (seenIamRole) {
return null;
}
seenIamRole = true;
iamRoleArn = extractNullValue(iamRoleM);
offset = iamRoleM.end();
} else {
return null;
}
@@ -268,7 +282,7 @@ public final class CopyStatementParser {
delimiter = csv ? "," : "|";
}
return new S3Unload(select, bucket, prefix, delimiter, header, gzip, csv,
addQuotes, nullAs, manifest, allowOverwrite, parallel, maxFileSizeBytes);
addQuotes, nullAs, manifest, allowOverwrite, parallel, maxFileSizeBytes, iamRoleArn);
}
private static S3CopyFrom parseCopy(String cleaned) {
@@ -319,11 +333,14 @@ public final class CopyStatementParser {
String delimiter = null;
int headerLines = 0;
String iamRoleArn = null;
boolean seenCsv = false;
boolean seenGzip = false;
boolean seenNull = false;
boolean seenDelimiter = false;
boolean seenHeader = false;
boolean seenIamRole = false;
Matcher csvMatcher = CSV_PATTERN.matcher(options);
Matcher gzipMatcher = GZIP_PATTERN.matcher(options);
@@ -331,6 +348,7 @@ public final class CopyStatementParser {
Matcher headerMatcher = HEADER_PATTERN.matcher(options);
Matcher delimiterMatcher = DELIMITER_PATTERN.matcher(options);
Matcher nullMatcher = NULL_AS_PATTERN.matcher(options);
Matcher iamRoleMatcher = IAM_ROLE_PATTERN.matcher(options);
int offset = 0;
int len = options.length();
@@ -384,6 +402,13 @@ public final class CopyStatementParser {
seenNull = true;
nullAs = extractNullValue(nullMatcher);
offset = nullMatcher.end();
} else if (matchClause(iamRoleMatcher, offset, len)) {
if (seenIamRole) {
return null;
}
seenIamRole = true;
iamRoleArn = extractNullValue(iamRoleMatcher);
offset = iamRoleMatcher.end();
} else {
return null;
}
@@ -393,7 +418,7 @@ public final class CopyStatementParser {
delimiter = csv ? "," : "|";
}
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv, nullAs);
return new S3CopyFrom(table, columns, bucket, keyOrPrefix, delimiter, headerLines, gzip, csv, nullAs, iamRoleArn);
}
private static boolean matchClause(Matcher m, int start, int end) {
@@ -1,9 +1,11 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
final class ExtendedS3Exchange {
@@ -15,8 +17,16 @@ final class ExtendedS3Exchange {
static void execute(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Statement statement, S3Service s3Service,
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
BackendResponseCoordinator coordinator, BackendResponseCoordinator.Ticket ticket) throws IOException {
execute(client, backend, executeFrame, statement, s3Service, iamService, null, List.of(), coordinator, ticket);
}
static void execute(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
BackendResponseCoordinator.Ticket ticket) throws IOException {
BackendResponseCoordinator.GateResult gate;
try {
gate = coordinator.awaitExtendedExecuteTurn(ticket);
@@ -33,12 +43,14 @@ final class ExtendedS3Exchange {
try {
switch (statement) {
case CopyStatementParser.S3CopyFrom copy -> {
CopyResult result = runCopy(client, backend, executeFrame, copy, s3Service, coordinator);
CopyResult result = runCopy(client, backend, executeFrame, copy, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator);
failed = !result.succeeded();
deferredReadyForQuery = result.deferredReadyForQuery();
}
case CopyStatementParser.S3Unload unload -> {
CopyResult result = runUnload(client, backend, executeFrame, unload, s3Service, coordinator);
CopyResult result = runUnload(client, backend, executeFrame, unload, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator);
failed = !result.succeeded();
deferredReadyForQuery = result.deferredReadyForQuery();
}
@@ -57,8 +69,8 @@ final class ExtendedS3Exchange {
private static CopyResult runCopy(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3CopyFrom spec, S3Service s3Service,
BackendResponseCoordinator coordinator) throws IOException {
CopyStatementParser.S3CopyFrom spec, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator) throws IOException {
OutputStream backendOut = backend.getOutputStream();
backendOut.write(executeFrame.toPacketBytes());
backendOut.flush();
@@ -77,7 +89,7 @@ final class ExtendedS3Exchange {
S3CopySimulator.CopyInput input;
try {
input = S3CopySimulator.prepareCopy(spec, s3Service);
input = S3CopySimulator.prepareCopy(spec, s3Service, iamService, clusterAccountId, iamRoleArns);
} catch (S3CopySimulator.S3TransferException e) {
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
forwardClientSyncToBackend(sync, backendOut, coordinator);
@@ -97,6 +109,8 @@ final class ExtendedS3Exchange {
String detail = e.getMessage() != null ? e.getMessage() : e.toString();
sendError(client, "XX000", "S3 COPY failed: " + detail);
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
} finally {
S3CopySimulator.releaseCopySession(input);
}
forwardClientSyncToBackend(sync, backendOut, coordinator);
@@ -106,8 +120,8 @@ final class ExtendedS3Exchange {
private static CopyResult runUnload(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Unload spec, S3Service s3Service,
BackendResponseCoordinator coordinator) throws IOException {
CopyStatementParser.S3Unload spec, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator) throws IOException {
OutputStream backendOut = backend.getOutputStream();
backendOut.write(executeFrame.toPacketBytes());
backendOut.flush();
@@ -125,7 +139,7 @@ final class ExtendedS3Exchange {
S3CopySimulator.UnloadCollector collector;
try {
collector = S3CopySimulator.prepareUnload(spec, s3Service);
collector = S3CopySimulator.prepareUnload(spec, s3Service, iamService, clusterAccountId, iamRoleArns);
} catch (S3CopySimulator.S3TransferException e) {
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
drainExecute(client, decoder, coordinator, false);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
@@ -12,6 +13,7 @@ import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.Semaphore;
/**
@@ -35,6 +37,9 @@ public class RedshiftAuthProxy {
private final RdsProxyTlsCertificates tlsCertificates;
private final PasswordValidator passwordValidator;
private final S3Service s3Service;
private final IamService iamService;
private final String clusterAccountId;
private final List<String> iamRoleArns;
private final int handshakeTimeoutMillis;
private final int backendConnectTimeoutMillis;
private final Semaphore connectionPermits;
@@ -46,7 +51,22 @@ public class RedshiftAuthProxy {
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator,
S3Service s3Service,
S3Service s3Service, IamService iamService,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections) {
this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, s3Service, iamService, null,
List.of(),
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections);
}
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator,
S3Service s3Service, IamService iamService,
String clusterAccountId,
List<String> iamRoleArns,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections) {
this.clusterKey = clusterKey;
@@ -59,6 +79,9 @@ public class RedshiftAuthProxy {
this.tlsCertificates = tlsCertificates;
this.passwordValidator = passwordValidator;
this.s3Service = s3Service;
this.iamService = iamService;
this.clusterAccountId = clusterAccountId;
this.iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns);
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
this.backendConnectTimeoutMillis = backendConnectTimeoutMillis;
this.connectionPermits = new Semaphore(Math.max(1, maxConnections));
@@ -175,7 +198,8 @@ public class RedshiftAuthProxy {
if (session != null) {
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
// PostgreSQL backend on the way through; every other message is relayed verbatim.
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service).run();
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
clusterAccountId, iamRoleArns).run();
}
} catch (Exception e) {
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.jboss.logging.Logger;
@@ -8,6 +9,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
@@ -41,6 +43,9 @@ public class RedshiftInterceptingBridge {
private final Socket client;
private final Socket backend;
private final S3Service s3Service;
private final IamService iamService;
private final String clusterAccountId;
private final List<String> iamRoleArns;
private final ExtendedQuerySession session = new ExtendedQuerySession();
private final BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
@@ -48,10 +53,23 @@ public class RedshiftInterceptingBridge {
private volatile boolean pumpBetweenMessages = true;
private volatile boolean pumpFinished = false;
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service) {
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService) {
this(client, backend, s3Service, iamService, null);
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId) {
this(client, backend, s3Service, iamService, clusterAccountId, List.of());
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns) {
this.client = client;
this.backend = backend;
this.s3Service = s3Service;
this.iamService = iamService;
this.clusterAccountId = clusterAccountId;
this.iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns);
}
@FunctionalInterface
@@ -138,10 +156,10 @@ public class RedshiftInterceptingBridge {
CopyStatementParser.S3Statement statement = parsed;
boolean intercepted = runWithBackendOwned(() -> switch (statement) {
case CopyStatementParser.S3CopyFrom copy -> S3CopySimulator.runCopyFrom(
client, backend, copy, s3Service, coordinator.lastReadyStatus(),
client, backend, copy, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
case CopyStatementParser.S3Unload unload -> S3CopySimulator.runUnload(
client, backend, unload, s3Service, coordinator.lastReadyStatus(),
client, backend, unload, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
});
if (intercepted) {
@@ -276,7 +294,8 @@ public class RedshiftInterceptingBridge {
}
try {
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
ExtendedS3Exchange.execute(client, backend, executeFrame, statement, s3Service, coordinator, ticket);
ExtendedS3Exchange.execute(client, backend, executeFrame, statement, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator, ticket);
} finally {
try {
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
@@ -12,6 +13,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
@@ -27,6 +29,7 @@ public class RedshiftProxyManager {
private final RdsSigV4Validator sigV4Validator;
private final RdsProxyTlsCertificates tlsCertificates;
private final S3Service s3Service;
private final IamService iamService;
private final EmulatorConfig config;
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
/**
@@ -39,10 +42,11 @@ public class RedshiftProxyManager {
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, EmulatorConfig config) {
S3Service s3Service, IamService iamService, EmulatorConfig config) {
this.sigV4Validator = sigV4Validator;
this.tlsCertificates = tlsCertificates;
this.s3Service = s3Service;
this.iamService = iamService;
this.config = config;
}
@@ -50,15 +54,26 @@ public class RedshiftProxyManager {
String backendHost, int backendPort, String advertisedHost,
String masterUsername, String masterPassword, String dbName,
PasswordValidator passwordValidator) {
startProxy(relayKey, proxyPort, backendHost, backendPort, advertisedHost, masterUsername,
masterPassword, dbName, passwordValidator, List.of());
}
public synchronized void startProxy(String relayKey, int proxyPort,
String backendHost, int backendPort, String advertisedHost,
String masterUsername, String masterPassword, String dbName,
PasswordValidator passwordValidator, List<String> iamRoleArns) {
// A prior unclosable entry for this key is left in place: its listener may still
// be bound, and only a successful stop (never a fresh start) may drop it.
// Make sure the self-signed proxy certificate covers the host clients will connect to,
// so sslmode=prefer/require handshakes succeed.
tlsCertificates.ensureHost(advertisedHost);
EmulatorConfig.RedshiftServiceConfig redshiftConfig = config.services().redshift();
String clusterAccountId = relayKey.substring(0, relayKey.indexOf(':'));
RedshiftAuthProxy proxy = new RedshiftAuthProxy(
relayKey, backendHost, backendPort, masterUsername, masterPassword, dbName,
sigV4Validator, tlsCertificates, passwordValidator, s3Service,
sigV4Validator, tlsCertificates, passwordValidator, s3Service, iamService,
clusterAccountId,
iamRoleArns,
redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(),
redshiftConfig.proxyMaxConnections());
try {
@@ -1,6 +1,13 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
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.S3Object;
import org.jboss.logging.Logger;
@@ -12,9 +19,13 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;
import java.util.zip.GZIPInputStream;
@@ -55,10 +66,129 @@ public final class S3CopySimulator {
private static final String SQLSTATE_INSUFFICIENT_PRIVILEGE = "42501";
private static final String SQLSTATE_INTERNAL = "XX000";
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final String UPPER_ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final String SECRET_CHARACTERS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/** COPY/UNLOAD is synchronous end-to-end; this only needs to outlive one statement. */
private static final Duration ROLE_SESSION_TTL = Duration.ofMinutes(5);
// S3Service's signed-request authorization only checks the bucket's resource policy: for a
// genuine HTTP request the identity-policy gate already happened upstream in
// IamEnforcementFilter before the request ever reached S3Service. This in-process call never
// goes through that filter, so the role's identity policy is evaluated here explicitly.
// Stateless (only needs an ObjectMapper), so a local instance avoids threading a new
// dependency through the whole proxy chain for this one check.
private static final IamPolicyEvaluator ROLE_POLICY_EVALUATOR = new IamPolicyEvaluator(new ObjectMapper());
private static final AssumeRolePolicyEvaluator ROLE_TRUST_POLICY_EVALUATOR =
new AssumeRolePolicyEvaluator(new ObjectMapper());
private S3CopySimulator() {
}
record CopyInput(CopyStatementParser.S3CopyFrom spec, List<String> keys, S3Service s3) {
record CopyInput(CopyStatementParser.S3CopyFrom spec, List<String> keys, S3Service s3,
IamService iamService, RoleSession roleSession) {
}
private record RoleSession(String accessKeyId, String sessionToken) {
}
/**
* Validates the role ARN, its account and Redshift trust policy, then mints a short-lived session.
*/
private static RoleSession resolveRoleSession(String iamRoleArn, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
AwsArnUtils.Arn parsed;
try {
parsed = AwsArnUtils.parse(iamRoleArn);
} catch (IllegalArgumentException e) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + iamRoleArn + "' could not be assumed: malformed ARN", e);
}
if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + iamRoleArn + "' could not be assumed: not an IAM role ARN", null);
}
if (clusterAccountId != null && !clusterAccountId.equals(parsed.accountId())) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + iamRoleArn + "' could not be assumed: cross-account role ARNs are not supported", null);
}
if (clusterAccountId != null && associatedRoleArns != null && !associatedRoleArns.contains(iamRoleArn)) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + iamRoleArn
+ "' could not be assumed: role is not associated with the Redshift cluster", null);
}
String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
Optional<IamRole> role = iamService.findRole(parsed.accountId(), roleName);
if (role.isEmpty()) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + iamRoleArn + "' could not be assumed: role does not exist", null);
}
if (clusterAccountId != null
&& !ROLE_TRUST_POLICY_EVALUATOR.allowsService(
role.get().getAssumeRolePolicyDocument(), "redshift.amazonaws.com")) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + iamRoleArn + "' could not be assumed: trust policy does not allow redshift.amazonaws.com",
null);
}
String accessKeyId = "ASIA" + randomString(UPPER_ALPHANUMERIC, 16);
// A session token is required: IamService.findSecretKey(accessKeyId, sessionToken) treats a
// null token on either side as a non-match, so a tokenless session can never be recognised
// as a known access key and every signed authorization call would fail closed.
String sessionToken = randomString(SECRET_CHARACTERS, 200);
iamService.registerSessionForAccount(parsed.accountId(), accessKeyId,
randomString(SECRET_CHARACTERS, 40), sessionToken, iamRoleArn,
Instant.now().plus(ROLE_SESSION_TTL), null);
return new RoleSession(accessKeyId, sessionToken);
}
private static void releaseRoleSession(RoleSession roleSession, String iamRoleArn, IamService iamService) {
if (roleSession == null) {
return;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(iamRoleArn);
iamService.unregisterSession(parsed.accountId(), roleSession.accessKeyId());
}
/**
* Evaluates the role's identity-based policy for one S3 action, skipped entirely when
* {@code FLOCI_SERVICES_S3_ENFORCE_AUTH} is off (matching the anonymous path's behavior).
*/
private static void authorizeRoleAction(S3Service s3, IamService iamService, String roleArn,
String action, String resourceArn) {
if (!s3.isAuthEnforced()) {
return;
}
CallerContext caller;
try {
caller = iamService.resolvePrincipalContext(roleArn);
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + roleArn + "' could not be assumed: " + e.getMessage(), e);
}
IamPolicyEvaluator.SimulationDecision decision =
ROLE_POLICY_EVALUATOR.simulatePrincipalPolicy(caller, action, resourceArn, Map.of());
if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for IAM Role '" + roleArn + "': " + action + " on " + resourceArn, null);
}
}
private static String bucketArn(String bucket) {
return "arn:aws:s3:::" + bucket;
}
private static String objectArn(String bucket, String key) {
return "arn:aws:s3:::" + bucket + "/" + key;
}
private static String randomString(String characters, int length) {
StringBuilder value = new StringBuilder(length);
for (int i = 0; i < length; i++) {
value.append(characters.charAt(SECURE_RANDOM.nextInt(characters.length())));
}
return value.toString();
}
interface UnloadCollector extends AutoCloseable {
@@ -85,35 +215,63 @@ public final class S3CopySimulator {
}
}
static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3) {
try {
s3.authorizeAnonymousListBucket(spec.bucket());
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e);
}
static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService) {
return prepareCopy(spec, s3, iamService, null);
}
List<String> keys;
try {
keys = resolveKeys(spec, s3);
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"S3 COPY could not list s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e);
}
if (keys.isEmpty()) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"S3 object s3://" + spec.bucket() + "/" + spec.keyOrPrefix() + " not found", null);
}
static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId) {
return prepareCopy(spec, s3, iamService, clusterAccountId, null);
}
static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
RoleSession roleSession = spec.iamRoleArn() != null
? resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
: null;
try {
for (String key : keys) {
s3.authorizeAnonymousGetObject(spec.bucket(), key);
try {
if (roleSession != null) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.bucket()));
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
} else {
s3.authorizeAnonymousListBucket(spec.bucket());
}
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e);
}
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e);
List<String> keys;
try {
keys = resolveKeys(spec, s3);
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"S3 COPY could not list s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e);
}
if (keys.isEmpty()) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"S3 object s3://" + spec.bucket() + "/" + spec.keyOrPrefix() + " not found", null);
}
try {
for (String key : keys) {
if (roleSession != null) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.bucket(), key));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), key);
}
}
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for s3://" + spec.bucket() + "/" + spec.keyOrPrefix(), e);
}
return new CopyInput(spec, List.copyOf(keys), s3, iamService, roleSession);
} catch (RuntimeException e) {
releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw e;
}
return new CopyInput(spec, List.copyOf(keys), s3);
}
static String copyBackendSql(CopyStatementParser.S3CopyFrom spec) {
@@ -121,36 +279,78 @@ public final class S3CopySimulator {
}
static void streamCopyInput(CopyInput input, OutputStream backendOut) throws IOException {
streamObjects(input.spec(), input.s3(), input.keys(), backendOut);
streamObjects(input.spec(), input.s3(), input.iamService(), input.roleSession(), input.keys(), backendOut);
}
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3) {
static void releaseCopySession(CopyInput input) {
releaseRoleSession(input.roleSession(), input.spec().iamRoleArn(), input.iamService());
}
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService) {
return prepareUnload(spec, s3, iamService, null);
}
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService,
String clusterAccountId) {
return prepareUnload(spec, s3, iamService, clusterAccountId, null);
}
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
RoleSession roleSession = spec.iamRoleArn() != null
? resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
: null;
String probeKey = unloadDataKey(spec, 0);
try {
s3.authorizeAnonymousPutObject(spec.bucket(), probeKey);
if (spec.manifest()) {
s3.authorizeAnonymousPutObject(spec.bucket(), spec.prefix() + "manifest");
}
if (!spec.allowOverwrite()) {
s3.authorizeAnonymousListBucket(spec.bucket());
if (targetPrefixHasObjects(spec, s3)) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"S3 prefix s3://" + spec.bucket() + "/" + spec.prefix()
+ " is not empty; specify ALLOWOVERWRITE to overwrite", null);
if (roleSession != null) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), probeKey));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), probeKey);
if (spec.manifest()) {
String manifestKey = spec.prefix() + "manifest";
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), manifestKey));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), manifestKey);
}
if (!spec.allowOverwrite()) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.bucket()));
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
if (targetPrefixHasObjects(spec, s3)) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"S3 prefix s3://" + spec.bucket() + "/" + spec.prefix()
+ " is not empty; specify ALLOWOVERWRITE to overwrite", null);
}
}
} else {
s3.authorizeAnonymousPutObject(spec.bucket(), probeKey);
if (spec.manifest()) {
s3.authorizeAnonymousPutObject(spec.bucket(), spec.prefix() + "manifest");
}
if (!spec.allowOverwrite()) {
s3.authorizeAnonymousListBucket(spec.bucket());
if (targetPrefixHasObjects(spec, s3)) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"S3 prefix s3://" + spec.bucket() + "/" + spec.prefix()
+ " is not empty; specify ALLOWOVERWRITE to overwrite", null);
}
}
}
} catch (AwsException e) {
releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw new S3TransferException(unloadWriteSqlState(e), unloadWriteMessage(e, spec), e);
} catch (RuntimeException e) {
releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw e;
}
if (!UNLOAD_HEAP_MIB.tryAcquire(UNLOAD_INITIAL_MIB)) {
releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw new S3TransferException(SQLSTATE_CONFIGURATION_LIMIT_EXCEEDED,
"UNLOAD memory budget exhausted; retry shortly", null);
}
try {
return new S3UnloadCollector(spec, s3);
return new S3UnloadCollector(spec, s3, iamService, roleSession);
} catch (IOException e) {
UNLOAD_HEAP_MIB.release(UNLOAD_INITIAL_MIB);
releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw new S3TransferException(SQLSTATE_INTERNAL, "UNLOAD failed: " + e.getMessage(), e);
}
}
@@ -167,65 +367,82 @@ public final class S3CopySimulator {
* client). Part 4 always handles; the value exists so a later interceptor can decline.
*/
public static boolean runCopyFrom(Socket client, Socket backend,
CopyStatementParser.S3CopyFrom spec, S3Service s3,
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
char txStatus) throws IOException {
return runCopyFrom(client, backend, spec, s3, txStatus, null);
return runCopyFrom(client, backend, spec, s3, iamService, txStatus, null);
}
public static boolean runCopyFrom(Socket client, Socket backend,
CopyStatementParser.S3CopyFrom spec, S3Service s3,
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
char txStatus, IntConsumer onStatusChange) throws IOException {
return runCopyFrom(client, backend, spec, s3, iamService, null, txStatus, onStatusChange);
}
public static boolean runCopyFrom(Socket client, Socket backend,
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, char txStatus, IntConsumer onStatusChange) throws IOException {
return runCopyFrom(client, backend, spec, s3, iamService, clusterAccountId, null, txStatus, onStatusChange);
}
public static boolean runCopyFrom(Socket client, Socket backend,
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns,
char txStatus, IntConsumer onStatusChange) throws IOException {
CopyInput input;
try {
input = prepareCopy(spec, s3);
input = prepareCopy(spec, s3, iamService, clusterAccountId, associatedRoleArns);
} catch (S3TransferException e) {
LOG.debugv(e, "COPY preparation failed for s3://{0}/{1}", spec.bucket(), spec.keyOrPrefix());
sendError(client, backend, e.sqlState(), e.getMessage(), txStatus, onStatusChange);
return true;
}
OutputStream backendOut = backend.getOutputStream();
backendOut.write(PostgresWireDecoder.encodeQuery(copyBackendSql(spec)));
backendOut.flush();
PostgresWireDecoder backendDecoder = new PostgresWireDecoder(backend.getInputStream());
PostgresWireDecoder.FrontendMessage first;
try {
first = nextNonAsync(backendDecoder, client);
} catch (IOException e) {
LOG.warnv(e, "backend read failed while awaiting CopyInResponse");
closeQuietly(backend);
sendError(client, null, SQLSTATE_INTERNAL, "S3 COPY failed: backend closed or timed out", txStatus, onStatusChange);
closeQuietly(client);
return true;
}
if (first == null) {
LOG.warn("backend closed before answering the fabricated COPY");
closeQuietly(backend);
sendError(client, null, SQLSTATE_INTERNAL, "S3 COPY failed: backend closed before COPY started", txStatus, onStatusChange);
closeQuietly(client);
return true;
}
if (first.type() != 'G') {
// Backend rejected the COPY itself (e.g. no such table). Its ErrorResponse and the
// ReadyForQuery that follows are the client's one response.
forward(client, first);
drainToReadyForQuery(backendDecoder, client, onStatusChange);
return true;
}
OutputStream backendOut = backend.getOutputStream();
backendOut.write(PostgresWireDecoder.encodeQuery(copyBackendSql(spec)));
backendOut.flush();
// The CopyIn stream is open. Any failure from here is resolved with exactly one response:
// a CopyFail to the backend, whose ErrorResponse/ReadyForQuery is relayed to the client;
// or, if the backend is unreachable, one synthesized ErrorResponse/ReadyForQuery.
try {
streamCopyInput(input, backendOut);
writeCopyDone(backendOut);
drainToReadyForQuery(backendDecoder, client, onStatusChange);
} catch (RuntimeException | IOException e) {
LOG.warnv(e, "S3 COPY streaming failed; aborting the open CopyIn");
abortOpenCopyIn(client, backend, backendOut, backendDecoder, e, txStatus, onStatusChange);
PostgresWireDecoder backendDecoder = new PostgresWireDecoder(backend.getInputStream());
PostgresWireDecoder.FrontendMessage first;
try {
first = nextNonAsync(backendDecoder, client);
} catch (IOException e) {
LOG.warnv(e, "backend read failed while awaiting CopyInResponse");
closeQuietly(backend);
sendError(client, null, SQLSTATE_INTERNAL, "S3 COPY failed: backend closed or timed out", txStatus, onStatusChange);
closeQuietly(client);
return true;
}
if (first == null) {
LOG.warn("backend closed before answering the fabricated COPY");
closeQuietly(backend);
sendError(client, null, SQLSTATE_INTERNAL, "S3 COPY failed: backend closed before COPY started", txStatus, onStatusChange);
closeQuietly(client);
return true;
}
if (first.type() != 'G') {
// Backend rejected the COPY itself (e.g. no such table). Its ErrorResponse and the
// ReadyForQuery that follows are the client's one response.
forward(client, first);
drainToReadyForQuery(backendDecoder, client, onStatusChange);
return true;
}
// The CopyIn stream is open. Any failure from here is resolved with exactly one response:
// a CopyFail to the backend, whose ErrorResponse/ReadyForQuery is relayed to the client;
// or, if the backend is unreachable, one synthesized ErrorResponse/ReadyForQuery.
try {
streamCopyInput(input, backendOut);
writeCopyDone(backendOut);
drainToReadyForQuery(backendDecoder, client, onStatusChange);
} catch (RuntimeException | IOException e) {
LOG.warnv(e, "S3 COPY streaming failed; aborting the open CopyIn");
abortOpenCopyIn(client, backend, backendOut, backendDecoder, e, txStatus, onStatusChange);
}
return true;
} finally {
releaseCopySession(input);
}
return true;
}
private static void abortOpenCopyIn(Socket client, Socket backend, OutputStream backendOut,
@@ -290,9 +507,14 @@ public final class S3CopySimulator {
}
private static void streamObjects(CopyStatementParser.S3CopyFrom spec, S3Service s3,
IamService iamService, RoleSession roleSession,
List<String> keys, OutputStream backendOut) throws IOException {
byte[] buffer = new byte[CHUNK];
for (int i = 0; i < keys.size(); i++) {
if (roleSession != null) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.bucket(), keys.get(i)));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), keys.get(i));
}
S3Object object = s3.getObject(spec.bucket(), keys.get(i));
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
InputStream in = new ByteArrayInputStream(data);
@@ -492,16 +714,28 @@ public final class S3CopySimulator {
}
public static boolean runUnload(Socket client, Socket backend,
CopyStatementParser.S3Unload spec, S3Service s3, char txStatus) throws IOException {
return runUnload(client, backend, spec, s3, txStatus, null);
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, char txStatus) throws IOException {
return runUnload(client, backend, spec, s3, iamService, txStatus, null);
}
public static boolean runUnload(Socket client, Socket backend,
CopyStatementParser.S3Unload spec, S3Service s3, char txStatus,
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, char txStatus,
IntConsumer onStatusChange) throws IOException {
return runUnload(client, backend, spec, s3, iamService, null, txStatus, onStatusChange);
}
public static boolean runUnload(Socket client, Socket backend,
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, String clusterAccountId,
char txStatus, IntConsumer onStatusChange) throws IOException {
return runUnload(client, backend, spec, s3, iamService, clusterAccountId, null, txStatus, onStatusChange);
}
public static boolean runUnload(Socket client, Socket backend,
CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService, String clusterAccountId,
List<String> associatedRoleArns, char txStatus, IntConsumer onStatusChange) throws IOException {
UnloadCollector collector;
try {
collector = prepareUnload(spec, s3);
collector = prepareUnload(spec, s3, iamService, clusterAccountId, associatedRoleArns);
} catch (S3TransferException e) {
LOG.debugv(e, "UNLOAD preparation failed for s3://{0}/{1}", spec.bucket(), spec.prefix());
sendError(client, backend, e.sqlState(), e.getMessage(), txStatus, onStatusChange);
@@ -645,6 +879,8 @@ public final class S3CopySimulator {
private static final class S3UnloadCollector implements UnloadCollector {
private final CopyStatementParser.S3Unload spec;
private final S3Service s3;
private final IamService iamService;
private final RoleSession roleSession;
private final long threshold;
private final String contentType;
private final List<String> writtenKeys = new ArrayList<>();
@@ -666,9 +902,12 @@ public final class S3CopySimulator {
private int sliceIndex;
private int heldMib = UNLOAD_INITIAL_MIB;
private S3UnloadCollector(CopyStatementParser.S3Unload spec, S3Service s3) throws IOException {
private S3UnloadCollector(CopyStatementParser.S3Unload spec, S3Service s3,
IamService iamService, RoleSession roleSession) throws IOException {
this.spec = spec;
this.s3 = s3;
this.iamService = iamService;
this.roleSession = roleSession;
threshold = spec.maxFileSizeBytes() > 0 ? spec.maxFileSizeBytes() : UNLOAD_TARGET_FILE_BYTES;
contentType = spec.gzip() ? "application/gzip" : "text/plain";
acc = newAccumulator();
@@ -734,7 +973,12 @@ public final class S3CopySimulator {
if (spec.manifest()) {
try {
String key = spec.prefix() + "manifest";
s3.authorizeAnonymousPutObject(spec.bucket(), key);
if (roleSession != null) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), key));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousPutObject(spec.bucket(), key);
}
s3.putObject(spec.bucket(), key,
manifestJson(spec.bucket(), writtenKeys, writtenLengths)
.getBytes(StandardCharsets.UTF_8),
@@ -753,7 +997,7 @@ public final class S3CopySimulator {
}
closeAcc(acc, sink);
if (spec.manifest()) {
deleteWritten(s3, spec, writtenKeys);
deleteWritten(s3, iamService, spec, writtenKeys, roleSession);
}
aborted = true;
}
@@ -768,6 +1012,7 @@ public final class S3CopySimulator {
}
UNLOAD_HEAP_MIB.release(heldMib);
heldMib = 0;
releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
closed = true;
}
@@ -791,7 +1036,12 @@ public final class S3CopySimulator {
private void writePayload(byte[] payload, int index) {
String key = unloadDataKey(spec, index);
try {
s3.authorizeAnonymousPutObject(spec.bucket(), key);
if (roleSession != null) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.bucket(), key));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousPutObject(spec.bucket(), key);
}
s3.putObject(spec.bucket(), key, payload, contentType, Map.of());
} catch (AwsException e) {
fail(unloadWriteSqlState(e), unloadWriteMessage(e, spec), e);
@@ -894,7 +1144,9 @@ public final class S3CopySimulator {
}
}
private static void deleteWritten(S3Service s3, CopyStatementParser.S3Unload spec, List<String> keys) {
private static void deleteWritten(S3Service s3, IamService iamService,
CopyStatementParser.S3Unload spec, List<String> keys,
RoleSession roleSession) {
if (spec.allowOverwrite()) {
// Under ALLOWOVERWRITE a slice key may have replaced a pre-existing object, and there is no
// reliable way to tell an overwrite from a fresh write (the check and the write are not
@@ -908,7 +1160,12 @@ public final class S3CopySimulator {
// created by this operation and is safe to remove.
for (String k : keys) {
try {
s3.authorizeAnonymousDeleteObject(spec.bucket(), k);
if (roleSession != null) {
authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject", objectArn(spec.bucket(), k));
s3.authorizeSignedDeleteObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), k);
} else {
s3.authorizeAnonymousDeleteObject(spec.bucket(), k);
}
s3.deleteObject(spec.bucket(), k);
} catch (RuntimeException e) {
LOG.debugv(e, "could not remove partial UNLOAD object s3://{0}/{1}", spec.bucket(), k);
@@ -735,6 +735,30 @@ public class S3Service implements Resettable, ResourceProvider {
authorizeDeleteObject(bucketName, key, null, RequestAuthorization.unsigned());
}
/**
* Authorize {@code s3:GetObject} as a signed principal (an IAM role session's access key),
* reusing the identity-policy + resource-policy evaluation a genuine SigV4 request goes
* through. Used for Redshift {@code COPY ... IAM_ROLE '<arn>'}.
*/
public void authorizeSignedGetObject(String accessKeyId, String sessionToken, String bucketName, String key) {
authorizeGetObject(bucketName, key, null, new RequestAuthorization(true, accessKeyId, sessionToken));
}
/** Authorize a signed {@code s3:PutObject}; see {@link #authorizeSignedGetObject}. */
public void authorizeSignedPutObject(String accessKeyId, String sessionToken, String bucketName, String key) {
authorizePutObject(bucketName, key, new RequestAuthorization(true, accessKeyId, sessionToken));
}
/** Authorize a signed {@code s3:ListBucket}; see {@link #authorizeSignedGetObject}. */
public void authorizeSignedListBucket(String accessKeyId, String sessionToken, String bucketName) {
authorizeListBucket(bucketName, new RequestAuthorization(true, accessKeyId, sessionToken));
}
/** 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));
}
public void authorizeCloudFrontOacGetObject(
String bucketName, String key, String distributionArn) {
authorizeCloudFrontGetObject(
@@ -929,7 +953,7 @@ public class S3Service implements Resettable, ResourceProvider {
.orElse(false);
}
boolean isAuthEnforced() {
public boolean isAuthEnforced() {
return enforceAuth;
}