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

+11 -1
View File
@@ -171,6 +171,15 @@ set to `Enabled`, which needs an `S3BackupConfiguration`, each batch is also wri
and compression. The backup is written after the batch is staged and queued, and a failed backup write is logged without
holding the load back or re-staging the batch, so that batch then has no backup copy.
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
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
is kept, as for any failed load. With enforcement off, no role is checked. The S3 backup write is not checked yet.
A JDBC connection that stops answering is dropped after 150 seconds.
Compression of the intermediate objects is not added to the `COPY` for you: as on AWS, put `GZIP` in `CopyOptions`
@@ -196,7 +205,8 @@ 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 `COPY` carries no credentials, so the proxy reads the staged object as an anonymous client. With S3
- 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
@@ -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);
@@ -30,6 +30,7 @@ import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
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.anyMap;
@@ -316,6 +317,17 @@ class FirehoseLambdaTransformerTest {
assertNull(outcome.errorKey());
}
@Test
void anErrorOutputGuardThatThrowsPreventsTheWrite() {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed")));
assertThrows(IllegalStateException.class, () -> transformer.transform(
stream(lambdaProcessor()), "b", List.of(record("a")), DELIVERY_TIME,
key -> { throw new IllegalStateException("permission denied: " + key); }));
verify(s3Service, never()).putObject(anyString(), anyString(), any(), anyString(), anyMap());
}
@Test
void processingFailedRoutesOnlyThatRecordToTheErrorOutput() throws Exception {
replyWith(ids -> records(outcome(ids.get(0), "ProcessingFailed"), ok(ids.get(1), "kept")));
@@ -2,7 +2,9 @@ package io.github.hectorvent.floci.services.firehose;
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.ServiceRoleAuthorizer;
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,15 +20,18 @@ import java.sql.SQLException;
import java.sql.Statement;
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.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.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -37,6 +42,7 @@ class FirehoseRedshiftDeliveryTest {
private RedshiftService redshift;
private RedshiftServerlessService serverless;
private SecretsManagerService secrets;
private ServiceRoleAuthorizer roleAuthorizer;
private final List<String[]> executed = new ArrayList<>();
private FirehoseRedshiftDelivery delivery;
@@ -49,7 +55,8 @@ class FirehoseRedshiftDeliveryTest {
when(cluster.getMasterUsername()).thenReturn("admin");
when(redshift.describeClustersForAccount("000000000000", "c1")).thenReturn(List.of(cluster));
serverless = mock(RedshiftServerlessService.class);
delivery = new FirehoseRedshiftDelivery(redshift, serverless, secrets, mapper,
roleAuthorizer = mock(ServiceRoleAuthorizer.class);
delivery = new FirehoseRedshiftDelivery(redshift, serverless, secrets, roleAuthorizer, mapper,
(url, user, password, sql) -> executed.add(new String[] {url, user, password, sql}));
}
@@ -162,6 +169,60 @@ class FirehoseRedshiftDeliveryTest {
""", RedshiftDestination.class);
}
private static final String STREAM_ARN = "arn:aws:firehose:us-east-1:000000000000:deliverystream/rs";
private static final String LOAD_ROLE = "arn:aws:iam::000000000000:role/firehose";
private static final String STAGING_ROLE = "arn:aws:iam::000000000000:role/firehose-staging";
private RedshiftDestination destinationWithStagingRole() throws Exception {
RedshiftDestination destination = destination();
DeliveryStreamDescription.S3Destination s3 = new DeliveryStreamDescription.S3Destination();
s3.setRoleArn(STAGING_ROLE);
destination.setS3(s3);
return destination;
}
@Test
void stagingChecksTheS3ConfigurationRoleForPutObjectOnTheObject() throws Exception {
when(roleAuthorizer.refusal(STAGING_ROLE, "000000000000", "firehose.amazonaws.com", STREAM_ARN,
List.of(new ServiceRoleAuthorizer.Permission("s3:PutObject", "arn:aws:s3:::stage/k1"))))
.thenReturn(Optional.of("The role " + STAGING_ROLE + " does not trust firehose.amazonaws.com."));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> delivery
.requireStagingAccess("000000000000", STREAM_ARN, destinationWithStagingRole(), "stage", "k1"));
assertTrue(e.getMessage().contains("s3://stage/k1") && e.getMessage().contains("does not trust"),
e.getMessage());
}
@Test
void loadChecksTheDestinationRoleForGetObjectOnTheObject() throws Exception {
when(roleAuthorizer.refusal(LOAD_ROLE, "000000000000", "firehose.amazonaws.com", STREAM_ARN,
List.of(new ServiceRoleAuthorizer.Permission("s3:GetObject", "arn:aws:s3:::stage/k1"))))
.thenReturn(Optional.of("The role " + LOAD_ROLE + " is not authorized to perform s3:GetObject."));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> delivery
.requireLoadAccess("000000000000", STREAM_ARN, destinationWithStagingRole(), "stage", "k1"));
assertTrue(e.getMessage().contains("not authorized"), e.getMessage());
}
@Test
void aPermittedRoleStagesAndLoads() throws Exception {
delivery.requireStagingAccess("000000000000", STREAM_ARN, destinationWithStagingRole(), "stage", "k1");
delivery.requireLoadAccess("000000000000", STREAM_ARN, destinationWithStagingRole(), "stage", "k1");
verify(roleAuthorizer, times(2)).refusal(anyString(), eq("000000000000"), eq("firehose.amazonaws.com"),
eq(STREAM_ARN), any());
}
@Test
void stagingWithoutAnS3ConfigurationRoleDelegatesToAuthorizer() throws Exception {
delivery.requireStagingAccess("000000000000", STREAM_ARN, destination(), "stage", "k1");
verify(roleAuthorizer).refusal(eq(""), eq("000000000000"), eq("firehose.amazonaws.com"),
eq(STREAM_ARN), eq(List.of()));
}
@Test
void runsCopyWithoutAnIamRoleThroughTheProxyPortInSimpleMode() throws Exception {
delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1");
@@ -213,7 +274,8 @@ class FirehoseRedshiftDeliveryTest {
@Test
void jdbcFailureIsWrappedWithTableClusterAndSqlState() {
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets, mapper,
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets,
roleAuthorizer, mapper,
(url, user, password, sql) -> {
throw new SQLException("relation \"events\" does not exist", "42P01");
});
@@ -0,0 +1,170 @@
package io.github.hectorvent.floci.services.firehose;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
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.ScpProvider;
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** The role checks of a Redshift destination against the real {@link ServiceRoleAuthorizer}, with IAM enforcement on. */
class FirehoseRedshiftRoleAccessTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String STREAM_ARN = "arn:aws:firehose:us-east-1:" + ACCOUNT_ID + ":deliverystream/rs";
private static final String LOAD_ROLE = "arn:aws:iam::" + ACCOUNT_ID + ":role/firehose-load";
private static final String STAGING_ROLE = "arn:aws:iam::" + ACCOUNT_ID + ":role/firehose-staging";
private static final String TRUST = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"firehose.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static final String TRUST_OTHER_STREAM = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"firehose.amazonaws.com"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"aws:SourceArn":"arn:aws:firehose:us-east-1:000000000000:deliverystream/other"}}}]}""";
private static final String TRUST_LAMBDA = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static final String ALLOW_PUT = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::stage/*"}]}""";
private static final String ALLOW_GET = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::stage/*"}]}""";
private static final String DENY_GET = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:*","Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::stage/*"}]}""";
private IamService iamService;
private FirehoseRedshiftDelivery delivery;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().iam().enforcementEnabled()).thenReturn(true);
iamService = mock(IamService.class);
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
Instance<ScpProvider> scpProvider = mock(Instance.class);
when(scpProvider.isResolvable()).thenReturn(false);
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(),
(url, user, password, sql) -> { });
}
private void role(String name, String arn, String trust, String policy) {
when(iamService.findRole(ACCOUNT_ID, name))
.thenReturn(Optional.of(new IamRole("id-" + name, name, "/", arn, trust)));
when(iamService.resolvePrincipalContext(arn)).thenReturn(CallerContext.of(List.of(policy)));
}
private static RedshiftDestination destination() {
RedshiftDestination destination = new RedshiftDestination();
destination.setRoleArn(LOAD_ROLE);
S3Destination s3 = new S3Destination();
s3.setRoleArn(STAGING_ROLE);
destination.setS3(s3);
return destination;
}
@Test
void trustedRolesWithThePermissionsStageAndLoad() {
role("firehose-staging", STAGING_ROLE, TRUST, ALLOW_PUT);
role("firehose-load", LOAD_ROLE, TRUST, ALLOW_GET);
assertDoesNotThrow(() -> delivery.requireStagingAccess(ACCOUNT_ID, STREAM_ARN, destination(), "stage", "k"));
assertDoesNotThrow(() -> delivery.requireLoadAccess(ACCOUNT_ID, STREAM_ARN, destination(), "stage", "k"));
}
@Test
void aStagingRoleThatDoesNotTrustFirehoseIsRefused() {
role("firehose-staging", STAGING_ROLE, TRUST_LAMBDA, ALLOW_PUT);
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> delivery.requireStagingAccess(ACCOUNT_ID, STREAM_ARN, destination(), "stage", "k"));
assertTrue(e.getMessage().contains("does not trust firehose.amazonaws.com"), e.getMessage());
}
@Test
void aTrustConditionOnAnotherStreamRefusesThisOne() {
role("firehose-load", LOAD_ROLE, TRUST_OTHER_STREAM, ALLOW_GET);
assertThrows(IllegalStateException.class,
() -> delivery.requireLoadAccess(ACCOUNT_ID, STREAM_ARN, destination(), "stage", "k"));
}
@Test
void aStagingRoleWithoutPutObjectIsRefused() {
role("firehose-staging", STAGING_ROLE, TRUST, ALLOW_GET);
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> delivery.requireStagingAccess(ACCOUNT_ID, STREAM_ARN, destination(), "stage", "k"));
assertTrue(e.getMessage().contains("s3:PutObject"), e.getMessage());
}
@Test
void anExplicitDenyOnGetObjectRefusesTheLoad() {
role("firehose-load", LOAD_ROLE, TRUST, DENY_GET);
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> delivery.requireLoadAccess(ACCOUNT_ID, STREAM_ARN, destination(), "stage", "k"));
assertTrue(e.getMessage().contains("s3:GetObject"), e.getMessage());
}
@Test
void aRoleOfAnotherAccountIsRefused() {
RedshiftDestination destination = destination();
destination.setRoleArn("arn:aws:iam::999999999999:role/firehose-load");
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> delivery.requireLoadAccess(ACCOUNT_ID, STREAM_ARN, destination, "stage", "k"));
assertTrue(e.getMessage().contains("belongs to another account"), e.getMessage());
}
@Test
void aMissingStagingRoleIsRefused() {
RedshiftDestination destination = destination();
destination.getS3().setRoleArn(null);
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> delivery.requireStagingAccess(ACCOUNT_ID, STREAM_ARN, destination, "stage", "k"));
assertTrue(e.getMessage().contains("not a valid ARN"), e.getMessage());
}
@Test
void aBlankLoadRoleIsRefused() {
RedshiftDestination destination = destination();
destination.setRoleArn(" ");
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> delivery.requireLoadAccess(ACCOUNT_ID, STREAM_ARN, destination, "stage", "k"));
assertTrue(e.getMessage().contains("not a valid ARN"), e.getMessage());
}
}
@@ -30,6 +30,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -39,6 +40,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -98,7 +100,7 @@ class FirehoseRedshiftServiceTest {
@Test
void recordsAreTransformedByTheRedshiftDestinationsLambdaBeforeStaging() throws Exception {
createStream(LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
when(transformer.transform(any(), eq("stage"), any(), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
List.of("{\"id\":2}".getBytes(StandardCharsets.UTF_8)), 0, 0, null));
service.flush(STREAM);
@@ -132,14 +134,14 @@ class FirehoseRedshiftServiceTest {
service.flush(STREAM);
verify(transformer, never()).transform(any(), anyString(), any(), any());
verify(transformer, never()).transform(any(), anyString(), any(), any(), any());
verifyStagedTimes(1);
}
@Test
void whenTheLambdaDropsEveryRecordNothingIsStagedOrLoaded() throws Exception {
createStream(LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(
when(transformer.transform(any(), eq("stage"), any(), any(), any())).thenReturn(
new FirehoseLambdaTransformer.Outcome(List.of(), 1, 0, null));
service.flush(STREAM);
@@ -151,7 +153,7 @@ class FirehoseRedshiftServiceTest {
@Test
void backupEnabledWithLambdaTransformKeepsTheUntransformedSourceRecords() throws Exception {
createStream(BACKUP_ENABLED + LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
when(transformer.transform(any(), eq("stage"), any(), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
List.of("{\"id\":2}".getBytes(StandardCharsets.UTF_8)), 0, 0, null));
service.flush(STREAM);
@@ -169,7 +171,7 @@ class FirehoseRedshiftServiceTest {
@Test
void backupEnabledWhenLambdaDropsEveryRecordStillWritesTheSourceRecordsToBackup() throws Exception {
createStream(BACKUP_ENABLED + LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(
when(transformer.transform(any(), eq("stage"), any(), any(), any())).thenReturn(
new FirehoseLambdaTransformer.Outcome(List.of(), 1, 0, null));
service.flush(STREAM);
@@ -185,7 +187,7 @@ class FirehoseRedshiftServiceTest {
@Test
void backupWriteFailureWhenLambdaDropsEveryRecordLeavesTheBatchBufferedForRetry() throws Exception {
createStream(BACKUP_ENABLED + LAMBDA_PROCESSING);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(
when(transformer.transform(any(), eq("stage"), any(), any(), any())).thenReturn(
new FirehoseLambdaTransformer.Outcome(List.of(), 1, 0, null));
doThrow(new IllegalStateException("s3 unavailable")).when(s3Service)
.putObject(eq("bk"), anyString(), any(byte[].class), anyString(), anyMap(), any());
@@ -240,12 +242,12 @@ class FirehoseRedshiftServiceTest {
RedshiftDestination valid = mapper.readValue("{" + LAMBDA_PROCESSING.substring(2) + "}",
RedshiftDestination.class);
service.updateRedshiftDestination(STREAM, "1", destinationId, valid);
when(transformer.transform(any(), eq("stage"), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
when(transformer.transform(any(), eq("stage"), any(), any(), any())).thenReturn(new FirehoseLambdaTransformer.Outcome(
List.of("{\"id\":3}".getBytes(StandardCharsets.UTF_8)), 0, 0, null));
service.flush(STREAM);
verify(transformer, times(1)).transform(any(), eq("stage"), any(), any());
verify(transformer, times(1)).transform(any(), eq("stage"), any(), any(), any());
ArgumentCaptor<byte[]> body = ArgumentCaptor.forClass(byte[].class);
verify(s3Service).putObject(eq("stage"), anyString(), body.capture(), anyString(), anyMap(), any());
assertEquals("{\"id\":3}\n", new String(body.getValue(), StandardCharsets.UTF_8));
@@ -300,6 +302,61 @@ class FirehoseRedshiftServiceTest {
verifyStagedTimes(1);
}
@Test
void aRefusedStagingRoleStagesAndLoadsNothingAndKeepsTheRecordsBuffered() throws Exception {
createStream("");
doThrow(new IllegalStateException("role does not trust firehose.amazonaws.com"))
.when(delivery).requireStagingAccess(anyString(), anyString(), any(), anyString(), anyString());
service.flush(STREAM);
verifyStagedTimes(0);
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
reset(delivery);
service.flush(STREAM);
verifyStagedTimes(1);
verify(delivery, times(1)).copy(anyString(), anyString(), any(), eq("stage"), anyString());
}
@Test
void whenTransformationErrorOutputIsRefusedByStagingRoleTheBatchRemainsBuffered() throws Exception {
createStream(LAMBDA_PROCESSING);
doThrow(new IllegalStateException("Firehose cannot stage error output"))
.when(delivery).requireStagingAccess(anyString(), anyString(), any(), eq("stage"), eq("error/processing-failed.json"));
doAnswer(inv -> {
Consumer<String> guard = inv.getArgument(4);
guard.accept("error/processing-failed.json");
return new FirehoseLambdaTransformer.Outcome(List.of(), 0, 1, "error/processing-failed.json");
}).when(transformer).transform(any(), eq("stage"), any(), any(), any());
service.flush(STREAM);
verifyStagedTimes(0);
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
}
@Test
void aRefusedLoadRoleRetriesTheLoadWithoutRestagingTheBatch() throws Exception {
createStream("");
doThrow(new IllegalStateException("role is not authorized to perform s3:GetObject"))
.when(delivery).requireLoadAccess(anyString(), anyString(), any(), anyString(), anyString());
service.flush(STREAM);
verifyStagedTimes(1);
verify(delivery, never()).copy(anyString(), anyString(), any(), anyString(), anyString());
Mockito.doNothing().when(delivery)
.requireLoadAccess(anyString(), anyString(), any(), anyString(), anyString());
pastBackoff();
service.retryPendingRedshiftCopies();
verifyStagedTimes(1);
verify(delivery, times(1)).copy(anyString(), anyString(), any(), eq("stage"), anyString());
}
@Test
void failedCopyIsLoggedAndNotRestagedOrRebuffered() throws Exception {
createStream("");
@@ -79,6 +79,14 @@ class RedshiftDestinationValidatorTest {
assertTrue(messageOf(dest).contains("s3BackupConfiguration.bucketARN"));
}
@Test
void intermediateRoleMustBeAnIamRoleArn() throws Exception {
RedshiftDestination dest = valid();
dest.getS3().setRoleArn("not-an-arn");
assertTrue(messageOf(dest).contains("s3Configuration.roleARN"));
}
@Test
void secretsManagerRoleMustBeAnIamRoleArn() throws Exception {
RedshiftDestination dest = valid();