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-data): keep MQTT 5 properties and a literal % in HTTP Publish (#2186)
iot-rocketc93030d0e388
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4246ef17..397ed3e9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IoT — HTTP `Publish` keeps the MQTT 5 properties and a literal `%` in the topic** — `Publish` ignored `userProperties`, `payloadFormatIndicator`, `contentType`, `responseTopic`, `correlationData` and `messageExpiry`, so MQTT 5 subscribers got none of them and `GetRetainedMessage` returned no `userProperties`; they now reach subscribers and the retained message, and invalid values are refused with AWS's `InvalidRequestException` messages. `Publish`, `GetRetainedMessage` and the `AUTH=true` topic ARN decoded the topic a second time, so `p%41q` became `pAq`; the topic is now kept as sent. `/_ministack/reset` kept messages retained over MQTT when no iot-data call had loaded that module; it now clears them. Contributed by @iot-rocket.- **CloudFormation — AppSync data sources and resolvers keep their configuration** — `AWS::AppSync::DataSource` dropped `Description`, `HttpConfig` and `EventBridgeConfig` and stored `DynamoDBConfig` and `LambdaConfig` in the template's PascalCase, and `AWS::AppSync::Resolver` dropped `Kind`, `Runtime`, `Code`, `PipelineConfig` and `MaxBatchSize`, so a DynamoDB resolver from a stack answered `null` and an `APPSYNC_JS` resolver never ran; both now go through `CreateDataSource` and `CreateResolver` and read back as on AWS, and a new data source `Name` or resolver `TypeName` or `FieldName` is reported as a replacement. `GetDataSource` and `GetResolver` leave out a description, service role or mapping template that was never set, a DynamoDB data source reports `useCallerCredentials` and `versioned`, an EventBridge one keeps `eventBridgeConfig`, and a resolver reports `maxBatchSize`. Contributed by @iot-rocket.- **CloudFormation — `AWS::AutoScaling::LifecycleHook` updates** — a stack update ran the create again, so a member dropped from the template went back to its default and a hook with a generated name moved to another group stayed on the old group too; the hook now updates in place and keeps a dropped member, and an `AutoScalingGroupName` or `LifecycleHookName` change replaces it. `NotificationMetadata` is stored and returned by `DescribeLifecycleHooks`, and a group deleted by its stack takes its lifecycle hooks along. Contributed by @iot-rocket.- **IoT — mTLS refusals close without a CONNACK under `AUTH=true`** — with `AUTH=true` the mTLS listener closes the connection of an unknown, inactive, revoked or doubly-registered client certificate after its CONNECT without sending a CONNACK, as AWS does on MQTT 3.1.1 and 5; without `AUTH` it still answers a "not authorized" CONNACK, and the log names the reason either way. Contributed by @iot-rocket.diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 77c5a57b..acbe4c5c 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1537,11 +1537,10 @@ def extract_resource_arn(service: str, method: str, path: str,parts = [p for p in path.split("/") if p]# Publish and the retained-message calls take everything after the# prefix as the topic, and a topic is multi-level: the ARN is- # topic/sensors/a/temperature, not topic/sensors. The separators arrive- # percent-encoded from the SDK, which is why iot_data._publish unquotes- # as well.+ # topic/sensors/a/temperature, not topic/sensors. The path is already+ # decoded, so a %41 left in it is part of the topic name.if len(parts) > 1 and parts[0] in ("topics", "retainedMessage"):- topic = unquote("/".join(parts[1:]))+ topic = "/".join(parts[1:])return f"arn:aws:iot:{region}:{account_id}:topic/{topic}"_IOT_RESOURCES = {"things": "thing",diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 7ec917d1..1a4a64c9 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -395,6 +395,8 @@ def reset() -> None:_job_executions.clear()_job_templates.clear()_tags.clear()+ # Retained messages are part of the state get_state() saves.+ _retained.clear()with _CA_LOCK:_ca_cert_pem = None_ca_key_pem = Nonediff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.pyindex 9185cdb1..f5fc8a04 100644--- a/ministack/services/iot_data.py+++ b/ministack/services/iot_data.py@@ -51,6 +51,11 @@ _HTTP_RESTRICTED_TOPIC_RE = re.compile(r"^\$aws/(things/[^/]+/(jobs|defender)/|commands/)")+# Publish's x-amz-mqtt5-payload-format-indicator values and the byte each one stands for.+_PAYLOAD_FORMAT_INDICATORS = {"UNSPECIFIED_BYTES": 0, "UTF8_DATA": 1}+# The broker's message expiry limit (seven days); longer intervals are capped.+_MAX_MESSAGE_EXPIRY = 604800+def _validate_topic(topic: str) -> tuple | None:"""Return an error response if ``topic`` is invalid, else None."""@@ -122,7 +127,7 @@ async def handle_request(if method == "POST" and path.startswith("/topics/"):access_key = extract_access_key_id(headers, query_params)- return await _publish(path[len("/topics/"):], body, qp, access_key)+ return await _publish(path[len("/topics/"):], body, qp, headers, access_key)# Device Shadow: /things/{thingName}/shadow[?name={shadowName}]if path.startswith("/things/") and path.endswith("/shadow"):@@ -201,13 +206,8 @@ async def _shadow(method: str, path: str, body: bytes, qp: dict) -> tuple:return json_response(doc)-async def _publish(raw_topic: str, body: bytes, qp: dict, access_key: str) -> tuple:- """``POST /topics/{topic}`` — forward body to the broker.-- ``raw_topic`` is what came after ``/topics/`` in the URL. The SDK URL-- encodes ``/`` separators so we decode here and validate before relaying.- """- topic = unquote(raw_topic or "")+async def _publish(topic: str, body: bytes, qp: dict, headers: dict, access_key: str) -> tuple:+ """``POST /topics/{topic}``: forward the body to the broker; the path arrives decoded, so ``%41`` stays literal."""err = _validate_topic(topic)if err is not None:return err@@ -223,6 +223,9 @@ async def _publish(raw_topic: str, body: bytes, qp: dict, access_key: str) -> tu"InvalidRequestException", "qos must be 0 or 1", 400)retain = str(qp.get("retain", "")).lower() in ("1", "true", "yes")+ properties, err = _publish_properties(headers, qp)+ if err is not None:+ return errif not _iot_module.broker_is_available():return error_response_json(@@ -239,6 +242,7 @@ async def _publish(raw_topic: str, body: bytes, qp: dict, access_key: str) -> tubody or b"",qos=qos,retain=retain,+ properties=properties,principal=_iot_module._caller_principal(access_key),)except Exception as e:@@ -250,6 +254,68 @@ async def _publish(raw_topic: str, body: bytes, qp: dict, access_key: str) -> tureturn 200, {"Content-Type": "application/json"}, b""+def _b64decode(value: str) -> bytes | None:+ """Base64 with or without its padding, or None when the value is not base64."""+ try:+ return base64.b64decode(value + "=" * (-len(value) % 4), validate=True)+ except ValueError:+ return None+++def _publish_properties(headers: dict, qp: dict) -> tuple[bytes, tuple | None]:+ """The MQTT 5 property block a Publish request asks for, or the error response refusing it."""++ def invalid(message: str) -> tuple[bytes, tuple]:+ return b"", error_response_json("InvalidRequestException", message, 400)++ props: list[tuple[int, object]] = []+ indicator = headers.get("x-amz-mqtt5-payload-format-indicator")+ if indicator:+ if indicator not in _PAYLOAD_FORMAT_INDICATORS:+ return invalid("Invalid Payload Format Indicator")+ props.append((_iot_module.PROP_PAYLOAD_FORMAT_INDICATOR, _PAYLOAD_FORMAT_INDICATORS[indicator]))+ expiry = qp.get("messageExpiry")+ if expiry is not None:+ seconds = int(expiry) if expiry.isascii() and expiry.isdigit() else -1+ if not 0 <= seconds < 2**32:+ return invalid("Message expiry interval must be an unsigned 4-byte integer")+ props.append((_iot_module.PROP_MESSAGE_EXPIRY_INTERVAL, min(seconds, _MAX_MESSAGE_EXPIRY)))+ response_topic = qp.get("responseTopic")+ if response_topic:+ if "+" in response_topic or "#" in response_topic:+ return invalid(+ "This response topic isn't valid. Response topics must not contain"+ " MQTT wildcard characters (+ or #)"+ )+ props.append((_iot_module.PROP_RESPONSE_TOPIC, response_topic))+ correlation = headers.get("x-amz-mqtt5-correlation-data")+ if correlation:+ data = _b64decode(correlation)+ if data is None:+ return invalid("Invalid Base64 string")+ props.append((_iot_module.PROP_CORRELATION_DATA, data))+ if qp.get("contentType"):+ props.append((_iot_module.PROP_CONTENT_TYPE, qp["contentType"]))+ encoded = headers.get("x-amz-mqtt5-user-properties")+ if encoded:+ raw = _b64decode(encoded)+ if raw is None:+ return invalid("Invalid Base64 string")+ try:+ pairs = json.loads(raw)+ except ValueError:+ pairs = None+ if not isinstance(pairs, list) or not all(+ isinstance(pair, dict) and all(isinstance(v, str) for v in pair.values())+ for pair in pairs+ ):+ return invalid("Invalid JSON string for User Properties")+ if any(len(pair) > 1 for pair in pairs):+ return invalid("Only one User Property is allowed in single JSONObject")+ props += [(_iot_module.PROP_USER_PROPERTY, item) for pair in pairs for item in pair.items()]+ return (_iot_module._encode_properties(props) if props else b""), None++def _user_properties(properties: bytes) -> bytes:"""MQTT 5 user properties as the JSON array AWS returns, or b"" without any."""if not properties:@@ -265,9 +331,8 @@ def _user_properties(properties: bytes) -> bytes:return json.dumps(pairs, ensure_ascii=False, separators=(",", ":")).encode("utf-8")-def _get_retained_message(raw_topic: str) -> tuple:+def _get_retained_message(topic: str) -> tuple:"""``GET /retainedMessage/{topic}``: the retained message stored for the topic."""- topic = unquote(raw_topic)if not topic:return error_response_json("InvalidRequestException", "unknown", 400)if "+" in topic or "#" in topic:diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex a6817e85..e2fe38a2 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -2436,22 +2436,23 @@ class TestResourceArn:service, "POST", path, headers, b"", {}, "eu-central-1", "123") == "arn:aws:iot:eu-central-1:123:topic/sensors/rack-1/temperature"- def test_publish_resolves_the_same_topic_however_the_sdk_sent_it(self):- """Publish's URI label is non-greedy, so botocore percent-encodes the- separators and the ASGI server hands them back decoded. Both spellings- have to name one resource, or the grant matches on one path only."""+ def test_publish_topic_arn_keeps_a_literal_percent_sequence(self):+ """A %41 or %2F left in the decoded Publish path is part of the topic name and stays in the ARN."""from ministack.core.iam_actions import extract_iam_action, extract_resource_arnfrom ministack.core.router import detect_serviceheaders = _sigv4_headers("iotdata", "data-ats.iot.eu-central-1.amazonaws.com")- expected = "arn:aws:iot:eu-central-1:123:topic/sensors/rack-1/temperature"- for path in ("/topics/sensors/rack-1/temperature",- "/topics/sensors%2Frack-1%2Ftemperature"):- service = detect_service("POST", path, headers, {})- assert extract_iam_action(service, "POST", path, headers, b"", {}) == "iot:Publish"+ for method, path, action, topic in (+ ("POST", "/topics/sensors/p%41q", "iot:Publish", "sensors/p%41q"),+ ("POST", "/topics/sensors/p%2Fq", "iot:Publish", "sensors/p%2Fq"),+ ("GET", "/retainedMessage/sensors/p%25q", "iot:GetRetainedMessage", "sensors/p%25q"),+ ):+ service = detect_service(method, path, headers, {})+ assert service == "iot-data"+ assert extract_iam_action(service, method, path, headers, b"", {}) == actionassert extract_resource_arn(- service, "POST", path, headers, b"", {}, "eu-central-1", "123"- ) == expected+ service, method, path, headers, b"", {}, "eu-central-1", "123"+ ) == f"arn:aws:iot:eu-central-1:123:topic/{topic}"def test_create_job_resolves_through_the_router(self):from ministack.core.iam_actions import extract_iam_action, extract_resource_arndiff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 99605de0..e24b8665 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -86,6 +86,35 @@ def test_get_retained_message_returns_the_retained_publish():assert "userProperties" not in resp+def test_get_retained_message_returns_http_publish_user_properties():+ """The user properties of a retained HTTP Publish come back as AWS's compact JSON array."""+ client = _own_account_iot_data()+ client.publish(+ topic="sensors/props", retain=True, payload=b"{}",+ userProperties=[{"app": "demo"}, {"k": "v1"}, {"k": "v2"}, {"u": "ü"}],+ contentType="application/json",+ )+ resp = client.get_retained_message(topic="sensors/props")+ assert resp["userProperties"] == '[{"app":"demo"},{"k":"v1"},{"k":"v2"},{"u":"ü"}]'.encode()+++def test_retained_topic_keeps_a_literal_percent_sequence():+ """A topic holding %41, %25 or %2F is stored and read back as written, not decoded a second time."""+ client = _own_account_iot_data()+ topics = ("pct/p%41q", "pct/p%25q", "pct/p%2Fq")+ for topic in topics:+ client.publish(topic=topic, retain=True, payload=topic.encode())+ for topic in topics:+ resp = client.get_retained_message(topic=topic)+ assert (resp["topic"], resp["payload"]) == (topic, topic.encode())+ for decoded in ("pct/pAq", "pct/p%q", "pct/p/q"):+ with pytest.raises(ClientError) as ei:+ client.get_retained_message(topic=decoded)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ listed = {e["topic"] for e in client.list_retained_messages()["retainedTopics"]}+ assert listed == set(topics)++def test_get_retained_message_errors():client = _own_account_iot_data(parameter_validation=False)with pytest.raises(ClientError) as ei:@@ -240,6 +269,20 @@ def test_retained_user_properties_and_time_survive_persistence():iot_module.broker_reset()+def test_iot_reset_clears_retained_messages():+ """The iot module saves retained messages, so its reset drops them even when iot_data was never loaded."""+ import asyncio++ from ministack.services import iot as iot_module++ account = "123456789012"+ asyncio.run(iot_module.broker_publish(account, "eu-west-1", "dev/kept", b"x", retain=True))+ assert iot_module.broker_get_retained(account, "eu-west-1", "dev/kept") is not None+ iot_module.reset()+ assert iot_module.broker_get_retained(account, "eu-west-1", "dev/kept") is None+ assert iot_module.get_state()["mqtt_broker"]["retained"] == []++def test_iot_data_publish_rejects_wildcard_topic():"""Wildcard characters in publish topics must produce a 400."""import urllib.request@@ -325,6 +368,45 @@ def test_iot_data_publish_reserved_topics(iot_data_client, topic, message):assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+_BAD_EXPIRY = "Message expiry interval must be an unsigned 4-byte integer"+_BAD_RESPONSE_TOPIC = (+ "This response topic isn't valid. Response topics must not contain MQTT wildcard characters (+ or #)"+)+_BAD_USER_PROPERTIES = "Invalid JSON string for User Properties"+++ ("kwargs", "user_properties_header", "message"),+ [+ ({"payloadFormatIndicator": "BOGUS"}, None, "Invalid Payload Format Indicator"),+ ({"messageExpiry": -1}, None, _BAD_EXPIRY),+ ({"messageExpiry": 2**32}, None, _BAD_EXPIRY),+ ({"responseTopic": "reply/+/x"}, None, _BAD_RESPONSE_TOPIC),+ ({"responseTopic": "reply/#"}, None, _BAD_RESPONSE_TOPIC),+ ({"correlationData": "not base64!"}, None, "Invalid Base64 string"),+ ({"userProperties": [{"a": "1", "b": "2"}]}, None,+ "Only one User Property is allowed in single JSONObject"),+ ({"userProperties": [{"a": 1}]}, None, _BAD_USER_PROPERTIES),+ ({"userProperties": {"a": "1"}}, None, _BAD_USER_PROPERTIES),+ ({}, base64.b64encode(b'["a"]').decode(), _BAD_USER_PROPERTIES),+ ({}, base64.b64encode(b"not json").decode(), _BAD_USER_PROPERTIES),+ ({}, '[{"a":"1"}]', "Invalid Base64 string"),+ ],+)+def test_iot_data_publish_refuses_invalid_mqtt5_properties(kwargs, user_properties_header, message):+ """The MQTT 5 headers and query parameters of Publish are refused with AWS's messages."""+ client = _own_account_iot_data(parameter_validation=False)+ if user_properties_header is not None:+ def _header(request, **_kw):+ request.headers["x-amz-mqtt5-user-properties"] = user_properties_header+ client.meta.events.register("before-sign.iot-data.Publish", _header)+ with pytest.raises(ClientError) as ei:+ client.publish(topic="props/refused", payload=b"x", **kwargs)+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+ assert ei.value.response["Error"]["Message"] == message+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400++# ---------------------------------------------------------------------------# MQTT-over-WebSocket round-trip# ---------------------------------------------------------------------------@@ -2784,6 +2866,62 @@ def test_mqtt5_publish_round_trip_forwards_properties():assert _prop(props, PROP_USER_PROPERTY) == ("tenant", "acme")+def test_http_publish_forwards_mqtt5_properties(iot_data_client):+ """HTTP Publish hands its MQTT 5 headers and query parameters to a 5.0 subscriber as properties."""+ topic = _unique("v5/http")+ publishes = [+ {+ "userProperties": [{"app": "demo"}, {"k": "v1"}, {"k": "v2"}, {"u": "ü"}],+ "payloadFormatIndicator": "UTF8_DATA",+ "contentType": "application/json",+ "responseTopic": f"{topic}/reply",+ "correlationData": base64.b64encode(b"\x00\x01req-7").decode(),+ "messageExpiry": 60,+ },+ # Unpadded base64, an empty object, empty strings and an interval above+ # the broker's seven-day limit.+ {+ "payloadFormatIndicator": "UNSPECIFIED_BYTES",+ "correlationData": "cmVxLTc",+ "userProperties": [{}],+ "contentType": "",+ "responseTopic": "",+ "messageExpiry": 604801,+ },+ {},+ ]++ async def scenario():+ async with _connect(MQTT_5) as (sub, _c1):+ await sub.send(_make_subscribe(1, topic, protocol_level=MQTT_5, options=0x00))+ await sub.await_packet(PKT_SUBACK)+ delivered = []+ for kwargs in publishes:+ await asyncio.to_thread(iot_data_client.publish, topic=topic, payload=b"{}", **kwargs)+ _flags, body = await sub.await_packet(PKT_PUBLISH)+ delivered.append(_parse_publish(body, MQTT_5)[2])+ return delivered++ full, edges, none = _run(scenario())+ assert full == [+ (PROP_PAYLOAD_FORMAT_INDICATOR, 1),+ (0x02, 60),+ (PROP_RESPONSE_TOPIC, f"{topic}/reply"),+ (PROP_CORRELATION_DATA, b"\x00\x01req-7"),+ (PROP_CONTENT_TYPE, "application/json"),+ (PROP_USER_PROPERTY, ("app", "demo")),+ (PROP_USER_PROPERTY, ("k", "v1")),+ (PROP_USER_PROPERTY, ("k", "v2")),+ (PROP_USER_PROPERTY, ("u", "ü")),+ ]+ assert edges == [+ (PROP_PAYLOAD_FORMAT_INDICATOR, 0),+ (0x02, 604800),+ (PROP_CORRELATION_DATA, b"req-7"),+ ]+ assert none == []++def test_mqtt311_publisher_reaches_mqtt5_subscriber():"""Cross-version delivery: the 5.0 subscriber gets an empty property block."""topic = _unique("cross/311to5")