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): resend unacknowledged QoS 1 messages as AWS IoT does (#2403)
iot-rocketab0e7099532a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 48fbf30f..dd21a6ae 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Auth — SigV4a signatures are verified under `AUTH=true`** — requests signed with `AWS4-ECDSA-P256-SHA256`, which SDKs use for Multi-Region Access Points, were refused for every IAM user. Header and presigned S3 signatures are now checked with the P-256 key SigV4a derives from the secret, with their date or expiry, and an `X-Amz-Region-Set` that leaves out the serving region is refused (`RegionSetMismatch` on S3, the unknown-key error elsewhere). Contributed by @iot-rocket.### Fixed+- **IoT — QoS 1 redelivery follows AWS IoT** — the broker resent an unacknowledged QoS 1 message every 10 seconds with the DUP flag set; it now resends it 30 seconds after the last delivery (`IOT_RETRANSMIT_SECONDS` keeps changing that), and with DUP 0, as AWS IoT Core does, on the open connection and after a persistent session resumes. Contributed by @iot-rocket.- **Auth — requests without credentials are anonymous in every service** — under `AUTH=true` a request with no `Authorization` header and no query signature ran as the account root everywhere but S3, so unsigned STS, SQS, DynamoDB or Lambda calls were served. It is now refused in the service's own error, as on AWS: `MissingAuthenticationToken` 403 from Query and REST-XML services, `MissingAuthenticationTokenException` from JSON services, `AccessDenied` 403 from SQS, `UnrecognizedClientException` from Secrets Manager. Query credentials without `X-Amz-Algorithm` count as none. Operations the SDKs send unsigned (Cognito sign-in, `GetId`, `AssumeRoleWithWebIdentity`), SNS `ConfirmSubscription` and `Unsubscribe`, API Gateway and Function URL invokes and S3 keep their behaviour. Contributed by @iot-rocket.- **AppSync Events — `AUTH=true` checks the Event API's authorization** — under `AUTH=true` an HTTP publish, a WebSocket connection or a subscription was accepted with any API key or none unless `APPSYNC_EVENTS_ENFORCE_AUTH` was set. It now needs what the API or the channel namespace accepts, as on AWS: a key registered on the API for `API_KEY`, a SigV4 signature for `AWS_IAM`, a bearer token for Cognito and OIDC. A refused publish answers 401 `UnauthorizedException`, with AWS's "You are not authorized to make this call." for a key the API does not know. `APPSYNC_EVENTS_ENFORCE_AUTH` works as before with `AUTH` unset. Contributed by @iot-rocket.- **Cognito — pre token generation for `client_credentials`** — a `client_credentials` grant invoked a `V2_0` pre token generation trigger; it now invokes the trigger only when `LambdaVersion` is `V3_0`, as AWS documents and does. Contributed by @iot-rocket.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 5c5a1131..a76fb8eb 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -8909,7 +8909,7 @@ class _InFlightMessage:self.retransmit_count = 0-_RETRANSMIT_INTERVAL_SECONDS = int(os.environ.get("IOT_RETRANSMIT_SECONDS", "10"))+_RETRANSMIT_INTERVAL_SECONDS = int(os.environ.get("IOT_RETRANSMIT_SECONDS", "30"))# MQTT 5 Retain Handling (§3.8.3.1), the one subscription option that is spent@@ -11031,9 +11031,10 @@ class _WSSession:if now - msg.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:msg.retransmit_count += 1msg.sent_at = now+ # AWS IoT does not support the DUP flag: a resend goes out with DUP 0.await self.send_bytes(_make_publish(- msg.topic, msg.payload, qos=1, packet_id=pid, dup=True,+ msg.topic, msg.payload, qos=1, packet_id=pid,retain=msg.retain,properties=self._publish_properties(msg.properties),)diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 5d3ec5ce..a4283109 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -4874,7 +4874,6 @@ import asyncioimport structfrom ministack.services.iot import (- _RETRANSMIT_INTERVAL_SECONDS,PKT_CONNACK,PKT_CONNECT,PKT_DISCONNECT,@@ -6129,7 +6128,7 @@ def test_unacknowledged_qos1_message_is_resent_when_the_session_resumes(monkeypaawait session2.handle_packet(PKT_CONNECT, 0, connect)assert _parse_connack(sent2) == (True, 0)assert _extract_publish_frames(sent2) == [- ("data/unacked", b"m1", 1, 1, True),+ ("data/unacked", b"m1", 1, 1, False),("data/unacked", b"m2", 1, 2, False),]for pid in (1, 2):@@ -6175,7 +6174,7 @@ def test_unacknowledged_qos1_message_waits_for_its_retransmit_interval_after_a_rassert _extract_publish_frames(sent2) == []await asyncio.sleep(0.5)# The payload follows an empty property block.- assert _extract_publish_frames(sent2) == [("data/unacked5", b"\x00m1", 1, 1, True)]+ assert _extract_publish_frames(sent2) == [("data/unacked5", b"\x00m1", 1, 1, False)]await session2.handle_packet(PKT_DISCONNECT, 0, b"")await session2.cleanup()assert list(_persistent_sessions[key].in_flight) == [1]@@ -7154,8 +7153,8 @@ def test_cleanup_clears_in_flight():reset()-def test_retransmit_sends_dup_flag():- """Retransmission sends PUBLISH with DUP flag set."""+def test_retransmit_resends_after_30_seconds_with_dup_clear():+ """An unacknowledged QoS 1 message goes out again after 30 s with the same packet id and DUP 0."""reset()async def _run():@@ -7176,35 +7175,18 @@ def test_retransmit_sends_dup_flag():assert len(publishes) == 1assert publishes[0][4] is False # dup flag- # Manually trigger retransmission by manipulating sent_atpid = list(session._in_flight.keys())[0]msg = session._in_flight[pid]- # Set sent_at far in the past to trigger retransmit- msg.sent_at = 0-+ now = asyncio.get_event_loop().time()sent.clear()+ msg.sent_at = now - 29+ await session._retransmit_due()+ assert _extract_publish_frames(sent) == []- # Run one iteration of retransmit logic manually- import asyncio as _asyncio- now = _asyncio.get_event_loop().time()- for p, m in list(session._in_flight.items()):- if now - m.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:- m.retransmit_count += 1- m.sent_at = now- from ministack.services.iot import _make_publish- await session.send_bytes(- _make_publish(m.topic, m.payload, qos=1, packet_id=p, dup=True)- )-- # Verify retransmitted publish has DUP=True- publishes = _extract_publish_frames(sent)- assert len(publishes) == 1- topic, payload, qos, packet_id, dup = publishes[0]- assert topic == "test/dup"- assert payload == b"dup-payload"- assert qos == 1- assert packet_id == pid- assert dup is True+ msg.sent_at = now - 30+ await session._retransmit_due()+ assert _extract_publish_frames(sent) == [("test/dup", b"dup-payload", 1, pid, False)]+ assert msg.retransmit_count == 1await session.cleanup()