Skip to content

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

fix(iot): support AWS::IoT::TopicRule in CloudFormation (#1073)

maximoosemineb1dac57bdbde
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7efea614..f2694ecf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **IoT — `AWS::IoT::TopicRule` CloudFormation support** — deploying an `AWS::IoT::TopicRule` previously failed with `Unsupported resource type: AWS::IoT::TopicRule` and rolled the stack back. A provisioner now creates and deletes the rule (normalizing the PascalCase `TopicRulePayload` — `Sql`, `Actions`, `Lambda`/`FunctionArn`, … — to the API's camelCase shape), `Ref` returns the rule name and `Fn::GetAtt Arn` the rule ARN. The IoT control plane gains the backing operations: `CreateTopicRule`, `GetTopicRule`, `ListTopicRules`, `ReplaceTopicRule`, and `DeleteTopicRule`. Rules are account-scoped and persisted with the rest of the IoT state.
+
### Fixed
- **DynamoDB — validation parity with real AWS on reads, deletes, batches, and transactions** — validation gaps that let malformed requests succeed silently (all verified against **real AWS DynamoDB**): (1) `GetItem`, `DeleteItem`, and `BatchGetItem` now reject key attributes carrying an empty string/binary value, as `PutItem` already did; (2) `BatchWriteItem` validates every member *before* applying any — previously a bad member returned the correct `ValidationException` but earlier members were already written; (3) `TransactWriteItems` validates every member before applying anything and matches real AWS's two failure shapes: an empty-string/binary key value (or malformed item) is an up-front top-level `ValidationException`, whereas a wrong-typed key or an update-expression type error is surfaced as a `TransactionCanceledException` with a positional `ValidationError` cancellation reason — previously an invalid member was silently committed with no error at all; (4) `Query` rejects a `KeyConditionExpression` `BETWEEN` with inverted bounds at parse time with the AWS error message, instead of returning an empty result; (5) `Query` validates key-condition operands like key values — an empty string/binary operand on a key attribute is rejected; (6) `Query` rejects an `ExclusiveStartKey` whose sort value violates the range-key predicate (`The provided starting key does not match the range key predicate`) — such a cursor can never have been issued by a previous page; (7) `UpdateItem` `SET` rejects a document path that doesn't resolve on the item (`The provided expression refers to an attribute that does not exist in the item`) — e.g. `list_append` on a missing attribute, where `if_not_exists` is the sanctioned form; previously the assignment was silently skipped; (8) `UpdateItem` `ADD`/`DELETE` reject non-Number/Set operands (`Incorrect operand type for operator or function`, with the AWS quirk that the `typeSet` is reported as `ALLOWED_FOR_ADD_OPERAND` even for `DELETE`) and operands whose type doesn't match the existing attribute (`An operand in the update expression has an incorrect data type`) — previously `ADD` could silently *replace* a set attribute with a number, and `DELETE` silently no-opped. All error shapes verified against real AWS DynamoDB. Contributed by @ifutivic.
- **DynamoDB — `Query`/`Scan` return `LastEvaluatedKey` when results end exactly at `Limit`** — real DynamoDB doesn't look ahead: whenever it stops because of the limit it returns a `LastEvaluatedKey`, even if nothing remains, and the follow-up page comes back empty with no key. MiniStack only returned the key when strictly more items remained, so SDK pagination helpers that rely on the exact-limit page (e.g. "has more pages" checks) diverged from AWS. Verified against DynamoDB Local. Contributed by @ifutivic.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 10589903..4305c9ef 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -33,6 +33,7 @@ import ministack.services.ecr as _ecr
import ministack.services.ecs as _ecs
import ministack.services.eventbridge as _eb
import ministack.services.iam as _iam
+import ministack.services.iot as _iot
import ministack.services.kinesis as _kinesis
import ministack.services.kms as _kms
import ministack.services.lambda_svc as _lambda_svc
@@ -1087,6 +1088,34 @@ def _eb_rule_delete(physical_id, props):
_eb._targets.pop(key, None)
+# --- IoT Topic Rule (AWS::IoT::TopicRule) ---
+
+
+def _pascal_to_camel(obj):
+ """Recursively lower-case the first letter of every dict key.
+
+ CloudFormation PascalCases the IoT API's camelCase TopicRulePayload fields
+ (Sql, Actions, Lambda, FunctionArn, ...); this reverses that so the stored
+ rule matches the control-plane / routing shape.
+ """
+ if isinstance(obj, dict):
+ return {(k[:1].lower() + k[1:] if k else k): _pascal_to_camel(v) for k, v in obj.items()}
+ if isinstance(obj, list):
+ return [_pascal_to_camel(v) for v in obj]
+ return obj
+
+
+def _iot_topic_rule_create(logical_id, props, stack_name):
+ name = props.get("RuleName") or _physical_name(stack_name, logical_id).replace("-", "_")
+ payload = _pascal_to_camel(props.get("TopicRulePayload", {}))
+ _iot.put_topic_rule(name, payload)
+ return name, {"Arn": _iot._topic_rule_arn(name)}
+
+
+def _iot_topic_rule_delete(physical_id, props):
+ _iot.delete_topic_rule(physical_id)
+
+
# --- EventBridge Scheduler (AWS::Scheduler::Schedule) ---
@@ -4352,6 +4381,7 @@ _RESOURCE_HANDLERS = {
"AWS::CloudWatch::Alarm": {"create": _cw_metric_alarm_create, "delete": _cw_metric_alarm_delete},
"AWS::RDS::DBCluster": {"create": _rds_db_cluster_create, "delete": _rds_db_cluster_delete},
"AWS::RDS::DBInstance": {"create": _rds_db_instance_create, "delete": _rds_db_instance_delete},
+ "AWS::IoT::TopicRule": {"create": _iot_topic_rule_create, "delete": _iot_topic_rule_delete},
# EventBridge Scheduler
"AWS::Scheduler::Schedule": {"create": _scheduler_schedule_create, "delete": _scheduler_schedule_delete},
"AWS::Scheduler::ScheduleGroup": {"create": _scheduler_group_create, "delete": _scheduler_group_delete},
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 0a47dd03..48db3b5a 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -75,6 +75,7 @@ _thing_types: AccountScopedDict = AccountScopedDict()
_thing_groups: AccountScopedDict = AccountScopedDict()
_certificates: AccountScopedDict = AccountScopedDict() # certificateId -> Certificate dict
_policies: AccountScopedDict = AccountScopedDict() # policyName -> Policy dict
+_topic_rules: AccountScopedDict = AccountScopedDict() # ruleName -> TopicRule dict
# Local CA state — lazily generated on first use, persisted across restarts.
import threading
@@ -155,6 +156,7 @@ def get_state() -> dict:
"thing_groups": copy.deepcopy(_thing_groups),
"certificates": copy.deepcopy(_certificates),
"policies": copy.deepcopy(_policies),
+ "topic_rules": copy.deepcopy(_topic_rules),
"ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}
if _ca_cert_pem and _ca_key_pem
else {},
@@ -171,6 +173,7 @@ def restore_state(data: dict | None) -> None:
_thing_groups.update(data.get("thing_groups", {}))
_certificates.update(data.get("certificates", {}))
_policies.update(data.get("policies", {}))
+ _topic_rules.update(data.get("topic_rules", {}))
ca_data = data.get("ca")
if ca_data:
cert = ca_data.get("ca_cert_pem")
@@ -190,6 +193,7 @@ def reset() -> None:
_thing_groups.clear()
_certificates.clear()
_policies.clear()
+ _topic_rules.clear()
with _CA_LOCK:
_ca_cert_pem = None
_ca_key_pem = None
@@ -255,6 +259,14 @@ def _policy_arn(name: str) -> str:
return f"arn:aws:iot:{get_region()}:{get_account_id()}:policy/{name}"
+def _topic_rule_arn(name: str) -> str:
+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:rule/{name}"
+
+
+# Rule names are stricter than other IoT resources: [a-zA-Z0-9_] only.
+_RULE_NAME_RE = re.compile(r"^[a-zA-Z0-9_]{1,128}$")
+
+
def _validate_name(name: str | None, field: str) -> tuple | None:
if not name or not _NAME_RE.match(name):
return error_response_json(
@@ -363,6 +375,12 @@ async def handle_request(
if path.startswith("/policies/"):
return _handle_policy(method, path, body, qp)
+ # Topic rules
+ if path == "/rules" and method == "GET":
+ return _list_topic_rules(qp)
+ if path.startswith("/rules/"):
+ return _handle_topic_rule(method, path, body)
+
return error_response_json(
"InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
)
@@ -1331,6 +1349,101 @@ def _list_attached_policies(path: str, qp: dict) -> tuple:
return json_response({"policies": out})
+# ---------------------------------------------------------------------------
+# Topic rules
+# ---------------------------------------------------------------------------
+
+
+def _rule_topic_filter(sql: str) -> str:
+ """Extract the topic filter from a rule SQL ``FROM '<topic>'`` clause."""
+ m = re.search(r"\bFROM\s+'([^']*)'", sql or "", re.IGNORECASE)
+ return m.group(1) if m else ""
+
+
+def put_topic_rule(name: str, payload: dict, *, created_at: float | None = None) -> dict:
+ """Store a topic rule from an API-shape (camelCase) ``TopicRulePayload``."""
+ rule = {
+ "ruleName": name,
+ "sql": payload.get("sql", ""),
+ "actions": payload.get("actions", []) or [],
+ "ruleDisabled": bool(payload.get("ruleDisabled", False)),
+ "awsIotSqlVersion": payload.get("awsIotSqlVersion", "2016-03-23"),
+ "description": payload.get("description", ""),
+ "errorAction": payload.get("errorAction"),
+ "createdAt": created_at if created_at is not None else _now_epoch(),
+ }
+ _topic_rules[name] = rule
+ return rule
+
+
+def delete_topic_rule(name: str) -> None:
+ _topic_rules.pop(name, None)
+
+
+def _handle_topic_rule(method: str, path: str, body: bytes) -> tuple:
+ name = path[len("/rules/"):]
+ if method == "POST":
+ return _create_topic_rule(name, _parse_body(body))
+ if method == "GET":
+ return _get_topic_rule(name)
+ if method == "PATCH":
+ return _replace_topic_rule(name, _parse_body(body))
+ if method == "DELETE":
+ return _delete_topic_rule(name)
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
+ )
+
+
+def _create_topic_rule(name: str, payload: dict) -> tuple:
+ if not _RULE_NAME_RE.match(name or ""):
+ return error_response_json(
+ "InvalidRequestException",
+ "Invalid ruleName: must match [a-zA-Z0-9_]{1,128}",
+ 400,
+ )
+ if name in _topic_rules:
+ return error_response_json(
+ "ResourceAlreadyExistsException", f"Rule {name!r} already exists", 409
+ )
+ if not payload.get("sql"):
+ return error_response_json("SqlParseException", "sql is required", 400)
+ put_topic_rule(name, payload)
+ return json_response({})
+
+
+def _replace_topic_rule(name: str, payload: dict) -> tuple:
+ if name not in _topic_rules:
+ return _error_not_found("Rule", name)
+ put_topic_rule(name, payload)
+ return json_response({})
+
+
+def _get_topic_rule(name: str) -> tuple:
+ rule = _topic_rules.get(name)
+ if rule is None:
+ return _error_not_found("Rule", name)
+ return json_response({"ruleArn": _topic_rule_arn(name), "rule": rule})
+
+
+def _delete_topic_rule(name: str) -> tuple:
+ _topic_rules.pop(name, None)
+ return json_response({})
+
+
+def _list_topic_rules(qp: dict) -> tuple:
+ rules = []
+ for r in _topic_rules.values():
+ rules.append({
+ "ruleName": r["ruleName"],
+ "ruleArn": _topic_rule_arn(r["ruleName"]),
+ "topicPattern": _rule_topic_filter(r["sql"]),
+ "createdAt": r["createdAt"],
+ "ruleDisabled": r["ruleDisabled"],
+ })
+ return json_response({"rules": rules})
+
+
# ---------------------------------------------------------------------------
# Helper exports for iot_data
# ---------------------------------------------------------------------------
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 6da01e38..0a112f58 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -6,6 +6,7 @@ iot-data Publish) is covered separately in ``test_iot_data.py``.
"""
import json
+import time
import uuid
import pytest
@@ -407,6 +408,139 @@ def test_iot_attach_detach_policy(iot_client):
iot_client.delete_certificate(certificateId=cert["certificateId"])
+# ---------------------------------------------------------------------------
+# Topic rules
+# ---------------------------------------------------------------------------
+
+
+def _rule_name(prefix: str = "rule") -> str:
+ return f"{prefix}_{uuid.uuid4().hex[:8]}"
+
+
+def test_iot_topic_rule_lifecycle(iot_client):
+ name = _rule_name()
+ payload = {
+ "sql": "SELECT * FROM 'devices/+/data'",
+ "ruleDisabled": False,
+ "awsIotSqlVersion": "2016-03-23",
+ "actions": [
+ {"lambda": {"functionArn": "arn:aws:lambda:us-east-1:000000000000:function:foo"}}
+ ],
+ }
+ iot_client.create_topic_rule(ruleName=name, topicRulePayload=payload)
+
+ got = iot_client.get_topic_rule(ruleName=name)
+ assert got["ruleArn"] == f"arn:aws:iot:us-east-1:000000000000:rule/{name}"
+ assert got["rule"]["sql"] == payload["sql"]
+ assert got["rule"]["actions"] == payload["actions"]
+ assert got["rule"]["ruleDisabled"] is False
+
+ listing = iot_client.list_topic_rules()["rules"]
+ entry = next(r for r in listing if r["ruleName"] == name)
+ assert entry["topicPattern"] == "devices/+/data"
+
+ iot_client.delete_topic_rule(ruleName=name)
+ with pytest.raises(ClientError) as ei:
+ iot_client.get_topic_rule(ruleName=name)
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_iot_topic_rule_duplicate_rejected(iot_client):
+ name = _rule_name()
+ payload = {"sql": "SELECT * FROM 'a'", "actions": []}
+ iot_client.create_topic_rule(ruleName=name, topicRulePayload=payload)
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_topic_rule(ruleName=name, topicRulePayload=payload)
+ assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"
+ iot_client.delete_topic_rule(ruleName=name)
+
+
+def test_iot_replace_topic_rule(iot_client):
+ name = _rule_name()
+ iot_client.create_topic_rule(
+ ruleName=name, topicRulePayload={"sql": "SELECT * FROM 'a'", "actions": []}
+ )
+ iot_client.replace_topic_rule(
+ ruleName=name, topicRulePayload={"sql": "SELECT * FROM 'b'", "actions": []}
+ )
+ assert iot_client.get_topic_rule(ruleName=name)["rule"]["sql"] == "SELECT * FROM 'b'"
+ iot_client.delete_topic_rule(ruleName=name)
+
+
+def test_iot_replace_missing_topic_rule_404(iot_client):
+ with pytest.raises(ClientError) as ei:
+ iot_client.replace_topic_rule(
+ ruleName=_rule_name(), topicRulePayload={"sql": "SELECT * FROM 'a'", "actions": []}
+ )
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_iot_topic_rule_cfn_deploy(cfn, iot_client):
+ stack = "iot-topicrule-" + uuid.uuid4().hex[:8]
+ rule = _rule_name("ingest")
+ template = {
+ "Resources": {
+ "IngestRule": {
+ "Type": "AWS::IoT::TopicRule",
+ "Properties": {
+ "RuleName": rule,
+ "TopicRulePayload": {
+ "Sql": "SELECT * FROM 'sensors/+/telemetry'",
+ "RuleDisabled": False,
+ "AwsIotSqlVersion": "2016-03-23",
+ "Actions": [
+ {"Lambda": {"FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:ingest"}}
+ ],
+ },
+ },
+ }
+ },
+ "Outputs": {
+ "RuleArn": {"Value": {"Fn::GetAtt": ["IngestRule", "Arn"]}},
+ "RuleRef": {"Value": {"Ref": "IngestRule"}},
+ },
+ }
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps(template))
+ st = _wait_stack_iot(cfn, stack)
+ assert st["StackStatus"] == "CREATE_COMPLETE"
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in st["Outputs"]}
+ assert outputs["RuleRef"] == rule
+ assert outputs["RuleArn"] == f"arn:aws:iot:us-east-1:000000000000:rule/{rule}"
+
+ # PascalCase TopicRulePayload is normalized to the API camelCase shape.
+ stored = iot_client.get_topic_rule(ruleName=rule)["rule"]
+ assert stored["actions"] == [
+ {"lambda": {"functionArn": "arn:aws:lambda:us-east-1:000000000000:function:ingest"}}
+ ]
+
+ cfn.delete_stack(StackName=stack)
+ _wait_stack_gone_iot(cfn, stack)
+ with pytest.raises(ClientError):
+ iot_client.get_topic_rule(ruleName=rule)
+
+
+def _wait_stack_iot(cfn, name, timeout=30):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ st = cfn.describe_stacks(StackName=name)["Stacks"][0]
+ if not st["StackStatus"].endswith("_IN_PROGRESS"):
+ return st
+ time.sleep(0.5)
+ raise TimeoutError(f"Stack {name} did not settle")
+
+
+def _wait_stack_gone_iot(cfn, name, timeout=30):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ try:
+ st = cfn.describe_stacks(StackName=name)["Stacks"][0]
+ except ClientError:
+ return
+ if st["StackStatus"] == "DELETE_COMPLETE":
+ return
+ time.sleep(0.5)
+
+
# ---------------------------------------------------------------------------
# Local CA admin endpoint
# ---------------------------------------------------------------------------