Skip to content

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

fix(iot): stop a trailing # from matching the level above it (#2352)

iot-rocket35ac6b2e7be7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9f7b7497..0c906138 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Route 53 — VPC associations for private hosted zones** — `AssociateVPCWithHostedZone`, `DisassociateVPCFromHostedZone` and `ListHostedZonesByVPC` (paged with `MaxItems` and `NextToken`). They refuse a public zone (`PublicZoneVPCAssociation`), a VPC already associated with a zone of the same name (`ConflictingDomainExists`), a VPC the zone doesn't have (404 `VPCAssociationNotFound`) and the zone's last VPC (`LastVPCAssociation`). Contributed by @kharabasz.
### Fixed
+- **IoT — `#` does not match the level above it** — a subscription or topic rule with a filter ending in `/#` (`a/c2/#`) also got messages published to the level above (`a/c2`), as the MQTT specification allows; AWS IoT Core delivers only `a/c2/` and deeper, and so does the broker now, for subscriptions and rules. A republish topic at that level is still refused, as on AWS. Contributed by @iot-rocket.
- **EventBridge — archive KMS keys** — `CreateArchive` and `UpdateArchive` dropped `KmsKeyIdentifier`, so `DescribeArchive` never returned it and Terraform re-planned `kms_key_identifier` on every run; the key is now stored and returned, an update that omits it keeps it, and an empty identifier on update clears it; `ListArchives` entries carry only the `Archive` summary fields. Contributed by @kharabasz.
- **WAF v2 — `CreateIPSet` and `CreateRuleGroup` refuse a duplicate name** — a second IP set or rule group with the name and scope of an existing one is now refused with `WAFDuplicateItemException` (`AWS WAF couldn’t perform the operation because some resource in your request is a duplicate of an existing one.`, also from `CreateWebACL` and `CreateRegexPatternSet`). Both stored the duplicate silently, so a client that retries a create after losing the response ended up with two. Contributed by @OS-kiranmalsetty.
- **Cognito — pre token generation event fields** — the event always said `"version": "1"`, a `NEW_PASSWORD_REQUIRED` answer was `TokenGeneration_Authentication` and a `client_credentials` grant had an empty `userName`; the event now carries `"1"`, `"2"` or `"3"` for `V1_0`, `V2_0` and `V3_0`, `TokenGeneration_NewPasswordChallenge` and `ClientCredentials`, as AWS sends them. Contributed by @iot-rocket.
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 61b76b62..740e00db 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -8966,6 +8966,9 @@ def _subscription_matches(filter_: str, topic: str) -> bool:
"""Whether a subscription's or rule's filter matches; ``$aws/events`` skips filters that start with a wildcard."""
if topic.startswith("$aws/events/") and filter_[:1] in ("#", "+"):
return False
+ # AWS IoT delivers nothing to `a/#` from the level above it, `a`.
+ if filter_.endswith("/#") and topic.count("/") < filter_.count("/"):
+ return False
return _topic_matches(filter_, topic)
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 89c9cdbf..d4e0b52a 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -5034,6 +5034,32 @@ def test_iot_broker_wildcard_region_does_not_widen_its_own_filters():
reset()
+def test_iot_broker_trailing_hash_does_not_match_the_level_above():
+ """``a/c2/#`` gets ``a/c2/`` and ``a/c2/x`` but, as on AWS, not ``a/c2``; ``a/#`` and ``#`` get all three."""
+ reset()
+
+ async def _run():
+ account_id = "123456789012"
+ received = {}
+ for topic_filter in ("a/c2", "a/c2/#", "+/c2/#", "a/#", "#"):
+ async def callback(topic, payload, qos, key=topic_filter):
+ received.setdefault(key, []).append(topic)
+
+ await broker_subscribe(account_id, _TEST_REGION, topic_filter, callback)
+ for topic in ("a/c2", "a/c2/", "a/c2/x"):
+ await broker_publish(account_id, _TEST_REGION, topic, b"x")
+ assert received == {
+ "a/c2": ["a/c2"],
+ "a/c2/#": ["a/c2/", "a/c2/x"],
+ "+/c2/#": ["a/c2/", "a/c2/x"],
+ "a/#": ["a/c2", "a/c2/", "a/c2/x"],
+ "#": ["a/c2", "a/c2/", "a/c2/x"],
+ }
+
+ asyncio.run(_run())
+ reset()
+
+
def test_iot_broker_leading_wildcard_does_not_match_aws_events():
"""``#`` and ``+/...`` get ``$aws/things`` but not ``$aws/events``, live and queued."""
reset()
@@ -5123,6 +5149,37 @@ def test_iot_topic_rule_leading_wildcard_does_not_match_aws_events(monkeypatch):
]
+def test_iot_topic_rule_trailing_hash_does_not_fire_on_the_level_above(monkeypatch):
+ """A rule ``FROM 'a/c2/#'`` fires on ``a/c2/`` and ``a/c2/x`` but, as on AWS, not on ``a/c2``."""
+ from ministack.services import iot as iot_module
+
+ reset()
+ iot_module._topic_rules.clear()
+ account_id = "123456789012"
+ iot_module._topic_rules.set_scoped(account_id, _TEST_REGION, "hash", {
+ "ruleName": "hash", "sql": "SELECT * FROM 'a/c2/#'", "ruleDisabled": False, "actions": [],
+ })
+ fired = []
+
+ async def _capture_rule_action(
+ dispatched_account_id, dispatched_region, rule, payload, topic="", client_id=None
+ ):
+ fired.append(topic)
+
+ monkeypatch.setattr(iot_module, "_run_rule_actions", _capture_rule_action)
+
+ async def _run():
+ for topic in ("a/c2", "a/c2/", "a/c2/x"):
+ await broker_publish(account_id, _TEST_REGION, topic, b"{}")
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module._topic_rules.clear()
+ reset()
+ assert fired == ["a/c2/", "a/c2/x"]
+
+
def test_iot_broker_persistent_sessions_are_region_isolated():
reset()