Skip to content

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

release v1.4.10 (#1262)

Nahuel Nucerad08d01ce91a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0a5404a8..26fcf137 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,15 +5,24 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
-## [Unreleased]
+## [1.4.10] — 2026-08-03
### Added
- **CloudFront — cache, origin request, and response headers policies** — full CRUD plus `GetConfig` and `ListDistributionsBy...Id` for `CachePolicy` (`/2020-05-31/cache-policy`), `OriginRequestPolicy` (`/origin-request-policy`), and `ResponseHeadersPolicy` (`/response-headers-policy`), so Terraform's `aws_cloudfront_cache_policy`, `aws_cloudfront_origin_request_policy`, and `aws_cloudfront_response_headers_policy` create, read, update, and delete end-to-end. Each config round-trips in full: `CachePolicyConfig` (`MinTTL`/`DefaultTTL`/`MaxTTL` and `ParametersInCacheKeyAndForwardedToOrigin`), `OriginRequestPolicyConfig` (header/cookie/query-string behaviors and name lists), and `ResponseHeadersPolicyConfig` (CORS, security headers, server-timing, custom and remove headers). `ETag` is returned on every read, `If-Match` is enforced on update/delete (`InvalidIfMatchVersion` / `PreconditionFailed`), and the `...AlreadyExists` / `NoSuch...` / `...InUse` error codes match AWS. Reported by @wparad.
+- **Cognito — state is now account- and region-scoped** — user pools, pool domains, identity pools, and identity tags were account-scoped and leaked across regions. They now scope by account and region, and unsigned IDP / Identity data-plane requests infer the owning region from pool and identity IDs, tokens, sessions, or unambiguous client ownership. Persisted state carries the versioned regional schema (on-disk format v3) that an older binary refuses rather than misreads; legacy resources self-place from their region-bearing IDs. Contributed by @Areson.
+- **CloudFormation — state is now account- and region-scoped** — stacks, stack events, exports, and change sets were account-scoped, so same-name stacks collided across regions and exports leaked into cross-region `Fn::ImportValue` lookups. They now scope by account and region; asynchronous stack work retains the owning region and nested stacks stay co-located with their parent. Contributed by @Areson.
+- **EKS — `ListIdentityProviderConfigs`** — `GET /clusters/{name}/identity-provider-configs` was unimplemented and returned `No route`. It now returns the AWS-shaped `identityProviderConfigs` list (`{name, type}`) and a `ResourceNotFoundException` for an unknown cluster. Contributed by @b-rajesh.
+- **DynamoDB PartiQL — `RETURNING`, `REMOVE`, and richer `WHERE` predicates** — `ExecuteStatement` now supports `RETURNING ALL OLD *` / `ALL NEW *` / `MODIFIED OLD *` / `MODIFIED NEW *` on `UPDATE` and `RETURNING ALL OLD *` on `DELETE`, the `REMOVE` clause, and `begins_with` / `IN` / `IS MISSING` / `IS NOT MISSING` predicates. An `UPDATE` whose `WHERE` matches no item now returns `ConditionalCheckFailedException` rather than a silent no-op, matching AWS.
### Fixed
-- **IoT — binary topic-rule payloads are no longer corrupted** — the rules engine built every rule event by decoding the payload as UTF-8 with `errors="replace"`, so a payload that is not valid UTF-8 reached the action with each non-ASCII byte replaced by `U+FFFD`. `encode(<expr>, 'base64')` is now supported and encodes the payload as published, so `SELECT encode(*, 'base64') AS data FROM 'telemetry'` delivers `{"data": "<base64>"}` that decodes back to the published bytes — the documented way to reach a Lambda action, which does not accept binary input. No lossy decode remains on the publish → rule → invoke path; a payload that is not valid UTF-8 and whose SELECT projects no attributes dispatches no action rather than dispatching corrupted text.
-- **IoT — topic-rule SQL is now evaluated** — the rules engine routed a publish to its actions but ignored the rule's `SELECT` clause, so a rule declaring `SELECT deviceId AS id FROM 'sensors/+/telemetry'` delivered the whole message instead of the projection. The SELECT clause is now parsed and projected — `*`, attribute paths, `AS` aliases, `topic()` / `topic(n)`, `timestamp()`, and literals, with unaliased items named as AWS names them and missing attributes omitted — for both delivery paths, Basic Ingest (where `topic()` reports the topic after the rule prefix) and a publish matching the `FROM` filter. A JSON payload under `SELECT *` still arrives as the parsed object.
+- **IoT — binary topic-rule payloads are no longer corrupted** — the rules engine built every rule event by decoding the payload as UTF-8 with `errors="replace"`, so a payload that is not valid UTF-8 reached the action with each non-ASCII byte replaced by `U+FFFD`. `encode(<expr>, 'base64')` is now supported and encodes the payload as published, so `SELECT encode(*, 'base64') AS data FROM 'telemetry'` delivers `{"data": "<base64>"}` that decodes back to the published bytes — the documented way to reach a Lambda action, which does not accept binary input. No lossy decode remains on the publish → rule → invoke path; a payload that is not valid UTF-8 and whose SELECT projects no attributes dispatches no action rather than dispatching corrupted text. Contributed by @maximoosemine.
+- **IoT — topic-rule SQL is now evaluated** — the rules engine routed a publish to its actions but ignored the rule's `SELECT` clause, so a rule declaring `SELECT deviceId AS id FROM 'sensors/+/telemetry'` delivered the whole message instead of the projection. The SELECT clause is now parsed and projected — `*`, attribute paths, `AS` aliases, `topic()` / `topic(n)`, `timestamp()`, and literals, with unaliased items named as AWS names them and missing attributes omitted — for both delivery paths, Basic Ingest (where `topic()` reports the topic after the rule prefix) and a publish matching the `FROM` filter. A JSON payload under `SELECT *` still arrives as the parsed object. Contributed by @maximoosemine.
- **ACM — wildcard SAN DNS validation record now matches its base domain** — a certificate with a wildcard subject alternative name emitted a validation `ResourceRecord` named `_acme-challenge.*.example.com`, so Terraform's `aws_acm_certificate_validation` never found the record its `aws_route53_record` had created and failed with `missing DNS validation record`. Real ACM strips the leading `*.`, so `*.example.com` and `example.com` share one `_acme-challenge.example.com` CNAME with an identical name and value. `RequestCertificate` now emits that collapsed record, so the wildcard and apex entries line up and the validation resource resolves. Reported by @wparad.
+- **API Gateway — HTTP API routes are selected by specificity, not creation order** — the v2 router returned the first route whose method and path matched in insertion order, so a dedicated route (e.g. `POST /items`) could lose to a greedy `ANY /{proxy+}` catch-all depending on which was created first during `terraform apply`. Matching routes are now ranked so the most specific one wins, as real API Gateway always dispatches to the most specific match. Contributed by @Lukasdoe.
+- **EC2 — `DescribeAvailabilityZones` now returns real AZ IDs** — every zone reported its `ZoneId` as a copy of its `ZoneName` (e.g. `us-east-1a` under both), but AWS deliberately differs: names are shuffled per account while IDs are region-coded and stable. `ZoneId` is now the region-coded form (`use1-az1`, `euc1-az1`, `apse2-az1`, …), matching AWS's coding across every region. Contributed by @bandle.
+- **DynamoDB — `ProjectionExpression` list-index results no longer carry `null` placeholders** — projecting a list element (e.g. `#i[2]`) returned the element behind sparse `null` entries (`[null, null, {…}]`) instead of the single projected element, and a sibling attribute in the same projection left the placeholders in place. Projected list results are now compacted to only the referenced elements.
+- **Persistence — MediaConnect state now persists, and regionalized services carry downgrade protection** — MediaConnect had restore logic but was never registered for saves, so its state was lost across restarts; it now persists. Kinesis, Firehose, KMS, EventBridge, ElastiCache, Pipes, Scheduler, SNS, and MediaConnect now advertise the on-disk format version (v3) that an older binary refuses rather than misreading their region-scoped state. Contributed by @Areson.
+- **CloudWatch — `DescribeAlarms` over CBOR broke the Terraform AWS provider ≥ 6.50** — alarm `StateUpdatedTimestamp` / `AlarmConfigurationUpdatedTimestamp` were serialized as bare unsigned integers in the smithy-rpc-v2-cbor response, so the provider's typed decoder (CloudWatch uses CBOR from provider 6.50) failed the read-back with `unexpected value type cbor.Uint` and `aws_cloudwatch_metric_alarm` could not be created. Timestamp members are now encoded as CBOR tag 1 (epoch date-time), which the decoder expects; integer members such as `Period` and `EvaluationPeriods` are unchanged. Reported by @sdreger.
## [1.4.9] — 2026-08-01
diff --git a/README.md b/README.md
index 355c2c15..ebeae9cc 100644
--- a/README.md
+++ b/README.md
@@ -215,11 +215,11 @@ use1.list_tables()["TableNames"] # → ["users"]
euw1.list_tables()["TableNames"] # → [] — eu-west-1 is independent
```
-**Region-isolated services:** AppConfig, Bedrock (all four services), CloudWatch, CloudWatch Logs, DynamoDB (tables, metadata, Streams), Lambda (functions, event source mappings, durable executions), MSK, RDS, S3 Tables, Secrets Manager, SQS, SSM Parameter Store, and Step Functions (1.4.0); EventBridge Pipes (1.4.1); SNS, Kinesis, KMS, and ElastiCache (1.4.2); EventBridge, ECS, and Firehose (1.4.3); EventBridge Scheduler, CodeBuild, and Resource Groups (1.4.4); Batch and SES (1.4.5); Athena, Auto Scaling, Cloud Map, EFS, EMR, Inspector2, Amazon MQ, AppSync, and S3 Files (1.4.6); Amazon Bedrock AgentCore, Amazon MWAA, Amazon EKS, and AWS Transfer Family (1.4.7); AWS IoT and AppSync Events (1.4.8); EC2, CloudTrail, ECR, Glue, OpenSearch, WAFv2, Backup, ACM, Elastic Load Balancing (ALB/NLB), MediaConnect, and RDS Data (1.4.9).
+**Region-isolated services:** AppConfig, Bedrock (all four services), CloudWatch, CloudWatch Logs, DynamoDB (tables, metadata, Streams), Lambda (functions, event source mappings, durable executions), MSK, RDS, S3 Tables, Secrets Manager, SQS, SSM Parameter Store, and Step Functions (1.4.0); EventBridge Pipes (1.4.1); SNS, Kinesis, KMS, and ElastiCache (1.4.2); EventBridge, ECS, and Firehose (1.4.3); EventBridge Scheduler, CodeBuild, and Resource Groups (1.4.4); Batch and SES (1.4.5); Athena, Auto Scaling, Cloud Map, EFS, EMR, Inspector2, Amazon MQ, AppSync, and S3 Files (1.4.6); Amazon Bedrock AgentCore, Amazon MWAA, Amazon EKS, and AWS Transfer Family (1.4.7); AWS IoT and AppSync Events (1.4.8); EC2, CloudTrail, ECR, Glue, OpenSearch, WAFv2, Backup, ACM, Elastic Load Balancing (ALB/NLB), MediaConnect, and RDS Data (1.4.9); Cognito and CloudFormation (1.4.10).
Cross-resource references resolve in the referenced ARN's own account and region (SNS→SQS fanout, EventBridge targets, event source mappings), and cross-region references that real AWS rejects return the same errors AWS returns — e.g. invoking a `eu-west-1` Lambda from a `us-east-1` Step Functions task fails with `Functions from 'eu-west-1' are not reachable in this region`, exactly as on AWS.
-**Not yet region-isolated:** S3, IAM/STS, EC2, ECR, Glue, API Gateway v1/v2, Cognito, CloudFormation, CloudFront, Route 53, WAF, ACM, Backup, Organizations, CloudTrail, and the remaining control-plane services — these share state across regions within an account (as all services did before 1.4.0); use unique resource names there if your tests exercise two regions. Region isolation for them lands in subsequent releases.
+**Not yet region-isolated:** S3, IAM/STS, API Gateway v1/v2, CloudFront, Route 53, Organizations, and the remaining control-plane services — these share state across regions within an account (as all services did before 1.4.0); use unique resource names there if your tests exercise two regions. Region isolation for them lands in subsequent releases.
**Upgrading with `PERSIST_STATE=1`:** existing state files load and migrate automatically (on-disk format v2 with a version stamp — a newer-format file is refused instead of mis-parsed on downgrade). Each record's region is recovered from its stored ARNs; legacy records that carry no ARN migrate to the default region (`MINISTACK_REGION`).
@@ -434,7 +434,7 @@ subnet = ec2.create_subnet(
| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 29 actions; CMK specs: RSA (2048/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
-| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |
+| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, **Policies**: CreateCachePolicy, GetCachePolicy, GetCachePolicyConfig, UpdateCachePolicy, DeleteCachePolicy, ListDistributionsByCachePolicyId, CreateOriginRequestPolicy, GetOriginRequestPolicy, GetOriginRequestPolicyConfig, UpdateOriginRequestPolicy, DeleteOriginRequestPolicy, ListDistributionsByOriginRequestPolicyId, CreateResponseHeadersPolicy, GetResponseHeadersPolicy, GetResponseHeadersPolicyConfig, UpdateResponseHeadersPolicy, DeleteResponseHeadersPolicy, ListDistributionsByResponseHeadersPolicyId, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; cache / origin request / response headers policies round-trip their full config with `ETag` / `If-Match` optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |
| **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN |
| **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging; `CreateTrail`/`UpdateTrail` persist `KmsKeyId` (normalized to a key ARN; omitted when unset) so `aws_cloudtrail` converges without drift |
| **Resource Groups** | CreateGroup, GetGroup, DeleteGroup, UpdateGroup, ListGroups, GetGroupQuery, UpdateGroupQuery, GetGroupConfiguration, PutGroupConfiguration, GroupResources, UngroupResources, ListGroupResources, ListGroupingStatuses, SearchResources, Tag, Untag, GetTags, GetAccountSettings, UpdateAccountSettings | 19 of 23 spec ops; tag-sync ops omitted (not exposed by AWS CLI / Terraform); `Group` accepts bare name or full ARN |
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 8322bfc6..884e695d 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -917,21 +917,24 @@ async def handle_execute(api_id, stage, path, method, headers, body, query_param
def _route_specificity(method: str, route_path: str) -> tuple:
"""Rank a candidate route by how specifically it matches a request.
- Real API Gateway always dispatches to the most specific matching route,
- independent of the order in which routes were created. We approximate that
- ordering with a tuple compared lexicographically (higher is more specific):
-
- 1. Number of literal (non-parameter) path segments — an exact path beats
+ Real API Gateway selects the most specific match with this priority
+ (docs, "Routing API requests"): (1) a full match for route+method, then
+ (2) a match with a greedy ``{proxy+}`` path variable, then (3) ``$default``.
+ So the *primary* discriminator is full-match-beats-greedy — a full match
+ always outranks a greedy one, even one with more literal segments. The tuple
+ is compared lexicographically (higher is more specific):
+
+ 1. Non-greedy (full match) over greedy (``{proxy+}`` catch-all).
+ 2. Number of literal (non-parameter) path segments — a static path beats
one with placeholders.
- 2. Explicit method over ``ANY`` — ``POST /items`` beats ``ANY /items``.
- 3. Non-greedy over greedy — a route without ``{proxy+}`` beats a catch-all.
+ 3. Explicit method over ``ANY`` — ``POST /items`` beats ``ANY /items``.
"""
segments = route_path.strip("/").split("/")
literal_segments = sum(
1 for s in segments if not (s.startswith("{") and s.endswith("}"))
)
is_greedy = any(s == "{proxy+}" for s in segments)
- return (literal_segments, 0 if method == "ANY" else 1, 0 if is_greedy else 1)
+ return (0 if is_greedy else 1, literal_segments, 0 if method == "ANY" else 1)
def _match_route(api_id, method, path):
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 5d771e15..852c4f5c 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -1055,7 +1055,10 @@ def _describe_alarms(params, cbor_data, is_cbor, is_json=False):
if is_cbor:
return _cbor_ok(
- {"MetricAlarms": metric_alarms, "CompositeAlarms": composite_results}
+ {
+ "MetricAlarms": [_cbor_alarm(a) for a in metric_alarms],
+ "CompositeAlarms": [_cbor_alarm(a) for a in composite_results],
+ }
)
if is_json:
return _json_ok(
@@ -1110,7 +1113,7 @@ def _describe_alarms_for_metric(params, cbor_data, is_cbor, is_json=False):
]
if is_cbor:
- return _cbor_ok({"MetricAlarms": result})
+ return _cbor_ok({"MetricAlarms": [_cbor_alarm(a) for a in result]})
if is_json:
return _json_ok({"MetricAlarms": result})
@@ -1158,7 +1161,7 @@ def _describe_alarm_history(params, cbor_data, is_cbor, is_json=False):
items = items[:max_records]
if is_cbor:
- return _cbor_ok({"AlarmHistoryItems": items})
+ return _cbor_ok({"AlarmHistoryItems": [_cbor_history_item(i) for i in items]})
if is_json:
return _json_ok({"AlarmHistoryItems": items})
@@ -1546,6 +1549,43 @@ def _p(params, key, default=""):
return val[0] if isinstance(val, list) else val
+def _cbor_timestamp(value):
+ """Encode an epoch/ISO timestamp as CBOR tag 1 (epoch date-time).
+
+ smithy-rpc-v2-cbor (used by the Terraform AWS provider >= 6.50 for
+ CloudWatch) expects Timestamp members as CBOR tag 1. A bare Python ``int``
+ serializes as a CBOR unsigned integer, which the provider's typed decoder
+ rejects with ``unexpected value type cbor.Uint`` (issue #1261).
+ """
+ import cbor2
+
+ epoch = _parse_ts(value) if isinstance(value, str) else value
+ if epoch is None:
+ return value
+ return cbor2.CBORTag(1, float(epoch))
+
+
+def _cbor_alarm(alarm):
+ """Return a CBOR-safe copy of an alarm with Timestamp members tag-1 encoded."""
+ out = dict(alarm)
+ for field in (
+ "StateUpdatedTimestamp",
+ "AlarmConfigurationUpdatedTimestamp",
+ "StateTransitionedTimestamp",
+ ):
+ if out.get(field) is not None:
+ out[field] = _cbor_timestamp(out[field])
+ return out
+
+
+def _cbor_history_item(item):
+ """Return a CBOR-safe copy of an alarm-history item with a tag-1 Timestamp."""
+ out = dict(item)
+ if out.get("Timestamp") is not None:
+ out["Timestamp"] = _cbor_timestamp(out["Timestamp"])
+ return out
+
+
def _cbor_ok(data: dict):
try:
import cbor2
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 04e9cac5..fab5e401 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -1383,9 +1383,22 @@ _SELECT_ATTR_RE = re.compile(r"^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$")
def _rule_select_clause(sql: str) -> str:
- """Extract the SELECT clause of a rule SQL statement."""
- m = _SELECT_CLAUSE_RE.search(sql or "")
- return m.group(1).strip() if m else "*"
+ """Extract the SELECT clause of a rule SQL statement.
+
+ FROM is optional for Basic Ingest rules, so a rule may be just
+ ``SELECT <projection>`` with no ``FROM '<topic>'``. Try the FROM form first
+ (it stops at ``FROM '`` so inner subquery FROMs are preserved), then fall
+ back to everything after SELECT for the FROM-less form.
+ """
+ sql = sql or ""
+ m = _SELECT_CLAUSE_RE.search(sql)
+ if m:
+ return m.group(1).strip()
+ m = re.match(r"\s*SELECT\s+(.+)$", sql, re.IGNORECASE | re.DOTALL)
+ if not m:
+ return "*"
+ proj = re.split(r"\s+WHERE\s+", m.group(1), maxsplit=1, flags=re.IGNORECASE)[0]
+ return proj.strip()
def _split_select_items(clause: str) -> list[str]:
diff --git a/pyproject.toml b/pyproject.toml
index 46fab61d..40807172 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.4.9"
+version = "1.4.10"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 240c1e3e..0736de3e 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -258,6 +258,25 @@ def test_apigw_match_route_default_fallback():
assert route["routeKey"] == "$default"
[email protected]("greedy_first", [False, True])
+def test_apigw_match_route_full_match_beats_greedy_with_more_literals(greedy_first):
+ """AWS priority is full-match-beats-greedy, independent of literal count: a
+ fully-parameterized route (`GET /{x}/{y}/{z}`) is a full match and must win
+ over a greedy route with more literal segments (`GET /a/b/{proxy+}`), which
+ is only a tier-2 greedy match, for the request `/a/b/c`.
+ """
+ from ministack.services import apigateway as apigw_mod
+
+ full = "GET /{x}/{y}/{z}"
+ greedy = "GET /a/b/{proxy+}"
+ keys = [greedy, full] if greedy_first else [full, greedy]
+ api_id = _make_api_with_routes(apigw_mod, keys)
+
+ route = apigw_mod._match_route(api_id, "GET", "/a/b/c")
+ assert route is not None
+ assert route["routeKey"] == full
+
+
def test_apigw_create_integration(apigw):
api_id = apigw.create_api(Name="integ-api", ProtocolType="HTTP")["ApiId"]
resp = apigw.create_integration(
diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.py
index 06b7b344..ef4ece4c 100644
--- a/tests/test_cloudwatch.py
+++ b/tests/test_cloudwatch.py
@@ -577,3 +577,50 @@ def test_cloudwatch_disable_alarm_actions(cw):
alarm = cw.describe_alarms(AlarmNames=["heimdall-disable-actions"])["MetricAlarms"][0]
assert alarm["ActionsEnabled"] is False
cw.delete_alarms(AlarmNames=["heimdall-disable-actions"])
+
+
+def test_cloudwatch_describe_alarms_cbor_timestamps_are_tag1():
+ """DescribeAlarms over smithy-rpc-v2-cbor must encode Timestamp members as
+ CBOR tag 1 (epoch datetime), not a bare unsigned int, or the Terraform AWS
+ provider >= 6.50 fails with `unexpected value type cbor.Uint` (issue #1261).
+ Integer members (Period, EvaluationPeriods) stay CBOR integers, which the
+ Smithy Integer decoder accepts.
+ """
+ import datetime as _dt
+
+ import cbor2
+
+ from ministack.core import responses as _resp
+ from ministack.services import cloudwatch as _cw
+
+ acct_tok = _resp._request_account_id.set("000000000000")
+ region_tok = _resp._request_region.set("us-east-1")
+ name = f"cbor-alarm-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ _cw._put_metric_alarm({}, {
+ "AlarmName": name,
+ "ComparisonOperator": "GreaterThanThreshold",
+ "EvaluationPeriods": 1,
+ "MetricName": "Errors",
+ "Namespace": "AWS/Lambda",
+ "Period": 300,
+ "Statistic": "Sum",
+ "Threshold": 1,
+ }, is_cbor=True)
+
+ status, _headers, body = _cw._describe_alarms({}, {"AlarmNames": [name]}, is_cbor=True)
+ assert status == 200
+ decoded = cbor2.loads(body)
+ alarm = next(a for a in decoded["MetricAlarms"] if a["AlarmName"] == name)
+
+ # cbor2 decodes a CBOR tag-1 value back into a datetime — proof the wire
+ # bytes were tag 1, not a bare uint.
+ assert isinstance(alarm["StateUpdatedTimestamp"], _dt.datetime)
+ assert isinstance(alarm["AlarmConfigurationUpdatedTimestamp"], _dt.datetime)
+ # Integer members remain plain integers.
+ assert isinstance(alarm["Period"], int) and alarm["Period"] == 300
+ assert isinstance(alarm["EvaluationPeriods"], int)
+ finally:
+ _cw._alarms.pop_scoped("000000000000", "us-east-1", name, None)
+ _resp._request_region.reset(region_tok)
+ _resp._request_account_id.reset(acct_tok)
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 9bb7c7e2..5dd4772e 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -2429,3 +2429,15 @@ def test_rule_event_aliased_star_nests_the_message():
"SELECT * AS payload FROM 'telemetry'", "telemetry", b'{"temp": 22}'
)
assert event == {"payload": {"temp": 22}}
+
+
+def test_rule_event_from_less_basic_ingest_projects():
+ """FROM is optional for Basic Ingest rules, so a FROM-less `SELECT` must
+ still project rather than fall through to `*` and deliver the whole message.
+ """
+ from ministack.services.iot import _rule_event
+
+ event = _rule_event(
+ "SELECT deviceId AS id, temp", "$aws/rules/myrule", b'{"deviceId": "d1", "temp": 22, "extra": "x"}'
+ )
+ assert event == {"id": "d1", "temp": 22}