fix(cloudformation): forward Firehose processing and logging configuration (#6277)

* feat(firehose): store and echo CloudWatchLoggingOptions on S3 destinations

CreateDeliveryStream and UpdateDestination silently dropped CloudWatchLoggingOptions because the S3 destination model had no such member. The block is now stored and echoed on both ExtendedS3DestinationDescription and S3DestinationDescription, defaulting to {"Enabled": false} when omitted, as real AWS does. UpdateDestination merges it member-wise, so an update naming only Enabled keeps the stored log group and stream.

* fix(cloudformation): forward Firehose processing and logging configuration

FirehoseCfnProvisioner now reads RoleARN, ErrorOutputPrefix, CloudWatchLoggingOptions and, for the extended S3 destination only, ProcessingConfiguration, resolving intrinsics before handing them to the service. A Lambda transform declared in a template therefore runs on delivery and is echoed by DescribeDeliveryStream, as on AWS. An omitted member stays null so an UpdateStack keeps the stored value, and an unreadable block fails the resource with ValidationError.

* test(cloudformation): cover a stack Firehose stream's Lambda transform end to end

A stack-created extended S3 stream now reads back its role, error prefix, logging options and
Lambda processor, runs that processor on delivery, and picks up a new function on UpdateStack.

* docs(firehose): describe logging options and the CloudFormation members applied

Document how CloudWatchLoggingOptions is stored, defaulted and merged on the S3 destinations, and note which DeliveryStream properties the CloudFormation provisioner applies.

* fix(cloudformation): validate a Firehose stream's forwarded destination like CreateDeliveryStream

The provisioner now runs the same wire-shape validation CreateDeliveryStream applies, so a bad processor or CompressionFormat fails the resource instead of being stored. A structured destination member present as anything but an object also fails rather than being silently dropped.

* docs(cloudformation): name every Firehose property the provisioner applies

* fix(firehose): validate CloudWatchLoggingOptions names against AWS constraints

LogGroupName and LogStreamName are now checked against AWS's 512-character bound and their modeled patterns, reporting both rules when both fail, as probed against real AWS.

* chore: retrigger CI after a transient npm publish race

native arm64 / sdk-test-node ran npm install between the publication of @aws-sdk/lib-storage 3.1156.0 and @aws-sdk/client-s3 3.1156.0, and failed with ERESOLVE.

* test(firehose): share the delivery and Lambda transform helpers in FirehoseRequests

Moves encode, putRecordBatch, firstKey and the record-id driven Lambda transform answer out of CloudFormationFirehoseIntegrationTest and FirehoseLambdaTransformIntegrationTest into one testing fixture both now use.

* fix(firehose): require both log names when CloudWatch logging is enabled

With Enabled true, a missing or empty LogGroupName or LogStreamName is now refused with AWS's InvalidArgumentException, group before stream, on the merged result for UpdateDestination and ahead of the other semantic checks, as probed against real AWS.

* fix(firehose): fill the defaults on a Redshift destination's S3 backup

Create and describe now apply the S3 defaults, including CloudWatchLoggingOptions Enabled false, to a Redshift destination's backup configuration as well as its intermediate one, so persisted streams heal on read.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-23 07:00:08 -04:00
1 parent ba353021e1
commit deeb3b3075
15 files changed
+814 -98

No files matched your search

@@ -1,18 +1,37 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.github.hectorvent.floci.testing.FirehoseRequests.answerTransforms;
import static io.github.hectorvent.floci.testing.FirehoseRequests.encode;
import static io.github.hectorvent.floci.testing.FirehoseRequests.firstKey;
import static io.github.hectorvent.floci.testing.FirehoseRequests.putRecordBatch;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
/**
* End-to-end check that CloudFormation provisions an AWS::KinesisFirehose::DeliveryStream for real
* (into FirehoseService) rather than stubbing it. Delivery streams are metadata (no container), so
* the test is Docker-free.
* the test is Docker-free; the Lambda processor is mocked for the same reason.
*/
@QuarkusTest
class CloudFormationFirehoseIntegrationTest {
@@ -21,6 +40,22 @@ class CloudFormationFirehoseIntegrationTest {
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String FIREHOSE_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/firehose/aws4_request";
private static final String FIREHOSE_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String EXTENDED_DESTINATION =
"DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.";
private static final String LAMBDA_ARN = EXTENDED_DESTINATION
+ "ProcessingConfiguration.Processors[0].Parameters.find { it.ParameterName == 'LambdaArn' }.ParameterValue";
@InjectMock
LambdaService lambdaService;
@Inject
FirehoseService firehoseService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createStackProvisionsDeliveryStreamVisibleToFirehose() {
@@ -90,4 +125,122 @@ class CloudFormationFirehoseIntegrationTest {
.body(containsString(streamName))
.body(containsString("GZIP"));
}
@Test
void aStackStreamRunsItsLambdaProcessorAndReadsBackItsLogging() {
String suffix = Long.toString(System.nanoTime(), 36);
String streamName = "cfn-firehose-transform-" + suffix;
String stackName = "cfn-firehose-transform-stack-" + suffix;
String bucket = "cfn-firehose-transform-" + suffix;
String logGroup = "/aws/kinesisfirehose/" + suffix;
String firstFunction = "transform-" + suffix;
String secondFunction = "transform-next-" + suffix;
String firstArn = "arn:aws:lambda:us-east-1:000000000000:function:" + firstFunction;
String secondArn = "arn:aws:lambda:us-east-1:000000000000:function:" + secondFunction;
stackRequest("CreateStack", stackName, transformTemplate(suffix, streamName, bucket, firstFunction));
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
describeDeliveryStream(streamName)
.body(EXTENDED_DESTINATION + "RoleARN", equalTo("arn:aws:iam::000000000000:role/firehose-delivery"))
.body(EXTENDED_DESTINATION + "ErrorOutputPrefix", equalTo("errors/!{firehose:error-output-type}/"))
.body(EXTENDED_DESTINATION + "CloudWatchLoggingOptions.Enabled", equalTo(true))
.body(EXTENDED_DESTINATION + "CloudWatchLoggingOptions.LogGroupName", equalTo(logGroup))
.body(EXTENDED_DESTINATION + "CloudWatchLoggingOptions.LogStreamName", equalTo("DestinationDelivery"))
.body(EXTENDED_DESTINATION + "ProcessingConfiguration.Enabled", equalTo(true))
.body(LAMBDA_ARN, equalTo(firstArn))
.body("DeliveryStreamDescription.Destinations[0].S3DestinationDescription"
+ ".CloudWatchLoggingOptions.LogGroupName", equalTo(logGroup));
List<byte[]> payloads = answerTransforms(lambdaService, (recordId, index) ->
"{\"recordId\":\"" + recordId + "\",\"result\":\"Ok\",\"data\":\"" + encode("TRANSFORMED-" + index) + "\"}");
putRecordBatch(streamName, "one", "two");
firehoseService.flush(streamName);
given()
.when()
.get("/" + bucket + "/" + firstKey(bucket, "data/"))
.then()
.statusCode(200)
.body(equalTo("TRANSFORMED-0\nTRANSFORMED-1\n"));
assertEquals(1, payloads.size());
verify(lambdaService).invokeArn(eq(firstArn), any(), any());
stackRequest("UpdateStack", stackName, transformTemplate(suffix, streamName, bucket, secondFunction));
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
describeDeliveryStream(streamName)
.body(LAMBDA_ARN, equalTo(secondArn))
.body(EXTENDED_DESTINATION + "CloudWatchLoggingOptions.LogGroupName", equalTo(logGroup));
}
private static String transformTemplate(String suffix, String streamName, String bucket, String function) {
return """
{
"Resources": {
"Logs": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "/aws/kinesisfirehose/%s"}
},
"Stream": {
"Type": "AWS::KinesisFirehose::DeliveryStream",
"Properties": {
"DeliveryStreamName": "%s",
"DeliveryStreamType": "DirectPut",
"ExtendedS3DestinationConfiguration": {
"BucketARN": "arn:aws:s3:::%s",
"RoleARN": {"Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/firehose-delivery"},
"Prefix": "data/",
"ErrorOutputPrefix": {"Fn::Join": ["", ["errors/", "!{firehose:error-output-type}/"]]},
"CloudWatchLoggingOptions": {
"Enabled": true,
"LogGroupName": {"Ref": "Logs"},
"LogStreamName": "DestinationDelivery"
},
"ProcessingConfiguration": {
"Enabled": true,
"Processors": [
{
"Type": "Lambda",
"Parameters": [
{
"ParameterName": "LambdaArn",
"ParameterValue": {"Fn::Sub": "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:%s"}
}
]
}
]
}
}
}
}
}
}
""".formatted(suffix, streamName, bucket, function);
}
private static void stackRequest(String action, String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private static ValidatableResponse describeDeliveryStream(String streamName) {
return given()
.header("Authorization", FIREHOSE_AUTH)
.header("X-Amz-Target", "Firehose_20150804.DescribeDeliveryStream")
.contentType(FIREHOSE_CONTENT_TYPE)
.body("{\"DeliveryStreamName\":\"" + streamName + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -57,6 +57,7 @@ class LeafCfnProvisionerTest {
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> i.getArgument(0));
ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack");
}
@@ -360,6 +361,114 @@ class LeafCfnProvisionerTest {
assertNull(s3.getValue().getPrefix());
}
@Test
void processingLoggingRoleAndErrorPrefixReachTheStream() {
ArgumentCaptor<DeliveryStreamDescription.S3Destination> s3 =
ArgumentCaptor.forClass(DeliveryStreamDescription.S3Destination.class);
when(firehose.createDeliveryStream(anyString(), s3.capture(), any())).thenReturn("arn");
provisioner.provision(resource("Stream", "AWS::KinesisFirehose::DeliveryStream"), props("""
{
"DeliveryStreamName": "s",
"ExtendedS3DestinationConfiguration": {
"BucketARN": "arn:bucket",
"RoleARN": "arn:aws:iam::000000000000:role/delivery",
"ErrorOutputPrefix": "errors/!{firehose:error-output-type}/",
"CloudWatchLoggingOptions": {"Enabled": true, "LogGroupName": "g", "LogStreamName": "st"},
"ProcessingConfiguration": {
"Enabled": true,
"Processors": [{"Type": "Lambda", "Parameters": [
{"ParameterName": "LambdaArn", "ParameterValue": "arn:aws:lambda:us-east-1:000000000000:function:f"}
]}]
}
}
}
"""), ctx);
DeliveryStreamDescription.S3Destination destination = s3.getValue();
assertEquals("arn:aws:iam::000000000000:role/delivery", destination.getRoleArn());
assertEquals("errors/!{firehose:error-output-type}/", destination.getErrorOutputPrefix());
assertEquals(Boolean.TRUE, destination.getCloudWatchLoggingOptions().getEnabled());
assertEquals("g", destination.getCloudWatchLoggingOptions().getLogGroupName());
assertEquals("st", destination.getCloudWatchLoggingOptions().getLogStreamName());
assertTrue(destination.isProcessingEnabled());
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:f", destination.getProcessingConfiguration()
.getProcessors().get(0).getParameters().get(0).getParameterValue());
}
@Test
void theLegacyDestinationCarriesLoggingButNoProcessor() {
ArgumentCaptor<DeliveryStreamDescription.S3Destination> s3 =
ArgumentCaptor.forClass(DeliveryStreamDescription.S3Destination.class);
when(firehose.createDeliveryStream(anyString(), s3.capture(), any())).thenReturn("arn");
provisioner.provision(resource("Stream", "AWS::KinesisFirehose::DeliveryStream"), props("""
{
"DeliveryStreamName": "s",
"S3DestinationConfiguration": {
"BucketARN": "arn:bucket",
"CloudWatchLoggingOptions": {"LogGroupName": "g"},
"ProcessingConfiguration": {"Enabled": true, "Processors": []}
}
}
"""), ctx);
assertEquals("g", s3.getValue().getCloudWatchLoggingOptions().getLogGroupName());
assertNull(s3.getValue().getProcessingConfiguration(),
"S3DestinationConfiguration models no processor, as on the API path");
}
@Test
void anUnreadableLoggingBlockFailsTheResource() {
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(
resource("Stream", "AWS::KinesisFirehose::DeliveryStream"), props("""
{
"DeliveryStreamName": "s",
"ExtendedS3DestinationConfiguration": {
"BucketARN": "arn:bucket",
"CloudWatchLoggingOptions": {"Enabled": {"not": "a boolean"}}
}
}
"""), ctx));
assertEquals("ValidationError", error.getErrorCode());
}
@Test
void aBlockThatIsNotAnObjectFailsTheResource() {
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(
resource("Stream", "AWS::KinesisFirehose::DeliveryStream"), props("""
{
"DeliveryStreamName": "s",
"ExtendedS3DestinationConfiguration": {
"BucketARN": "arn:bucket",
"ProcessingConfiguration": []
}
}
"""), ctx));
assertEquals("ValidationError", error.getErrorCode());
}
@Test
void anUnknownProcessorTypeFailsTheResource() {
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(
resource("Stream", "AWS::KinesisFirehose::DeliveryStream"), props("""
{
"DeliveryStreamName": "s",
"ExtendedS3DestinationConfiguration": {
"BucketARN": "arn:bucket",
"ProcessingConfiguration": {
"Enabled": true,
"Processors": [{"Type": "Lambd", "Parameters": [
{"ParameterName": "LambdaArn", "ParameterValue": "arn:aws:lambda:us-east-1:000000000000:function:f"}
]}]
}
}
}
"""), ctx));
assertEquals("ValidationException", error.getErrorCode());
verify(firehose, never()).createDeliveryStream(anyString(), any(), any());
}
@Test
void deleteReachesTheService() {
provisioner.delete("AWS::KinesisFirehose::DeliveryStream", "s", REGION);
@@ -54,6 +54,11 @@ class FirehoseExtendedS3IntegrationTest {
"Prefix": "events/data/",
"ErrorOutputPrefix": "events/errors/",
"CompressionFormat": "GZIP",
"CloudWatchLoggingOptions": {
"Enabled": true,
"LogGroupName": "/aws/kinesisfirehose/extended",
"LogStreamName": "DestinationDelivery"
},
"BufferingHints": { "SizeInMBs": 64, "IntervalInSeconds": 120 }
}
}
@@ -88,6 +93,10 @@ class FirehoseExtendedS3IntegrationTest {
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.BufferingHints.SizeInMBs", equalTo(64))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.BufferingHints.IntervalInSeconds", equalTo(120))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.EncryptionConfiguration.NoEncryptionConfig", equalTo("NoEncryption"))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.CloudWatchLoggingOptions.Enabled", equalTo(true))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.CloudWatchLoggingOptions.LogGroupName", equalTo("/aws/kinesisfirehose/extended"))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.CloudWatchLoggingOptions.LogStreamName", equalTo("DestinationDelivery"))
.body("DeliveryStreamDescription.Destinations[0].S3DestinationDescription.CloudWatchLoggingOptions.LogGroupName", equalTo("/aws/kinesisfirehose/extended"))
.body("DeliveryStreamDescription.Destinations[0].S3DestinationDescription.BucketARN", equalTo(BUCKET_ARN))
.body("DeliveryStreamDescription.Destinations[0].S3DestinationDescription.RoleARN", equalTo(ROLE_ARN));
}
@@ -124,6 +133,8 @@ class FirehoseExtendedS3IntegrationTest {
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.BufferingHints.SizeInMBs", equalTo(5))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.BufferingHints.IntervalInSeconds", equalTo(300))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.EncryptionConfiguration.NoEncryptionConfig", equalTo("NoEncryption"))
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.CloudWatchLoggingOptions.Enabled", equalTo(false))
.body("DeliveryStreamDescription.Destinations[0].S3DestinationDescription.CloudWatchLoggingOptions.Enabled", equalTo(false))
// #2200: a create response that omits S3BackupMode, followed by a later describe
// that fills it in, applied cleanly and then re-planned dirty forever in Terraform.
.body("DeliveryStreamDescription.Destinations[0].ExtendedS3DestinationDescription.S3BackupMode", equalTo("Disabled"));
@@ -435,6 +446,30 @@ class FirehoseExtendedS3IntegrationTest {
assertTrue(key.matches("events/" + TIME_PREFIX_REGEX + stream + SUFFIX_REGEX), key);
}
@Test
@Order(17)
void createDeliveryStreamRefusesEnabledLoggingWithoutAStreamName() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateDeliveryStream")
.body("""
{
"DeliveryStreamName": "logging-without-stream-name",
"ExtendedS3DestinationConfiguration": {
"RoleARN": "%s",
"BucketARN": "%s",
"CloudWatchLoggingOptions": { "Enabled": true, "LogGroupName": "g" }
}
}
""".formatted(ROLE_ARN, BUCKET_ARN))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidArgumentException"))
.body("message", equalTo("CloudWatch Log Stream Name is required if CloudWatch Logging is enabled"));
}
private void createDeliveryStream(String streamName, String bucket, String extraDestinationJson) {
given()
.contentType(CONTENT_TYPE)
@@ -1,7 +1,6 @@
package io.github.hectorvent.floci.services.firehose;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
@@ -9,24 +8,21 @@ import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.github.hectorvent.floci.testing.FirehoseRequests.answerTransforms;
import static io.github.hectorvent.floci.testing.FirehoseRequests.encode;
import static io.github.hectorvent.floci.testing.FirehoseRequests.firstKey;
import static io.github.hectorvent.floci.testing.FirehoseRequests.putRecordBatch;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
/**
* End-to-end coverage of the Lambda transform on the real delivery path: what
@@ -54,7 +50,6 @@ class FirehoseLambdaTransformIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "Firehose_20150804.";
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:transform";
private static final Pattern KEY_PATTERN = Pattern.compile("<Key>([^<]+)</Key>");
@InjectMock
LambdaService lambdaService;
@@ -69,8 +64,8 @@ class FirehoseLambdaTransformIntegrationTest {
String stream = "transform-ok-stream";
String bucket = "transform-ok-archive";
createDeliveryStream(stream, bucket);
respondWith((recordId, index) -> "{\"recordId\":\"" + recordId + "\",\"result\":\"Ok\",\"data\":\""
+ encode("TRANSFORMED-" + index) + "\"}");
answerTransforms(lambdaService, (recordId, index) ->
"{\"recordId\":\"" + recordId + "\",\"result\":\"Ok\",\"data\":\"" + encode("TRANSFORMED-" + index) + "\"}");
putRecordBatch(stream, "one", "two");
@@ -87,7 +82,7 @@ class FirehoseLambdaTransformIntegrationTest {
String stream = "transform-failed-stream";
String bucket = "transform-failed-archive";
createDeliveryStream(stream, bucket);
respondWith((recordId, index) -> index == 0
answerTransforms(lambdaService, (recordId, index) -> index == 0
? "{\"recordId\":\"" + recordId + "\",\"result\":\"ProcessingFailed\"}"
: "{\"recordId\":\"" + recordId + "\",\"result\":\"Ok\",\"data\":\"" + encode("kept") + "\"}");
@@ -116,7 +111,8 @@ class FirehoseLambdaTransformIntegrationTest {
String stream = "transform-dropped-stream";
String bucket = "transform-dropped-archive";
createDeliveryStream(stream, bucket);
respondWith((recordId, index) -> "{\"recordId\":\"" + recordId + "\",\"result\":\"Dropped\"}");
answerTransforms(lambdaService, (recordId, index) ->
"{\"recordId\":\"" + recordId + "\",\"result\":\"Dropped\"}");
putRecordBatch(stream, "one", "two");
@@ -126,7 +122,7 @@ class FirehoseLambdaTransformIntegrationTest {
.then()
.statusCode(200)
.extract().asString();
assertFalse(KEY_PATTERN.matcher(listing).find(), "expected no delivered object, got: " + listing);
assertFalse(listing.contains("<Key>"), "expected no delivered object, got: " + listing);
}
@Test
@@ -134,7 +130,7 @@ class FirehoseLambdaTransformIntegrationTest {
String stream = "transform-payload-stream";
String bucket = "transform-payload-archive";
createDeliveryStream(stream, bucket);
List<byte[]> payloads = respondWith((recordId, index) ->
List<byte[]> payloads = answerTransforms(lambdaService, (recordId, index) ->
"{\"recordId\":\"" + recordId + "\",\"result\":\"Dropped\"}");
putRecordBatch(stream, "one", "two");
@@ -146,39 +142,6 @@ class FirehoseLambdaTransformIntegrationTest {
assertTrue(payload.contains("\"data\":\"" + encode("two") + "\""), payload);
}
/**
* Answers each invocation from the record ids it actually carries, which the caller
* cannot name: they are minted per batch. Returns the payloads the mock received.
*/
private List<byte[]> respondWith(RecordResponder responder) {
List<byte[]> payloads = new ArrayList<>();
Mockito.when(lambdaService.invokeArn(anyString(), any(), any())).thenAnswer(invocation -> {
byte[] payload = invocation.getArgument(1);
payloads.add(payload);
List<String> entries = new ArrayList<>();
Matcher recordIds = Pattern.compile("\"recordId\":\"([^\"]+)\"")
.matcher(new String(payload, StandardCharsets.UTF_8));
for (int index = 0; recordIds.find(); index++) {
entries.add(responder.respond(recordIds.group(1), index));
}
InvokeResult result = new InvokeResult();
result.setStatusCode(200);
result.setPayload(("{\"records\":[" + String.join(",", entries) + "]}")
.getBytes(StandardCharsets.UTF_8));
return result;
});
return payloads;
}
@FunctionalInterface
private interface RecordResponder {
String respond(String recordId, int index);
}
private static String encode(String body) {
return Base64.getEncoder().encodeToString(body.getBytes(StandardCharsets.UTF_8));
}
private void createDeliveryStream(String streamName, String bucket) {
given()
.contentType(CONTENT_TYPE)
@@ -210,37 +173,4 @@ class FirehoseLambdaTransformIntegrationTest {
.statusCode(200)
.body("DeliveryStreamARN", notNullValue());
}
private void putRecordBatch(String streamName, String... bodies) {
List<String> records = new ArrayList<>();
for (String body : bodies) {
records.add("{\"Data\": \"" + encode(body) + "\"}");
}
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "PutRecordBatch")
.body("{ \"DeliveryStreamName\": \"" + streamName + "\", \"Records\": ["
+ String.join(",", records) + "] }")
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedPutCount", equalTo(0));
}
private String firstKey(String bucket, String prefix) {
String listing = given()
.when()
.get("/" + bucket)
.then()
.statusCode(200)
.extract().asString();
Matcher key = KEY_PATTERN.matcher(listing);
while (key.find()) {
if (key.group(1).startsWith(prefix)) {
return key.group(1);
}
}
throw new AssertionError("expected an object under " + prefix + " in " + bucket + ", got: " + listing);
}
}
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
@@ -84,8 +85,8 @@ class FirehoseRedshiftServiceTest {
mock(FirehoseLambdaTransformer.class), delivery, Runnable::run);
}
private void createStream(String extraMembers) throws Exception {
RedshiftDestination destination = mapper.readValue("""
private RedshiftDestination destination(String extraMembers) throws Exception {
return mapper.readValue("""
{"RoleARN": "arn:aws:iam::000000000000:role/firehose",
"ClusterJDBCURL": "jdbc:redshift://c1.abc.us-east-1.redshift.amazonaws.com:5439/dev",
"Username": "admin", "Password": "Secret123",
@@ -93,10 +94,18 @@ class FirehoseRedshiftServiceTest {
"S3Configuration": {"RoleARN": "arn:aws:iam::000000000000:role/firehose", "BucketARN": "arn:aws:s3:::stage"}
%s}
""".formatted(extraMembers), RedshiftDestination.class);
service.createDeliveryStream("us-east-1", STREAM, null, destination, List.of(), null, null);
}
private void createStream(String extraMembers) throws Exception {
service.createDeliveryStream("us-east-1", STREAM, null, destination(extraMembers), List.of(), null, null);
service.putRecord(STREAM, new Record("{\"id\":1}".getBytes(StandardCharsets.UTF_8)));
}
private S3Destination describedBackup(String streamName) {
return service.describeDeliveryStream(streamName).getDestinations().get(0)
.getRedshiftDestinationDescription().getS3Backup();
}
private void copyFails() {
doThrow(new IllegalStateException("relation does not exist"))
.when(delivery).copy(anyString(), anyString(), any(), anyString(), anyString());
@@ -169,6 +178,25 @@ class FirehoseRedshiftServiceTest {
verify(delivery, times(1)).copy(anyString(), anyString(), any(), eq("stage"), anyString());
}
@Test
void aRedshiftBackupGetsTheLoggingDefaultsOnCreate() throws Exception {
createStream(BACKUP_ENABLED);
service.createDeliveryStream("us-east-1", "rs-logging", null, destination(
", \"S3BackupMode\": \"Enabled\", \"S3BackupConfiguration\": "
+ "{\"RoleARN\": \"arn:aws:iam::000000000000:role/firehose\", \"BucketARN\": \"arn:aws:s3:::bk\","
+ " \"CloudWatchLoggingOptions\": {\"LogGroupName\": \"g\"}}"),
List.of(), null, null);
S3Destination omitted = describedBackup(STREAM);
assertEquals(false, omitted.getCloudWatchLoggingOptions().getEnabled());
assertEquals("UNCOMPRESSED", omitted.getCompressionFormat());
S3Destination withoutEnabled = describedBackup("rs-logging");
assertEquals(false, withoutEnabled.getCloudWatchLoggingOptions().getEnabled());
assertEquals("g", withoutEnabled.getCloudWatchLoggingOptions().getLogGroupName());
assertEquals("UNCOMPRESSED", withoutEnabled.getCompressionFormat());
}
@Test
void backupObjectUsesTheBackupConfigurationPrefix() throws Exception {
createStream(", \"S3BackupMode\": \"Enabled\", \"S3BackupConfiguration\": "
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
@@ -235,6 +236,34 @@ class FirehoseServiceTest {
"legacy entries from another region must not be adopted");
}
@Test
@SuppressWarnings("unchecked")
void aPersistedRedshiftBackupGetsTheDefaultsOnDescribe() {
S3Destination intermediate = new S3Destination();
intermediate.setBucketArn("arn:aws:s3:::stage");
S3Destination backup = new S3Destination();
backup.setBucketArn("arn:aws:s3:::bk");
RedshiftDestination redshift = new RedshiftDestination();
redshift.setS3BackupMode("Enabled");
redshift.setS3(intermediate);
redshift.setS3Backup(backup);
// Built the way Jackson reads a stored stream: the no-arg constructor fills no defaults.
DeliveryStreamDescription persisted = new DeliveryStreamDescription();
persisted.setDeliveryStreamName("persisted");
persisted.setDeliveryStreamARN("arn:aws:firehose:us-east-1:000000000000:deliverystream/persisted");
persisted.setAccountId("000000000000");
persisted.setDestinations(List.of(new DeliveryStreamDescription.Destination(redshift)));
AccountAwareStorageBackend<DeliveryStreamDescription> streams =
(AccountAwareStorageBackend<DeliveryStreamDescription>) backends.get("firehose/streams.json");
streams.putForAccount("000000000000", "us-east-1/persisted", persisted);
S3Destination described = firehoseService.describeDeliveryStream("persisted").getDestinations().get(0)
.getRedshiftDestinationDescription().getS3Backup();
assertEquals(false, described.getCloudWatchLoggingOptions().getEnabled());
assertEquals("UNCOMPRESSED", described.getCompressionFormat());
}
@Test
void isolatesSameStreamNameAcrossAccountsAndRegionsIncludingFlushAndDelete() {
String firstArn = firehoseService.createDeliveryStream("us-east-1", "111111111111", "shared", null,
@@ -387,6 +416,107 @@ class FirehoseServiceTest {
assertTrue(key.matches("events/2026/01/01/09/my-stream-3-2026-01-01-09-00-00-" + UUID_REGEX), key);
}
@Test
void cloudWatchLoggingOptionsDefaultToDisabledAndMergeMemberWise() {
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::logging-bucket");
firehoseService.createDeliveryStream("logged-stream", s3);
DeliveryStreamDescription.CloudWatchLoggingOptions logging =
firehoseService.describeDeliveryStream("logged-stream").s3Destination().getCloudWatchLoggingOptions();
assertEquals(Boolean.FALSE, logging.getEnabled());
assertNull(logging.getLogGroupName());
S3Destination enable = new S3Destination();
enable.setCloudWatchLoggingOptions(logging(true, "group", "stream"));
firehoseService.updateDestination("logged-stream", "1", "destinationId-000000000001", enable);
S3Destination disableOnly = new S3Destination();
disableOnly.setCloudWatchLoggingOptions(logging(false, null, null));
firehoseService.updateDestination("logged-stream", "2", "destinationId-000000000001", disableOnly);
logging = firehoseService.describeDeliveryStream("logged-stream").s3Destination().getCloudWatchLoggingOptions();
assertEquals(Boolean.FALSE, logging.getEnabled());
assertEquals("group", logging.getLogGroupName(), "an update naming only Enabled keeps the stored group");
assertEquals("stream", logging.getLogStreamName());
}
private static final String LOG_GROUP_REQUIRED =
"CloudWatch Log Group Name is required if CloudWatch Logging is enabled";
private static final String LOG_STREAM_REQUIRED =
"CloudWatch Log Stream Name is required if CloudWatch Logging is enabled";
@Test
void enabledLoggingRequiresTheGroupThenTheStreamName() {
assertLoggingRefused(LOG_GROUP_REQUIRED, () -> firehoseService.createDeliveryStream("no-names",
loggedDestination(logging(true, null, null))));
assertLoggingRefused(LOG_STREAM_REQUIRED, () -> firehoseService.createDeliveryStream("group-only",
loggedDestination(logging(true, "g", null))));
assertLoggingRefused(LOG_GROUP_REQUIRED, () -> firehoseService.createDeliveryStream("empty-names",
loggedDestination(logging(true, "", ""))));
firehoseService.createDeliveryStream("disabled-no-names", loggedDestination(logging(false, null, null)));
assertEquals(Boolean.FALSE, firehoseService.describeDeliveryStream("disabled-no-names")
.s3Destination().getCloudWatchLoggingOptions().getEnabled());
}
@Test
void anUpdateEnablingLoggingIsCheckedAgainstTheStoredNames() {
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::logging-bucket");
firehoseService.createDeliveryStream("enable-later", s3);
assertLoggingRefused(LOG_GROUP_REQUIRED, () -> firehoseService.updateDestination("enable-later", "1",
"destinationId-000000000001", loggedDestination(logging(true, null, null))));
assertEquals("1", firehoseService.describeDeliveryStream("enable-later").getVersionId());
firehoseService.updateDestination("enable-later", "1", "destinationId-000000000001",
loggedDestination(logging(false, "g", "s")));
firehoseService.updateDestination("enable-later", "2", "destinationId-000000000001",
loggedDestination(logging(true, null, null)));
DeliveryStreamDescription.CloudWatchLoggingOptions logging =
firehoseService.describeDeliveryStream("enable-later").s3Destination().getCloudWatchLoggingOptions();
assertEquals(Boolean.TRUE, logging.getEnabled());
assertEquals("g", logging.getLogGroupName());
assertEquals("s", logging.getLogStreamName());
assertLoggingRefused(LOG_STREAM_REQUIRED, () -> firehoseService.updateDestination("enable-later", "3",
"destinationId-000000000001", loggedDestination(logging(null, null, ""))));
assertEquals("s", firehoseService.describeDeliveryStream("enable-later")
.s3Destination().getCloudWatchLoggingOptions().getLogStreamName());
}
@Test
void theLoggingErrorPrecedesTheBufferingHintsOne() {
S3Destination s3 = loggedDestination(logging(true, null, null));
DeliveryStreamDescription.BufferingHints hints = new DeliveryStreamDescription.BufferingHints();
hints.setSizeInMBs(5);
s3.setBufferingHints(hints);
assertLoggingRefused(LOG_GROUP_REQUIRED, () -> firehoseService.createDeliveryStream("partial-hints", s3));
}
private static S3Destination loggedDestination(DeliveryStreamDescription.CloudWatchLoggingOptions logging) {
S3Destination s3 = new S3Destination();
s3.setBucketArn("arn:aws:s3:::logging-bucket");
s3.setCloudWatchLoggingOptions(logging);
return s3;
}
private static void assertLoggingRefused(String message, Runnable call) {
AwsException e = assertThrows(AwsException.class, call::run);
assertEquals("InvalidArgumentException", e.getErrorCode());
assertEquals(message, e.getMessage());
}
private static DeliveryStreamDescription.CloudWatchLoggingOptions logging(Boolean enabled, String group,
String stream) {
DeliveryStreamDescription.CloudWatchLoggingOptions options = new DeliveryStreamDescription.CloudWatchLoggingOptions();
options.setEnabled(enabled);
options.setLogGroupName(group);
options.setLogStreamName(stream);
return options;
}
@Test
void timeBasedFlushKeepsBufferWhileDefaultIntervalHasNotElapsed() {
firehoseService.createDeliveryStream("idle-stream", null);
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.firehose;
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.DeliveryStreamDescription.CloudWatchLoggingOptions;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessingConfiguration;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Processor;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ProcessorParameter;
@@ -759,4 +760,65 @@ class S3DestinationValidatorTest {
error.getMessage());
}
private static final String LOG_GROUP_PATTERN = "Member must satisfy regular expression pattern: "
+ "[\\.\\-_/#A-Za-z0-9]*";
private static final String LOG_STREAM_PATTERN = "Member must satisfy regular expression pattern: [^:*]*";
private static S3Destination withLogging(String logGroupName, String logStreamName) {
CloudWatchLoggingOptions logging = new CloudWatchLoggingOptions();
logging.setEnabled(true);
logging.setLogGroupName(logGroupName);
logging.setLogStreamName(logStreamName);
S3Destination config = new S3Destination();
config.setCloudWatchLoggingOptions(logging);
return config;
}
@Test
void logStreamNameWithAColonFailsItsPattern() {
AwsException error = assertThrows(AwsException.class, () -> S3DestinationValidator.validateWireShape(
withLogging(null, "bad:stream"), "extendedS3DestinationConfiguration"));
assertEquals("ValidationException", error.getErrorCode());
assertEquals("1 validation error detected: Value at 'extendedS3DestinationConfiguration"
+ ".cloudWatchLoggingOptions.logStreamName' failed to satisfy constraint: "
+ LOG_STREAM_PATTERN, error.getMessage());
}
/** Probed: unlike FileExtension, both rules are reported, the length one first. */
@Test
void anOverlongLogGroupNameWithABadCharacterReportsLengthThenPattern() {
AwsException error = assertThrows(AwsException.class, () -> S3DestinationValidator.validateWireShape(
withLogging("a".repeat(513) + " ", null), "extendedS3DestinationConfiguration"));
String path = "Value at 'extendedS3DestinationConfiguration.cloudWatchLoggingOptions.logGroupName'"
+ " failed to satisfy constraint: ";
assertEquals("2 validation errors detected: "
+ path + "Member must have length less than or equal to 512; "
+ path + LOG_GROUP_PATTERN, error.getMessage());
}
@Test
void logGroupViolationsPrecedeLogStreamOnes() {
AwsException error = assertThrows(AwsException.class, () -> S3DestinationValidator.validateWireShape(
withLogging("bad group", "bad:stream"), "s3DestinationConfiguration"));
assertEquals("2 validation errors detected: "
+ "Value at 's3DestinationConfiguration.cloudWatchLoggingOptions.logGroupName'"
+ " failed to satisfy constraint: " + LOG_GROUP_PATTERN + "; "
+ "Value at 's3DestinationConfiguration.cloudWatchLoggingOptions.logStreamName'"
+ " failed to satisfy constraint: " + LOG_STREAM_PATTERN, error.getMessage());
}
@Test
void wellFormedLoggingNamesPass() {
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(
withLogging("/aws/kinesisfirehose/my-stream", "DestinationDelivery"),
"extendedS3DestinationConfiguration"));
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(
withLogging("a".repeat(512), "b".repeat(512)), "extendedS3DestinationConfiguration"));
assertDoesNotThrow(() -> S3DestinationValidator.validateWireShape(
withLogging("", ""), "extendedS3DestinationConfiguration"));
}
}
@@ -0,0 +1,89 @@
package io.github.hectorvent.floci.testing;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
public final class FirehoseRequests {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final Pattern RECORD_ID_PATTERN = Pattern.compile("\"recordId\":\"([^\"]+)\"");
private static final Pattern KEY_PATTERN = Pattern.compile("<Key>([^<]+)</Key>");
private FirehoseRequests() {}
public static String encode(String body) {
return Base64.getEncoder().encodeToString(body.getBytes(StandardCharsets.UTF_8));
}
public static void putRecordBatch(String streamName, String... bodies) {
List<String> records = new ArrayList<>();
for (String body : bodies) {
records.add("{\"Data\": \"" + encode(body) + "\"}");
}
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", "Firehose_20150804.PutRecordBatch")
.body("{\"DeliveryStreamName\": \"" + streamName + "\", \"Records\": ["
+ String.join(",", records) + "]}")
.when().post("/")
.then()
.statusCode(200)
.body("FailedPutCount", equalTo(0));
}
public static String firstKey(String bucket, String prefix) {
String listing = given()
.when().get("/" + bucket)
.then()
.statusCode(200)
.extract().asString();
Matcher key = KEY_PATTERN.matcher(listing);
while (key.find()) {
if (key.group(1).startsWith(prefix)) {
return key.group(1);
}
}
throw new AssertionError("expected an object under " + prefix + " in " + bucket + ", got: " + listing);
}
/**
* Answers each transform invocation from the record ids it actually carries, which the caller
* cannot name: they are minted per batch. Returns the payloads the mock received.
*/
public static List<byte[]> answerTransforms(LambdaService lambdaService, RecordResponder responder) {
List<byte[]> payloads = new ArrayList<>();
Mockito.when(lambdaService.invokeArn(anyString(), any(), any())).thenAnswer(invocation -> {
byte[] payload = invocation.getArgument(1);
payloads.add(payload);
List<String> entries = new ArrayList<>();
Matcher recordIds = RECORD_ID_PATTERN.matcher(new String(payload, StandardCharsets.UTF_8));
for (int index = 0; recordIds.find(); index++) {
entries.add(responder.respond(recordIds.group(1), index));
}
InvokeResult result = new InvokeResult();
result.setStatusCode(200);
result.setPayload(("{\"records\":[" + String.join(",", entries) + "]}")
.getBytes(StandardCharsets.UTF_8));
return result;
});
return payloads;
}
@FunctionalInterface
public interface RecordResponder {
String respond(String recordId, int index);
}
}