Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat: add Firehose support, virtual-hosted S3, and DynamoDB fix (#14)

Nahuel Nucera2c2f51abfae8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cdb3850b..da7c1942 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,27 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.0.7] — 2026-03-27
+
+### Added
+- **Amazon Data Firehose** (`services/firehose.py`) — full control and data plane
+ - `CreateDeliveryStream`, `DeleteDeliveryStream`, `DescribeDeliveryStream`, `ListDeliveryStreams`
+ - `PutRecord`, `PutRecordBatch` — base64-encoded record ingestion; S3-destination streams write records synchronously to the local S3 emulator
+ - `UpdateDestination` — concurrency-safe via `CurrentDeliveryStreamVersionId` / `VersionId`
+ - `TagDeliveryStream`, `UntagDeliveryStream`, `ListTagsForDeliveryStream`
+ - `StartDeliveryStreamEncryption`, `StopDeliveryStreamEncryption`
+ - Destination types: `ExtendedS3`, `S3` (deprecated alias), `HttpEndpoint`, `Redshift`, `OpenSearch`, `Splunk`, `Snowflake`, `Iceberg`
+ - Credential scope: `kinesis-firehose`; target prefix: `Firehose_20150804`
+ - AWS-compliant `DescribeDeliveryStream` response: `EncryptionConfiguration` always present in `ExtendedS3DestinationDescription` (default `NoEncryption`); `DeliveryStreamEncryptionConfiguration` only included when encryption is configured; `Source` block populated for `KinesisStreamAsSource` streams
+ - `UpdateDestination` merges fields when destination type is unchanged; replaces fully on type change — matching AWS behaviour
+ - 16 integration tests, all passing
+- **Virtual-hosted style S3**: `{bucket}.localhost[:{port}]` host header routing — requests are rewritten to path-style and forwarded to the S3 handler; compatible with AWS SDK virtual-hosted endpoint configuration
+
+### Fixed
+- **DynamoDB expression evaluator short-circuit bug**: `OR`/`AND` operators in `ConditionExpression` and `FilterExpression` now always consume both operands' tokens before applying the logical result — Python's boolean short-circuit was skipping right-hand token consumption when the left operand was already truthy/falsy, causing `Invalid expression: Expected RPAREN, got NAME_REF` on expressions like `attribute_not_exists(#0) OR #1 <= :0` (reported by PynamoDB users with numeric `ExpressionAttributeNames` keys)
+
+---
+
## [1.0.6] — 2026-03-27
### Added
@@ -211,6 +232,5 @@ Initial public release. Built as a free, open-source alternative to LocalStack.
- Cognito (user pools, sign-up/sign-in)
- Route53 (hosted zones, record sets)
- ACM (certificate management)
-- Firehose
- Virtual-hosted style S3 (`bucket.localhost:4566` routing)
diff --git a/README.md b/README.md
index 6d3e61ff..cb3b07e6 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@
LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.
-- **22 AWS services** emulated on a single port (4566)
+- **23 AWS services** emulated on a single port (4566)
- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK
- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers
- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
@@ -199,6 +199,7 @@ sfn.create_state_machine(
| **ElastiCache** | CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, RebootCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups, ModifyReplicationGroup, IncreaseReplicaCount, DecreaseReplicaCount, CreateCacheSubnetGroup, DescribeCacheSubnetGroups, ModifyCacheSubnetGroup, DeleteCacheSubnetGroup, CreateCacheParameterGroup, DescribeCacheParameterGroups, ModifyCacheParameterGroup, ResetCacheParameterGroup, DeleteCacheParameterGroup, DescribeCacheParameters, DescribeCacheEngineVersions, CreateUser, DescribeUsers, DeleteUser, ModifyUser, CreateUserGroup, DescribeUserGroups, DeleteUserGroup, ModifyUserGroup, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, DescribeEvents | `CreateCacheCluster` spins up real Redis/Memcached Docker container |
| **Glue** | CreateDatabase, DeleteDatabase, GetDatabase, GetDatabases, CreateTable, DeleteTable, GetTable, GetTables, UpdateTable, BatchDeleteTable, CreatePartition, GetPartitions, BatchCreatePartition, BatchGetPartition, CreatePartitionIndex, GetPartitionIndexes, CreateConnection, GetConnections, CreateCrawler, UpdateCrawler, GetCrawler, GetCrawlerMetrics, StartCrawler, CreateJob, GetJob, GetJobs, StartJobRun, GetJobRun, GetJobRuns, CreateTrigger, GetTrigger, DeleteTrigger, UpdateTrigger, StartTrigger, StopTrigger, ListTriggers, GetTriggers, CreateWorkflow, GetWorkflow, DeleteWorkflow, UpdateWorkflow, StartWorkflowRun, CreateSecurityConfiguration, GetSecurityConfiguration, GetSecurityConfigurations, DeleteSecurityConfiguration, CreateClassifier, GetClassifier, GetClassifiers, DeleteClassifier, TagResource, UntagResource, GetTags | Python shell jobs actually execute via subprocess |
| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |
+| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId` |
---
@@ -409,19 +410,19 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (434 tests across all 21 services)
+# Run the full test suite (450 tests across all 23 services)
pytest tests/ -v
```
Expected output:
```
-collected 434 items
+collected 450 items
tests/test_services.py::test_s3_create_bucket PASSED
...
tests/test_services.py::test_apigwv1_execute_mock_response_parameters PASSED
-434 passed in ~60s
+450 passed in ~60s
```
---
@@ -507,6 +508,7 @@ config:
| **Glue Data Catalog + Jobs** | ✅ | ❌ | ✅ |
| **API Gateway v2 (HTTP API)** | ✅ | ✅ | ✅ |
| **API Gateway v1 (REST API)** | ✅ | ✅ | ✅ |
+| **Firehose** | ✅ | ✅ | ✅ |
| Cognito | ❌ | ✅ | ✅ |
| CloudFormation | ❌ | partial | ✅ |
| Cost | **Free** | Was free, now paid | $35+/mo |
diff --git a/app.py b/app.py
index 9ac10e49..ce53fe8d 100644
--- a/app.py
+++ b/app.py
@@ -16,6 +16,9 @@ from urllib.parse import parse_qs, urlparse
# Matches host headers like "{apiId}.execute-api.localhost" or "{apiId}.execute-api.localhost:4566"
_EXECUTE_API_RE = re.compile(r"^([a-f0-9]{8})\.execute-api\.localhost(?::\d+)?$")
+# Matches virtual-hosted S3: "{bucket}.localhost" or "{bucket}.localhost:4566"
+# Must not match execute-api or other known sub-services
+_S3_VHOST_RE = re.compile(r"^([^.]+)\.localhost(?::\d+)?$")
from core.router import detect_service, extract_region, extract_account_id
from core.persistence import save_all, load_state, PERSIST_STATE
@@ -23,6 +26,7 @@ from services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwa
from services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctions
from services import ecs, rds, elasticache, glue, athena
from services import apigateway
+from services import firehose
from services import apigateway_v1
from services.iam_sts import handle_iam_request, handle_sts_request
@@ -56,6 +60,7 @@ SERVICE_HANDLERS = {
"glue": glue.handle_request,
"athena": athena.handle_request,
"apigateway": apigateway.handle_request,
+ "firehose": firehose.handle_request,
}
SERVICE_NAME_ALIASES = {
@@ -66,6 +71,7 @@ SERVICE_NAME_ALIASES = {
"stepfunctions": "states",
"execute-api": "apigateway",
"apigatewayv2": "apigateway",
+ "kinesis-firehose": "firehose",
}
@@ -101,7 +107,7 @@ BANNER = r"""
Local AWS Service Emulator — Port {port}
Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,
SSM, EventBridge, Kinesis, CloudWatch, SES, Step Functions,
- ECS, RDS, ElastiCache, Glue, Athena, API Gateway
+ ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose
"""
@@ -190,6 +196,34 @@ async def app(scope, receive, send):
await _send_response(send, status, resp_headers, resp_body)
return
+ # Virtual-hosted S3: {bucket}.localhost[:{port}] — rewrite to path-style and forward to S3
+ _s3_vhost = _S3_VHOST_RE.match(host)
+ if _s3_vhost and not _execute_match:
+ bucket = _s3_vhost.group(1)
+ _non_s3_hosts = {"s3", "sqs", "sns", "dynamodb", "lambda", "iam", "sts",
+ "secretsmanager", "logs", "ssm", "events", "kinesis",
+ "monitoring", "ses", "states", "ecs", "rds", "elasticache",
+ "glue", "athena", "apigateway"}
+ if bucket not in _non_s3_hosts:
+ vhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"
+ try:
+ status, resp_headers, resp_body = await s3.handle_request(
+ method, vhost_path, headers, body, query_params
+ )
+ except Exception as e:
+ logger.exception(f"Error handling virtual-hosted S3 request: {e}")
+ status, resp_headers, resp_body = 500, {"Content-Type": "application/xml"}, (
+ f"<Error><Code>InternalError</Code><Message>{e}</Message></Error>".encode()
+ )
+ resp_headers.update({
+ "Access-Control-Allow-Origin": "*",
+ "x-amzn-requestid": request_id,
+ "x-amz-request-id": request_id,
+ "x-amz-id-2": request_id,
+ })
+ await _send_response(send, status, resp_headers, resp_body)
+ return
+
service = detect_service(method, path, headers, query_params)
region = extract_region(headers)
@@ -317,6 +351,7 @@ def _reset_all_state():
(glue, glue.reset), (athena, athena.reset),
(apigateway, apigateway.reset),
(apigateway_v1, apigateway_v1.reset),
+ (firehose, firehose.reset),
]:
try:
fn()
diff --git a/core/router.py b/core/router.py
index ce59827e..6efafc62 100644
--- a/core/router.py
+++ b/core/router.py
@@ -96,6 +96,10 @@ SERVICE_PATTERNS = {
"target_prefixes": ["AmazonAthena"],
"host_patterns": [r"athena\."],
},
+ "firehose": {
+ "target_prefixes": ["Firehose_20150804"],
+ "host_patterns": [r"firehose\.", r"kinesis-firehose\."],
+ },
"apigateway": {
"host_patterns": [r"apigateway\.", r"execute-api\."],
"path_patterns": [r"^/v2/apis"],
@@ -138,6 +142,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"elasticache": "elasticache",
"glue": "glue",
"athena": "athena",
+ "kinesis-firehose": "firehose",
}
if svc_name in scope_map:
return scope_map[svc_name]
diff --git a/services/dynamodb.py b/services/dynamodb.py
index 8c10308d..cd8faf9b 100644
--- a/services/dynamodb.py
+++ b/services/dynamodb.py
@@ -883,14 +883,16 @@ class _ExprEval:
left = self._and_expr()
while self._is_kw('OR'):
self.advance()
- left = left or self._and_expr()
+ right = self._and_expr()
+ left = left or right
return left
def _and_expr(self):
left = self._not_expr()
while self._is_kw('AND'):
self.advance()
- left = self._not_expr() and left
+ right = self._not_expr()
+ left = left and right
return left
def _not_expr(self):
diff --git a/services/firehose.py b/services/firehose.py
new file mode 100644
index 00000000..87c5c09b
--- /dev/null
+++ b/services/firehose.py
@@ -0,0 +1,568 @@
+"""
+Amazon Data Firehose (formerly Kinesis Data Firehose) Emulator.
+JSON-based API via X-Amz-Target (Firehose_20150804).
+
+Supports:
+ CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream,
+ ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination,
+ TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream,
+ StartDeliveryStreamEncryption, StopDeliveryStreamEncryption.
+
+Destinations supported: ExtendedS3, S3 (deprecated alias), HttpEndpoint.
+Records put to an S3 destination are written synchronously to the local S3
+emulator (bucket must already exist). All other destinations buffer records
+in-memory (accessible for testing via PutRecord/PutRecordBatch round-trip).
+"""
+
+import asyncio
+import base64
+import json
+import logging
+import threading
+import time
+
+from core.responses import json_response, error_response_json, new_uuid, now_epoch
+
+logger = logging.getLogger("firehose")
+
+ACCOUNT_ID = "000000000000"
+REGION = "us-east-1"
+
+# ─── in-memory state ──────────────────────────────────────────────────────────
+
+_streams: dict = {} # name -> stream descriptor
+_lock = threading.Lock()
+_dest_counter = 0
+
+
+def reset():
+ global _streams, _dest_counter
+ with _lock:
+ _streams = {}
+ _dest_counter = 0
+
+
+# ─── helpers ─────────────────────────────────────────────────────────────────
+
+def _stream_arn(name: str) -> str:
+ return f"arn:aws:firehose:{REGION}:{ACCOUNT_ID}:deliverystream/{name}"
+
+
+def _next_dest_id() -> str:
+ global _dest_counter
+ _dest_counter += 1
+ return f"destinationId-{_dest_counter:012d}"
+
+
+def _not_found(name: str):
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"Firehose {name} under account {ACCOUNT_ID} not found.",
+ 400,
+ )
+
+
+def _in_use(name: str):
+ return error_response_json(
+ "ResourceInUseException",
+ f"Firehose {name} is not in the ACTIVE state.",
+ 400,
+ )
+
+
+def _invalid(msg: str):
+ return error_response_json("InvalidArgumentException", msg, 400)
+
+
+def _dest_description(dest: dict) -> dict:
+ """Return the destination description block for DescribeDeliveryStream."""
+ dtype = dest["type"]
+ out = {"DestinationId": dest["id"]}
+ if dtype in ("ExtendedS3", "S3"):
+ key = "ExtendedS3DestinationDescription" if dtype == "ExtendedS3" else "S3DestinationDescription"
+ cfg = dest["config"]
+ desc = {
+ "BucketARN": cfg.get("BucketARN", ""),
+ "RoleARN": cfg.get("RoleARN", ""),
+ "BufferingHints": cfg.get("BufferingHints", {"SizeInMBs": 5, "IntervalInSeconds": 300}),
+ "CompressionFormat": cfg.get("CompressionFormat", "UNCOMPRESSED"),
+ "EncryptionConfiguration": cfg.get("EncryptionConfiguration", {"NoEncryptionConfig": "NoEncryption"}),
+ "Prefix": cfg.get("Prefix", ""),
+ "ErrorOutputPrefix": cfg.get("ErrorOutputPrefix", ""),
+ "S3BackupMode": cfg.get("S3BackupMode", "Disabled"),
+ }
+ for opt in ("ProcessingConfiguration", "CloudWatchLoggingOptions",
+ "DataFormatConversionConfiguration", "DynamicPartitioningConfiguration"):
+ if opt in cfg:
+ desc[opt] = cfg[opt]
+ out[key] = desc
+ elif dtype == "HttpEndpoint":
+ cfg = dest["config"]
+ out["HttpEndpointDestinationDescription"] = {
+ "EndpointConfiguration": cfg.get("EndpointConfiguration", {}),
+ "BufferingHints": cfg.get("BufferingHints", {"SizeInMBs": 5, "IntervalInSeconds": 300}),
+ "S3BackupMode": cfg.get("S3BackupMode", "FailedDataOnly"),
+ }
+ else:
+ out[f"{dtype}DestinationDescription"] = dest["config"]
+ return out
+
+
+def _build_description(stream: dict) -> dict:
+ desc = {
+ "DeliveryStreamName": stream["name"],
+ "DeliveryStreamARN": stream["arn"],
+ "DeliveryStreamStatus": stream["status"],
+ "DeliveryStreamType": stream["type"],
+ "VersionId": str(stream["version"]),
+ "CreateTimestamp": stream["created_at"],
+ "LastUpdateTimestamp": stream["updated_at"],
+ "HasMoreDestinations": False,
+ "Destinations": [_dest_description(d) for d in stream["destinations"]],
+ }
+ enc = stream.get("encryption")
+ if enc:
+ desc["DeliveryStreamEncryptionConfiguration"] = enc
+ # Source block — only present for non-DirectPut streams
+ if stream["type"] == "KinesisStreamAsSource" and stream.get("kinesis_source"):
+ desc["Source"] = {"KinesisStreamSourceDescription": stream["kinesis_source"]}
+ return desc
+
+
+def _resolve_dest_type_and_config(data: dict):
+ """Extract destination type and config from CreateDeliveryStream / UpdateDestination request."""
+ for key, dtype in (
+ ("ExtendedS3DestinationConfiguration", "ExtendedS3"),
+ ("S3DestinationConfiguration", "S3"),
+ ("HttpEndpointDestinationConfiguration", "HttpEndpoint"),
+ ("RedshiftDestinationConfiguration", "Redshift"),
+ ("ElasticsearchDestinationConfiguration", "Elasticsearch"),
+ ("AmazonopensearchserviceDestinationConfiguration", "AmazonOpenSearch"),
+ ("AmazonOpenSearchServerlessDestinationConfiguration", "AmazonOpenSearchServerless"),
+ ("SplunkDestinationConfiguration", "Splunk"),
+ ("SnowflakeDestinationConfiguration", "Snowflake"),
+ ("IcebergDestinationConfiguration", "Iceberg"),
+ ):
+ if key in data:
+ return dtype, data[key]
+ return None, None
+
+
+def _resolve_dest_update_config(data: dict):
+ """Extract destination type and config from UpdateDestination request."""
+ for key, dtype in (
+ ("ExtendedS3DestinationUpdate", "ExtendedS3"),
+ ("S3DestinationUpdate", "S3"),
+ ("HttpEndpointDestinationUpdate", "HttpEndpoint"),
+ ("RedshiftDestinationUpdate", "Redshift"),
+ ("ElasticsearchDestinationUpdate", "Elasticsearch"),
+ ("AmazonopensearchserviceDestinationUpdate", "AmazonOpenSearch"),
+ ("AmazonOpenSearchServerlessDestinationUpdate", "AmazonOpenSearchServerless"),
+ ("SplunkDestinationUpdate", "Splunk"),
+ ("SnowflakeDestinationUpdate", "Snowflake"),
+ ("IcebergDestinationUpdate", "Iceberg"),
+ ):
+ if key in data:
+ return dtype, data[key]
+ return None, None
+
+
+def _deliver_to_s3(stream: dict, dest: dict, record_data: bytes):
+ """Best-effort delivery of a record to the local S3 emulator.
+
+ Called while holding _lock so must not block the event loop.
+ Schedules a coroutine on the running loop (fire-and-forget).
+ """
+ try:
+ from services import s3 as s3_svc
+
+ cfg = dest["config"]
+ bucket_arn = cfg.get("BucketARN", "")
+ bucket = bucket_arn.split(":::")[-1] if ":::" in bucket_arn else bucket_arn
+ prefix = cfg.get("Prefix", "")
+ ts = time.strftime("%Y/%m/%d/%H", time.gmtime())
+ key = f"{prefix}{ts}/{stream['name']}-{new_uuid()}"
+
+ async def _put():
+ fake_headers = {
+ "content-type": "application/octet-stream",
+ "content-length": str(len(record_data)),
+ "host": "s3.localhost",
+ }
+ await s3_svc.handle_request("PUT", f"/{bucket}/{key}", fake_headers, record_data, {})
+
+ try:
+ loop = asyncio.get_running_loop()
+ loop.create_task(_put())
+ except RuntimeError:
+ asyncio.run(_put())
+ except Exception as e:
+ logger.warning("Firehose S3 delivery failed: %s", e)
+
+
+def _record_id() -> str:
+ """Generate a Firehose-style RecordId (long numeric string)."""
+ ts = int(time.time() * 1000)
+ uid = new_uuid().replace("-", "")
+ return f"{ts:020d}{uid}"
+
+
+# ─── operations ──────────────────────────────────────────────────────────────
+
+def _create_delivery_stream(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ if not name:
+ return _invalid("DeliveryStreamName is required.")
+
+ with _lock:
+ if name in _streams:
+ return error_response_json(
+ "ResourceInUseException",
+ f"Delivery stream {name} already exists.",
+ 400,
+ )
+ if len(_streams) >= 5000:
+ return error_response_json(
+ "LimitExceededException",
+ "You have reached the limit on the number of delivery streams.",
+ 400,
+ )
+
+ dtype, cfg = _resolve_dest_type_and_config(data)
+ # A stream with no destination is valid (destination added later via UpdateDestination)
+ destinations = []
+ if dtype and cfg is not None:
+ destinations.append({
+ "id": _next_dest_id(),
+ "type": dtype,
+ "config": cfg,
+ "records": [],
+ })
+
+ stream_type = data.get("DeliveryStreamType", "DirectPut")
+ now = now_epoch()
+ stream = {
+ "name": name,
+ "arn": _stream_arn(name),
+ "status": "ACTIVE",
+ "type": stream_type,
+ "version": 1,
+ "created_at": now,
+ "updated_at": now,
+ "destinations": destinations,
+ "tags": {t["Key"]: t.get("Value", "") for t in data.get("Tags", [])},
+ "encryption": None,
+ "kinesis_source": None,
+ }
+
+ # Capture Kinesis source config for Source block in DescribeDeliveryStream
+ if stream_type == "KinesisStreamAsSource":
+ ks_cfg = data.get("KinesisStreamSourceConfiguration", {})
+ stream["kinesis_source"] = {
+ "KinesisStreamARN": ks_cfg.get("KinesisStreamARN", ""),
+ "RoleARN": ks_cfg.get("RoleARN", ""),
+ "DeliveryStartTimestamp": now,
+ }
+
+ enc_input = data.get("DeliveryStreamEncryptionConfigurationInput")
+ if enc_input:
+ enc = {"Status": "ENABLED", "KeyType": enc_input.get("KeyType", "AWS_OWNED_CMK")}
+ if "KeyARN" in enc_input:
+ enc["KeyARN"] = enc_input["KeyARN"]
+ stream["encryption"] = enc
+
+ _streams[name] = stream
+
+ return json_response({"DeliveryStreamARN": stream["arn"]})
+
+
+def _delete_delivery_stream(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ with _lock:
+ if name not in _streams:
+ return _not_found(name)
+ stream = _streams[name]
+ if stream["status"] == "CREATING":
+ return _in_use(name)
+ del _streams[name]
+ return json_response({})
+
+
+def _describe_delivery_stream(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ desc = _build_description(stream)
+ return json_response({"DeliveryStreamDescription": desc})
+
+
+def _list_delivery_streams(data: dict):
+ dtype_filter = data.get("DeliveryStreamType")
+ limit = min(int(data.get("Limit", 10)), 10000)
+ start = data.get("ExclusiveStartDeliveryStreamName")
+
+ with _lock:
+ if dtype_filter:
+ names = sorted(n for n, s in _streams.items() if s["type"] == dtype_filter)
+ else:
+ names = sorted(_streams.keys())
+
+ if start:
+ try:
+ idx = names.index(start)
+ names = names[idx + 1:]
+ except ValueError:
+ pass
+
+ has_more = len(names) > limit
+ return json_response({
+ "DeliveryStreamNames": names[:limit],
+ "HasMoreDeliveryStreams": has_more,
+ })
+
+
+def _put_record(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ record = data.get("Record", {})
+ raw_data = record.get("Data", "")
+
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ if stream["status"] != "ACTIVE":
+ return error_response_json("ServiceUnavailableException", "Service unavailable.", 503)
+
+ try:
+ decoded = base64.b64decode(raw_data)
+ except Exception:
+ return _invalid("Record.Data must be valid base64.")
+
+ if len(decoded) > 1024 * 1000:
+ return _invalid("Record size exceeds 1,000 KiB limit.")
+
+ record_id = _record_id()
+ for dest in stream["destinations"]:
+ dest["records"].append({"id": record_id, "data": raw_data, "ts": now_epoch()})
+ if dest["type"] in ("ExtendedS3", "S3"):
+ _deliver_to_s3(stream, dest, decoded)
+
+ return json_response({"RecordId": record_id, "Encrypted": False})
+
+
+def _put_record_batch(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ records = data.get("Records", [])
+
+ if not records:
+ return _invalid("Records must not be empty.")
+ if len(records) > 500:
+ return _invalid("A maximum of 500 records can be sent per batch.")
+
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ if stream["status"] != "ACTIVE":
+ return error_response_json("ServiceUnavailableException", "Service unavailable.", 503)
+
+ responses = []
+ failed = 0
+ for rec in records:
+ raw_data = rec.get("Data", "")
+ try:
+ decoded = base64.b64decode(raw_data)
+ if len(decoded) > 1024 * 1000:
+ raise ValueError("Record too large")
+ record_id = _record_id()
+ for dest in stream["destinations"]:
+ dest["records"].append({"id": record_id, "data": raw_data, "ts": now_epoch()})
+ if dest["type"] in ("ExtendedS3", "S3"):
+ _deliver_to_s3(stream, dest, decoded)
+ responses.append({"RecordId": record_id, "Encrypted": False})
+ except Exception as e:
+ failed += 1
+ responses.append({
+ "ErrorCode": "ServiceUnavailableException",
+ "ErrorMessage": str(e),
+ })
+
+ return json_response({
+ "FailedPutCount": failed,
+ "Encrypted": False,
+ "RequestResponses": responses,
+ })
+
+
+def _update_destination(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ dest_id = data.get("DestinationId", "")
+ version_id = data.get("CurrentDeliveryStreamVersionId", "")
+
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ if str(stream["version"]) != str(version_id):
+ return error_response_json(
+ "ConcurrentModificationException",
+ "Request includes an invalid stream version ID.",
+ 400,
+ )
+ dest = next((d for d in stream["destinations"] if d["id"] == dest_id), None)
+ if not dest:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"Destination {dest_id} not found in stream {name}.",
+ 400,
+ )
+
+ dtype, cfg = _resolve_dest_update_config(data)
+ if dtype and cfg is not None:
+ if dtype == dest["type"]:
+ # Same destination type — merge fields (AWS behaviour)
+ dest["config"] = {**dest["config"], **cfg}
+ else:
+ # Destination type change — full replacement
+ dest["type"] = dtype
+ dest["config"] = cfg
+
+ stream["version"] += 1
+ stream["updated_at"] = now_epoch()
+
+ return json_response({})
+
+
+def _tag_delivery_stream(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ tags = data.get("Tags", [])
+ if not tags:
+ return _invalid("Tags must not be empty.")
+
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ if len(stream["tags"]) + len(tags) > 50:
+ return error_response_json(
+ "LimitExceededException",
+ "A delivery stream cannot have more than 50 tags.",
+ 400,
+ )
+ for tag in tags:
+ stream["tags"][tag["Key"]] = tag.get("Value", "")
+
+ return json_response({})
+
+
+def _untag_delivery_stream(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ keys = data.get("TagKeys", [])
+ if not keys:
+ return _invalid("TagKeys must not be empty.")
+
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ for k in keys:
+ stream["tags"].pop(k, None)
+
+ return json_response({})
+
+
+def _list_tags_for_delivery_stream(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ limit = min(int(data.get("Limit", 50)), 50)
+ start = data.get("ExclusiveStartTagKey")
+
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ all_tags = [{"Key": k, "Value": v} for k, v in sorted(stream["tags"].items())]
+
+ if start:
+ try:
+ idx = next(i for i, t in enumerate(all_tags) if t["Key"] == start)
+ all_tags = all_tags[idx + 1:]
+ except StopIteration:
+ pass
+
+ has_more = len(all_tags) > limit
+ return json_response({
+ "Tags": all_tags[:limit],
+ "HasMoreTags": has_more,
+ })
+
+
+def _start_delivery_stream_encryption(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ if stream["status"] != "ACTIVE":
+ return _in_use(name)
+ enc_input = data.get("DeliveryStreamEncryptionConfigurationInput", {})
+ stream["encryption"] = {
+ "Status": "ENABLED",
+ "KeyType": enc_input.get("KeyType", "AWS_OWNED_CMK"),
+ }
+ if "KeyARN" in enc_input:
+ stream["encryption"]["KeyARN"] = enc_input["KeyARN"]
+ stream["updated_at"] = now_epoch()
+ return json_response({})
+
+
+def _stop_delivery_stream_encryption(data: dict):
+ name = data.get("DeliveryStreamName", "")
+ with _lock:
+ stream = _streams.get(name)
+ if not stream:
+ return _not_found(name)
+ if stream["status"] != "ACTIVE":
+ return _in_use(name)
+ stream["encryption"] = {"Status": "DISABLED"}
+ stream["updated_at"] = now_epoch()
+ return json_response({})
+
+
+# ─── dispatch ────────────────────────────────────────────────────────────────
+
+_HANDLERS = {
+ "CreateDeliveryStream": _create_delivery_stream,
+ "DeleteDeliveryStream": _delete_delivery_stream,
+ "DescribeDeliveryStream": _describe_delivery_stream,
+ "ListDeliveryStreams": _list_delivery_streams,
+ "PutRecord": _put_record,
+ "PutRecordBatch": _put_record_batch,
+ "UpdateDestination": _update_destination,
+ "TagDeliveryStream": _tag_delivery_stream,
+ "UntagDeliveryStream": _untag_delivery_stream,
+ "ListTagsForDeliveryStream": _list_tags_for_delivery_stream,
+ "StartDeliveryStreamEncryption": _start_delivery_stream_encryption,
+ "StopDeliveryStreamEncryption": _stop_delivery_stream_encryption,
+}
+
+
+async def handle_request(method, path, headers, body, query_params):
+ target = headers.get("x-amz-target", "")
+ # Target format: Firehose_20150804.OperationName
+ action = target.split(".")[-1] if "." in target else ""
+
+ if not action:
+ return error_response_json("InvalidArgumentException", "Missing X-Amz-Target header.", 400)
+
+ handler = _HANDLERS.get(action)
+ if not handler:
+ return error_response_json("InvalidArgumentException", f"Unknown operation: {action}", 400)
+
+ try:
+ data = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return error_response_json("InvalidArgumentException", "Request body is not valid JSON.", 400)
+
+ return handler(data)
diff --git a/tests/conftest.py b/tests/conftest.py
index 6f7e6b4e..245e003f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -117,6 +117,10 @@ def glue():
def athena():
return make_client("athena")
[email protected](scope="session")
+def fh():
+ return make_client("firehose")
+
@pytest.fixture(scope="session")
def apigw():
return make_client("apigatewayv2")
diff --git a/tests/test_services.py b/tests/test_services.py
index 4c60fb5e..5ac32a26 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -7318,3 +7318,266 @@ def test_apigwv1_execute_mock_response_parameters(apigw_v1):
resp = _urlreq.urlopen(req)
assert resp.headers.get("X-Custom-Header") == "myvalue"
apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+# ---------------------------------------------------------------------------
+# Firehose
+# ---------------------------------------------------------------------------
+
+def test_firehose_create_and_describe(fh):
+ name = "intg-fh-basic"
+ arn = fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="DirectPut",
+ ExtendedS3DestinationConfiguration={
+ "BucketARN": "arn:aws:s3:::my-bucket",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ )["DeliveryStreamARN"]
+ assert "firehose" in arn
+ assert name in arn
+
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ assert desc["DeliveryStreamName"] == name
+ assert desc["DeliveryStreamStatus"] == "ACTIVE"
+ assert desc["DeliveryStreamType"] == "DirectPut"
+ assert len(desc["Destinations"]) == 1
+ assert "ExtendedS3DestinationDescription" in desc["Destinations"][0]
+ assert desc["VersionId"] == "1"
+
+
+def test_firehose_list_streams(fh):
+ fh.create_delivery_stream(DeliveryStreamName="intg-fh-list-a", DeliveryStreamType="DirectPut")
+ fh.create_delivery_stream(DeliveryStreamName="intg-fh-list-b", DeliveryStreamType="DirectPut")
+ resp = fh.list_delivery_streams()
+ names = resp["DeliveryStreamNames"]
+ assert "intg-fh-list-a" in names
+ assert "intg-fh-list-b" in names
+ assert resp["HasMoreDeliveryStreams"] is False
+
+
+def test_firehose_put_record(fh):
+ name = "intg-fh-put"
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ import base64
+ data = base64.b64encode(b"hello firehose").decode()
+ resp = fh.put_record(DeliveryStreamName=name, Record={"Data": data})
+ assert "RecordId" in resp
+ assert len(resp["RecordId"]) > 0
+ assert resp["Encrypted"] is False
+
+
+def test_firehose_put_record_batch(fh):
+ name = "intg-fh-batch"
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ import base64
+ records = [{"Data": base64.b64encode(f"record-{i}".encode()).decode()} for i in range(5)]
+ resp = fh.put_record_batch(DeliveryStreamName=name, Records=records)
+ assert resp["FailedPutCount"] == 0
+ assert len(resp["RequestResponses"]) == 5
+ for r in resp["RequestResponses"]:
+ assert "RecordId" in r
+
+
+def test_firehose_delete_stream(fh):
+ name = "intg-fh-delete"
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ fh.delete_delivery_stream(DeliveryStreamName=name)
+ from botocore.exceptions import ClientError
+ try:
+ fh.describe_delivery_stream(DeliveryStreamName=name)
+ assert False, "should have raised"
+ except ClientError as e:
+ assert e.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_firehose_tags(fh):
+ name = "intg-fh-tags"
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ fh.tag_delivery_stream(DeliveryStreamName=name, Tags=[
+ {"Key": "Env", "Value": "test"},
+ {"Key": "Team", "Value": "data"},
+ ])
+ resp = fh.list_tags_for_delivery_stream(DeliveryStreamName=name)
+ tag_map = {t["Key"]: t["Value"] for t in resp["Tags"]}
+ assert tag_map["Env"] == "test"
+ assert tag_map["Team"] == "data"
+
+ fh.untag_delivery_stream(DeliveryStreamName=name, TagKeys=["Env"])
+ resp2 = fh.list_tags_for_delivery_stream(DeliveryStreamName=name)
+ keys = [t["Key"] for t in resp2["Tags"]]
+ assert "Env" not in keys
+ assert "Team" in keys
+
+
+def test_firehose_update_destination(fh):
+ name = "intg-fh-update-dest"
+ fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="DirectPut",
+ ExtendedS3DestinationConfiguration={
+ "BucketARN": "arn:aws:s3:::original-bucket",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ )
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ dest_id = desc["Destinations"][0]["DestinationId"]
+ version_id = desc["VersionId"]
+
+ fh.update_destination(
+ DeliveryStreamName=name,
+ DestinationId=dest_id,
+ CurrentDeliveryStreamVersionId=version_id,
+ ExtendedS3DestinationUpdate={
+ "BucketARN": "arn:aws:s3:::updated-bucket",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ )
+ desc2 = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ assert desc2["VersionId"] == "2"
+ s3_cfg = desc2["Destinations"][0]["ExtendedS3DestinationDescription"]
+ assert s3_cfg["BucketARN"] == "arn:aws:s3:::updated-bucket"
+
+
+def test_firehose_encryption(fh):
+ name = "intg-fh-enc"
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ fh.start_delivery_stream_encryption(
+ DeliveryStreamName=name,
+ DeliveryStreamEncryptionConfigurationInput={"KeyType": "AWS_OWNED_CMK"},
+ )
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ assert desc["DeliveryStreamEncryptionConfiguration"]["Status"] == "ENABLED"
+
+ fh.stop_delivery_stream_encryption(DeliveryStreamName=name)
+ desc2 = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ assert desc2["DeliveryStreamEncryptionConfiguration"]["Status"] == "DISABLED"
+
+
+def test_firehose_duplicate_create_error(fh):
+ name = "intg-fh-dup"
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ from botocore.exceptions import ClientError
+ try:
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ assert False, "should have raised"
+ except ClientError as e:
+ assert e.response["Error"]["Code"] == "ResourceInUseException"
+
+
+def test_firehose_not_found_error(fh):
+ from botocore.exceptions import ClientError
+ try:
+ fh.describe_delivery_stream(DeliveryStreamName="no-such-stream-xyz")
+ assert False, "should have raised"
+ except ClientError as e:
+ assert e.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_firehose_list_with_type_filter(fh):
+ fh.create_delivery_stream(DeliveryStreamName="intg-fh-type-dp", DeliveryStreamType="DirectPut")
+ resp = fh.list_delivery_streams(DeliveryStreamType="DirectPut")
+ assert "intg-fh-type-dp" in resp["DeliveryStreamNames"]
+
+
+def test_firehose_s3_dest_has_encryption_config(fh):
+ name = "intg-fh-enc-cfg"
+ fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="DirectPut",
+ ExtendedS3DestinationConfiguration={
+ "BucketARN": "arn:aws:s3:::my-bucket",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ )
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ s3 = desc["Destinations"][0]["ExtendedS3DestinationDescription"]
+ assert "EncryptionConfiguration" in s3
+ assert s3["EncryptionConfiguration"] == {"NoEncryptionConfig": "NoEncryption"}
+
+
+def test_firehose_no_enc_config_when_not_set(fh):
+ name = "intg-fh-no-enc"
+ fh.create_delivery_stream(DeliveryStreamName=name, DeliveryStreamType="DirectPut")
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ assert "DeliveryStreamEncryptionConfiguration" not in desc
+
+
+def test_firehose_kinesis_source_block(fh):
+ name = "intg-fh-kinesis-src"
+ fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="KinesisStreamAsSource",
+ KinesisStreamSourceConfiguration={
+ "KinesisStreamARN": "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ ExtendedS3DestinationConfiguration={
+ "BucketARN": "arn:aws:s3:::my-bucket",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ )
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ assert "Source" in desc
+ ks = desc["Source"]["KinesisStreamSourceDescription"]
+ assert ks["KinesisStreamARN"] == "arn:aws:kinesis:us-east-1:000000000000:stream/my-stream"
+ assert ks["RoleARN"] == "arn:aws:iam::000000000000:role/firehose-role"
+ assert "DeliveryStartTimestamp" in ks
+
+
+def test_firehose_update_destination_merges_same_type(fh):
+ name = "intg-fh-merge"
+ fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="DirectPut",
+ ExtendedS3DestinationConfiguration={
+ "BucketARN": "arn:aws:s3:::original-bucket",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ "Prefix": "original/",
+ },
+ )
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ dest_id = desc["Destinations"][0]["DestinationId"]
+
+ fh.update_destination(
+ DeliveryStreamName=name,
+ DestinationId=dest_id,
+ CurrentDeliveryStreamVersionId=desc["VersionId"],
+ ExtendedS3DestinationUpdate={
+ "BucketARN": "arn:aws:s3:::updated-bucket",
+ },
+ )
+ desc2 = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ s3 = desc2["Destinations"][0]["ExtendedS3DestinationDescription"]
+ # Updated field
+ assert s3["BucketARN"] == "arn:aws:s3:::updated-bucket"
+ # Merged field preserved
+ assert s3["Prefix"] == "original/"
+ assert s3["RoleARN"] == "arn:aws:iam::000000000000:role/firehose-role"
+
+
+def test_firehose_update_destination_replaces_on_type_change(fh):
+ name = "intg-fh-type-change"
+ fh.create_delivery_stream(
+ DeliveryStreamName=name,
+ DeliveryStreamType="DirectPut",
+ ExtendedS3DestinationConfiguration={
+ "BucketARN": "arn:aws:s3:::my-bucket",
+ "RoleARN": "arn:aws:iam::000000000000:role/firehose-role",
+ },
+ )
+ desc = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ dest_id = desc["Destinations"][0]["DestinationId"]
+
+ fh.update_destination(
+ DeliveryStreamName=name,
+ DestinationId=dest_id,
+ CurrentDeliveryStreamVersionId=desc["VersionId"],
+ HttpEndpointDestinationUpdate={
+ "EndpointConfiguration": {"Url": "https://my-endpoint.example.com"},
+ },
+ )
+ desc2 = fh.describe_delivery_stream(DeliveryStreamName=name)["DeliveryStreamDescription"]
+ dest = desc2["Destinations"][0]
+ assert "HttpEndpointDestinationDescription" in dest
+ assert "ExtendedS3DestinationDescription" not in dest