feat(firehose): load Redshift COPY with temporary credentials of the stream role (#7337)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-03 13:49:06 -04:00
1 parent fca988cea1
commit 814232c43f
13 files changed
+352 -37

No files matched your search

@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.DatabaseSecretCredentials;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
@@ -21,6 +22,7 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
@@ -37,6 +39,8 @@ public class FirehoseRedshiftDelivery {
private static final int CONNECT_TIMEOUT_SECONDS = 10;
private static final int SOCKET_TIMEOUT_SECONDS = 150;
private static final String FIREHOSE_PRINCIPAL = ServicePrincipals.of("firehose");
/** Outlives one COPY, whose socket timeout is the longest it can run. */
private static final Duration LOAD_CREDENTIALS_TTL = Duration.ofMinutes(15);
/** Seam for tests; production opens a real JDBC connection. */
interface SqlRunner {
@@ -53,24 +57,27 @@ public class FirehoseRedshiftDelivery {
private final RedshiftServerlessService serverlessService;
private final SecretsManagerService secretsManagerService;
private final ServiceRoleAuthorizer roleAuthorizer;
private final IamService iamService;
private final ObjectMapper mapper;
private final SqlRunner runner;
@Inject
public FirehoseRedshiftDelivery(RedshiftService redshiftService, RedshiftServerlessService serverlessService,
SecretsManagerService secretsManagerService,
ServiceRoleAuthorizer roleAuthorizer, ObjectMapper mapper) {
this(redshiftService, serverlessService, secretsManagerService, roleAuthorizer, mapper,
ServiceRoleAuthorizer roleAuthorizer, IamService iamService,
ObjectMapper mapper) {
this(redshiftService, serverlessService, secretsManagerService, roleAuthorizer, iamService, mapper,
FirehoseRedshiftDelivery::runJdbc);
}
FirehoseRedshiftDelivery(RedshiftService redshiftService, RedshiftServerlessService serverlessService,
SecretsManagerService secretsManagerService, ServiceRoleAuthorizer roleAuthorizer,
ObjectMapper mapper, SqlRunner runner) {
IamService iamService, ObjectMapper mapper, SqlRunner runner) {
this.redshiftService = redshiftService;
this.serverlessService = serverlessService;
this.secretsManagerService = secretsManagerService;
this.roleAuthorizer = roleAuthorizer;
this.iamService = iamService;
this.mapper = mapper;
this.runner = runner;
}
@@ -126,20 +133,36 @@ public class FirehoseRedshiftDelivery {
: clusterBackend(accountId, target);
String[] credentials = credentials(destination, backend, region);
RedshiftDestination.CopyCommand command = destination.getCopyCommand();
String sql = RedshiftCopySql.build(command.getDataTableName(), command.getDataTableColumns(), bucket, key,
command.getCopyOptions());
String jdbcUrl = "jdbc:postgresql://" + backend.host() + ":" + backend.port() + "/" + backend.database()
+ "?preferQueryMode=simple";
// Minted per attempt: the retry loop calls copy again, and credentials from the last try may have expired.
RedshiftRoleAccess.RoleSession loadCredentials = mintLoadCredentials(destination.getRoleArn());
try {
String sql = RedshiftCopySql.build(command.getDataTableName(), command.getDataTableColumns(), bucket, key,
command.getCopyOptions(), loadCredentials);
runner.execute(jdbcUrl, credentials[0], credentials[1], sql);
} catch (SQLException e) {
throw new IllegalStateException("COPY into " + command.getDataTableName() + " on "
+ backend.description() + " failed (SQLSTATE " + e.getSQLState() + "): " + e.getMessage(), e);
+ backend.description() + " failed (SQLSTATE " + e.getSQLState() + "): "
+ RedshiftCopySql.redact(e.getMessage(), loadCredentials), e);
} finally {
RedshiftRoleAccess.releaseRoleSession(loadCredentials, destination.getRoleArn(), iamService);
}
LOG.debugv("Firehose copied s3://{0}/{1} into {2} on {3}", bucket, key,
command.getDataTableName(), backend.description());
}
/**
* Temporary credentials of the destination's {@code RoleARN}, which is what Firehose loads with. The trust
* and permissions were checked by {@link #requireLoadAccess}, so only the role's existence is left: with
* enforcement off a stream may name a role IAM does not know, and the load then runs without credentials.
*/
private RedshiftRoleAccess.RoleSession mintLoadCredentials(String roleArn) {
return RedshiftRoleAccess.roleExists(roleArn, iamService)
? RedshiftRoleAccess.resolveRoleSession(roleArn, iamService, null, null, LOAD_CREDENTIALS_TTL)
: null;
}
private Backend clusterBackend(String accountId, RedshiftJdbcUrl target) {
Cluster cluster = redshiftService.describeClustersForAccount(accountId, target.clusterIdentifier()).get(0);
// The database name in the URL is ignored: the emulated container database is always "dev".
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@@ -13,9 +15,10 @@ import java.util.regex.Pattern;
* quoting rules rather than a simplified one, because the statement is later run in simple query mode, where
* PostgreSQL executes every {@code ;}-separated statement it receives.
*
* <p>{@link #build} adds no {@code IAM_ROLE} or credentials. AWS hands the cluster temporary credentials of the
* stream's role; the wire proxy reads a staged object straight from Floci's S3 when the statement names no role,
* whereas an {@code IAM_ROLE} would have to exist in IAM and be associated with the cluster.
* <p>{@link #build} adds an {@code IAM_ROLE} never: the stream's role is not necessarily associated with the cluster.
* AWS hands the cluster temporary credentials of that role, so a caller that has minted them passes them in and they
* go in as a {@code CREDENTIALS} clause, which the wire proxy reads S3 with. Without them the proxy reads the staged
* object as an unsigned request.
*/
final class RedshiftCopySql {
@@ -24,10 +27,17 @@ final class RedshiftCopySql {
private static final Pattern SIMPLE_NAME = Pattern.compile(NAME);
private static final Pattern BUCKET = Pattern.compile("[^/'\"\\s]+");
private static final Pattern OBJECT_KEY = Pattern.compile("[^'\"\\s]*");
private static final Pattern CREDENTIAL_VALUE = Pattern.compile("[A-Za-z0-9+/=_.-]+");
private RedshiftCopySql() {}
static String build(String table, String columns, String bucket, String key, String copyOptions) {
return build(table, columns, bucket, key, copyOptions, null);
}
/** @param credentials temporary credentials the COPY reads S3 with, or null to send none */
static String build(String table, String columns, String bucket, String key, String copyOptions,
RedshiftRoleAccess.RoleSession credentials) {
if (!isValidTableName(table)) {
throw new IllegalArgumentException("DataTableName is not a table identifier: " + table);
}
@@ -50,6 +60,9 @@ final class RedshiftCopySql {
sql.append(" (").append(String.join(", ", trimmed)).append(')');
}
sql.append(" FROM 's3://").append(bucket).append('/').append(key).append('\'');
if (credentials != null) {
sql.append(" CREDENTIALS '").append(credentialsClause(credentials)).append('\'');
}
// The closing terminator is dropped: the statement is sent on its own, and a second one cannot follow it.
String options = copyOptions == null ? "" : withoutTrailingTerminator(copyOptions).trim();
if (!options.isEmpty()) {
@@ -58,6 +71,28 @@ final class RedshiftCopySql {
return sql.toString();
}
/** The message never echoes a value: a credential that cannot be quoted safely must not reach a log either. */
private static String credentialsClause(RedshiftRoleAccess.RoleSession credentials) {
for (String value : List.of(credentials.accessKeyId(), credentials.secretAccessKey(),
credentials.sessionToken())) {
if (!CREDENTIAL_VALUE.matcher(value).matches()) {
throw new IllegalArgumentException("The temporary credentials for the COPY contain a character "
+ "that cannot be placed in a CREDENTIALS clause.");
}
}
return "aws_access_key_id=" + credentials.accessKeyId()
+ ";aws_secret_access_key=" + credentials.secretAccessKey()
+ ";token=" + credentials.sessionToken();
}
/** Replaces the secret and token of {@code credentials} in {@code text}, for anything that leaves the process. */
static String redact(String text, RedshiftRoleAccess.RoleSession credentials) {
if (text == null || credentials == null) {
return text;
}
return text.replace(credentials.secretAccessKey(), "***").replace(credentials.sessionToken(), "***");
}
static boolean isValidTableName(String table) {
return table != null && QUALIFIED_NAME.matcher(table).matches();
}
@@ -52,6 +52,7 @@ import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -446,6 +447,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
private final Map<String, Map<String, IamPolicy>> awsManagedPoliciesByPartition = new ConcurrentHashMap<>();
/**
* Lazy so IAM never depends on Organizations at construction (Organizations already depends on
* IAM). Null when the service is built by hand, where no organization exists.
*/
@Inject
Instance<ScpProvider> scpProvider;
/**
* The service control policy levels that cap {@code accountId}, or null when SCPs do not apply
* to it, for callers that evaluate a principal outside the request filter.
*/
public List<List<String>> effectiveScpLevels(String accountId) {
return scpProvider != null && scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId) : null;
}
@Inject
public IamService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver,
Clock clock) {
@@ -96,8 +96,8 @@ public final class RedshiftAuditSql {
public static String sanitize(String sql) {
List<Redaction> redactions = new ArrayList<>();
collectPasswordRedactions(sql, tokens(sql), redactions);
collectPasswordRedactions(sql, tokens(sql, true), redactions);
collectSecretRedactions(sql, tokens(sql), redactions);
collectSecretRedactions(sql, tokens(sql, true), redactions);
redactions.sort(Comparator.comparingInt(Redaction::start));
StringBuilder sanitized = new StringBuilder(sql.length());
int copied = 0;
@@ -110,12 +110,17 @@ public final class RedshiftAuditSql {
return sanitized.append(sql, copied, sql.length()).toString();
}
private static void collectPasswordRedactions(String sql, List<Token> tokens, List<Redaction> redactions) {
private static void collectSecretRedactions(String sql, List<Token> tokens, List<Redaction> redactions) {
for (int i = 0; i + 1 < tokens.size(); i++) {
if (!tokens.get(i).keyword("PASSWORD")) {
if (!secretClause(tokens.get(i))) {
continue;
}
Token value = tokens.get(++i);
int valueIndex = i + 1;
if (tokens.get(valueIndex).keyword("AS") && valueIndex + 1 < tokens.size()) {
valueIndex++;
}
Token value = tokens.get(valueIndex);
i = valueIndex;
if (value.kind() == Kind.SYMBOL) {
continue;
}
@@ -132,6 +137,12 @@ public final class RedshiftAuditSql {
}
}
/** PASSWORD of a user statement, and the COPY or UNLOAD clauses that carry a secret key or session token. */
private static boolean secretClause(Token token) {
return token.keyword("PASSWORD") || token.keyword("CREDENTIALS") || token.keyword("SECRET_ACCESS_KEY")
|| token.keyword("SESSION_TOKEN");
}
private static boolean ambiguousPasswordString(Token token) {
String text = token.text();
return token.kind() == Kind.STRING && text.indexOf('\\') >= 0
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.ServicePrincipals;
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.IamService.CallerArns;
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;
@@ -96,9 +97,7 @@ public final class RedshiftRoleAccess {
}
// The path counts, as STS AssumeRole takes it: an ARN naming the role under another path names no role,
// so the iam:PassRole check on the ARN the cluster was given covers the role assumed here.
String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
Optional<IamRole> role = iamService.findRole(parsed.accountId(), roleName)
.filter(found -> IamService.roleArnMatches(iamRoleArn, found));
Optional<IamRole> role = findRole(iamRoleArn, iamService);
if (role.isEmpty()) {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + iamRoleArn + "' could not be assumed: role does not exist", null);
@@ -124,6 +123,32 @@ public final class RedshiftRoleAccess {
return new RoleSession(accessKeyId, secretAccessKey, sessionToken);
}
/**
* Looks up the role {@code iamRoleArn} names, honouring its path through {@link IamService#roleArnMatches}.
*/
public static Optional<IamRole> findRole(String iamRoleArn, IamService iamService) {
if (iamRoleArn == null || !AwsArnUtils.isArn(iamRoleArn)) {
return Optional.empty();
}
AwsArnUtils.Arn parsed;
try {
parsed = AwsArnUtils.parse(iamRoleArn);
} catch (IllegalArgumentException e) {
return Optional.empty();
}
if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
return Optional.empty();
}
String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
return iamService.findRole(parsed.accountId(), roleName)
.filter(found -> IamService.roleArnMatches(iamRoleArn, found));
}
/** Returns whether {@code iamRoleArn} names a role IAM knows. */
public static boolean roleExists(String iamRoleArn, IamService iamService) {
return findRole(iamRoleArn, iamService).isPresent();
}
/**
* 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
@@ -179,9 +204,8 @@ public final class RedshiftRoleAccess {
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) {
String accountId = iamService.findAccountForAccessKeyId(session.accessKeyId()).orElse(null);
if (!allowedUnderOrganizationPolicies(iamService, caller, accountId, action, resourceArn, context)) {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for access key '" + session.accessKeyId() + "': " + action + " on "
+ resourceArn, null);
@@ -217,14 +241,28 @@ public final class RedshiftRoleAccess {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"IAM Role '" + roleArn + "' could not be assumed: " + e.getMessage(), e);
}
IamPolicyEvaluator.SimulationDecision decision =
ROLE_POLICY_EVALUATOR.simulatePrincipalPolicy(caller, action, resourceArn, conditionContext);
if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
Map<String, List<String>> context = new HashMap<>(conditionContext);
new CallerArns(roleArn, roleArn).putPrincipalKeys(context);
if (!allowedUnderOrganizationPolicies(iamService, caller, AwsArnUtils.parse(roleArn).accountId(), action,
resourceArn, context)) {
throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"S3 access denied for IAM Role '" + roleArn + "': " + action + " on " + resourceArn, null);
}
}
/**
* Identity, session and boundary policies as {@code simulatePrincipalPolicy} reads them, plus the
* service control policies of the principal's account, which that simulation leaves out.
*/
private static boolean allowedUnderOrganizationPolicies(IamService iamService, CallerContext caller,
String accountId, String action, String resourceArn,
Map<String, List<String>> context) {
List<List<String>> scpLevels = accountId == null ? null : iamService.effectiveScpLevels(accountId);
CallerContext capped = scpLevels == null ? caller : caller.withScpLevels(scpLevels);
return ROLE_POLICY_EVALUATOR.evaluate(capped, List.of(), action, resourceArn, context)
== IamPolicyEvaluator.Decision.ALLOW;
}
/**
* Authorizes {@code s3:ListBucket} as the role's signed session: the identity policy first, then
* the bucket policy through the signed-request path COPY uses, so a bucket-policy deny applies