feat(firehose): authorize the roles of a Redshift destination (#7296)

* feat(firehose): authorize the roles of a Redshift destination

With IAM enforcement on, check the role of the intermediate S3Configuration
(trust firehose.amazonaws.com, s3:PutObject) before a batch is staged, and
the destination RoleARN (same trust, s3:GetObject) before the COPY runs.
A refused staging keeps the records buffered; a refused load retries against
the object already staged, so a batch is never staged twice.

The COPY still carries no credentials; minting them and authenticating the
proxy's S3 read come in follow-up changes.

* fix(firehose): guard transform error writes and validate staging roles

Check staging role permissions on Lambda transformation error output before writing to S3 so rejected writes keep batches buffered. Validate S3 destination role ARNs during destination creation/update and ensure empty roles are not exempt from authorization checks when IAM enforcement is active.

* fix(firehose): keep ordinary S3 streams on 4-arg transform overload

Avoid calling the 5-arg transform overload for ordinary S3 streams so existing 4-arg mocks (such as in FirehoseDataFormatConversionTest) continue to match.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-02 09:43:36 -04:00
1 parent b821dcd718
commit 2be776aa4f
10 files changed
+424 -18

No files matched your search

@@ -29,6 +29,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
/**
* Runs a flushed batch through the stream's Lambda transform before it is
@@ -94,6 +95,16 @@ public class FirehoseLambdaTransformer {
public Outcome transform(DeliveryStreamDescription stream, String bucket, List<byte[]> records,
Instant deliveryTime) {
return transform(stream, bucket, records, deliveryTime, errorKey -> { });
}
/**
* Same as the four argument form, with {@code errorOutputGuard} called with the key of the error object just
* before it is written. A guard that throws keeps the object from being written, so a caller can refuse a write
* its delivery role is not allowed to make.
*/
public Outcome transform(DeliveryStreamDescription stream, String bucket, List<byte[]> records,
Instant deliveryTime, Consumer<String> errorOutputGuard) {
S3Destination s3 = stream.s3Destination();
Processor processor = lambdaProcessor(stream);
if (processor == null) {
@@ -126,7 +137,7 @@ public class FirehoseLambdaTransformer {
String errorKey = failures.isEmpty() ? null
: writeErrorOutput(stream, s3, bucket, failures, deliveryTime, functionArn,
invocation.attemptsMade());
invocation.attemptsMade(), errorOutputGuard);
return new Outcome(delivered, dropped, failures.size(), errorKey);
}
@@ -366,9 +377,10 @@ public class FirehoseLambdaTransformer {
*/
private String writeErrorOutput(DeliveryStreamDescription stream, S3Destination s3, String bucket,
List<FailedRecord> failures, Instant deliveryTime,
String functionArn, int attemptsMade) {
String functionArn, int attemptsMade, Consumer<String> errorOutputGuard) {
String errorKey = S3ObjectKeyResolver.resolveErrorKey(s3, stream.getDeliveryStreamName(),
stream.getVersionId(), deliveryTime, ERROR_OUTPUT_TYPE);
errorOutputGuard.accept(errorKey);
ByteArrayOutputStream body = new ByteArrayOutputStream();
for (FailedRecord failure : failures) {
Map<String, Object> line = new LinkedHashMap<>();
@@ -3,9 +3,13 @@ package io.github.hectorvent.floci.services.firehose;
import com.fasterxml.jackson.databind.ObjectMapper;
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.ServiceRoleAuthorizer;
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
@@ -17,6 +21,8 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
/**
@@ -30,6 +36,7 @@ public class FirehoseRedshiftDelivery {
private static final Logger LOG = Logger.getLogger(FirehoseRedshiftDelivery.class);
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");
/** Seam for tests; production opens a real JDBC connection. */
interface SqlRunner {
@@ -45,24 +52,66 @@ public class FirehoseRedshiftDelivery {
private final RedshiftService redshiftService;
private final RedshiftServerlessService serverlessService;
private final SecretsManagerService secretsManagerService;
private final ServiceRoleAuthorizer roleAuthorizer;
private final ObjectMapper mapper;
private final SqlRunner runner;
@Inject
public FirehoseRedshiftDelivery(RedshiftService redshiftService, RedshiftServerlessService serverlessService,
SecretsManagerService secretsManagerService, ObjectMapper mapper) {
this(redshiftService, serverlessService, secretsManagerService, mapper, FirehoseRedshiftDelivery::runJdbc);
SecretsManagerService secretsManagerService,
ServiceRoleAuthorizer roleAuthorizer, ObjectMapper mapper) {
this(redshiftService, serverlessService, secretsManagerService, roleAuthorizer, mapper,
FirehoseRedshiftDelivery::runJdbc);
}
FirehoseRedshiftDelivery(RedshiftService redshiftService, RedshiftServerlessService serverlessService,
SecretsManagerService secretsManagerService, ObjectMapper mapper, SqlRunner runner) {
SecretsManagerService secretsManagerService, ServiceRoleAuthorizer roleAuthorizer,
ObjectMapper mapper, SqlRunner runner) {
this.redshiftService = redshiftService;
this.serverlessService = serverlessService;
this.secretsManagerService = secretsManagerService;
this.roleAuthorizer = roleAuthorizer;
this.mapper = mapper;
this.runner = runner;
}
/**
* Refuses a batch whose intermediate object the role of the stream's {@code S3Configuration} may not write.
* Firehose assumes that role to stage the batch, so it has to trust {@code firehose.amazonaws.com} for this
* stream and allow {@code s3:PutObject} on the object.
*
* @throws IllegalStateException when the role may not stage the object
*/
public void requireStagingAccess(String accountId, String streamArn, RedshiftDestination destination,
String bucket, String key) {
requireAccess(accountId, streamArn, destination.getS3() == null ? null : destination.getS3().getRoleArn(),
"s3:PutObject", bucket, key, "stage");
}
/**
* Refuses a load whose staged object the destination's {@code RoleARN} may not read, with the same trust
* requirement as {@link #requireStagingAccess} and {@code s3:GetObject} on the object.
*
* @throws IllegalStateException when the role may not read the object
*/
public void requireLoadAccess(String accountId, String streamArn, RedshiftDestination destination,
String bucket, String key) {
requireAccess(accountId, streamArn, destination.getRoleArn(), "s3:GetObject", bucket, key, "load");
}
private void requireAccess(String accountId, String streamArn, String roleArn, String action, String bucket,
String key, String step) {
// A missing role is not exempt: the authorizer refuses it with enforcement on and ignores it with enforcement off.
String role = roleArn == null ? "" : roleArn;
List<Permission> permissions = role.isBlank()
? List.of() : List.of(new Permission(action, RedshiftRoleAccess.objectArn(role, bucket, key)));
Optional<String> refusal = roleAuthorizer.refusal(role, accountId, FIREHOSE_PRINCIPAL, streamArn, permissions);
if (refusal.isPresent()) {
throw new IllegalStateException("Firehose cannot " + step + " s3://" + bucket + "/" + key + ": "
+ refusal.get());
}
}
/**
* Runs the destination's COPY for the object at {@code s3://bucket/key}.
*
@@ -1162,8 +1162,13 @@ public class FirehoseService implements ResourceProvider {
List<byte[]> records = toFlush;
if (s3 != null && stream.isProcessingEnabled()) {
ensureBucket(bucket, stream);
FirehoseLambdaTransformer.Outcome transformed =
lambdaTransformer.transform(stream, bucket, records, clock.instant());
FirehoseLambdaTransformer.Outcome transformed = isRedshiftStream(stream) && redshiftDelivery != null
? lambdaTransformer.transform(stream, bucket, records, clock.instant(),
errorKey -> redshiftDelivery.requireStagingAccess(stream.getAccountId(),
stream.getDeliveryStreamARN(),
stream.getDestinations().get(0).getRedshiftDestinationDescription(),
bucket, errorKey))
: lambdaTransformer.transform(stream, bucket, records, clock.instant());
LOG.infov("Transformed {0} records from stream {1} ({2} dropped, {3} failed)",
records.size(), streamName, transformed.droppedRecords(), transformed.failedRecords());
records = transformed.records();
@@ -1194,6 +1199,10 @@ public class FirehoseService implements ResourceProvider {
String key = S3ObjectKeyResolver.resolveKey(s3, stream.getDeliveryStreamName(),
stream.getVersionId(), clock.instant(), compression);
if (isRedshiftStream(stream) && redshiftDelivery != null) {
redshiftDelivery.requireStagingAccess(stream.getAccountId(), stream.getDeliveryStreamARN(),
stream.getDestinations().get(0).getRedshiftDestinationDescription(), bucket, key);
}
ensureBucket(bucket, stream);
byte[] rawPayload = concatenateRecords(records);
@@ -1350,6 +1359,8 @@ public class FirehoseService implements ResourceProvider {
try {
String region = AwsArnUtils.regionOrDefault(stream.getDeliveryStreamARN(),
regionResolver.getDefaultRegion());
redshiftDelivery.requireLoadAccess(stream.getAccountId(), stream.getDeliveryStreamARN(), redshift,
pending.bucket, pending.key);
redshiftDelivery.copy(stream.getAccountId(), region, redshift, pending.bucket, pending.key);
return true;
} catch (RuntimeException e) {
@@ -161,6 +161,8 @@ final class RedshiftDestinationValidator {
"secretsManagerConfiguration.secretARN", violations);
}
}
collectS3RoleViolations(dest.getS3(), shape, "s3Configuration", violations);
collectS3RoleViolations(dest.getS3Backup(), shape, "s3BackupConfiguration", violations);
S3DestinationValidator.collectProcessingViolations(dest.getProcessingConfiguration(), shape, violations);
S3Destination s3 = dest.getS3();
if (s3 != null && s3.getPrefix() != null && UNREADABLE_KEY_CHARS.matcher(s3.getPrefix()).find()) {
@@ -174,6 +176,19 @@ final class RedshiftDestinationValidator {
}
}
/**
* The role Firehose assumes for an S3 location has the same length and pattern as the destination's own, so a blank
* one is refused here rather than reaching a delivery that would skip the role checks.
*/
private static void collectS3RoleViolations(S3Destination s3, String shape, String member,
List<String> violations) {
if (s3 == null || s3.getRoleArn() == null) {
return;
}
checkLength(s3.getRoleArn(), 1, 512, shape, member + ".roleARN", violations);
checkPattern(s3.getRoleArn(), ROLE_ARN, ROLE_ARN_REGEX, shape, member + ".roleARN", violations);
}
/** The bucket and role an S3 configuration cannot do without: with no bucket, staging falls back to a shared one. */
private static void requireS3Locators(S3Destination s3, String shape, String member, List<String> violations) {
require(s3.getBucketArn(), shape, member + ".bucketARN", violations);