Skip to content

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

fix: API Gateway dates as Unix numbers, S3 vhost TF4+, CloudWatch ARN tag lookup, SQS (#34)

Nahuel Nucera37427f8e4cec
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 316ddcb5..872bbc55 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.5] — 2026-03-30
+
+### Fixed
+- **API Gateway v1** — `createdDate` / `lastUpdatedDate` fields now returned as Unix timestamps (integers) instead of ISO strings. Terraform AWS provider v4+ deserializes these as JSON Numbers and raised `expected Timestamp to be a JSON Number, got string instead` on `CreateRestApi`.
+- **API Gateway v2** — same fix applied to `createdDate` / `lastUpdatedDate` on APIs and stages.
+- **S3 virtual-hosted style** — host pattern now also matches `{bucket}.s3.localhost[:{port}]` in addition to `{bucket}.localhost[:{port}]`. Terraform AWS provider v4+ uses the `.s3.` subdomain when `force_path_style = false`.
+- **CloudWatch Logs `ListTagsForResource`** — ARN lookup now accepts both `arn:...:log-group:{name}` and `arn:...:log-group:{name}:*`. Terraform passes the ARN without the trailing `:*` that MiniStack appends internally, causing `ResourceNotFoundException`.
+- **SQS `SendMessageBatch`** — now rejects batches with more than 10 entries with `AWS.SimpleQueueService.TooManyEntriesInBatchRequest`, matching real AWS behaviour. Previously MiniStack silently accepted oversized batches.
+- **DynamoDB `BatchWriteItem`** — now includes `ConsumedCapacity` as a list in the response when `ReturnConsumedCapacity` is set to `TOTAL` or `INDEXES`. Previously the field was absent entirely.
+
+### Tests
+- 5 regression tests added (one per fix above) — 693 integration tests total, all passing
+
+---
+
## [1.1.4] — 2026-03-30
### Added
diff --git a/README.md b/README.md
index a35b2d2d..52f43049 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.
-- **26 AWS services** emulated on a single port (4566)
+- **30 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
@@ -512,6 +512,7 @@ provider "aws" {
ec2 = "http://localhost:4566"
emr = "http://localhost:4566"
efs = "http://localhost:4566"
+ elbv2 = "http://localhost:4566"
}
}
```
diff --git a/ministack/app.py b/ministack/app.py
index 67fd6af8..3c31a416 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -16,9 +16,12 @@ 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+)?$")
+# Matches virtual-hosted S3:
+# "{bucket}.localhost" or "{bucket}.localhost:4566" (boto3/SDK default)
+# "{bucket}.s3.localhost" or "{bucket}.s3.localhost:4566" (Terraform AWS provider v4+)
+# Does NOT match execute-api, alb, or other sub-service hostnames.
+_S3_VHOST_RE = re.compile(r"^([^.]+)(?:\.s3)?\.localhost(?::\d+)?$")
+_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache)\.")
from ministack.core.router import detect_service, extract_region, extract_account_id
from ministack.core.persistence import save_all, load_state, PERSIST_STATE
@@ -255,7 +258,7 @@ async def app(scope, receive, send):
# 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:
+ if _s3_vhost and not _execute_match and not _S3_VHOST_EXCLUDE_RE.search(host):
bucket = _s3_vhost.group(1)
_non_s3_hosts = {"s3", "sqs", "sns", "dynamodb", "lambda", "iam", "sts",
"secretsmanager", "logs", "ssm", "events", "kinesis",
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index af7c421d..bc672e55 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -412,7 +412,7 @@ def _create_api(data):
"name": data.get("name", "unnamed"),
"protocolType": data.get("protocolType", "HTTP"),
"apiEndpoint": f"http://{api_id}.execute-api.localhost:4566",
- "createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "createdDate": int(time.time()),
"routeSelectionExpression": data.get("routeSelectionExpression", "$request.method $request.path"),
"tags": data.get("tags", {}),
"corsConfiguration": data.get("corsConfiguration", {}),
@@ -567,8 +567,8 @@ def _create_stage(api_id, data):
stage = {
"stageName": stage_name,
"autoDeploy": data.get("autoDeploy", False),
- "createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
- "lastUpdatedDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "createdDate": int(time.time()),
+ "lastUpdatedDate": int(time.time()),
"stageVariables": data.get("stageVariables", {}),
"description": data.get("description", ""),
"defaultRouteSettings": data.get("defaultRouteSettings", {}),
@@ -598,7 +598,7 @@ def _update_stage(api_id, stage_name, data):
"defaultRouteSettings", "routeSettings"):
if k in data:
stage[k] = data[k]
- stage["lastUpdatedDate"] = time.strftime("%Y-%m-%dT%H:%M:%SZ")
+ stage["lastUpdatedDate"] = int(time.time())
return _apigw_response(stage)
@@ -616,7 +616,7 @@ def _create_deployment(api_id, data):
deployment = {
"deploymentId": deployment_id,
"deploymentStatus": "DEPLOYED",
- "createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "createdDate": int(time.time()),
"description": data.get("description", ""),
}
_deployments.setdefault(api_id, {})[deployment_id] = deployment
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index e12d5a72..eed768ca 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -75,9 +75,11 @@ import logging
from ministack.core.responses import new_uuid
-def _now_iso():
- """Return current UTC time as ISO 8601 string matching AWS format."""
- return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
+def _now_unix():
+ """Return current UTC time as Unix timestamp (float).
+ API Gateway v1 createdDate/lastUpdatedDate fields must be numbers, not strings.
+ Terraform's AWS provider deserializes them as JSON Number and errors on ISO strings."""
+ return int(time.time())
logger = logging.getLogger("apigateway_v1")
@@ -747,7 +749,7 @@ def _create_rest_api(data):
"id": api_id,
"name": data.get("name", "unnamed"),
"description": data.get("description", ""),
- "createdDate": _now_iso(),
+ "createdDate": _now_unix(),
"version": data.get("version", ""),
"binaryMediaTypes": data.get("binaryMediaTypes", []),
"minimumCompressionSize": data.get("minimumCompressionSize"),
@@ -1097,7 +1099,7 @@ def _create_deployment(api_id, data):
deployment = {
"id": deployment_id,
"description": data.get("description", ""),
- "createdDate": _now_iso(),
+ "createdDate": _now_unix(),
"apiSummary": _build_api_summary(api_id),
}
_deployments_v1.setdefault(api_id, {})[deployment_id] = deployment
@@ -1108,14 +1110,14 @@ def _create_deployment(api_id, data):
existing_stage = _stages_v1.get(api_id, {}).get(stage_name)
if existing_stage:
existing_stage["deploymentId"] = deployment_id
- existing_stage["lastUpdatedDate"] = _now_iso()
+ existing_stage["lastUpdatedDate"] = _now_unix()
else:
stage = {
"stageName": stage_name,
"deploymentId": deployment_id,
"description": data.get("stageDescription", ""),
- "createdDate": _now_iso(),
- "lastUpdatedDate": _now_iso(),
+ "createdDate": _now_unix(),
+ "lastUpdatedDate": _now_unix(),
"variables": data.get("variables", {}),
"methodSettings": {},
"accessLogSettings": {},
@@ -1171,8 +1173,8 @@ def _create_stage(api_id, data):
"stageName": stage_name,
"deploymentId": data.get("deploymentId", ""),
"description": data.get("description", ""),
- "createdDate": _now_iso(),
- "lastUpdatedDate": _now_iso(),
+ "createdDate": _now_unix(),
+ "lastUpdatedDate": _now_unix(),
"variables": data.get("variables", {}),
"methodSettings": data.get("methodSettings", {}),
"accessLogSettings": data.get("accessLogSettings", {}),
@@ -1205,7 +1207,7 @@ def _update_stage(api_id, stage_name, data):
return _v1_error("NotFoundException", f"Invalid Stage identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(stage, patch_ops)
- stage["lastUpdatedDate"] = _now_iso()
+ stage["lastUpdatedDate"] = _now_unix()
return _v1_response(stage)
@@ -1315,8 +1317,8 @@ def _create_api_key(data):
"name": data.get("name", ""),
"description": data.get("description", ""),
"enabled": data.get("enabled", True),
- "createdDate": _now_iso(),
- "lastUpdatedDate": _now_iso(),
+ "createdDate": _now_unix(),
+ "lastUpdatedDate": _now_unix(),
"value": key_value,
"stageKeys": data.get("stageKeys", []),
"tags": data.get("tags", {}),
@@ -1342,7 +1344,7 @@ def _update_api_key(key_id, data):
return _v1_error("NotFoundException", f"Invalid API Key identifier specified", 404)
patch_ops = data.get("patchOperations", [])
_apply_patch(key, patch_ops)
- key["lastUpdatedDate"] = _now_iso()
+ key["lastUpdatedDate"] = _now_unix()
return _v1_response(key)
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 77f776bb..2dbd22b3 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -55,9 +55,12 @@ def _make_group_arn(name):
def _resolve_group_by_arn(arn):
- """Return the group name whose ARN matches, or None."""
+ """Return the group name whose ARN matches, or None.
+ Accepts both 'arn:...:log-group:name' and 'arn:...:log-group:name:*'
+ since Terraform and the AWS console use both forms."""
+ arn_normalized = arn.rstrip(":*")
for name, g in _log_groups.items():
- if g["arn"] == arn:
+ if g["arn"].rstrip(":*") == arn_normalized:
return name
return None
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index c01931b2..c4f534ed 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -547,7 +547,15 @@ def _batch_write_item(data):
return key_err
table["items"].get(pk_val, {}).pop(sk_val, None)
_update_counts(table)
- return json_response({"UnprocessedItems": unprocessed})
+ result = {"UnprocessedItems": unprocessed}
+ rc = data.get("ReturnConsumedCapacity", "NONE")
+ if rc != "NONE":
+ result["ConsumedCapacity"] = [
+ {"TableName": t, "CapacityUnits": 1.0}
+ for t in request_items
+ if t in _tables
+ ]
+ return json_response(result)
def _batch_get_item(data):
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index a507ceee..1048c43c 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -446,9 +446,13 @@ def _act_purge_queue(data: dict, qurl: str) -> dict:
def _act_send_message_batch(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
_get_q(url)
+ entries = data.get("Entries", [])
+ if len(entries) > 10:
+ raise _Err("AWS.SimpleQueueService.TooManyEntriesInBatchRequest",
+ "Too many messages in a batch request. A maximum of 10 messages are allowed.")
ok: list = []
fail: list = []
- for e in data.get("Entries", []):
+ for e in entries:
try:
sub: dict = {
"QueueUrl": url,
diff --git a/pyproject.toml b/pyproject.toml
index 0a21338b..4b49a7cc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.4"
+version = "1.1.5"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_services.py b/tests/test_services.py
index 388f7353..08b734ff 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -12089,3 +12089,92 @@ def test_efs_backup_policy(efs):
)
resp = efs.describe_backup_policy(FileSystemId=fs_id)
assert resp["BackupPolicy"]["Status"] == "ENABLED"
+
+
+# ---------------------------------------------------------------------------
+# Regression: API Gateway v1 createdDate must be a Unix timestamp (number),
+# not an ISO string. Terraform AWS provider errors with:
+# "expected Timestamp to be a JSON Number, got string instead"
+# ---------------------------------------------------------------------------
+
+def test_apigwv1_created_date_is_unix_timestamp(apigw_v1):
+ resp = apigw_v1.create_rest_api(name="tf-date-test")
+ created = resp["createdDate"]
+ # boto3 parses numeric timestamps as datetime.datetime — if it were a string
+ # botocore would raise a deserialization error before we even get here.
+ import datetime
+ assert isinstance(created, datetime.datetime), (
+ f"createdDate should be datetime (parsed from Unix int), got {type(created)}"
+ )
+ apigw_v1.delete_rest_api(restApiId=resp["id"])
+
+
+def test_apigwv2_created_date_is_unix_timestamp(apigw):
+ resp = apigw.create_api(Name="tf-date-test-v2", ProtocolType="HTTP")
+ created = resp["CreatedDate"]
+ import datetime
+ assert isinstance(created, datetime.datetime), (
+ f"CreatedDate should be datetime (parsed from Unix int), got {type(created)}"
+ )
+ apigw.delete_api(ApiId=resp["ApiId"])
+
+
+# ---------------------------------------------------------------------------
+# Regression: CloudWatch Logs ListTagsForResource fails when the ARN passed
+# by Terraform lacks the trailing ':*' that MiniStack appends when storing.
+# ---------------------------------------------------------------------------
+
+def test_logs_list_tags_for_resource_arn_without_star(logs):
+ name = "/tf/regression/arn-no-star"
+ logs.create_log_group(logGroupName=name, tags={"env": "test"})
+ # Get the ARN as stored (includes :*)
+ groups = logs.describe_log_groups(logGroupNamePrefix=name)["logGroups"]
+ stored_arn = groups[0]["arn"]
+ assert stored_arn.endswith(":*"), f"Expected stored ARN to end with :*, got {stored_arn}"
+
+ # Terraform sends the ARN without :* — this must not raise ResourceNotFoundException
+ arn_no_star = stored_arn[:-2] # strip ':*'
+ resp = logs.list_tags_for_resource(resourceArn=arn_no_star)
+ assert resp["tags"]["env"] == "test"
+ logs.delete_log_group(logGroupName=name)
+
+
+# ---------------------------------------------------------------------------
+# Regression: SQS SendMessageBatch must reject batches larger than 10 entries.
+# AWS returns TooManyEntriesInBatchRequest; MiniStack was silently accepting them.
+# ---------------------------------------------------------------------------
+
+def test_sqs_send_message_batch_limit(sqs):
+ import pytest
+ from botocore.exceptions import ClientError
+ q = sqs.create_queue(QueueName="batch-limit-regression")["QueueUrl"]
+ entries = [{"Id": str(i), "MessageBody": f"msg {i}"} for i in range(11)]
+ with pytest.raises(ClientError) as exc_info:
+ sqs.send_message_batch(QueueUrl=q, Entries=entries)
+ assert exc_info.value.response["Error"]["Code"] == "AWS.SimpleQueueService.TooManyEntriesInBatchRequest"
+ sqs.delete_queue(QueueUrl=q)
+
+
+# ---------------------------------------------------------------------------
+# Regression: DynamoDB BatchWriteItem must include ConsumedCapacity list when
+# ReturnConsumedCapacity="TOTAL" is set. Was returning the key absent entirely.
+# ---------------------------------------------------------------------------
+
+def test_dynamodb_batch_write_consumed_capacity(ddb):
+ ddb.create_table(
+ TableName="batch-cap-regression",
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ resp = ddb.batch_write_item(
+ RequestItems={"batch-cap-regression": [
+ {"PutRequest": {"Item": {"pk": {"S": "k1"}}}},
+ ]},
+ ReturnConsumedCapacity="TOTAL",
+ )
+ assert "ConsumedCapacity" in resp, "ConsumedCapacity must be present when ReturnConsumedCapacity=TOTAL"
+ assert isinstance(resp["ConsumedCapacity"], list), "ConsumedCapacity must be a list for BatchWriteItem"
+ assert resp["ConsumedCapacity"][0]["TableName"] == "batch-cap-regression"
+ assert resp["ConsumedCapacity"][0]["CapacityUnits"] == 1.0
+ ddb.delete_table(TableName="batch-cap-regression")