Repository navigation
Expand file tree
/
Copy pathtest_iot_data.py
More file actions
3848 lines (3173 loc) · 142 KB
/
Copy pathtest_iot_data.py
File metadata and controls
3848 lines (3173 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Integration tests for the IoT Core data plane (Phase 1b).
Covers the ``iot-data Publish`` HTTP API and the MQTT-over-WebSocket bridge
that powers the original use case from issue #564 (Lambda publishes via
HTTP → browser subscribes via WebSocket).
The bridge implements MQTT 3.1.1 framing internally (no external broker
binary). Multi-tenancy is enforced by transparent topic prefixing in the
bridge layer.
"""
from __future__ import annotations
import base64
import io as _io
import json
import os
import socket
import ssl
import struct
import subprocess
import sys
import threading
import time
import urllib.request
import uuid
import zipfile as _zipfile
from urllib.parse import quote, urlparse
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
from conftest import iot_test_ca, patch_endpoint_dns, sqs_policy_allow_sns
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
def _unique(prefix: str) -> str:
return f"{prefix}-{uuid.uuid4().hex[:8]}"
# ---------------------------------------------------------------------------
# HTTP Publish (boto3 ``iot-data`` client)
# ---------------------------------------------------------------------------
def test_iot_data_publish_returns_200(iot_data_client):
resp = iot_data_client.publish(topic=_unique("topic"), payload=b"hello")
md = resp["ResponseMetadata"]
assert md["HTTPStatusCode"] == 200
def test_iot_data_publish_accepts_qos_and_retain(iot_data_client):
topic = _unique("retained")
resp = iot_data_client.publish(
topic=topic, qos=1, retain=True, payload=b"sticky"
)
assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
def test_iot_data_publish_rejects_wildcard_topic():
"""Wildcard characters in publish topics must produce a 400."""
import urllib.request
req = urllib.request.Request(
f"{ENDPOINT}/topics/" + quote("foo/+/bar", safe=""),
data=b"x",
method="POST",
headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/0/0/iotdata/aws4_request"},
)
try:
urllib.request.urlopen(req, timeout=5)
pytest.fail("expected HTTP 400")
except urllib.error.HTTPError as e:
assert e.code == 400
def test_iot_data_publish_rejects_empty_topic():
import urllib.request
req = urllib.request.Request(
f"{ENDPOINT}/topics/",
data=b"x",
method="POST",
headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/0/0/iotdata/aws4_request"},
)
try:
urllib.request.urlopen(req, timeout=5)
pytest.fail("expected error")
except urllib.error.HTTPError as e:
# Either 400 (we caught it) or 404 (router didn't match) is acceptable —
# both signal "this isn't a valid Publish call".
assert e.code in (400, 404)
def test_iot_data_publish_oversized_topic_400():
import urllib.request
long_topic = "a" * 300
req = urllib.request.Request(
f"{ENDPOINT}/topics/" + quote(long_topic, safe=""),
data=b"x",
method="POST",
headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/0/0/iotdata/aws4_request"},
)
try:
urllib.request.urlopen(req, timeout=5)
pytest.fail("expected HTTP 400")
except urllib.error.HTTPError as e:
assert e.code == 400
_NO_DOLLAR = "Topic can't start with $"
_MQTT_ONLY = "Invalid publish to restricted topic using HTTP"
@pytest.mark.parametrize(
("topic", "message"),
[
("$aws/events/certificates/registered/x", _NO_DOLLAR),
("$AWS/events/certificates/registered/x", _NO_DOLLAR),
("$aws/jobs/x", _NO_DOLLAR),
("$aws/rules", _NO_DOLLAR),
("$foo/bar", _NO_DOLLAR),
("$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/rules/no_such_rule/x", None),
("$aws/things/t1/jobs", 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."""
if message is None:
resp = iot_data_client.publish(topic=topic, payload=b"{}")
assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
return
with pytest.raises(ClientError) as ei:
iot_data_client.publish(topic=topic, payload=b"{}")
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
# ---------------------------------------------------------------------------
#
# The reference test for the unblocking use case from issue #564:
# 1. WebSocket client subscribes to topic T
# 2. Lambda calls iot-data Publish on T over HTTP
# 3. WebSocket subscriber receives the message within 2 seconds.
pytest.importorskip("websockets")
import asyncio # noqa: E402
import websockets # noqa: E402
# Minimal MQTT 3.1.1 codec for the test client.
def _enc_remaining(n: int) -> bytes:
out = bytearray()
while True:
b = n & 0x7F
n >>= 7
if n > 0:
b |= 0x80
out.append(b)
if n == 0:
return bytes(out)
def _enc_str(s: str) -> bytes:
raw = s.encode("utf-8")
return struct.pack("!H", len(raw)) + raw
def _decode_remaining(buf: bytes, off: int) -> tuple[int, int]:
multiplier = 1
value = 0
pos = off
while True:
b = buf[pos]
pos += 1
value += (b & 0x7F) * multiplier
if b & 0x80 == 0:
return value, pos
multiplier *= 128
def _parse_packet(buf: bytes) -> tuple[int, int, bytes, int] | None:
"""Try to extract one packet. Returns (type, flags, body, total_consumed) or None."""
if len(buf) < 2:
return None
first = buf[0]
try:
remaining, header_end = _decode_remaining(buf, 1)
except IndexError:
return None
total = header_end + remaining
if len(buf) < total:
return None
return (first >> 4) & 0x0F, first & 0x0F, buf[header_end:total], total
def _record_publish(msg, received: list) -> int | None:
"""Append any PUBLISH frame in ``msg`` to ``received``; return its packet type."""
buf = msg if isinstance(msg, (bytes, bytearray)) else msg.encode("latin-1")
parsed = _parse_packet(bytes(buf))
if not parsed:
return None
ptype, _flags, body, _ = parsed
if ptype == 3: # PUBLISH
topic_len = struct.unpack_from("!H", body, 0)[0]
delivered_topic = body[2:2 + topic_len].decode("utf-8")
payload = body[2 + topic_len:]
received.append((delivered_topic, payload))
return ptype
# The handshake budget for a WS subscriber. Generous on purpose: a single
# timeout here kills the thread before it can set `ready`, and every caller
# then reports the same unhelpful "did not become ready" instead of why.
_WS_HANDSHAKE_TIMEOUT = 15.0
async def _ws_subscribe_and_collect(
ws_url: str, topic: str, ready_event: threading.Event, received: list, stop: threading.Event
):
async with websockets.connect(ws_url, subprotocols=["mqtt"]) as ws:
await ws.send(_make_connect("test-client"))
# Wait for CONNACK
await asyncio.wait_for(ws.recv(), timeout=_WS_HANDSHAKE_TIMEOUT)
# Subscribe
await ws.send(_make_subscribe(packet_id=1, topic=topic, qos=0))
# Retained PUBLISH frames may precede SUBACK in the in-process broker.
while True:
msg = await asyncio.wait_for(ws.recv(), timeout=_WS_HANDSHAKE_TIMEOUT)
if _record_publish(msg, received) == 9: # SUBACK
break
ready_event.set()
# Collect PUBLISH frames until stop or timeout.
end_at = time.time() + 5
while not stop.is_set() and time.time() < end_at:
try:
msg = await asyncio.wait_for(ws.recv(), timeout=0.5)
except asyncio.TimeoutError:
continue
_record_publish(msg, received)
async def _ws_unsubscribe_one_and_collect(
ws_url: str,
topics: list[str],
drop: str,
ready_event: threading.Event,
received: list,
stop: threading.Event,
):
"""Subscribe to every topic in ``topics``, then UNSUBSCRIBE from ``drop``."""
async with websockets.connect(ws_url, subprotocols=["mqtt"]) as ws:
await ws.send(_make_connect("unsub-client"))
await asyncio.wait_for(ws.recv(), timeout=_WS_HANDSHAKE_TIMEOUT)
for packet_id, topic in enumerate(topics, start=1):
await ws.send(_make_subscribe(packet_id=packet_id, topic=topic, qos=0))
while True:
msg = await asyncio.wait_for(ws.recv(), timeout=_WS_HANDSHAKE_TIMEOUT)
if _record_publish(msg, received) == 9: # SUBACK
break
await ws.send(_make_unsubscribe(packet_id=len(topics) + 1, topics=[drop]))
while True:
msg = await asyncio.wait_for(ws.recv(), timeout=_WS_HANDSHAKE_TIMEOUT)
if _record_publish(msg, received) == 11: # UNSUBACK
break
ready_event.set()
end_at = time.time() + 5
while not stop.is_set() and time.time() < end_at:
try:
msg = await asyncio.wait_for(ws.recv(), timeout=0.5)
except asyncio.TimeoutError:
continue
_record_publish(msg, received)
def test_iot_ws_unsubscribe_keeps_the_other_subscriptions(iot_data_client):
"""UNSUBSCRIBE over the real WebSocket bridge drops only the named filter."""
kept = _unique("unsub/kept")
dropped = _unique("unsub/dropped")
parsed = urlparse(ENDPOINT)
ws_host = parsed.hostname or "localhost"
ws_port = parsed.port or 4566
ws_url = f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
ready = threading.Event()
stop = threading.Event()
received: list = []
t = threading.Thread(
target=lambda: asyncio.run(_ws_unsubscribe_one_and_collect(
ws_url, [kept, dropped], dropped, ready, received, stop
)),
daemon=True,
)
t.start()
assert ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT), "WebSocket subscriber did not become ready"
iot_data_client.publish(topic=dropped, payload=b"should-not-arrive")
iot_data_client.publish(topic=kept, payload=b"should-arrive")
deadline = time.time() + 5
while time.time() < deadline and not received:
time.sleep(0.05)
# Give a message on the unsubscribed topic every chance to show up late.
time.sleep(0.6)
stop.set()
t.join(timeout=2)
assert received == [(kept, b"should-arrive")]
def test_iot_lambda_publishes_browser_subscribes_e2e(iot_data_client):
"""The unblocking use case from issue #564.
A WebSocket client subscribes; the iot-data HTTP Publish API delivers
a message that arrives over the subscribed WebSocket within 5 seconds.
"""
topic = _unique("e2e/sensor")
parsed = urlparse(ENDPOINT)
ws_host = parsed.hostname or "localhost"
ws_port = parsed.port or 4566
# Use the IoT data hostname so the ASGI dispatch routes us to the broker.
ws_url = f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
ready = threading.Event()
stop = threading.Event()
received: list = []
def _runner():
asyncio.run(_ws_subscribe_and_collect(ws_url, topic, ready, received, stop))
t = threading.Thread(target=_runner, daemon=True)
t.start()
assert ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT), "WebSocket subscriber did not become ready"
payload = b"telemetry-from-lambda"
iot_data_client.publish(topic=topic, payload=payload)
deadline = time.time() + 5
while time.time() < deadline and not received:
time.sleep(0.05)
stop.set()
t.join(timeout=2)
assert received, "Subscriber did not receive any PUBLISH frames within 5s"
delivered_topic, delivered_payload = received[0]
assert delivered_topic == topic
assert delivered_payload == payload
def test_iot_ws_publish_isolated_between_regions():
"""The same account and topic must remain isolated by IoT data region."""
import boto3
from botocore.config import Config
topic = _unique("regional/sensor")
parsed = urlparse(ENDPOINT)
ws_host = parsed.hostname or "localhost"
ws_port = parsed.port or 4566
def _ws_url(region):
credential = quote(
f"test/20260726/{region}/iotdevicegateway/aws4_request",
safe="",
)
return (
f"ws://prefix-ats.iot.{region}.{ws_host}:{ws_port}/mqtt"
f"?X-Amz-Credential={credential}"
)
east_ready = threading.Event()
west_ready = threading.Event()
stop = threading.Event()
east_received = []
west_received = []
east_thread = threading.Thread(
target=lambda: asyncio.run(_ws_subscribe_and_collect(
_ws_url("us-east-1"),
topic,
east_ready,
east_received,
stop,
)),
daemon=True,
)
west_thread = threading.Thread(
target=lambda: asyncio.run(_ws_subscribe_and_collect(
_ws_url("us-west-2"),
topic,
west_ready,
west_received,
stop,
)),
daemon=True,
)
east_thread.start()
west_thread.start()
assert east_ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT)
assert west_ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT)
east_client = boto3.client(
"iot-data",
endpoint_url=ENDPOINT,
aws_access_key_id="test",
aws_secret_access_key="test",
region_name="us-east-1",
config=Config(retries={"mode": "standard"}),
)
east_client.publish(topic=topic, payload=b"east-only")
deadline = time.time() + 5
while time.time() < deadline and not east_received:
time.sleep(0.05)
time.sleep(0.6)
stop.set()
east_thread.join(timeout=2)
west_thread.join(timeout=2)
assert east_received == [(topic, b"east-only")]
assert west_received == []
@pytest.mark.parametrize("wildcard_region", ["+", "#"])
def test_iot_ws_credential_region_wildcards_cannot_bypass_isolation(
wildcard_region,
):
"""Credential-region wildcards cannot receive live or retained messages."""
import boto3
from botocore.config import Config
topic = _unique("wildcard-region/sensor")
parsed = urlparse(ENDPOINT)
ws_host = parsed.hostname or "localhost"
ws_port = parsed.port or 4566
credential = quote(
(
"test/20260726/"
f"{wildcard_region}/iotdevicegateway/aws4_request"
),
safe="",
)
ws_url = (
f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
f"?X-Amz-Credential={credential}"
)
live_ready = threading.Event()
live_stop = threading.Event()
live_received = []
live_thread = threading.Thread(
target=lambda: asyncio.run(_ws_subscribe_and_collect(
ws_url,
topic,
live_ready,
live_received,
live_stop,
)),
daemon=True,
)
live_thread.start()
assert live_ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT)
east_client = boto3.client(
"iot-data",
endpoint_url=ENDPOINT,
aws_access_key_id="test",
aws_secret_access_key="test",
region_name="us-east-1",
config=Config(retries={"mode": "standard"}),
)
east_client.publish(topic=topic, payload=b"east", retain=True)
time.sleep(0.6)
live_stop.set()
live_thread.join(timeout=2)
assert live_received == []
retained_ready = threading.Event()
retained_stop = threading.Event()
retained_received = []
retained_thread = threading.Thread(
target=lambda: asyncio.run(_ws_subscribe_and_collect(
ws_url,
topic,
retained_ready,
retained_received,
retained_stop,
)),
daemon=True,
)
retained_thread.start()
assert retained_ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT)
time.sleep(0.6)
retained_stop.set()
retained_thread.join(timeout=2)
assert retained_received == []
def test_iot_ws_topic_isolation_between_accounts(iot_data_client):
"""A subscriber in account A must NOT see a publish from account B.
Multi-tenancy via transparent topic prefixing in the bridge.
"""
import boto3
from botocore.config import Config
topic = _unique("isolation/probe")
parsed = urlparse(ENDPOINT)
ws_host = parsed.hostname or "localhost"
ws_port = parsed.port or 4566
# Subscribe as account A — embed the access key in a SigV4-shaped query
# parameter the bridge knows how to read.
cred = quote("111111111111/20240101/us-east-1/iotdevicegateway/aws4_request")
ws_url = (
f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
f"?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={cred}"
)
ready = threading.Event()
stop = threading.Event()
received: list = []
def _runner():
asyncio.run(_ws_subscribe_and_collect(ws_url, topic, ready, received, stop))
t = threading.Thread(target=_runner, daemon=True)
t.start()
assert ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT)
# Publish from account B using a 12-digit access key.
client_b = boto3.client(
"iot-data",
endpoint_url=ENDPOINT,
aws_access_key_id="222222222222",
aws_secret_access_key="x",
region_name="us-east-1",
config=Config(retries={"mode": "standard"}),
)
client_b.publish(topic=topic, payload=b"from-b")
# Give the broker time to (not) deliver.
time.sleep(1.5)
stop.set()
t.join(timeout=2)
assert received == [], (
"Subscriber in account A should not have received a publish from account B "
f"(got {received!r})"
)
def test_iot_ws_same_account_publish_delivers(iot_data_client):
"""Positive case: a subscriber in account A DOES receive a publish from account A.
Validates that topic prefixing correctly scopes delivery within the same
account — the counterpart to the negative isolation test above.
"""
import boto3
from botocore.config import Config
topic = _unique("same-acct/sensor")
parsed = urlparse(ENDPOINT)
ws_host = parsed.hostname or "localhost"
ws_port = parsed.port or 4566
account = "333333333333"
cred = quote(f"{account}/20240101/us-east-1/iotdevicegateway/aws4_request")
ws_url = (
f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
f"?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={cred}"
)
ready = threading.Event()
stop = threading.Event()
received: list = []
def _runner():
asyncio.run(_ws_subscribe_and_collect(ws_url, topic, ready, received, stop))
t = threading.Thread(target=_runner, daemon=True)
t.start()
assert ready.wait(timeout=_WS_HANDSHAKE_TIMEOUT)
# Publish from the SAME account.
client_a = boto3.client(
"iot-data",
endpoint_url=ENDPOINT,
aws_access_key_id=account,
aws_secret_access_key="x",
region_name="us-east-1",
config=Config(retries={"mode": "standard"}),
)
payload = b"hello-from-same-account"
client_a.publish(topic=topic, payload=payload)
deadline = time.time() + 5
while time.time() < deadline and not received:
time.sleep(0.05)
stop.set()
t.join(timeout=2)
assert received, "Subscriber should have received the publish from the same account"
delivered_topic, delivered_payload = received[0]
assert delivered_topic == topic
assert delivered_payload == payload
# ---------------------------------------------------------------------------
# Device Shadow (GetThingShadow / UpdateThingShadow / DeleteThingShadow)
# ---------------------------------------------------------------------------
def _read_shadow(resp) -> dict:
return json.loads(resp["payload"].read())
def test_get_thing_shadow_missing_raises_not_found(iot_data_client):
with pytest.raises(ClientError) as ei:
iot_data_client.get_thing_shadow(thingName=_unique("nothing"))
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_update_thing_shadow_reported_and_read_back(iot_data_client):
thing = _unique("dev")
resp = iot_data_client.update_thing_shadow(
thingName=thing,
payload=json.dumps({"state": {"reported": {"temp": 22, "missedReadings": 3}}}).encode(),
)
accepted = _read_shadow(resp)
# The /accepted response echoes only the reported section it received.
assert accepted["state"] == {"reported": {"temp": 22, "missedReadings": 3}}
assert accepted["version"] == 1
assert "reported" in accepted["metadata"]
got = _read_shadow(iot_data_client.get_thing_shadow(thingName=thing))
assert got["state"]["reported"] == {"temp": 22, "missedReadings": 3}
assert got["version"] == 1
def test_update_thing_shadow_merges_and_computes_delta(iot_data_client):
thing = _unique("dev")
iot_data_client.update_thing_shadow(
thingName=thing, payload=json.dumps({"state": {"reported": {"temp": 22}}}).encode()
)
iot_data_client.update_thing_shadow(
thingName=thing, payload=json.dumps({"state": {"desired": {"temp": 25}}}).encode()
)
got = _read_shadow(iot_data_client.get_thing_shadow(thingName=thing))
assert got["state"]["desired"] == {"temp": 25}
assert got["state"]["reported"] == {"temp": 22}
# delta = desired fields differing from reported.
assert got["state"]["delta"] == {"temp": 25}
assert got["version"] == 2
def test_update_thing_shadow_null_removes_field(iot_data_client):
thing = _unique("dev")
iot_data_client.update_thing_shadow(
thingName=thing,
payload=json.dumps({"state": {"reported": {"a": 1, "b": 2}}}).encode(),
)
iot_data_client.update_thing_shadow(
thingName=thing, payload=json.dumps({"state": {"reported": {"b": None}}}).encode()
)
got = _read_shadow(iot_data_client.get_thing_shadow(thingName=thing))
assert got["state"]["reported"] == {"a": 1}
def test_named_shadow_is_isolated_from_classic(iot_data_client):
thing = _unique("dev")
iot_data_client.update_thing_shadow(
thingName=thing, payload=json.dumps({"state": {"reported": {"classic": True}}}).encode()
)
iot_data_client.update_thing_shadow(
thingName=thing, shadowName="cfg",
payload=json.dumps({"state": {"reported": {"named": True}}}).encode(),
)
classic = _read_shadow(iot_data_client.get_thing_shadow(thingName=thing))
named = _read_shadow(iot_data_client.get_thing_shadow(thingName=thing, shadowName="cfg"))
assert classic["state"]["reported"] == {"classic": True}
assert named["state"]["reported"] == {"named": True}
def test_delete_thing_shadow(iot_data_client):
thing = _unique("dev")
iot_data_client.update_thing_shadow(
thingName=thing, payload=json.dumps({"state": {"reported": {"x": 1}}}).encode()
)
iot_data_client.delete_thing_shadow(thingName=thing)
with pytest.raises(ClientError) as ei:
iot_data_client.get_thing_shadow(thingName=thing)
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_update_thing_shadow_version_conflict(iot_data_client):
thing = _unique("dev")
iot_data_client.update_thing_shadow(
thingName=thing, payload=json.dumps({"state": {"reported": {"x": 1}}}).encode()
)
# Stale version is rejected.
with pytest.raises(ClientError) as ei:
iot_data_client.update_thing_shadow(
thingName=thing,
payload=json.dumps({"state": {"reported": {"x": 2}}, "version": 99}).encode(),
)
assert ei.value.response["Error"]["Code"] == "ConflictException"
# ---------------------------------------------------------------------------
# Topic-rule routing (publish → rule → Lambda)
# ---------------------------------------------------------------------------
# Handler forwards the received rule event to the SQS queue named by SINK_URL,
# so the test can observe that the rule fired and with what payload.
_RULE_SINK_HANDLER = (
"import boto3, json, os\n"
"def handler(event, context):\n"
" s = boto3.client('sqs', endpoint_url=os.environ['AWS_ENDPOINT_URL'])\n"
" s.send_message(QueueUrl=os.environ['SINK_URL'], MessageBody=json.dumps(event))\n"
" return {'ok': True}\n"
)
def _make_sink_lambda(lam, sink_url):
buf = _io.BytesIO()
with _zipfile.ZipFile(buf, "w") as z:
z.writestr("index.py", _RULE_SINK_HANDLER)
name = _unique("rulefn")
lam.create_function(
FunctionName=name,
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test-role",
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
Environment={"Variables": {"SINK_URL": sink_url}},
)
return lam.get_function(FunctionName=name)["Configuration"]["FunctionArn"]
def _poll_sink(sqs, url, timeout=12):
body = _poll_body(sqs, url, timeout)
return json.loads(body) if body is not None else None
def test_iot_topic_rule_routes_publish_to_lambda(iot_client, iot_data_client, lam, sqs):
sink = sqs.create_queue(QueueName=_unique("rule-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("route").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT * FROM 'sensors/+/telemetry'",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
iot_data_client.publish(
topic="sensors/a1/telemetry",
payload=json.dumps({"temp": 22, "missedReadings": 3}).encode(),
)
event = _poll_sink(sqs, sink)
assert event == {"temp": 22, "missedReadings": 3}
iot_client.delete_topic_rule(ruleName=rule)
def test_iot_basic_ingest_routes_to_lambda(iot_client, iot_data_client, lam, sqs):
sink = sqs.create_queue(QueueName=_unique("ingest-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("ingest").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT * FROM 'unused'",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
# Basic Ingest: publishing to `$aws/rules/<ruleName>` invokes the rule
# directly, bypassing the topic filter.
iot_data_client.publish(
topic=f"$aws/rules/{rule}",
payload=json.dumps({"temp": 99, "basic": True}).encode(),
)
event = _poll_sink(sqs, sink)
assert event == {"temp": 99, "basic": True}
iot_client.delete_topic_rule(ruleName=rule)
def test_iot_disabled_rule_does_not_fire(iot_client, iot_data_client, lam, sqs):
sink = sqs.create_queue(QueueName=_unique("disabled-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("disabled").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT * FROM 'sensors/+/telemetry'",
"ruleDisabled": True,
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
iot_data_client.publish(
topic="sensors/a1/telemetry", payload=json.dumps({"temp": 1}).encode()
)
assert _poll_sink(sqs, sink, timeout=4) is None
iot_client.delete_topic_rule(ruleName=rule)
# Every byte value: not valid UTF-8, so it survives the rule path only if the
# payload is never text-decoded.
_BINARY_PAYLOAD = bytes(range(256))
def test_iot_rule_encode_base64_projection_basic_ingest(
iot_client, iot_data_client, lam, sqs
):
sink = sqs.create_queue(QueueName=_unique("encode-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("encode").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT encode(*, 'base64') AS data FROM 'telemetry'",
"awsIotSqlVersion": "2016-03-23",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
iot_data_client.publish(topic=f"$aws/rules/{rule}", payload=_BINARY_PAYLOAD)
event = _poll_sink(sqs, sink)
assert list(event) == ["data"]
assert base64.b64decode(event["data"]) == _BINARY_PAYLOAD
iot_client.delete_topic_rule(ruleName=rule)
def test_iot_rule_encode_base64_projection_topic_filter(
iot_client, iot_data_client, lam, sqs
):
sink = sqs.create_queue(QueueName=_unique("encode-filter-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("encfilter").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT encode(*, 'base64') AS data FROM 'telemetry'",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
iot_data_client.publish(topic="telemetry", payload=_BINARY_PAYLOAD)
event = _poll_sink(sqs, sink)
assert list(event) == ["data"]
assert base64.b64decode(event["data"]) == _BINARY_PAYLOAD
iot_client.delete_topic_rule(ruleName=rule)
def test_iot_rule_attribute_projection(iot_client, iot_data_client, lam, sqs):
sink = sqs.create_queue(QueueName=_unique("project-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("project").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT deviceId AS id, topic(2) AS device "
"FROM 'sensors/+/telemetry'",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
iot_data_client.publish(
topic="sensors/a1/telemetry",
payload=json.dumps({"deviceId": "d1", "temp": 22}).encode(),
)
assert _poll_sink(sqs, sink) == {"id": "d1", "device": "a1"}
def test_iot_rule_where_clause_gates_dispatch(iot_client, iot_data_client, lam, sqs):
"""Only publishes satisfying the WHERE predicate reach the rule's actions."""
sink = sqs.create_queue(QueueName=_unique("where-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("gated").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT * FROM 'alarms/+/state' WHERE severity = 'high' AND count > 1",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
# Non-matching: predicate false, then attribute missing entirely.
iot_data_client.publish(
topic="alarms/a1/state",
payload=json.dumps({"severity": "low", "count": 5}).encode(),
)
iot_data_client.publish(
topic="alarms/a1/state", payload=json.dumps({"count": 5}).encode()
)
# Matching.
iot_data_client.publish(
topic="alarms/a1/state",
payload=json.dumps({"severity": "high", "count": 2, "id": "x"}).encode(),
)
event = _poll_sink(sqs, sink)
assert event == {"severity": "high", "count": 2, "id": "x"}
# No further deliveries — the non-matching publishes never dispatched.
assert _poll_sink(sqs, sink, timeout=3) is None
iot_client.delete_topic_rule(ruleName=rule)
def test_iot_rule_where_topic_function_under_basic_ingest(
iot_client, iot_data_client, lam, sqs
):
"""Under Basic Ingest a WHERE reading `topic(n)` sees the topic *after* the
`$aws/rules/<name>/` prefix, so the same predicate gates both publish paths."""
sink = sqs.create_queue(QueueName=_unique("bi-where-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("biwhere").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
# The FROM filter is bypassed by Basic Ingest; the WHERE is not.
"sql": "SELECT * FROM 'unused' WHERE topic(2) = 'a1'",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
# topic() reports 'sensors/b7/telemetry' here — topic(2) is 'b7', so the
# predicate is false and nothing dispatches.
iot_data_client.publish(
topic=f"$aws/rules/{rule}/sensors/b7/telemetry",
payload=json.dumps({"temp": 1}).encode(),
)
# ...and 'a1' for this one, which matches. If the prefix were not stripped,
# topic(2) would be 'rules' for both and neither would dispatch.
iot_data_client.publish(
topic=f"$aws/rules/{rule}/sensors/a1/telemetry",
payload=json.dumps({"temp": 2}).encode(),
)
assert _poll_sink(sqs, sink) == {"temp": 2}
assert _poll_sink(sqs, sink, timeout=3) is None
iot_client.delete_topic_rule(ruleName=rule)
def test_iot_rule_where_or_clause_dispatches_either_branch(
iot_client, iot_data_client, lam, sqs
):
"""An `OR` predicate fires for either branch and stays closed otherwise."""
sink = sqs.create_queue(QueueName=_unique("or-where-sink"))["QueueUrl"]
fn_arn = _make_sink_lambda(lam, sink)
rule = _unique("orwhere").replace("-", "_")
iot_client.create_topic_rule(
ruleName=rule,
topicRulePayload={
"sql": "SELECT * FROM 'alarms/+/state' "
"WHERE (severity = 'high' OR severity = 'critical') AND count > 1",
"actions": [{"lambda": {"functionArn": fn_arn}}],
},
)
# Neither OR branch holds.
iot_data_client.publish(
topic="alarms/a1/state",
payload=json.dumps({"severity": "low", "count": 5}).encode(),
)
# A branch holds but the AND-ed clause does not.
iot_data_client.publish(
topic="alarms/a1/state",
payload=json.dumps({"severity": "critical", "count": 1}).encode(),
)