feat(redshift): take an S3 bucket as the source of an integration (#7466)

CreateIntegration accepts arn:aws:s3:::bucket with a Serverless namespace or cluster target. The bucket must exist in the integration's Region and have no period in its name, a bucket joins a target once, and a target takes at most 50. The integration reports SourceType s3-event-notifications, starts no poller and publishes no zero-ETL events.

fix(redshift): validate S3 integration source and target identities

fix(redshift): resolve unstored S3 bucket Region in default Region

Fall back to the deployment default Region when an S3 bucket has no stored Region, match bucket partition using RegionResolver.partitionForRegion, and remove the unused two-argument RedshiftZeroEtlEndpoints constructor.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-06 19:20:05 -04:00
1 parent ad8c35888f
commit 8cff513c8d
8 files changed
+581 -31

No files matched your search

+26
View File
@@ -450,6 +450,32 @@ approximation to indicate that initial backfill is in progress); it becomes `act
exhausted. The landing table is an append-only log, so an item changed while its table is still being
backfilled can appear twice: once from the scan and once from the stream.
### S3 event integrations
`CreateIntegration` also takes an Amazon S3 bucket as the source (`arn:aws:s3:::<bucket>`), the first step of
auto-copy. The target is a Serverless namespace ARN, or the provisioned cluster ARN described above; AWS's
`arn:aws:redshift:<region>:<account>:namespace:<id>` form of a provisioned target is not accepted yet.
`SourceType` is `s3-event-notifications`, and the `source-types` filter of `DescribeIntegrations` matches it.
```bash
aws --endpoint-url http://localhost:4566 redshift create-integration \
--integration-name lake-auto-copy \
--source-arn arn:aws:s3:::my-bucket \
--target-arn arn:aws:redshift-serverless:us-east-1:000000000000:namespace/<namespace-id>
```
The bucket has to exist in the caller's account (`IntegrationSourceNotFoundFault` otherwise), to be in the
Region of the integration, and to have no period in its name. A bucket with no stored Region is treated as
Floci's default Region. Its ARN must have empty Region and account fields and the integration's partition. A provisioned
target must match the local cluster's full ARN (`IntegrationTargetNotFoundFault` otherwise).
A bucket joins a target once (`IntegrationConflictOperationFault`), and a
target takes at most 50 S3 event integrations (`IntegrationQuotaExceededFault`). Those two fault names are
Floci's reading of the AWS API's fault list; their messages are not captured from AWS.
The integration is `active` as soon as it is created, where AWS reports `creating` first. It does not load
anything yet, and the bucket policy, the namespace resource policy and the existing notifications of the bucket
are not checked. [COPY JOB](#copy-job) statements work independently of the integration.
### Resource policies
A zero-ETL integration needs a resource policy on its target that lets the source in.
@@ -467,7 +467,7 @@ public class RedshiftQueryHandler {
encryptionContextMap(params),
tagMap(params),
regionResolver.resolveRegionFromAuth(authorizationHeader));
if (zeroEtlConsumer != null) {
if (zeroEtlConsumer != null && integration.isPollingEnabled()) {
zeroEtlConsumer.startPolling(integration);
}
String xml = new XmlBuilder()
@@ -1585,6 +1585,9 @@ public class RedshiftQueryHandler {
.elem("TargetArn", integration.getTargetArn())
.elem("Status", integration.getStatus())
.elem("CreateTime", integration.getCreateTime());
if (integration.getSourceType() != null) {
builder.elem("SourceType", integration.getSourceType());
}
if (integration.getDescription() != null) {
builder.elem("Description", integration.getDescription());
}
@@ -87,6 +87,8 @@ public class RedshiftService implements ManagedSecretRotator {
private final AccountAwareStorageBackend<ClusterParameterGroup> parameterGroups;
private final AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroups;
private static final int MIN_INTEGRATION_RECORDS = 20;
private static final String S3_EVENT_SOURCE_TYPE = "s3-event-notifications";
private static final int MAX_S3_INTEGRATIONS_PER_TARGET = 50;
private static final int MAX_INTEGRATION_RECORDS = 100;
private static final int MAX_INTEGRATION_DESCRIPTION = 1000;
private static final int MAX_INTEGRATION_NAME = 63;
@@ -601,23 +603,28 @@ public class RedshiftService implements ManagedSecretRotator {
if (targetArn == null || targetArn.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetArn is required.", 400);
}
// AWS takes a DynamoDB table as the source. A stream ARN is Floci's original form and is kept.
AwsArnUtils.Arn source = parseZeroEtlArn(sourceArn, "DynamoDB table");
if (!"dynamodb".equals(source.service()) || !source.resource().startsWith("table/")) {
throw new AwsException("InvalidParameterValue",
"SourceArn must identify a DynamoDB table or stream.", 400);
}
String sourceStreamArn;
if (RedshiftZeroEtlEndpoints.isStreamArn(sourceArn)) {
if (streamReader == null) {
throw new AwsException("InternalFailure", "DynamoDB stream service is unavailable.", 500);
}
streamReader.describeStream(DynamoDbStreamReader.Stream.of(sourceArn), null, null);
sourceStreamArn = sourceArn;
boolean s3Source = AwsArnUtils.isArnFor(sourceArn, "s3");
String sourceStreamArn = null;
if (s3Source) {
requireS3SourceBucket(sourceArn, region);
} else {
TableDefinition table = requireZeroEtlEndpoints().sourceTable(integrations.accountId(), sourceArn);
// Changes are read from the table's latest stream; the consumer follows one enabled later.
sourceStreamArn = table.getStreamArn();
// AWS takes a DynamoDB table as the source. A stream ARN is Floci's original form and is kept.
AwsArnUtils.Arn source = parseZeroEtlArn(sourceArn, "DynamoDB table");
if (!"dynamodb".equals(source.service()) || !source.resource().startsWith("table/")) {
throw new AwsException("InvalidParameterValue",
"SourceArn must identify a DynamoDB table or stream.", 400);
}
if (RedshiftZeroEtlEndpoints.isStreamArn(sourceArn)) {
if (streamReader == null) {
throw new AwsException("InternalFailure", "DynamoDB stream service is unavailable.", 500);
}
streamReader.describeStream(DynamoDbStreamReader.Stream.of(sourceArn), null, null);
sourceStreamArn = sourceArn;
} else {
TableDefinition table = requireZeroEtlEndpoints().sourceTable(integrations.accountId(), sourceArn);
// Changes are read from the table's latest stream; the consumer follows one enabled later.
sourceStreamArn = table.getStreamArn();
}
}
// AWS takes a Redshift Serverless namespace as the target. A provisioned cluster ARN is
// Floci's original form and is kept.
@@ -630,7 +637,10 @@ public class RedshiftService implements ManagedSecretRotator {
if (clusterIdentifier.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetArn must identify a Redshift cluster.", 400);
}
describeClusters(clusterIdentifier);
if (findClusterByArn(targetArn).isEmpty()) {
throw new AwsException("IntegrationTargetNotFoundFault",
"The specified integration target can't be found.", 404);
}
} else {
throw new AwsException("InvalidParameterValue",
"TargetArn must identify a Redshift Serverless namespace or a provisioned Redshift cluster.",
@@ -654,6 +664,10 @@ public class RedshiftService implements ManagedSecretRotator {
"The integration " + integrationName + " already exists.", 400);
}
if (s3Source) {
requireRoomForS3Integration(sourceArn, targetArn);
}
String integrationId = UUID.randomUUID().toString();
Integration integration = new Integration();
integration.setAccountId(integrations.accountId());
@@ -664,23 +678,72 @@ public class RedshiftService implements ManagedSecretRotator {
integration.setTargetArn(targetArn);
integration.setSourceStreamArn(sourceStreamArn);
integration.setTargetClusterIdentifier(clusterIdentifier);
integration.setLandingTableName("floci_zetl_" + integrationId.replace('-', '_'));
integration.setRetryCount(0);
integration.setLastError(null);
integration.setPollingEnabled(true);
// Floci approximation: report `syncing` while the backfill scan runs, then `active`.
integration.setStatus("syncing");
if (s3Source) {
// Nothing is replicated by a poll: the files an S3 event integration loads come from S3 events.
integration.setSourceType(S3_EVENT_SOURCE_TYPE);
integration.setPollingEnabled(false);
// Floci approximation: AWS reports `creating` first, and there is no setup here to wait for.
integration.setStatus("active");
} else {
integration.setLandingTableName("floci_zetl_" + integrationId.replace('-', '_'));
integration.setPollingEnabled(true);
// Floci approximation: report `syncing` while the backfill scan runs, then `active`.
integration.setStatus("syncing");
}
integration.setKmsKeyId(kmsKeyId);
integration.setCreateTime(DateTimeFormatter.ISO_INSTANT.format(Instant.now()));
integration.setDescription(description);
integration.setAdditionalEncryptionContext(additionalEncryptionContext);
integration.setTags(tags);
integrations.put(integrationId, integration);
LOG.infov("Created Redshift zero-ETL integration: {0}", integration.getIntegrationArn());
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.SYNCHRONIZING, integration);
LOG.infov("Created Redshift integration: {0}", integration.getIntegrationArn());
if (!s3Source) {
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.SYNCHRONIZING, integration);
}
return integration;
}
/**
* AWS takes the bucket of an S3 event integration as {@code arn:aws:s3:::bucket}. The bucket has to exist,
* to be in the Region of the integration, and to have no period in its name.
*/
private void requireS3SourceBucket(String sourceArn, String region) {
AwsArnUtils.Arn source = parseZeroEtlArn(sourceArn, "S3 bucket");
String bucket = source.resource();
if (!source.region().isEmpty() || !source.accountId().isEmpty()
|| !source.partition().equals(regionResolver.partitionForRegion(region))
|| bucket.isBlank() || bucket.contains("/") || bucket.contains(":")) {
throw new AwsException("InvalidParameterValue", "SourceArn must identify an Amazon S3 bucket.", 400);
}
if (bucket.indexOf('.') >= 0) {
throw new AwsException("InvalidParameterValue",
"An S3 event integration cannot use a bucket whose name contains a period.", 400);
}
String bucketRegion = requireZeroEtlEndpoints().sourceBucketRegion(integrations.accountId(), region, bucket);
if (!bucketRegion.equals(region)) {
throw new AwsException("InvalidParameterValue",
"The source bucket and the integration must be in the same Region.", 400);
}
}
/** One S3 event integration joins a bucket to a target, and a target takes at most 50 of them. */
private void requireRoomForS3Integration(String sourceArn, String targetArn) {
List<Integration> onTarget = integrations.scan(k -> true).stream()
.filter(existing -> S3_EVENT_SOURCE_TYPE.equals(existing.getSourceType())
&& targetArn.equals(existing.getTargetArn()))
.toList();
if (onTarget.stream().anyMatch(existing -> sourceArn.equals(existing.getSourceArn()))) {
throw new AwsException("IntegrationConflictOperationFault",
"An S3 event integration between this bucket and this target already exists.", 400);
}
if (onTarget.size() >= MAX_S3_INTEGRATIONS_PER_TARGET) {
throw new AwsException("IntegrationQuotaExceededFault",
"A target can have at most " + MAX_S3_INTEGRATIONS_PER_TARGET + " S3 event integrations.", 400);
}
}
private RedshiftZeroEtlEndpoints requireZeroEtlEndpoints() {
if (zeroEtlEndpoints == null) {
throw new AwsException("InternalFailure", "Zero-ETL endpoint resolution is unavailable.", 500);
@@ -878,7 +941,8 @@ public class RedshiftService implements ManagedSecretRotator {
case "source-arn" -> integration.getSourceArn();
case "status" -> integration.getStatus();
// source-types filters on the source's AWS service, which the ARN's third field names.
case "source-types" -> sourceType(integration.getSourceArn());
case "source-types" -> integration.getSourceType() != null ? integration.getSourceType()
: sourceType(integration.getSourceArn());
default -> throw new AwsException("InvalidParameterValue",
"Unrecognized filter name: " + name, 400);
};
@@ -916,10 +980,12 @@ public class RedshiftService implements ManagedSecretRotator {
if (stored.isPresent() && integrationArn.equals(stored.get().getIntegrationArn())) {
integrations.delete(key);
LOG.infov("Deleted Redshift zero-ETL integration: {0}", integrationArn);
// Deletion is immediate here, so both the start and the end of it are reported.
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.DELETION_INITIATED,
stored.get());
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.DELETED, stored.get());
if (stored.get().getSourceType() == null) {
// Deletion is immediate here, so both the start and the end of it are reported.
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.DELETION_INITIATED,
stored.get());
queueIntegrationEvent(RedshiftIntegrationEventPublisher.IntegrationEvent.DELETED, stored.get());
}
return stored.get();
}
}
@@ -2,11 +2,13 @@ package io.floci.aws.services.redshift;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.dynamodb.DynamoDbFacade;
import io.floci.aws.services.dynamodb.backend.DynamoDbOperations.Scope;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import io.floci.aws.services.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -19,11 +21,40 @@ public class RedshiftZeroEtlEndpoints {
private final DynamoDbFacade dynamoDb;
private final RedshiftServerlessService serverless;
private final S3Service s3;
private final RegionResolver regionResolver;
@Inject
public RedshiftZeroEtlEndpoints(DynamoDbFacade dynamoDb, RedshiftServerlessService serverless) {
public RedshiftZeroEtlEndpoints(DynamoDbFacade dynamoDb, RedshiftServerlessService serverless, S3Service s3,
RegionResolver regionResolver) {
this.dynamoDb = dynamoDb;
this.serverless = serverless;
this.s3 = s3;
this.regionResolver = regionResolver;
}
/**
* The Region of the bucket an S3 event integration takes as its source, read as {@code accountId}. A bucket
* that does not exist is an integration source that cannot be found.
*/
public String sourceBucketRegion(String accountId, String region, String bucketName) {
try {
return RequestScopes.callAs(accountId, region, () -> {
if (!s3.ownsBucket(bucketName)) {
throw sourceNotFound();
}
String bucketRegion = s3.getBucketRegion(bucketName);
if (bucketRegion == null || bucketRegion.isBlank()) {
return regionResolver.getDefaultRegion();
}
return bucketRegion;
});
} catch (AwsException e) {
if ("NoSuchBucket".equals(e.getErrorCode())) {
throw sourceNotFound();
}
throw e;
}
}
/**
@@ -23,6 +23,7 @@ public class Integration {
private String integrationName;
private String sourceArn;
private String targetArn;
private String sourceType;
private String sourceStreamArn;
private String targetClusterIdentifier;
private String landingTableName;
@@ -79,6 +80,9 @@ public class Integration {
public void setPollingEnabled(boolean pollingEnabled) { this.pollingEnabled = pollingEnabled; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
/** {@code s3-event-notifications} for an S3 event integration; null for a DynamoDB zero-ETL integration. */
public String getSourceType() { return sourceType; }
public void setSourceType(String sourceType) { this.sourceType = sourceType; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getKmsKeyId() { return kmsKeyId; }
@@ -0,0 +1,137 @@
package io.floci.aws.services.redshift;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.QueryRequests;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.RedshiftException;
import java.net.URI;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RedshiftS3EventIntegrationTest {
private static final String BUCKET = "s3-event-lake";
private static final String NAMESPACE = "s3-event-ns";
@Inject
S3Service s3Service;
@TestHTTPResource
URI endpoint;
private String namespaceArn;
private boolean created;
@BeforeEach
void ensureResources() {
RestAssuredJsonUtils.configureAwsContentTypes();
if (created) {
return;
}
s3Service.createBucket(BUCKET, "us-east-1");
namespaceArn = RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateNamespace", """
{"namespaceName":"%s","adminUsername":"admin","adminUserPassword":"Secret123","dbName":"dev"}
""".formatted(NAMESPACE)).then().statusCode(200)
.extract().path("namespace.namespaceArn");
created = true;
}
@Test
void aBucketIsIntegratedWithANamespaceDescribedFilteredAndDeleted() {
String bucketArn = "arn:aws:s3:::" + BUCKET;
String response = redshift("CreateIntegration", "IntegrationName", "s3-event-one",
"SourceArn", bucketArn, "TargetArn", namespaceArn)
.then().statusCode(200)
.body(containsString("<SourceArn>" + bucketArn + "</SourceArn>"))
.body(containsString("<SourceType>s3-event-notifications</SourceType>"))
.body(containsString("<Status>active</Status>"))
.extract().body().asString();
String integrationArn = response.substring(response.indexOf("<IntegrationArn>") + "<IntegrationArn>".length(),
response.indexOf("</IntegrationArn>"));
try {
redshift("DescribeIntegrations", "IntegrationArn", integrationArn)
.then().statusCode(200)
.body(containsString("<SourceType>s3-event-notifications</SourceType>"))
.body(containsString("<TargetArn>" + namespaceArn + "</TargetArn>"));
redshift("DescribeIntegrations", "Filters.DescribeIntegrationsFilter.1.Name", "source-types",
"Filters.DescribeIntegrationsFilter.1.Values.Value.1", "s3-event-notifications")
.then().statusCode(200).body(containsString(integrationArn));
redshift("CreateIntegration", "IntegrationName", "s3-event-two",
"SourceArn", bucketArn, "TargetArn", namespaceArn)
.then().statusCode(400).body(containsString("IntegrationConflictOperationFault"));
} finally {
redshift("DeleteIntegration", "IntegrationArn", integrationArn).then().statusCode(200);
}
redshift("DescribeIntegrations").then().statusCode(200).body(not(containsString(integrationArn)));
}
@Test
void aBucketThatDoesNotExistIsIntegrationSourceNotFound() {
redshift("CreateIntegration", "IntegrationName", "s3-event-missing",
"SourceArn", "arn:aws:s3:::no-such-bucket-here", "TargetArn", namespaceArn)
.then().statusCode(404).body(containsString("IntegrationSourceNotFoundFault"));
}
@Test
void aBucketNameWithAPeriodIsRefused() {
redshift("CreateIntegration", "IntegrationName", "s3-event-period",
"SourceArn", "arn:aws:s3:::lake.bucket", "TargetArn", namespaceArn)
.then().statusCode(400).body(containsString("InvalidParameterValue"));
}
@Test
void aBucketCreatedWithoutRegionConstraintCanJoinAnIntegrationInDefaultRegion() {
String bucketName = "s3-event-no-region";
s3Service.createBucket(bucketName, null);
String bucketArn = "arn:aws:s3:::" + bucketName;
String response = redshift("CreateIntegration", "IntegrationName", "s3-event-no-region-int",
"SourceArn", bucketArn, "TargetArn", namespaceArn)
.then().statusCode(200)
.body(containsString("<SourceArn>" + bucketArn + "</SourceArn>"))
.body(containsString("<Status>active</Status>"))
.extract().body().asString();
String integrationArn = response.substring(response.indexOf("<IntegrationArn>") + "<IntegrationArn>".length(),
response.indexOf("</IntegrationArn>"));
redshift("DeleteIntegration", "IntegrationArn", integrationArn).then().statusCode(200);
}
@Test
void sdkRejectsNoncanonicalBucketArns() {
try (RedshiftClient client = RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build()) {
for (String sourceArn : List.of("arn:aws:s3:us-east-1::" + BUCKET,
"arn:aws:s3::000000000000:" + BUCKET, "arn:aws-cn:s3:::" + BUCKET)) {
RedshiftException error = assertThrows(RedshiftException.class, () -> client.createIntegration(
request -> request.integrationName("s3-sdk-alternate").sourceArn(sourceArn)
.targetArn(namespaceArn)));
assertEquals(400, error.statusCode());
assertEquals("InvalidParameterValue", error.awsErrorDetails().errorCode());
}
}
}
private static Response redshift(String action, String... params) {
return QueryRequests.request("test", "redshift", action, params)
.formParam("Version", "2012-12-01")
.when().post("/");
}
}
@@ -2,7 +2,9 @@ package io.floci.aws.services.redshift;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.DockerHostResolver;
@@ -31,6 +33,7 @@ import io.floci.aws.services.redshift.model.SnapshotSchedule;
import io.floci.aws.services.redshift.proxy.RedshiftProxyManager;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import io.floci.aws.services.redshiftserverless.model.Namespace;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.secretsmanager.model.Secret;
import jakarta.ws.rs.core.MultivaluedHashMap;
@@ -887,6 +890,7 @@ class RedshiftServiceTest {
private RedshiftIntegrationEventPublisher integrationEvents;
private DynamoDbTableAccess zeroEtlTables;
private RedshiftServerlessService zeroEtlServerless;
private S3Service zeroEtlS3;
private RedshiftService service;
@BeforeEach
@@ -958,10 +962,12 @@ class RedshiftServiceTest {
zeroEtlTables = mock(DynamoDbTableAccess.class);
when(zeroEtlDynamoDb.tables()).thenReturn(zeroEtlTables);
zeroEtlServerless = mock(RedshiftServerlessService.class);
zeroEtlS3 = mock(S3Service.class);
when(zeroEtlS3.ownsBucket(any())).thenReturn(true);
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, mapper,
new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS), null, events, integrationEvents,
new RedshiftZeroEtlEndpoints(zeroEtlDynamoDb, zeroEtlServerless));
new RedshiftZeroEtlEndpoints(zeroEtlDynamoDb, zeroEtlServerless, zeroEtlS3, regionResolver));
}
private static final String ORDERS_TABLE_ARN = "arn:aws:dynamodb:us-east-1:111111111111:table/orders";
@@ -1071,6 +1077,258 @@ class RedshiftServiceTest {
error.getMessage());
}
private static final String BUCKET_ARN = "arn:aws:s3:::lake-bucket";
@ParameterizedTest
@ValueSource(strings = {"us-gov-west-1", "cn-north-1"})
void anS3EventIntegrationAcceptsTheBucketsRegionalPartition(String region) {
String partition = AwsRegions.partitionFor(region);
String sourceArn = AwsArnUtils.Arn.global(partition, "s3", "", "lake-bucket").toString();
String targetArn = AwsArnUtils.Arn.of("redshift-serverless", region, "111111111111", "namespace/test")
.toString();
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn(region);
when(zeroEtlServerless.findNamespaceByArn(targetArn, region)).thenReturn(Optional.of(new Namespace()));
when(integrationBackend.scan(any())).thenReturn(List.of());
Integration integration = service.createIntegration("partition-source", sourceArn, targetArn,
null, null, Map.of(), Map.of(), region);
assertEquals(sourceArn, integration.getSourceArn());
assertEquals(partition, AwsArnUtils.parse(integration.getIntegrationArn()).partition());
}
@Test
void anS3EventIntegrationRefusesAnotherAccountsBucket() {
when(zeroEtlS3.ownsBucket("lake-bucket")).thenReturn(false);
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1");
AwsException error = assertThrows(AwsException.class,
() -> createS3Integration("foreign-bucket", BUCKET_ARN));
assertEquals("IntegrationSourceNotFoundFault", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
verify(integrationBackend, never()).put(any(), any());
}
@ParameterizedTest
@ValueSource(strings = {
"arn:aws:s3:us-east-1::lake-bucket",
"arn:aws:s3::111111111111:lake-bucket",
"arn:aws:s3:us-east-1:111111111111:lake-bucket",
"arn:aws-cn:s3:::lake-bucket"
})
void anS3EventIntegrationRefusesAlternateArnsForAnIntegratedBucket(String sourceArn) {
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1");
Integration existing = new Integration();
existing.setIntegrationName("first");
existing.setSourceType("s3-event-notifications");
existing.setSourceArn(BUCKET_ARN);
existing.setTargetArn(NAMESPACE_ARN);
when(integrationBackend.scan(any())).thenReturn(List.of(existing));
AwsException error = assertThrows(AwsException.class,
() -> createS3Integration("alternate-source", sourceArn));
assertEquals("InvalidParameterValue", error.getErrorCode());
verify(integrationBackend, never()).put(any(), any());
}
@ParameterizedTest
@ValueSource(strings = {
"arn:aws:redshift:us-east-1:222222222222:cluster:warehouse",
"arn:aws:redshift:eu-west-1:111111111111:cluster:warehouse",
"arn:aws-cn:redshift:us-east-1:111111111111:cluster:warehouse"
})
void anS3EventIntegrationRefusesForgedClusterTargetArns(String targetArn) {
lifecycleCluster("available");
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1");
when(integrationBackend.scan(any())).thenReturn(List.of());
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(
"forged-target", BUCKET_ARN, targetArn, null, null, Map.of(), Map.of(), "us-east-1"));
assertEquals("IntegrationTargetNotFoundFault", error.getErrorCode());
verify(integrationBackend, never()).put(any(), any());
}
@Test
void anS3EventIntegrationAcceptsTheLocalClustersExactArn() {
lifecycleCluster("available");
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1");
when(integrationBackend.scan(any())).thenReturn(List.of());
String targetArn = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse";
Integration integration = service.createIntegration("local-target", BUCKET_ARN, targetArn,
null, null, Map.of(), Map.of(), "us-east-1");
assertEquals(targetArn, integration.getTargetArn());
assertEquals("warehouse", integration.getTargetClusterIdentifier());
}
@Test
void aBucketWithNoStoredRegionCanJoinAnIntegrationInTheDefaultRegion() {
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn(null);
when(integrationBackend.scan(any())).thenReturn(List.of());
assertEquals(BUCKET_ARN, createS3Integration("default-region", BUCKET_ARN).getSourceArn());
}
@Test
void aBucketWithNoStoredRegionCannotJoinAnIntegrationOutsideTheDefaultRegion() {
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn(null);
when(integrationBackend.scan(any())).thenReturn(List.of());
when(zeroEtlServerless.findNamespaceByArn(NAMESPACE_ARN, "us-east-1"))
.thenReturn(Optional.of(new Namespace()));
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(
"wrong-default-region", BUCKET_ARN, NAMESPACE_ARN, null, null, Map.of(), Map.of(), "eu-west-1"));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertTrue(error.getMessage().contains("same Region"));
verify(integrationBackend, never()).put(any(), any());
}
@Test
void aBucketWithNoStoredRegionUsesTheConfiguredDefaultRegionWhenNotUsEastOne() {
RegionResolver euResolver = new RegionResolver("eu-west-1", "111111111111");
RedshiftZeroEtlEndpoints endpoints = new RedshiftZeroEtlEndpoints(null, zeroEtlServerless, zeroEtlS3, euResolver);
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn(null);
assertEquals("eu-west-1", endpoints.sourceBucketRegion("111111111111", "eu-west-1", "lake-bucket"));
}
private Integration createS3Integration(String name, String sourceArn) {
when(zeroEtlServerless.findNamespaceByArn(NAMESPACE_ARN, "us-east-1")).thenReturn(Optional.of(new Namespace()));
return service.createIntegration(name, sourceArn, NAMESPACE_ARN, null, null, Map.of(), Map.of(), "us-east-1");
}
@Test
void createsAnS3EventIntegrationThatReplicatesNothing() {
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1");
when(integrationBackend.scan(any())).thenReturn(List.of());
Integration integration = createS3Integration("lake-to-warehouse", BUCKET_ARN);
assertEquals("s3-event-notifications", integration.getSourceType());
assertEquals(BUCKET_ARN, integration.getSourceArn());
assertEquals("active", integration.getStatus());
assertNull(integration.getSourceStreamArn());
assertNull(integration.getLandingTableName());
assertFalse(integration.isPollingEnabled());
verify(integrationBackend).put(any(), eq(integration));
verify(integrationEvents, never()).queue(any(), any(), any(), any());
}
@Test
void anS3EventIntegrationSourceThatIsNotAnExistingBucketIsRefused() {
when(zeroEtlS3.getBucketRegion("lake-bucket"))
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
when(integrationBackend.scan(any())).thenReturn(List.of());
AwsException error = assertThrows(AwsException.class, () -> createS3Integration("lake-to-warehouse", BUCKET_ARN));
assertEquals("IntegrationSourceNotFoundFault", error.getErrorCode());
}
@Test
void anS3EventIntegrationRefusesABucketWithAPeriodOrAnObjectKey() {
when(integrationBackend.scan(any())).thenReturn(List.of());
AwsException period = assertThrows(AwsException.class,
() -> createS3Integration("lake-to-warehouse", "arn:aws:s3:::lake.bucket"));
AwsException key = assertThrows(AwsException.class,
() -> createS3Integration("lake-to-warehouse", BUCKET_ARN + "/folder"));
assertEquals("InvalidParameterValue", period.getErrorCode());
assertTrue(period.getMessage().contains("period"));
assertEquals("InvalidParameterValue", key.getErrorCode());
assertTrue(key.getMessage().contains("Amazon S3 bucket"));
}
@Test
void anS3EventIntegrationRefusesABucketOfAnotherRegion() {
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("eu-west-1");
when(integrationBackend.scan(any())).thenReturn(List.of());
AwsException error = assertThrows(AwsException.class, () -> createS3Integration("lake-to-warehouse", BUCKET_ARN));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertTrue(error.getMessage().contains("same Region"));
}
@Test
void anS3EventIntegrationRefusesABucketFromAnotherPartition() {
when(integrationBackend.scan(any())).thenReturn(List.of());
AwsException error = assertThrows(AwsException.class,
() -> createS3Integration("foreign-partition", "arn:aws-cn:s3:::lake-bucket"));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertTrue(error.getMessage().contains("Amazon S3 bucket"));
}
@Test
void aBucketJoinsATargetOnlyOnce() {
when(zeroEtlS3.getBucketRegion("lake-bucket")).thenReturn("us-east-1");
Integration existing = new Integration();
existing.setIntegrationName("first");
existing.setSourceType("s3-event-notifications");
existing.setSourceArn(BUCKET_ARN);
existing.setTargetArn(NAMESPACE_ARN);
when(integrationBackend.scan(any())).thenReturn(List.of(existing));
AwsException error = assertThrows(AwsException.class, () -> createS3Integration("second", BUCKET_ARN));
assertEquals("IntegrationConflictOperationFault", error.getErrorCode());
}
@Test
void aTargetTakesAtMostFiftyS3EventIntegrations() {
when(zeroEtlS3.getBucketRegion(any())).thenReturn("us-east-1");
List<Integration> existing = new ArrayList<>();
for (int index = 0; index < 50; index++) {
Integration integration = new Integration();
integration.setIntegrationName("existing-" + index);
integration.setSourceType("s3-event-notifications");
integration.setSourceArn("arn:aws:s3:::bucket-" + index);
integration.setTargetArn(NAMESPACE_ARN);
existing.add(integration);
}
when(integrationBackend.scan(any())).thenReturn(existing);
AwsException error = assertThrows(AwsException.class, () -> createS3Integration("one-more", BUCKET_ARN));
assertEquals("IntegrationQuotaExceededFault", error.getErrorCode());
}
@Test
void deletingAnS3EventIntegrationReportsNoZeroEtlEvents() {
Integration stored = new Integration();
stored.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:s3-one");
stored.setSourceType("s3-event-notifications");
when(integrationBackend.keys()).thenReturn(Set.of("s3-one"));
when(integrationBackend.get("s3-one")).thenReturn(Optional.of(stored));
service.deleteIntegration(stored.getIntegrationArn());
verify(integrationBackend).delete("s3-one");
verify(integrationEvents, never()).queue(any(), any(), any(), any());
}
@Test
void sourceTypesFilterMatchesTheSourceTypeOfAnS3EventIntegration() {
Integration stored = new Integration();
stored.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:s3-one");
stored.setSourceType("s3-event-notifications");
stored.setSourceArn(BUCKET_ARN);
when(integrationBackend.scan(any())).thenReturn(List.of(stored));
RedshiftService.IntegrationPage page = service.describeIntegrations(null, null, null,
List.of(new RedshiftService.IntegrationFilter("source-types", List.of("s3-event-notifications"))));
assertEquals(1, page.integrations().size());
}
@Test
void createIntegrationQueuesSynchronizingAndPublishesAfterTheChange() {
String streamArn = "arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/2026-09-18T00:00:00.000";
@@ -2,10 +2,12 @@ package io.floci.aws.services.s3;
import io.floci.aws.core.common.AwsCanonicalUserId;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestContext;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints;
import io.floci.aws.services.s3.model.Bucket;
import io.floci.aws.services.s3.model.MultipartUpload;
import io.floci.aws.services.s3.model.PutObjectOptions;
@@ -47,6 +49,29 @@ class S3GlobalBucketNamespaceTest {
private final AtomicReference<String> caller = new AtomicReference<>(DEFAULT_ACCT);
@Test
void redshiftS3IntegrationSourceMustBelongToTheCallerEvenWithGlobalNamespace() {
Instance<RequestContext> context = mutableContext();
AccountAwareStorageBackend<Bucket> buckets =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, DEFAULT_ACCT);
AccountAwareStorageBackend<S3Object> objects =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, DEFAULT_ACCT);
S3Service service = new S3Service(buckets, objects, Path.of("s3-gns-redshift-test"), true, true);
RedshiftZeroEtlEndpoints endpoints = new RedshiftZeroEtlEndpoints(null, null, service,
new RegionResolver("us-east-1", DEFAULT_ACCT));
caller.set(ACCOUNT_A);
service.createBucket("redshift-source", "us-east-1");
assertEquals("us-east-1", endpoints.sourceBucketRegion(ACCOUNT_A, "us-east-1", "redshift-source"));
caller.set(ACCOUNT_B);
assertEquals("us-east-1", service.getBucketRegion("redshift-source"));
AwsException error = assertThrows(AwsException.class,
() -> endpoints.sourceBucketRegion(ACCOUNT_B, "us-east-1", "redshift-source"));
assertEquals("IntegrationSourceNotFoundFault", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
}
@SuppressWarnings("unchecked")
private Instance<RequestContext> mutableContext() {
RequestContext rc = mock(RequestContext.class);