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): hold MQTT clients to the reserved topics AWS allows (#2284)
iot-rocketa5885fa8736c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7b3e8abd..ac1e7284 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IoT — MQTT clients are held to the reserved topics AWS lets them use** — a client could subscribe to any `$` filter and publish to the replies AWS IoT writes itself (fleet provisioning, Jobs, Device Defender, MQTT file delivery, Device Location and commands), and an MQTT 5 publish to another `$` topic got DISCONNECT 0x87; the broker now refuses, before the policy check, a filter outside the reserved filters a client may use (SUBACK 0x8F on MQTT 5, a closed connection on 3.1.1) and a publish to those replies or to any other unknown `$` topic (PUBACK 0x90 on MQTT 5 and DISCONNECT 0x90 at QoS 0, a closed connection on 3.1.1), and HTTPS `Publish` answers "Topic can't start with $" for the fleet provisioning and Device Location replies, as AWS does. Contributed by @iot-rocket.- **IAM — trust policies with `NotPrincipal`** — `CreateRole`, `UpdateAssumeRolePolicy` and `AWS::IAM::Role` stored a trust policy with a `NotPrincipal` statement; they now answer `MalformedPolicyDocument` with IAM's message, `Allow with NotPrincipal is not allowed.` when an `Allow` statement carries it and `AssumeRole policy must not contain NotPrincipal field.` for a `Deny`, with `AUTH` on or off. Contributed by @iot-rocket.- **S3 — `x-amz-grant-*` headers** — `PutBucketAcl` and `PutObjectAcl` answered the grant headers with 400 `MissingSecurityHeader`, and `CreateBucket`, `PutObject` and `CopyObject` dropped them. On buckets with ACLs enabled all five now set an ACL of exactly the named grants, in the order S3 lists them, and refuse what S3 refuses: a malformed grant, an unknown group, an email grantee, and grant headers next to `x-amz-acl` or an ACL body. On a bucket with ACLs disabled (`BucketOwnerEnforced`) `PutBucketAcl` and `PutObjectAcl` refuse grant headers with 400 `AccessControlListNotSupported`. Contributed by @iot-rocket.- **S3 — Block Public Access settings and public bucket ACL grants** — any one of the four Block Public Access settings shut off every public grant on a bucket, none refused setting a public ACL, and a public bucket ACL opened every read and write in the bucket. `BlockPublicAcls` now refuses a call that sets a public ACL on a bucket with ACLs enabled (403 `AccessDenied`) and leaves the grants in place, `IgnorePublicAcls` drops public ACL grants and `RestrictPublicBuckets` the bucket policy. A bucket ACL grants what its permission covers: `READ` the listings, `WRITE` adding and removing objects, `READ_ACP` and `WRITE_ACP` the bucket ACL. Contributed by @iot-rocket.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 901fe48a..be5a1b11 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -8974,11 +8974,8 @@ def _validate_publish_topic(topic: str) -> bool:return True-# The reserved topic space a client may publish into. AWS closes the connection-# of an MQTT client that publishes to any other topic starting with ``$``-# (measured for ``$aws/events/...``, ``$aws/jobs/...`` and ``$foo/...``; a-# publish under ``$aws/rules/`` and ``$aws/things/`` is acknowledged). The HTTPS-# Publish in iot_data.py applies the same list and answers 400.+# The reserved topic families an HTTPS Publish may write into; iot_data.py+# answers 400 for any other topic starting with ``$``.RESERVED_PUBLISH_PREFIXES = ("$aws/rules/","$aws/things/",@@ -8988,9 +8985,38 @@ RESERVED_PUBLISH_PREFIXES = ("$aws/commands/",)+# Over MQTT a client may publish anywhere under $aws/rules/ and $aws/things/+# except to the replies and notifications AWS IoT itself writes there, and+# elsewhere in the reserved space only to the request topics below.+_RESERVED_REPLY_TOPIC_RE = re.compile(+ r"\$aws/things/[^/]+/(jobs/((get|start-next|[^/]+/(get|update))/(accepted|rejected)|notify|notify-next)"+ r"|defender/metrics/[^/]+/(accepted|rejected)|streams/[^/]+/(data|description|rejected)/[^/]+)"+)+_RESERVED_REQUEST_TOPIC_RE = re.compile(+ r"\$aws/(certificates/create(-from-csr)?/[^/]+|provisioning-templates/[^/]+/provision/[^/]+"+ r"|device_location/[^/]+/get_position_estimate|commands/[^/]+/[^/]+/executions/[^/]+/response/(json|cbor))"+)++# The reserved filters a client may subscribe to; a variable segment may be a "+".+_RESERVED_FILTER_RE = re.compile(+ r"\$aws/(things/.+|events/.+|sitewise/asset-models/[^/]+/assets/[^/]+/properties/[^/]+"+ r"|certificates/create(-from-csr)?/[^/]+/(accepted|rejected)"+ r"|provisioning-templates/[^/]+/provision/[^/]+/(accepted|rejected)"+ r"|device_location/[^/]+/get_position_estimate/(accepted|rejected)"+ r"|commands/[^/]+/[^/]+/executions/[^/]+/(request(/(json|cbor))?|response/(accepted|rejected)/(json|cbor)))"+)+def _reserved_topic_publish_allowed(topic: str) -> bool:- return not topic.startswith("$") or topic.startswith(RESERVED_PUBLISH_PREFIXES)+ if not topic.startswith("$"):+ return True+ if topic.startswith(("$aws/rules/", "$aws/things/")):+ return _RESERVED_REPLY_TOPIC_RE.fullmatch(topic) is None+ return _RESERVED_REQUEST_TOPIC_RE.fullmatch(topic) is not None+++def _reserved_filter_subscribe_allowed(topic_filter: str) -> bool:+ return not topic_filter.startswith("$") or _RESERVED_FILTER_RE.fullmatch(topic_filter) is not None_POLICY_VARIABLE_RE = re.compile(r"\$\{(iot:[A-Za-z.]+)\}")@@ -10368,6 +10394,7 @@ RC5_NO_SUBSCRIPTION_EXISTED = 0x11RC5_MALFORMED_PACKET = 0x81RC5_NOT_AUTHORIZED = 0x87RC5_SESSION_TAKEN_OVER = 0x8E+RC5_TOPIC_FILTER_INVALID = 0x8FRC5_TOPIC_NAME_INVALID = 0x90# Layout of the MQTT 5 SUBSCRIBE options byte (§3.8.3.1). MQTT 3.1.1 sends a@@ -11359,11 +11386,14 @@ class _WSSession:await self.send_bytes(_make_disconnect(RC5_TOPIC_NAME_INVALID))return Falseif not _reserved_topic_publish_allowed(topic):- # AWS closes the connection without a PUBACK (measured over- # MQTT 3.1.1; the MQTT 5 reason code is not measured).- _broker_logger.warning("IoT broker: PUBLISH to a reserved topic closes the connection: %r", topic)+ # Before the policy check: MQTT 5 answers a QoS 1 PUBLISH with+ # PUBACK 0x90 and keeps the connection, 3.1.1 closes it.+ _broker_logger.warning("IoT broker: PUBLISH to the reserved topic %r refused", topic)if self.protocol_version == MQTT_5:- await self.send_bytes(_make_disconnect(RC5_NOT_AUTHORIZED))+ if qos == 1 and packet_id is not None:+ await self.send_bytes(_make_puback(packet_id, reason_code=RC5_TOPIC_NAME_INVALID))+ return True+ await self.send_bytes(_make_disconnect(RC5_TOPIC_NAME_INVALID))return Falseif self.provisioning_template is not None and _mtls_claim_scope(self.certificate_id) is None:# AWS acknowledges a PUBLISH on an expired claim's connection, then closes it.@@ -11424,6 +11454,13 @@ class _WSSession:raise ValueError("SUBSCRIBE topic filter without options byte")subscription_options = body[off]off += 1+ if not _reserved_filter_subscribe_allowed(topic):+ # Before the policy check: 3.1.1 closes, MQTT 5 refuses this filter alone.+ _broker_logger.warning("IoT broker: SUBSCRIBE to the reserved filter %r refused", topic)+ if self.protocol_version != MQTT_5:+ return False+ granted.append(RC5_TOPIC_FILTER_INVALID)+ continueif not self._policy_allows("iot:Subscribe", f"topicfilter/{topic}"):# As on AWS: 3.1.1 closes, MQTT 5 refuses this filter alone._broker_logger.warning(diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.pyindex 078a960e..c6dc4357 100644--- a/ministack/services/iot_data.py+++ b/ministack/services/iot_data.py@@ -47,6 +47,8 @@ _RETAINED_PAGE_MAX = 200# under one of these reserved families. Within them, the device-side jobs,# Device Defender and commands topics are MQTT-only._HTTP_RESERVED_PREFIXES = _iot_module.RESERVED_PUBLISH_PREFIXES+# Families that take only their request topics, over HTTPS as over MQTT.+_HTTP_REQUEST_ONLY_PREFIXES = ("$aws/certificates/", "$aws/provisioning-templates/", "$aws/device_location/")_HTTP_RESTRICTED_TOPIC_RE = re.compile(r"^\$aws/(things/[^/]+/(jobs|defender)/|commands/)")@@ -74,7 +76,10 @@ def _validate_topic(topic: str) -> tuple | None:400,)if topic.startswith("$"):- if not topic.startswith(_HTTP_RESERVED_PREFIXES):+ if not topic.startswith(_HTTP_RESERVED_PREFIXES) or (+ topic.startswith(_HTTP_REQUEST_ONLY_PREFIXES)+ and _iot_module._RESERVED_REQUEST_TOPIC_RE.fullmatch(topic) is None+ ):return error_response_json("InvalidRequestException", "Topic can't start with $", 400)diff --git a/tests/test_iot.py b/tests/test_iot.pyindex aadb3d9e..126ef75e 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -2713,8 +2713,10 @@ async def _fleet_client(send, sent = _mock_send()session = _IoTWSSession(send, account, region, certificate_id)await session.handle_packet(PKT_CONNECT, 0, _build_connect_body(client_id))- filters = [f"{_FLEET_CREATE}/+"] + [- f"$aws/provisioning-templates/{t}/provision/json/+" for t in templates+ filters = [+ f"{topic}/{reply}"+ for topic in [_FLEET_CREATE, *map(_fleet_provision_topic, templates)]+ for reply in ("accepted", "rejected")]await session.handle_packet(PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [(f, 1) for f in filters])diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 6e551714..cea2521d 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -352,13 +352,19 @@ _MQTT_ONLY = "Invalid publish to restricted topic using HTTP"("$aws/things/t1/jobs/get", _MQTT_ONLY),("$aws/things/t1/defender/metrics/json", _MQTT_ONLY),("$aws/commands/things/t1/executions/1/response/json", _MQTT_ONLY),+ ("$aws/certificates/create/json/accepted", _NO_DOLLAR),+ ("$aws/provisioning-templates/t1/provision/json/rejected", _NO_DOLLAR),+ ("$aws/device_location/t1/get_position_estimate/accepted", _NO_DOLLAR),("$aws/rules/no_such_rule/x", None),("$aws/things/t1/jobs", None),+ ("$aws/certificates/create/json", None),+ ("$aws/device_location/t1/get_position_estimate", None),],)def test_iot_data_publish_reserved_topics(iot_data_client, topic, message):- """HTTPS Publish to a "$" topic is refused outside the reserved families- and for the MQTT-only jobs, Device Defender and commands topics."""+ """HTTPS Publish to a "$" topic is refused outside the reserved families,+ for the fleet provisioning and Device Location replies, and for the+ MQTT-only jobs, Device Defender and commands topics."""if message is None:resp = iot_data_client.publish(topic=topic, payload=b"{}")assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200@@ -3319,14 +3325,21 @@ def test_mqtt5_qos1_puback_carries_reason_code():@pytest.mark.parametrize("topic,acknowledged", [("$aws/rules/no-such-rule/x", True),("$aws/things/some-thing/shadow/update", True),+ ("$aws/things/some-thing/shadow/update/accepted", True),+ ("$aws/certificates/create/json", True),("$aws/events/certificates/registered/abc", False),("$aws/jobs/abc", False),("$foo/abc", False),-], ids=["rules", "shadow", "events", "jobs", "other-dollar"])+ ("$aws/things/some-thing/jobs/notify", False),+ ("$aws/certificates/create/json/accepted", False),+ ("$aws/provisioning-templates/some-template/provision/json/rejected", False),+], ids=["rules", "shadow", "shadow-reply", "fleet-request", "events", "jobs", "other-dollar", "jobs-reply",+ "fleet-reply", "template-reply"])def test_mqtt_publish_to_reserved_topic_closes_the_connection(topic, acknowledged):- """AWS acknowledges a publish under $aws/rules/ and $aws/things/ and closes- the connection of a client that publishes to any other $ topic (measured- over MQTT 3.1.1); the HTTPS Publish applies the same list."""+ """AWS acknowledges a publish under $aws/rules/ and $aws/things/ and to the+ fleet provisioning requests, and closes the connection of a client that+ publishes to a reply AWS IoT writes itself or to any other $ topic+ (MQTT 3.1.1)."""async def scenario():async with _connect(MQTT_311) as (pub, _c):@@ -3343,6 +3356,82 @@ def test_mqtt_publish_to_reserved_topic_closes_the_connection(topic, acknowledgeassert detail == b"\x00\x05"+def test_mqtt5_publish_to_a_reserved_reply_topic_answers_topic_name_invalid():+ """MQTT 5: PUBACK 0x90 for a QoS 1 publish to a reply AWS IoT writes, the connection stays; DISCONNECT for QoS 0."""++ async def scenario():+ async with _connect(MQTT_5) as (client, _c):+ await client.send(_make_publish("$aws/things/some-thing/jobs/notify", b"{}", qos=1, packet_id=1,+ protocol_level=MQTT_5))+ _flags, refused = await client.await_packet(PKT_PUBACK)+ await client.send(_make_publish(_unique("v5/plain"), b"{}", qos=1, packet_id=2, protocol_level=MQTT_5))+ _flags, accepted = await client.await_packet(PKT_PUBACK)+ await client.send(_make_publish("$aws/certificates/create/json/accepted", b"{}", protocol_level=MQTT_5))+ pkt_type, _flags, disconnect = await client.packet()+ return refused, accepted, pkt_type, disconnect++ refused, accepted, pkt_type, disconnect = _run(scenario())+ assert refused == b"\x00\x01\x90\x00", "packet id 1, Topic Name invalid, no properties"+ assert accepted == b"\x00\x02\x00\x00"+ assert (pkt_type, disconnect[0]) == (PKT_DISCONNECT, 0x90)+++# MQTT 5 SUBACK reason code per filter: 0x01 granted, 0x8F Topic Filter invalid.+_RESERVED_FILTERS = {+ "$aws/things/some-thing/shadow/update/+": 0x01,+ "$aws/things/+/jobs/#": 0x01,+ "$aws/events/#": 0x01,+ "$aws/certificates/create/+/accepted": 0x01,+ "$aws/provisioning-templates/+/provision/json/rejected": 0x01,+ "$aws/device_location/some-thing/get_position_estimate/accepted": 0x01,+ "$aws/commands/things/some-thing/executions/+/request/json": 0x01,+ "$aws/certificates/create/json": 0x8F,+ "$aws/certificates/create/json/+": 0x8F,+ "$aws/certificates/#": 0x8F,+ "$aws/provisioning-templates/some-template/provision/json/+": 0x8F,+ "$aws/rules/some_rule": 0x8F,+ "$aws/device_location/some-thing/get_position_estimate": 0x8F,+ "$aws/commands/things/some-thing/executions/e1/response/json": 0x8F,+ "$aws/things": 0x8F,+ "$aws/#": 0x8F,+ "$foo/abc": 0x8F,+}+++def test_mqtt5_subscribe_to_a_reserved_filter_answers_topic_filter_invalid():+ """MQTT 5 refuses a reserved filter a client may not subscribe to with SUBACK 0x8F, and the connection stays."""++ async def scenario():+ async with _connect(MQTT_5) as (client, _c):+ codes = {}+ for packet_id, topic_filter in enumerate(_RESERVED_FILTERS, start=1):+ await client.send(_make_subscribe(packet_id, topic_filter, qos=1, protocol_level=MQTT_5))+ _flags, suback = await client.await_packet(PKT_SUBACK)+ codes[topic_filter] = suback[3]+ return codes++ assert _run(scenario()) == _RESERVED_FILTERS++[email protected]("topic_filter,closed", [+ ("$aws/certificates/create/json/accepted", False),+ ("$aws/certificates/create/json/+", True),+], ids=["reply", "request-wildcard"])+def test_mqtt_subscribe_to_a_reserved_filter_closes_the_connection(topic_filter, closed):+ """MQTT 3.1.1: a SUBSCRIBE to a reserved filter a client may not use closes the connection without a SUBACK."""++ async def scenario():+ async with _connect(MQTT_311) as (client, _c):+ await client.send(_make_subscribe(1, topic_filter, qos=1))+ try:+ await client.await_packet(PKT_SUBACK, timeout=3)+ return False+ except (websockets.exceptions.ConnectionClosed, OSError):+ return True++ assert _run(scenario()) is closed++def test_mqtt311_qos1_puback_stays_two_bytes():"""The 3.1.1 PUBACK gains neither a reason code nor properties."""topic = _unique("v311/qos1")@@ -4695,8 +4784,8 @@ def test_mtls_provisioning_claim_connects_and_provisions(broker, tmp_path):peer = _Peer(_mtls_connect(broker, claim["certificatePem"], claim["keyPair"]["PrivateKey"], tmp_path))try:_assert_connack(peer.connect(_unique("claim")))- peer.subscribe(f"{create}/+", packet_id=1)- peer.subscribe(f"{provision}/+", packet_id=2)+ peer.subscribe(f"{create}/accepted", packet_id=1)+ peer.subscribe(f"{provision}/accepted", packet_id=2)peer.send(_make_publish(create, b"", qos=1, packet_id=3))topic, payload = peer.next_publish()assert topic == f"{create}/accepted"@@ -4849,8 +4938,8 @@ def test_mtls_provisioning_hook_names_the_thing(broker, tmp_path):peer = _Peer(_mtls_connect(broker, claim["certificatePem"], claim["keyPair"]["PrivateKey"], tmp_path))try:_assert_connack(peer.connect(_unique("claim")))- peer.subscribe(f"{create}/+", packet_id=1)- peer.subscribe(f"{provision}/+", packet_id=2)+ peer.subscribe(f"{create}/accepted", packet_id=1)+ peer.subscribe(f"{provision}/accepted", packet_id=2)peer.send(_make_publish(create, b"", qos=1, packet_id=3))topic, payload = peer.next_publish()assert topic == f"{create}/accepted"@@ -4927,8 +5016,8 @@ def test_mtls_provisioning_applies_the_default_template_version(broker, tmp_pathtry:_assert_connack(peer.connect(_unique("claim")))- peer.subscribe(f"{create}/+", packet_id=1)- peer.subscribe(f"{provision}/+", packet_id=2)+ peer.subscribe(f"{create}/accepted", packet_id=1)+ peer.subscribe(f"{provision}/accepted", packet_id=2)iot.create_provisioning_template_version(templateName=name, templateBody=body("v2"))register("a", "v1")iot.update_provisioning_template(templateName=name, defaultVersionId=2)