Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(iot): refuse a republish action inside the rule's own topic filter (#2146)
iot-rocketcd17f7f83b02
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f2330364..9c889653 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed++- **IoT — republish inside the rule's own topic filter** — `CreateTopicRule` and `ReplaceTopicRule` accepted a `republish` action whose topic the rule's `FROM` filter matches, so the rule fed on its own output; they now refuse it with AWS's `InvalidRequestException`, and an `AWS::IoT::TopicRule` with such an action fails its stack. Contributed by @iot-rocket.### Added- **IoT — `TagResource`, `UntagResource` and `ListTagsForResource`** — the three operations answered `Unsupported IoT path`, so the tags the Create calls accept could not be read back. They now work on thing types, thing groups, policies, topic rules, jobs, job templates, CA certificates, provisioning templates and domain configurations with AWS's limits and errors, Create calls and CloudFormation `Tags` write the same tags, and deleting a resource drops them. Contributed by @iot-rocket.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 1a775f1b..a7bd011a 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -4727,6 +4727,10 @@ class RuleRoleError(ValueError):`put_topic_rule`."""+class RuleRepublishError(ValueError):+ """A republish action inside the rule's own topic filter, raised by `put_topic_rule`."""++def _validate_rule_sql(sql: str) -> str | None:"""Return an error message when the rule SQL cannot be parsed, else None."""sql = sql or ""@@ -4781,6 +4785,27 @@ def _unimplemented_sql_functions(sql: str) -> list[str]:return sorted(names - _IMPLEMENTED_SQL_FUNCS - _SQL_KEYWORDS)+def _republish_inside_filter(sql: str, actions) -> str | None:+ """The refusal when an action republishes (templates unexpanded) into the rule's FROM filter, else None."""+ filter_ = _rule_topic_filter(sql)+ if not filter_:+ return None+ for action in actions or []:+ republish = action.get("republish") if isinstance(action, dict) else None+ target = republish.get("topic") if isinstance(republish, dict) else None+ if not isinstance(target, str):+ continue+ # `$$` is the documented escape for a topic that starts with `$`.+ if target.startswith("$$"):+ target = target[1:]+ # As in MQTT, a filter that starts with a wildcard does not match a `$` topic.+ if target.startswith("$") and filter_[:1] in ("#", "+"):+ continue+ if _topic_matches(filter_, target):+ return f"Republish topic cannot be within topic space of rule's topic pattern '{filter_}'"+ return None++def put_topic_rule(name: str, payload: dict, *, created_at: float | None = None) -> dict:"""Store a topic rule from an API-shape (camelCase) ``TopicRulePayload``.@@ -4792,11 +4817,16 @@ def put_topic_rule(name: str, payload: dict, *, created_at: float | None = None)AWS) but warns, so the resulting misfire is visible. Raises `RuleRoleError`(under AUTH=true) for an action role IAM cannot resolve, through the sametwo doors — real IoT probes the role at create time and fails the call.+ Raises `RuleRepublishError` for a republish action inside the rule's own+ topic filter (the errorAction is not checked)."""sql = payload.get("sql", "")error = _validate_rule_sql(sql)if error:raise RuleSqlError(error)+ refusal = _republish_inside_filter(sql, payload.get("actions"))+ if refusal:+ raise RuleRepublishError(refusal)for func in _unimplemented_sql_functions(sql):logger.warning("Topic rule %s calls %s(), which MiniStack does not implement: it "@@ -4878,7 +4908,7 @@ def _create_topic_rule(name: str, payload: dict, tagging: str | None = None) ->put_topic_rule(name, payload)except RuleSqlError as exc:return error_response_json("SqlParseException", str(exc), 400)- except RuleRoleError as exc:+ except (RuleRoleError, RuleRepublishError) as exc:return error_response_json("InvalidRequestException", str(exc), 400)_set_created_tags(_topic_rule_arn(name), tags)return json_response({})@@ -4891,7 +4921,7 @@ def _replace_topic_rule(name: str, payload: dict) -> tuple:put_topic_rule(name, payload)except RuleSqlError as exc:return error_response_json("SqlParseException", str(exc), 400)- except RuleRoleError as exc:+ except (RuleRoleError, RuleRepublishError) as exc:return error_response_json("InvalidRequestException", str(exc), 400)return json_response({})@@ -7527,10 +7557,10 @@ def _dispatch_rule_to_lambda().start()-# Depth guard for republish chains: rule A republishing onto a topic that rule-# A (or a cycle of rules) matches again would recurse without bound. Real AWS-# does not loop-protect either — such a rule is user error — but the emulator-# must at least not crash, so the chain is cut and logged past this depth.+# Depth guard for republish chains: put_topic_rule refuses an action that+# republishes into the rule's own filter, but an errorAction that does, a+# cycle across rules or a rule restored from saved state would still recurse+# without bound, so the chain is cut and logged past this depth._MAX_REPUBLISH_DEPTH = 8_republish_depth: contextvars.ContextVar[int] = contextvars.ContextVar("_iot_republish_depth", default=0@@ -7569,8 +7599,7 @@ async def _dispatch_rule_republish(depth = _republish_depth.get()if depth >= _MAX_REPUBLISH_DEPTH:_broker_logger.warning(- "IoT rule %s: republish depth limit (%d) reached — dropping republish to %r "- "(a rule republishing onto its own topic filter loops forever on AWS too)",+ "IoT rule %s: republish depth limit (%d) reached — dropping republish to %r",rule_name,_MAX_REPUBLISH_DEPTH,target_topic,diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 5093d8ce..14565cf0 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -20804,6 +20804,80 @@ def test_cfn_update_iot_topic_rule_in_place(cfn, iot_client):_delete_cfn_test_stack(cfn, stack_name)+def _cfn_iot_republish_rule(rule_name, target):+ return {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Role": {+ "Type": "AWS::IAM::Role",+ "Properties": {"AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"Service": "iot.amazonaws.com"},+ "Action": "sts:AssumeRole"}]}},+ },+ "Rule": {+ "Type": "AWS::IoT::TopicRule",+ "Properties": {+ "RuleName": rule_name,+ "TopicRulePayload": {+ "Sql": "SELECT * FROM 'things/in/#'",+ "Actions": [{"Republish": {+ "Topic": target,+ "RoleArn": {"Fn::GetAtt": ["Role", "Arn"]},+ }}],+ },+ },+ },+ },+ }+++def test_cfn_iot_topic_rule_republish_inside_own_filter_fails_create(cfn, iot_client):+ """The resource fails with IoT's refusal, the stack rolls back and no rule is stored."""+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name, rule_name = f"cfn-iotrule-self-{suffix}", f"cfn_rule_self_{suffix}"+ try:+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(_cfn_iot_republish_rule(rule_name, "things/in/x")),+ Capabilities=["CAPABILITY_IAM"],+ )+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "ROLLBACK_COMPLETE"+ assert _cfn_iot_failure(cfn, stack_name, "Rule", "CREATE_FAILED") == (+ "Republish topic cannot be within topic space of rule's topic pattern 'things/in/#'")+ with pytest.raises(ClientError) as ei:+ iot_client.get_topic_rule(ruleName=rule_name)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_iot_topic_rule_republish_inside_own_filter_fails_update(cfn, iot_client):+ """An update that moves the republish topic inside the filter fails and rolls back to the old rule."""+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name, rule_name = f"cfn-iotrule-selfup-{suffix}", f"cfn_rule_selfup_{suffix}"+ try:+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(_cfn_iot_republish_rule(rule_name, "out/topic")),+ Capabilities=["CAPABILITY_IAM"],+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ cfn.update_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(_cfn_iot_republish_rule(rule_name, "things/in/x")),+ Capabilities=["CAPABILITY_IAM"],+ )+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"+ assert _cfn_iot_failure(cfn, stack_name, "Rule", "UPDATE_FAILED") == (+ "Republish topic cannot be within topic space of rule's topic pattern 'things/in/#'")+ rule = iot_client.get_topic_rule(ruleName=rule_name)["rule"]+ assert rule["actions"][0]["republish"]["topic"] == "out/topic"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++def test_cfn_update_sns_topic_in_place(cfn, sns):"""A topic's DisplayName updates in place: the ARN — and a subscriptioncreated outside the stack — survive."""diff --git a/tests/test_iot.py b/tests/test_iot.pyindex ec5e2b4a..e800326d 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -2534,6 +2534,84 @@ def test_iot_create_topic_rule_accepts_full_where_grammar(iot_client):iot_client.delete_topic_rule(ruleName=name)+def _republish_role(iam) -> str:+ """A role the republish actions can name, so the rules also resolve it under AUTH=true."""+ trust = {"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Principal": {"Service": "iot.amazonaws.com"}, "Action": "sts:AssumeRole"}]}+ try:+ iam.create_role(RoleName="iot-republish-role", AssumeRolePolicyDocument=json.dumps(trust))+ except ClientError as exc:+ if exc.response["Error"]["Code"] != "EntityAlreadyExists":+ raise+ return iam.get_role(RoleName="iot-republish-role")["Role"]["Arn"]+++def _republish(role_arn: str, topic: str) -> dict:+ return {"republish": {"roleArn": role_arn, "topic": topic}}+++ "topic_filter, targets, disabled",+ [+ ("loop/#", ["loop/x"], False),+ ("loop/exact", ["loop/exact"], False),+ ("loop/+/c", ["loop/b/c"], False),+ ("loop/par/#", ["loop/par"], False),+ ("loop/#", ["loop/${clientid()}"], False),+ ("loop/#", ["loop/x"], True),+ ("loop/#", ["elsewhere", "loop/x"], False),+ ("$aws/things/t/shadow/update", ["$$aws/things/t/shadow/update"], False),+ ],+ ids=[+ "hash", "exact", "plus", "hash-parent-level", "template-suffix", "disabled", "second-action",+ "escaped-dollar",+ ],+)+def test_iot_create_topic_rule_republish_inside_own_filter_rejected(+ iot_client, iam, topic_filter, targets, disabled+):+ """A republish topic the rule's own FROM filter matches is refused, and nothing is stored."""+ role_arn, name = _republish_role(iam), _rule_name()+ with pytest.raises(ClientError) as ei:+ iot_client.create_topic_rule(ruleName=name, topicRulePayload={+ "sql": f"SELECT * FROM '{topic_filter}'",+ "ruleDisabled": disabled,+ "actions": [_republish(role_arn, target) for target in targets],+ })+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+ assert ei.value.response["Error"]["Message"] == (+ f"Republish topic cannot be within topic space of rule's topic pattern '{topic_filter}'"+ )+ with pytest.raises(ClientError) as ei:+ iot_client.get_topic_rule(ruleName=name)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++ "topic_filter, target, error_target",+ [+ ("loop/#", "elsewhere", None),+ ("loop/+", "loop/a/b", None),+ ("loop/#", "elsewhere", "loop/x"),+ ("loop/#", "${topic()}", None),+ ("+/b/c", "$$a/b/c", None),+ ],+ ids=["outside", "plus-one-level", "error-action-inside", "template-only", "dollar-under-leading-wildcard"],+)+def test_iot_create_topic_rule_republish_outside_own_filter_accepted(+ iot_client, iam, topic_filter, target, error_target+):+ """Only the actions' topics as written are checked, so these rules are stored."""+ role_arn, name = _republish_role(iam), _rule_name()+ payload = {"sql": f"SELECT * FROM '{topic_filter}'", "actions": [_republish(role_arn, target)]}+ if error_target:+ payload["errorAction"] = _republish(role_arn, error_target)+ iot_client.create_topic_rule(ruleName=name, topicRulePayload=payload)+ assert iot_client.get_topic_rule(ruleName=name)["rule"]["actions"] == [_republish(role_arn, target)]+ iot_client.delete_topic_rule(ruleName=name)++def test_iot_replace_topic_rule_garbage_sql_rejected(iot_client):name = _rule_name()iot_client.create_topic_rule(@@ -2549,6 +2627,24 @@ def test_iot_replace_topic_rule_garbage_sql_rejected(iot_client):iot_client.delete_topic_rule(ruleName=name)+def test_iot_replace_topic_rule_republish_inside_own_filter_rejected(iot_client, iam):+ role_arn, name = _republish_role(iam), _rule_name()+ iot_client.create_topic_rule(+ ruleName=name, topicRulePayload={"sql": "SELECT * FROM 'a'", "actions": [_republish(role_arn, "b")]}+ )+ with pytest.raises(ClientError) as ei:+ iot_client.replace_topic_rule(+ ruleName=name, topicRulePayload={"sql": "SELECT * FROM 'a'", "actions": [_republish(role_arn, "a")]}+ )+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+ assert ei.value.response["Error"]["Message"] == (+ "Republish topic cannot be within topic space of rule's topic pattern 'a'"+ )+ # The stored rule is untouched.+ assert iot_client.get_topic_rule(ruleName=name)["rule"]["actions"] == [_republish(role_arn, "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(@@ -5958,8 +6054,7 @@ def test_rule_republish_is_a_new_message_from_the_rule_role_session():def test_rule_republish_onto_own_topic_terminates():- """A rule republishing onto its own topic filter is user error, but the- broker must cut the chain instead of recursing forever."""+ """A rule restored from saved state can still republish onto its own filter; the broker cuts the chain."""from ministack.services import iot as iot_modulereset()