From 814232c43f2a00445421cf9ab8ca44f78bd9244f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:49:06 +0700 Subject: [PATCH] feat(firehose): load Redshift COPY with temporary credentials of the stream role (#7337) --- docs/services/firehose.md | 17 ++-- docs/services/redshift.md | 3 +- .../firehose/FirehoseRedshiftDelivery.java | 35 +++++++-- .../services/firehose/RedshiftCopySql.java | 41 +++++++++- .../floci/services/iam/IamService.java | 17 ++++ .../services/redshift/RedshiftAuditSql.java | 21 +++-- .../redshift/proxy/RedshiftRoleAccess.java | 56 ++++++++++--- .../FirehoseRedshiftDeliveryTest.java | 78 ++++++++++++++++++- .../FirehoseRedshiftRoleAccessTest.java | 2 +- .../firehose/RedshiftCopySqlTest.java | 30 +++++++ .../RedshiftAuditLogPublisherTest.java | 18 +++++ .../proxy/RedshiftRoleAccessTest.java | 52 +++++++++++++ .../redshift/proxy/S3CopySimulatorTest.java | 19 ++++- 13 files changed, 352 insertions(+), 37 deletions(-) diff --git a/docs/services/firehose.md b/docs/services/firehose.md index 24ab410a1a..c185887647 100644 --- a/docs/services/firehose.md +++ b/docs/services/firehose.md @@ -150,10 +150,13 @@ unterminated quote. One closing `;` at the very end is the exception (the API re A flush writes the batch to the intermediate S3 location, then runs `COPY [()] FROM 's3:///' ` against the cluster. A single -closing `;` in `CopyOptions` is dropped from the statement. The `COPY` names no `IAM_ROLE`: AWS gives the cluster -temporary credentials of the stream's `RoleARN`, and Floci instead lets the proxy read the staged object from its own -S3, so `RoleARN` is validated and stored but not used for the load (an `IAM_ROLE` would have to exist in IAM and be -associated with the cluster). The `COPY` goes through the cluster's wire proxy, so it behaves like a `COPY` sent by any +closing `;` in `CopyOptions` is dropped from the statement. The `COPY` names no `IAM_ROLE`: as on AWS, the cluster is +given temporary credentials of the stream's `RoleARN`, which need not be associated with it. When IAM knows the role, +Floci mints a fresh short-lived session for every attempt, passes it as `CREDENTIALS 'aws_access_key_id=...;aws_secret_access_key=...;token=...'` +and releases it afterwards, so the proxy reads the staged object as that role (see +[Redshift COPY from S3](redshift.md#copy-from-s3)). The secret and token are masked in any error the delivery +reports. When IAM does not know the role, which only passes with enforcement off, the `COPY` carries no credentials. +The `COPY` goes through the cluster's wire proxy, so it behaves like a `COPY` sent by any other client (see [Redshift COPY from S3](redshift.md#copy-from-s3)). Credentials come from `Username` and `Password`, or from the secret in `SecretsManagerConfiguration` when `Enabled` is true (the secret JSON needs `username` and `password`). An empty `DataTableColumns` omits the column list, so the proxy discovers the table columns. @@ -174,7 +177,7 @@ holding the load back or re-staging the batch, so that batch then has no backup With [IAM enforcement](iam.md) on, a batch is staged and loaded only if the roles involved are allowed to. The role of the intermediate `S3Configuration` must trust `firehose.amazonaws.com` (a trust policy condition on `aws:SourceArn` is matched against the delivery stream ARN) and allow `s3:PutObject` on the staged object, and the destination `RoleARN` must trust -the same principal and allow `s3:GetObject` on it. Identity policies, permissions boundaries and SCPs all count, and a +the same principal and allow `s3:GetObject` on it and `s3:ListBucket` on the intermediate bucket. Identity policies, permissions boundaries and SCPs all count, and a role of another account is refused. A refused staging write keeps the records buffered and tries again at the next flush, exactly like a failed S3 write. A refused load follows the usual retry path against the object already staged, so the batch is not staged twice, and once the `RetryOptions` window is over the batch is given up and its staged object @@ -205,10 +208,6 @@ Floci does not write the `redshift_failed` manifest objects that AWS creates aft `RoleArn`, buffer hints). Those defaults are carried over from the probed S3 behavior and not probed for Redshift specifically. With `S3BackupMode` enabled, the backup object holds the untransformed source records, even when the Lambda processor drops every record. -- The role checks above are authorization only: the `COPY` still carries no credentials, so the proxy reads the staged - object as an anonymous client. With S3 - authorization enforced and a private intermediate bucket the load fails and the staged object stays in S3; use a - bucket the anonymous principal can read, or leave enforcement off. - `CopyOptions` are validated for shape only. The `COPY` emulation does not implement every Redshift option (`LZOP`, `BZIP2`, `ZSTD`, `PARQUET` and others): such a statement is forwarded to PostgreSQL and fails, and the staged object stays in S3; retrying failed loads will follow in a separate change. Firehose never writes an `LZOP` object, diff --git a/docs/services/redshift.md b/docs/services/redshift.md index a87e663cae..48d4c363f2 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -837,7 +837,8 @@ order) through its own S3 service and streams the rows into the backing PostgreS 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 + stored, and the statement text keeps them out of Floci's own messages. 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 diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDelivery.java b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDelivery.java index 9f6e7afd31..d0abbd996e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDelivery.java +++ b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDelivery.java @@ -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". diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySql.java b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySql.java index bf881dc259..436ddc365e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySql.java +++ b/src/main/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySql.java @@ -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. * - *

{@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. + *

{@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(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 854288d582..3de9c61a00 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -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> 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; + + /** + * 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> effectiveScpLevels(String accountId) { + return scpProvider != null && scpProvider.isResolvable() + ? scpProvider.get().effectiveScpLevels(accountId) : null; + } + @Inject public IamService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, Clock clock) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditSql.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditSql.java index e12eab1f98..bb13b248f1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditSql.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditSql.java @@ -96,8 +96,8 @@ public final class RedshiftAuditSql { public static String sanitize(String sql) { List 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 tokens, List redactions) { + private static void collectSecretRedactions(String sql, List tokens, List 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 diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java index fdb9b4bc85..3f96833239 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java @@ -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 role = iamService.findRole(parsed.accountId(), roleName) - .filter(found -> IamService.roleArnMatches(iamRoleArn, found)); + Optional 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 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> 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> 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> context) { + List> 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 diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDeliveryTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDeliveryTest.java index d0e1e592a6..cdf6676b81 100644 --- a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDeliveryTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftDeliveryTest.java @@ -4,7 +4,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription; 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.model.IamRole; import io.github.hectorvent.floci.services.redshift.RedshiftService; import io.github.hectorvent.floci.services.redshift.model.Cluster; import io.github.hectorvent.floci.services.redshift.model.Endpoint; @@ -18,19 +20,24 @@ import org.junit.jupiter.api.Test; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; 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.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -43,6 +50,7 @@ class FirehoseRedshiftDeliveryTest { private RedshiftServerlessService serverless; private SecretsManagerService secrets; private ServiceRoleAuthorizer roleAuthorizer; + private IamService iamService; private final List executed = new ArrayList<>(); private FirehoseRedshiftDelivery delivery; @@ -56,7 +64,8 @@ class FirehoseRedshiftDeliveryTest { when(redshift.describeClustersForAccount("000000000000", "c1")).thenReturn(List.of(cluster)); serverless = mock(RedshiftServerlessService.class); roleAuthorizer = mock(ServiceRoleAuthorizer.class); - delivery = new FirehoseRedshiftDelivery(redshift, serverless, secrets, roleAuthorizer, mapper, + iamService = mock(IamService.class); + delivery = new FirehoseRedshiftDelivery(redshift, serverless, secrets, roleAuthorizer, iamService, mapper, (url, user, password, sql) -> executed.add(new String[] {url, user, password, sql})); } @@ -234,6 +243,71 @@ class FirehoseRedshiftDeliveryTest { assertEquals("COPY events FROM 's3://stage/k1' json 'auto'", executed.get(0)[3]); } + private void knownLoadRole() { + when(iamService.findRole("000000000000", "firehose")) + .thenReturn(Optional.of(new IamRole("id-firehose", "firehose", "/", LOAD_ROLE, "{}"))); + } + + private static String sessionKey(String sql) { + return sql.substring(sql.indexOf("aws_access_key_id=") + "aws_access_key_id=".length(), sql.indexOf(';')); + } + + @Test + void loadsWithTemporaryCredentialsOfTheDestinationRole() throws Exception { + knownLoadRole(); + + delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1"); + + String sql = executed.get(0)[3]; + assertTrue(sql.startsWith("COPY events FROM 's3://stage/k1' CREDENTIALS 'aws_access_key_id=ASIA"), sql); + assertTrue(sql.contains(";aws_secret_access_key="), sql); + assertTrue(sql.contains(";token="), sql); + assertTrue(sql.endsWith("' json 'auto'"), sql); + verify(iamService).registerSessionForAccount(eq("000000000000"), anyString(), anyString(), anyString(), + eq(LOAD_ROLE), any(Instant.class), isNull()); + } + + @Test + void everyAttemptMintsFreshCredentialsAndReleasesThem() throws Exception { + knownLoadRole(); + + delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1"); + delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1"); + + assertNotEquals(sessionKey(executed.get(0)[3]), sessionKey(executed.get(1)[3])); + verify(iamService, times(2)).unregisterSession(eq("000000000000"), anyString()); + } + + @Test + void aFailedCopyNeitherLeaksCredentialsIntoTheErrorNorKeepsTheSession() throws Exception { + knownLoadRole(); + List sent = new ArrayList<>(); + FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets, + roleAuthorizer, iamService, mapper, (url, user, password, sql) -> { + sent.add(sql); + throw new SQLException("rejected: " + sql, "XX000"); + }); + + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> failing.copy("000000000000", "us-east-1", destination(), "stage", "k1")); + + String secret = sent.get(0).substring(sent.get(0).indexOf("aws_secret_access_key=") + 22, + sent.get(0).indexOf(";token=")); + String token = sent.get(0).substring(sent.get(0).indexOf(";token=") + 7, sent.get(0).indexOf("' json")); + assertFalse(e.getMessage().contains(secret), e.getMessage()); + assertFalse(e.getMessage().contains(token), e.getMessage()); + verify(iamService).unregisterSession(eq("000000000000"), anyString()); + } + + @Test + void aRoleIamDoesNotKnowLoadsWithoutCredentials() throws Exception { + delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1"); + + assertFalse(executed.get(0)[3].contains("CREDENTIALS"), executed.get(0)[3]); + verify(iamService, never()).registerSessionForAccount(anyString(), anyString(), anyString(), anyString(), + anyString(), any(Instant.class), any()); + } + @Test void secretOverridesInlineCredentialsWhenEnabled() throws Exception { RedshiftDestination dest = destination(); @@ -275,7 +349,7 @@ class FirehoseRedshiftDeliveryTest { @Test void jdbcFailureIsWrappedWithTableClusterAndSqlState() { FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets, - roleAuthorizer, mapper, + roleAuthorizer, iamService, mapper, (url, user, password, sql) -> { throw new SQLException("relation \"events\" does not exist", "42P01"); }); diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftRoleAccessTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftRoleAccessTest.java index 6e382412d2..8af13a63f6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftRoleAccessTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/firehose/FirehoseRedshiftRoleAccessTest.java @@ -69,7 +69,7 @@ class FirehoseRedshiftRoleAccessTest { ServiceRoleAuthorizer authorizer = new ServiceRoleAuthorizer(config, iamService, evaluator, new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider); delivery = new FirehoseRedshiftDelivery(mock(RedshiftService.class), mock(RedshiftServerlessService.class), - mock(SecretsManagerService.class), authorizer, new ObjectMapper(), + mock(SecretsManagerService.class), authorizer, iamService, new ObjectMapper(), (url, user, password, sql) -> { }); } diff --git a/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySqlTest.java b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySqlTest.java index 9ff89dea34..a08cb07476 100644 --- a/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySqlTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/firehose/RedshiftCopySqlTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.firehose; +import io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -126,6 +127,35 @@ class RedshiftCopySqlTest { assertEquals("COPY events FROM 's3://stage/2026/10/19/f.gz' json 'auto' gzip", sql); } + @Test + void buildPutsCredentialsRightAfterTheSourceAndBeforeTheOptions() { + RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAEXAMPLE", "s3cr3t/+x", "tok=="); + + String sql = RedshiftCopySql.build("events", "id, name", "stage", "k", "json 'auto'", session); + + assertEquals("COPY events (id, name) FROM 's3://stage/k' CREDENTIALS " + + "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=s3cr3t/+x;token=tok==' json 'auto'", sql); + } + + @Test + void buildRefusesCredentialsItCannotQuoteWithoutEchoingThem() { + RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAEXAMPLE", "bad'secret", "tok"); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> RedshiftCopySql.build("t", null, "b", "k", null, session)); + + assertFalse(e.getMessage().contains("bad"), e.getMessage()); + } + + @Test + void redactHidesTheSecretAndTokenOnly() { + RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAEXAMPLE", "s3cr3t", "t0k3n9"); + + assertEquals("key ASIAEXAMPLE secret=*** token=***", + RedshiftCopySql.redact("key ASIAEXAMPLE secret=s3cr3t token=t0k3n9", session)); + assertEquals("plain", RedshiftCopySql.redact("plain", null)); + } + @Test void buildDropsTheClosingTerminatorOfTheApiReferenceExample() { String sql = RedshiftCopySql.build("t", null, "b", "k", "delimiter '\\t' lzop;"); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditLogPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditLogPublisherTest.java index 51c565eac7..de44898ae9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditLogPublisherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftAuditLogPublisherTest.java @@ -116,6 +116,24 @@ class RedshiftAuditLogPublisherTest { "ALTER USER alice PASSWORD 'top-secret'")); } + @Test + void redactsCopyCredentialClausesFromActivityRecords() { + assertEquals("COPY t FROM 's3://b/k' ACCESS_KEY_ID 'AKIAEXAMPLE' SECRET_ACCESS_KEY '[REDACTED]' " + + "SESSION_TOKEN '[REDACTED]'", + RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' ACCESS_KEY_ID 'AKIAEXAMPLE' " + + "SECRET_ACCESS_KEY 'top-secret' SESSION_TOKEN 'tok'")); + assertEquals("COPY t FROM 's3://b/k' ACCESS_KEY_ID AS 'AKIAEXAMPLE' SECRET_ACCESS_KEY AS '[REDACTED]' " + + "SESSION_TOKEN AS '[REDACTED]'", + RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' ACCESS_KEY_ID AS 'AKIAEXAMPLE' " + + "SECRET_ACCESS_KEY AS 'top-secret' SESSION_TOKEN AS 'tok'")); + assertEquals("COPY t FROM 's3://b/k' CREDENTIALS '[REDACTED]' CSV", + RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' " + + "CREDENTIALS 'aws_access_key_id=AKIA;aws_secret_access_key=top-secret' CSV")); + assertEquals("COPY t FROM 's3://b/k' CREDENTIALS AS '[REDACTED]' CSV", + RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' " + + "CREDENTIALS AS 'aws_access_key_id=AKIA;aws_secret_access_key=top-secret' CSV")); + } + @ParameterizedTest @ValueSource(strings = { "ALTER USER alice PASSWORD /* rotation */ 'secret'", diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccessTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccessTest.java index 3fe5cf287b..2c2186bc2d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccessTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccessTest.java @@ -17,8 +17,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; 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.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -120,6 +122,26 @@ class RedshiftRoleAccessTest { eq(session.sessionToken()), eq(held), any(Instant.class), isNull()); } + @Test + void findRoleLooksUpTheRoleHonouringItsPath() { + String held = "arn:aws:iam::111111111111:role/app/spectrum-role"; + String otherPath = "arn:aws:iam::111111111111:role/sandbox/spectrum-role"; + IamService iamService = iamServiceWithRole(TRUST_POLICY, held); + + assertTrue(RedshiftRoleAccess.findRole(held, iamService).isPresent()); + assertTrue(RedshiftRoleAccess.findRole(otherPath, iamService).isEmpty()); + assertTrue(RedshiftRoleAccess.findRole(ROLE_ARN, iamService).isEmpty()); + assertTrue(RedshiftRoleAccess.findRole("not-an-arn", iamService).isEmpty()); + assertTrue(RedshiftRoleAccess.findRole("arn:aws:iam::111111111111:user/someone", iamService).isEmpty()); + assertTrue(RedshiftRoleAccess.findRole(null, iamService).isEmpty()); + + assertTrue(RedshiftRoleAccess.roleExists(held, iamService)); + assertFalse(RedshiftRoleAccess.roleExists(otherPath, iamService)); + assertFalse(RedshiftRoleAccess.roleExists(ROLE_ARN, iamService)); + assertFalse(RedshiftRoleAccess.roleExists("not-an-arn", iamService)); + assertFalse(RedshiftRoleAccess.roleExists(null, iamService)); + } + @Test void resolveRoleSessionRefusesARoleWhoseTrustPolicyExcludesRedshift() { assertRefused("trust policy", ROLE_ARN, iamServiceWithRole(EC2_TRUST_POLICY), ACCOUNT, List.of(ROLE_ARN)); @@ -230,4 +252,34 @@ class RedshiftRoleAccessTest { // No exception, and resolvePrincipalContext is never consulted when enforcement is off. verifyNoInteractions(iamService); } + + @Test + void authorizeRoleActionSuppliesPrincipalArnToOrganizationPolicies() { + authorizeRoleWithOrganizationPolicy(ROLE_ARN); + } + + @Test + void authorizeRoleActionDeniesWhenPrincipalArnDoesNotMatchApprovedRoleInOrganizationPolicy() { + String otherRole = "arn:aws:iam::111111111111:role/other-role"; + S3CopySimulator.S3TransferException exception = assertThrows(S3CopySimulator.S3TransferException.class, + () -> authorizeRoleWithOrganizationPolicy(otherRole)); + + assertThat(exception.sqlState(), equalTo("42501")); + assertThat(exception.getMessage(), containsString("S3 access denied")); + } + + private void authorizeRoleWithOrganizationPolicy(String roleArn) { + S3Service s3 = mock(S3Service.class); + when(s3.isAuthEnforced()).thenReturn(true); + IamService iamService = mock(IamService.class); + when(iamService.resolvePrincipalContext(roleArn)).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}"""))); + when(iamService.effectiveScpLevels(ACCOUNT)).thenReturn(List.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"*","Resource":"*"}, + {"Effect":"Deny","Action":"s3:GetObject","Resource":"*", + "Condition":{"ArnNotLike":{"aws:PrincipalArn":"%s"}}}]}""".formatted(ROLE_ARN)))); + + RedshiftRoleAccess.authorizeRoleAction(s3, iamService, roleArn, "s3:GetObject", "arn:aws:s3:::bucket/key"); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulatorTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulatorTest.java index a153dba735..fbd8e3e400 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulatorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulatorTest.java @@ -43,6 +43,7 @@ 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.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; @@ -176,6 +177,22 @@ class S3CopySimulatorTest { return iamService; } + @Test + void anOrganizationPolicyDenyStillAppliesToTheKeysCopy() { + IamService iamService = knownKey(); + when(iamService.findAccountForAccessKeyId("ASIAEXAMPLE")).thenReturn(Optional.of("222222222222")); + when(iamService.effectiveScpLevels("222222222222")).thenReturn(List.of(List.of(policy( + "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}," + + "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}")))); + when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy( + "{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}")))); + + S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class, + () -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService)); + + assertEquals("42501", error.sqlState()); + } + @Test void aConditionalDenyOnThePrincipalArnStillAppliesToTheKeysCopy() { IamService iamService = knownKey(); @@ -233,7 +250,7 @@ class S3CopySimulatorTest { S3CopySimulator.prepareCopy(keyCopy(), s3, iamService); - verify(iamService).findAccountForAccessKeyId("ASIAEXAMPLE"); + verify(iamService, atLeastOnce()).findAccountForAccessKeyId("ASIAEXAMPLE"); } @Test