Repository navigation
Expand file tree
/
Copy pathtest_iot.py
More file actions
6743 lines (5558 loc) · 249 KB
/
Copy pathtest_iot.py
File metadata and controls
6743 lines (5558 loc) · 249 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 control plane (Phase 1a).
Exercises Things, ThingTypes, ThingGroups, Certificates (issued via the
Local CA), Policies, and DescribeEndpoint. The data plane (broker / WS /
iot-data Publish) is covered separately in ``test_iot_data.py``.
"""
import base64
import json
import logging
import re
import time
import uuid
import pytest
from botocore.exceptions import ClientError
from conftest import iot_test_ca
def _unique(prefix: str) -> str:
return f"{prefix}-{uuid.uuid4().hex[:8]}"
# ---------------------------------------------------------------------------
# Endpoint
# ---------------------------------------------------------------------------
def test_iot_describe_endpoint_data_ats(iot_client):
resp = iot_client.describe_endpoint(endpointType="iot:Data-ATS")
addr = resp["endpointAddress"]
assert "-ats.iot." in addr
assert "us-east-1" in addr
def test_iot_describe_endpoint_default_uses_data_ats(iot_client):
resp = iot_client.describe_endpoint()
assert "-ats.iot." in resp["endpointAddress"]
@pytest.mark.parametrize(
("endpoint_type", "message"),
[
("iot:Data", "iot:Data is not supported. Please use iot:Data-ATS instead."),
(
"iot:Jobs",
"IoT Jobs and Commands APIs are now available through iot:Data-ATS "
"endpoints instead of iot:Jobs endpoints. Please use iot:Data-ATS.",
),
],
)
def test_iot_describe_endpoint_retired_types_rejected(iot_client, endpoint_type, message):
with pytest.raises(ClientError) as ei:
iot_client.describe_endpoint(endpointType=endpoint_type)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
assert ei.value.response["Error"]["Message"] == message
assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
def test_iot_describe_endpoint_unknown_type_rejected(iot_client):
with pytest.raises(ClientError) as ei:
iot_client.describe_endpoint(endpointType="iot:Bogus")
assert ei.value.response["Error"]["Code"] in ("InvalidRequestException",)
# ---------------------------------------------------------------------------
# Thing CRUD
# ---------------------------------------------------------------------------
def test_iot_create_describe_thing(iot_client):
name = _unique("thing")
resp = iot_client.create_thing(thingName=name)
assert resp["thingName"] == name
assert resp["thingArn"].endswith(f":thing/{name}")
assert resp["thingId"]
desc = iot_client.describe_thing(thingName=name)
assert desc["thingName"] == name
assert desc["version"] == 1
iot_client.delete_thing(thingName=name)
def test_iot_create_thing_with_attributes(iot_client):
name = _unique("thing")
iot_client.create_thing(
thingName=name,
attributePayload={"attributes": {"color": "red", "size": "L"}},
)
desc = iot_client.describe_thing(thingName=name)
assert desc["attributes"] == {"color": "red", "size": "L"}
iot_client.delete_thing(thingName=name)
def test_iot_create_thing_idempotent_same_config(iot_client):
name = _unique("thing")
iot_client.create_thing(
thingName=name,
attributePayload={"attributes": {"color": "red"}},
)
# Same config must not raise.
resp2 = iot_client.create_thing(
thingName=name,
attributePayload={"attributes": {"color": "red"}},
)
assert resp2["thingName"] == name
iot_client.delete_thing(thingName=name)
def test_iot_create_thing_conflict_different_config(iot_client):
name = _unique("thing")
iot_client.create_thing(
thingName=name,
attributePayload={"attributes": {"color": "red"}},
)
with pytest.raises(ClientError) as ei:
iot_client.create_thing(
thingName=name,
attributePayload={"attributes": {"color": "blue"}},
)
assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"
iot_client.delete_thing(thingName=name)
def test_iot_describe_unknown_thing_404(iot_client):
with pytest.raises(ClientError) as ei:
iot_client.describe_thing(thingName=_unique("nope"))
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_iot_update_thing_increments_version(iot_client):
name = _unique("thing")
iot_client.create_thing(thingName=name)
iot_client.update_thing(
thingName=name,
attributePayload={"attributes": {"k": "v"}},
)
desc = iot_client.describe_thing(thingName=name)
assert desc["version"] == 2
assert desc["attributes"] == {"k": "v"}
iot_client.delete_thing(thingName=name)
def test_iot_update_thing_remove_thing_type_keeps_attributes(iot_client):
type_name = _unique("type")
name = _unique("thing")
iot_client.create_thing_type(thingTypeName=type_name)
iot_client.create_thing(
thingName=name, thingTypeName=type_name,
attributePayload={"attributes": {"k": "v"}},
)
iot_client.update_thing(thingName=name, removeThingType=True)
desc = iot_client.describe_thing(thingName=name)
assert desc.get("thingTypeName") is None
assert desc["attributes"] == {"k": "v"}
assert desc["version"] == 2
iot_client.delete_thing(thingName=name)
iot_client.deprecate_thing_type(thingTypeName=type_name)
iot_client.delete_thing_type(thingTypeName=type_name)
def test_iot_list_things_filter_by_attribute(iot_client):
a = _unique("thing")
b = _unique("thing")
iot_client.create_thing(
thingName=a, attributePayload={"attributes": {"region": "eu"}}
)
iot_client.create_thing(
thingName=b, attributePayload={"attributes": {"region": "us"}}
)
resp = iot_client.list_things(attributeName="region", attributeValue="eu")
names = {t["thingName"] for t in resp["things"]}
assert a in names and b not in names
iot_client.delete_thing(thingName=a)
iot_client.delete_thing(thingName=b)
def test_iot_list_things_filter_by_thing_type(iot_client):
type_a = _unique("type")
iot_client.create_thing_type(thingTypeName=type_a)
name = _unique("thing")
iot_client.create_thing(thingName=name, thingTypeName=type_a)
resp = iot_client.list_things(thingTypeName=type_a)
assert any(t["thingName"] == name for t in resp["things"])
iot_client.delete_thing(thingName=name)
iot_client.deprecate_thing_type(thingTypeName=type_a)
iot_client.delete_thing_type(thingTypeName=type_a)
# ---------------------------------------------------------------------------
# ThingType CRUD
# ---------------------------------------------------------------------------
def test_iot_thing_type_lifecycle(iot_client):
name = _unique("type")
iot_client.create_thing_type(thingTypeName=name)
desc = iot_client.describe_thing_type(thingTypeName=name)
assert desc["thingTypeName"] == name
assert desc["thingTypeMetadata"]["deprecated"] is False
iot_client.deprecate_thing_type(thingTypeName=name)
desc2 = iot_client.describe_thing_type(thingTypeName=name)
assert desc2["thingTypeMetadata"]["deprecated"] is True
iot_client.delete_thing_type(thingTypeName=name)
with pytest.raises(ClientError) as ei:
iot_client.describe_thing_type(thingTypeName=name)
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_iot_create_thing_type_idempotent_recreate(iot_client):
name = _unique("type")
first = iot_client.create_thing_type(thingTypeName=name)
# Identical re-create (no properties) returns 200 with the existing ids.
again = iot_client.create_thing_type(thingTypeName=name)
assert again["thingTypeId"] == first["thingTypeId"]
assert again["thingTypeArn"] == first["thingTypeArn"]
# Explicit empty properties count as identical to absent ones.
empty = iot_client.create_thing_type(
thingTypeName=name,
thingTypeProperties={"searchableAttributes": []},
)
assert empty["thingTypeId"] == first["thingTypeId"]
iot_client.deprecate_thing_type(thingTypeName=name)
iot_client.delete_thing_type(thingTypeName=name)
def test_iot_create_thing_type_conflicting_recreate_rejected(iot_client):
name = _unique("type")
iot_client.create_thing_type(thingTypeName=name)
with pytest.raises(ClientError) as ei:
iot_client.create_thing_type(
thingTypeName=name,
thingTypeProperties={"thingTypeDescription": "different"},
)
assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"
iot_client.deprecate_thing_type(thingTypeName=name)
iot_client.delete_thing_type(thingTypeName=name)
def test_iot_create_thing_type_idempotency_covers_all_properties(iot_client):
"""The comparison spans every modelled property and treats
searchableAttributes as unordered: a re-create differing only in
mqtt5Configuration conflicts, while the same attributes in another order
are idempotent."""
name = _unique("type")
mqtt5 = {"propagatingAttributes": [
{"userPropertyKey": "region", "thingAttribute": "site"},
]}
first = iot_client.create_thing_type(
thingTypeName=name,
thingTypeProperties={
"searchableAttributes": ["site", "region"],
"mqtt5Configuration": mqtt5,
},
)
same = iot_client.create_thing_type(
thingTypeName=name,
thingTypeProperties={
"searchableAttributes": ["region", "site"],
"mqtt5Configuration": mqtt5,
},
)
assert same["thingTypeId"] == first["thingTypeId"]
with pytest.raises(ClientError) as ei:
iot_client.create_thing_type(
thingTypeName=name,
thingTypeProperties={
"searchableAttributes": ["site", "region"],
"mqtt5Configuration": {"propagatingAttributes": [
{"userPropertyKey": "region", "thingAttribute": "other"},
]},
},
)
assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"
# The first create's configuration is the one that stuck.
described = iot_client.describe_thing_type(thingTypeName=name)
assert described["thingTypeProperties"]["mqtt5Configuration"] == mqtt5
iot_client.deprecate_thing_type(thingTypeName=name)
iot_client.delete_thing_type(thingTypeName=name)
def test_iot_delete_thing_type_active_rejected(iot_client):
name = _unique("type")
iot_client.create_thing_type(thingTypeName=name)
with pytest.raises(ClientError) as ei:
iot_client.delete_thing_type(thingTypeName=name)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
iot_client.deprecate_thing_type(thingTypeName=name)
iot_client.delete_thing_type(thingTypeName=name)
# ---------------------------------------------------------------------------
# ThingGroup CRUD + membership
# ---------------------------------------------------------------------------
def test_iot_delete_thing_group_with_child_groups_is_refused(iot_client):
parent, child = _unique("parent"), _unique("child")
iot_client.create_thing_group(thingGroupName=parent)
iot_client.create_thing_group(thingGroupName=child, parentGroupName=parent)
with pytest.raises(ClientError) as ei:
iot_client.delete_thing_group(thingGroupName=parent)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
assert ei.value.response["Error"]["Message"] == (
f"Cannot delete thing group : {parent} when there are still child groups attached to it"
)
assert iot_client.describe_thing_group(thingGroupName=child)["thingGroupMetadata"][
"parentGroupName"] == parent
iot_client.delete_thing_group(thingGroupName=child)
iot_client.delete_thing_group(thingGroupName=parent)
def test_iot_thing_group_membership(iot_client):
gname = _unique("group")
tname = _unique("thing")
iot_client.create_thing_group(thingGroupName=gname)
iot_client.create_thing(thingName=tname)
iot_client.add_thing_to_thing_group(thingGroupName=gname, thingName=tname)
things = iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
assert tname in things
iot_client.remove_thing_from_thing_group(thingGroupName=gname, thingName=tname)
things2 = iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
assert tname not in things2
iot_client.delete_thing(thingName=tname)
iot_client.delete_thing_group(thingGroupName=gname)
def test_iot_list_thing_groups_for_thing(iot_client):
tname = _unique("thing")
g1 = _unique("group")
g2 = _unique("group")
iot_client.create_thing(thingName=tname)
iot_client.create_thing_group(thingGroupName=g1)
iot_client.create_thing_group(thingGroupName=g2)
# A thing in no groups answers an empty list, not an error.
assert iot_client.list_thing_groups_for_thing(thingName=tname)["thingGroups"] == []
iot_client.add_thing_to_thing_group(thingGroupName=g1, thingName=tname)
iot_client.add_thing_to_thing_group(thingGroupName=g2, thingName=tname)
groups = iot_client.list_thing_groups_for_thing(thingName=tname)["thingGroups"]
assert {g["groupName"] for g in groups} == {g1, g2}
for g in groups:
assert g["groupArn"].endswith(":thinggroup/" + g["groupName"])
iot_client.remove_thing_from_thing_group(thingGroupName=g1, thingName=tname)
remaining = iot_client.list_thing_groups_for_thing(thingName=tname)["thingGroups"]
assert [g["groupName"] for g in remaining] == [g2]
with pytest.raises(ClientError) as ei:
iot_client.list_thing_groups_for_thing(thingName=_unique("absent"))
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
iot_client.delete_thing(thingName=tname)
iot_client.delete_thing_group(thingGroupName=g1)
iot_client.delete_thing_group(thingGroupName=g2)
# ---------------------------------------------------------------------------
# Certificates (issued via the Local CA)
# ---------------------------------------------------------------------------
def test_iot_create_keys_and_certificate_active(iot_client):
pytest.importorskip("cryptography")
resp = iot_client.create_keys_and_certificate(setAsActive=True)
assert resp["certificateId"]
assert resp["certificateArn"].endswith(":cert/" + resp["certificateId"])
assert "BEGIN CERTIFICATE" in resp["certificatePem"]
assert "BEGIN" in resp["keyPair"]["PrivateKey"]
assert "BEGIN PUBLIC KEY" in resp["keyPair"]["PublicKey"]
desc = iot_client.describe_certificate(certificateId=resp["certificateId"])
assert desc["certificateDescription"]["status"] == "ACTIVE"
# Deactivate and delete
iot_client.update_certificate(
certificateId=resp["certificateId"], newStatus="INACTIVE"
)
iot_client.delete_certificate(certificateId=resp["certificateId"])
def test_iot_create_keys_and_certificate_inactive(iot_client):
pytest.importorskip("cryptography")
resp = iot_client.create_keys_and_certificate(setAsActive=False)
desc = iot_client.describe_certificate(certificateId=resp["certificateId"])
assert desc["certificateDescription"]["status"] == "INACTIVE"
iot_client.delete_certificate(certificateId=resp["certificateId"])
def test_iot_delete_active_certificate_rejected(iot_client):
pytest.importorskip("cryptography")
resp = iot_client.create_keys_and_certificate(setAsActive=True)
cert_id = resp["certificateId"]
with pytest.raises(ClientError) as ei:
iot_client.delete_certificate(certificateId=cert_id)
assert ei.value.response["Error"]["Code"] == "CertificateStateException"
# 406 per the service model — the same status the CA-certificate delete
# answers with for the same exception.
assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 406
iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
iot_client.delete_certificate(certificateId=cert_id)
def test_iot_register_certificate_preserves_pem_verbatim(iot_client):
pytest.importorskip("cryptography")
# Issue a cert, capture its PEM, delete it, then re-register the SAME PEM.
issued = iot_client.create_keys_and_certificate(setAsActive=False)
cert_pem = issued["certificatePem"]
iot_client.delete_certificate(certificateId=issued["certificateId"])
resp = iot_client.register_certificate(
certificatePem=cert_pem, status="ACTIVE"
)
cert_id = resp["certificateId"]
desc = iot_client.describe_certificate(certificateId=cert_id)
assert desc["certificateDescription"]["certificatePem"] == cert_pem
iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
iot_client.delete_certificate(certificateId=cert_id)
def test_iot_register_certificate_set_as_active_query_param(iot_client):
pytest.importorskip("cryptography")
# boto3 sends setAsActive as a querystring parameter (per the botocore
# model), not in the JSON body — the cert must still come out ACTIVE.
issued = iot_client.create_keys_and_certificate(setAsActive=False)
cert_pem = issued["certificatePem"]
iot_client.delete_certificate(certificateId=issued["certificateId"])
cert_id = iot_client.register_certificate(
certificatePem=cert_pem, setAsActive=True
)["certificateId"]
desc = iot_client.describe_certificate(certificateId=cert_id)
assert desc["certificateDescription"]["status"] == "ACTIVE"
iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
iot_client.delete_certificate(certificateId=cert_id)
def test_iot_attach_detach_thing_principal(iot_client):
pytest.importorskip("cryptography")
name = _unique("thing")
iot_client.create_thing(thingName=name)
cert = iot_client.create_keys_and_certificate(setAsActive=True)
arn = cert["certificateArn"]
iot_client.attach_thing_principal(thingName=name, principal=arn)
principals = iot_client.list_thing_principals(thingName=name)["principals"]
assert arn in principals
things = iot_client.list_principal_things(principal=arn)["things"]
assert name in things
iot_client.detach_thing_principal(thingName=name, principal=arn)
principals2 = iot_client.list_thing_principals(thingName=name)["principals"]
assert arn not in principals2
iot_client.update_certificate(certificateId=cert["certificateId"], newStatus="INACTIVE")
iot_client.delete_certificate(certificateId=cert["certificateId"])
iot_client.delete_thing(thingName=name)
def test_iot_thing_arn_tail_parser_requires_iot_thing_scope():
from ministack.core.responses import (
get_account_id,
get_region,
set_request_account_id,
set_request_region,
)
from ministack.services import iot as _iot
original_account = get_account_id()
original_region = get_region()
try:
set_request_account_id("000000000000")
set_request_region("us-east-1")
assert _iot._thing_name_from_arn(
"arn:aws:iot:us-east-1:000000000000:thing/parser-thing"
) == "parser-thing"
assert _iot._thing_name_from_arn(
"arn:aws:sqs:us-east-1:000000000000:thing/parser-thing"
) == ""
assert _iot._thing_name_from_arn(
"arn:aws:iot:us-west-2:000000000000:thing/parser-thing"
) == ""
assert _iot._thing_name_from_arn(
"arn:aws:iot:us-east-1:000000000000:thing/parser-thing/extra"
) == ""
finally:
set_request_account_id(original_account)
set_request_region(original_region)
# ---------------------------------------------------------------------------
# Policies
# ---------------------------------------------------------------------------
_POLICY_DOC = json.dumps(
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Connect", "iot:Publish"],
"Resource": "*",
}
],
}
)
def test_iot_policy_lifecycle(iot_client):
name = _unique("policy")
resp = iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)
assert resp["policyName"] == name
assert resp["policyVersionId"] == "1"
got = iot_client.get_policy(policyName=name)
assert got["defaultVersionId"] == "1"
listing = iot_client.list_policies()["policies"]
assert any(p["policyName"] == name for p in listing)
iot_client.delete_policy(policyName=name)
def test_iot_create_policy_malformed_400(iot_client):
name = _unique("policy")
with pytest.raises(ClientError) as ei:
iot_client.create_policy(policyName=name, policyDocument="not-json")
assert ei.value.response["Error"]["Code"] == "MalformedPolicyException"
def test_iot_policy_versions(iot_client):
name = _unique("policy")
iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)
new_doc = json.dumps(
{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "iot:Subscribe", "Resource": "*"}
],
}
)
v2 = iot_client.create_policy_version(
policyName=name, policyDocument=new_doc, setAsDefault=True
)
assert v2["policyVersionId"] == "2"
versions = iot_client.list_policy_versions(policyName=name)["policyVersions"]
assert {v["versionId"] for v in versions} == {"1", "2"}
assert next(v for v in versions if v["versionId"] == "2")["isDefaultVersion"]
iot_client.delete_policy_version(policyName=name, policyVersionId="1")
iot_client.delete_policy(policyName=name)
def test_iot_attach_detach_policy(iot_client):
pytest.importorskip("cryptography")
name = _unique("policy")
iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)
cert = iot_client.create_keys_and_certificate(setAsActive=False)
arn = cert["certificateArn"]
iot_client.attach_policy(policyName=name, target=arn)
targets = iot_client.list_targets_for_policy(policyName=name)["targets"]
assert arn in targets
iot_client.detach_policy(policyName=name, target=arn)
targets2 = iot_client.list_targets_for_policy(policyName=name)["targets"]
assert arn not in targets2
iot_client.delete_policy(policyName=name)
iot_client.delete_certificate(certificateId=cert["certificateId"])
# ---------------------------------------------------------------------------
# Certificates: register-no-CA + legacy principal-policy family
# ---------------------------------------------------------------------------
def test_iot_register_certificate_without_ca_roundtrip(iot_client):
pytest.importorskip("cryptography")
# Issue a cert, capture its PEM, delete it, then re-register the SAME PEM
# through the no-CA variant.
issued = iot_client.create_keys_and_certificate(setAsActive=False)
cert_pem = issued["certificatePem"]
iot_client.delete_certificate(certificateId=issued["certificateId"])
resp = iot_client.register_certificate_without_ca(
certificatePem=cert_pem, status="ACTIVE"
)
cert_id = resp["certificateId"]
assert resp["certificateArn"].endswith(":cert/" + cert_id)
# The no-CA output carries ids only — no certificatePem echo.
assert "certificatePem" not in resp
desc = iot_client.describe_certificate(certificateId=cert_id)
assert desc["certificateDescription"]["certificatePem"] == cert_pem
assert desc["certificateDescription"]["status"] == "ACTIVE"
iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
iot_client.delete_certificate(certificateId=cert_id)
def test_iot_register_certificate_without_ca_duplicate_conflict(iot_client):
pytest.importorskip("cryptography")
issued = iot_client.create_keys_and_certificate(setAsActive=False)
cert_pem = issued["certificatePem"]
iot_client.delete_certificate(certificateId=issued["certificateId"])
cert_id = iot_client.register_certificate_without_ca(
certificatePem=cert_pem, status="INACTIVE"
)["certificateId"]
with pytest.raises(ClientError) as ei:
iot_client.register_certificate_without_ca(
certificatePem=cert_pem, status="INACTIVE"
)
err = ei.value.response
assert err["Error"]["Code"] == "ResourceAlreadyExistsException"
assert err["resourceId"] == cert_id
assert err["resourceArn"].endswith(":cert/" + cert_id)
iot_client.delete_certificate(certificateId=cert_id)
def test_iot_legacy_principal_policy_family(iot_client):
pytest.importorskip("cryptography")
policy = _unique("policy")
iot_client.create_policy(policyName=policy, policyDocument=_POLICY_DOC)
cert = iot_client.create_keys_and_certificate(setAsActive=False)
principal = cert["certificateArn"]
iot_client.attach_principal_policy(policyName=policy, principal=principal)
legacy = iot_client.list_principal_policies(principal=principal)["policies"]
assert any(p["policyName"] == policy for p in legacy)
# 1:1 with the modern target-scoped view of the same attachment.
modern = iot_client.list_attached_policies(target=principal)["policies"]
assert legacy == modern
principals = iot_client.list_policy_principals(policyName=policy)["principals"]
assert principals == [principal]
iot_client.detach_principal_policy(policyName=policy, principal=principal)
assert iot_client.list_principal_policies(principal=principal)["policies"] == []
assert iot_client.list_policy_principals(policyName=policy)["principals"] == []
assert iot_client.list_attached_policies(target=principal)["policies"] == []
iot_client.delete_policy(policyName=policy)
iot_client.delete_certificate(certificateId=cert["certificateId"])
def test_iot_legacy_principal_policy_unknown_policy_404(iot_client):
with pytest.raises(ClientError) as ei:
iot_client.attach_principal_policy(
policyName=_unique("nope"), principal="arn:aws:iot:cert/none"
)
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
# ---------------------------------------------------------------------------
# Provisioning templates (storage + CRUD — no fleet-provisioning MQTT workflow)
# ---------------------------------------------------------------------------
def _provisioning_template_body() -> str:
# The real service refuses a body without an AWS::IoT::Certificate
# resource, so every valid test body carries one.
return json.dumps({
"Parameters": {"SerialNumber": {"Type": "String"}},
"Resources": {
"certificate": {
"Type": "AWS::IoT::Certificate",
"Properties": {"CertificateId": {"Ref": "AWS::IoT::Certificate::Id"}},
},
"thing": {
"Type": "AWS::IoT::Thing",
"Properties": {"ThingName": {"Ref": "SerialNumber"}},
},
},
})
def test_iot_provisioning_template_lifecycle(iot_client):
name = _unique("provtemplate")
body = _provisioning_template_body()
role = "arn:aws:iam::000000000000:role/provisioning"
created = iot_client.create_provisioning_template(
templateName=name,
description="fleet template",
templateBody=body,
enabled=True,
provisioningRoleArn=role,
type="FLEET_PROVISIONING",
)
assert created["templateName"] == name
assert created["templateArn"].endswith(f":provisioningtemplate/{name}")
assert created["defaultVersionId"] == 1
desc = iot_client.describe_provisioning_template(templateName=name)
assert desc["templateArn"] == created["templateArn"]
assert desc["description"] == "fleet template"
assert desc["templateBody"] == body
assert desc["enabled"] is True
assert desc["provisioningRoleArn"] == role
assert desc["type"] == "FLEET_PROVISIONING"
assert desc["defaultVersionId"] == 1
assert "creationDate" in desc and "lastModifiedDate" in desc
listed = iot_client.list_provisioning_templates()["templates"]
summary = next(t for t in listed if t["templateName"] == name)
assert summary["templateArn"] == created["templateArn"]
assert summary["enabled"] is True
assert summary["type"] == "FLEET_PROVISIONING"
# Summaries carry no body, role, or description — same as the live service.
assert "templateBody" not in summary
assert "provisioningRoleArn" not in summary
assert "description" not in summary
with pytest.raises(ClientError) as ei:
iot_client.create_provisioning_template(
templateName=name, templateBody=body, provisioningRoleArn=role
)
assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"
assert ei.value.response["Error"]["Message"] == (
f"Template with name {name} already exists"
)
updated = iot_client.update_provisioning_template(
templateName=name, description="updated", enabled=False
)
# The live service answers 200 with an empty body and no version bump.
assert set(updated) == {"ResponseMetadata"}
desc = iot_client.describe_provisioning_template(templateName=name)
assert desc["description"] == "updated"
assert desc["enabled"] is False
assert desc["defaultVersionId"] == 1
# An unmentioned field survives the update.
assert desc["provisioningRoleArn"] == role
iot_client.delete_provisioning_template(templateName=name)
with pytest.raises(ClientError) as ei:
iot_client.describe_provisioning_template(templateName=name)
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
assert ei.value.response["Error"]["Message"] == (
f"Unable to find template named {name}"
)
def test_iot_provisioning_template_body_must_carry_certificate_resource(iot_client):
"""A body without an AWS::IoT::Certificate resource is refused with the
live service's message; unparseable body JSON is refused too."""
name = _unique("provtemplate")
role = "arn:aws:iam::000000000000:role/provisioning"
no_cert = json.dumps({"Resources": {
"thing": {"Type": "AWS::IoT::Thing", "Properties": {"ThingName": "t"}},
}})
with pytest.raises(ClientError) as ei:
iot_client.create_provisioning_template(
templateName=name, templateBody=no_cert, provisioningRoleArn=role
)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
assert ei.value.response["Error"]["Message"] == (
"The template body is invalid: Template must have certificate resource."
)
with pytest.raises(ClientError) as ei:
iot_client.create_provisioning_template(
templateName=name, templateBody="not json{", provisioningRoleArn=role
)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
with pytest.raises(ClientError):
iot_client.describe_provisioning_template(templateName=name)
def test_iot_provisioning_template_name_validation(iot_client):
role = "arn:aws:iam::000000000000:role/provisioning"
for bad in ("x" * 37, "no:colons"):
with pytest.raises(ClientError) as ei:
iot_client.create_provisioning_template(
templateName=bad,
templateBody=_provisioning_template_body(),
provisioningRoleArn=role,
)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
def test_iot_provisioning_template_update_unknown_404(iot_client):
name = _unique("provtemplate")
with pytest.raises(ClientError) as ei:
iot_client.update_provisioning_template(templateName=name, enabled=True)
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
assert ei.value.response["Error"]["Message"] == (
f"Unable to find template named {name}"
)
def test_iot_provisioning_template_pre_provisioning_hook_roundtrip(iot_client):
name = _unique("provtemplate")
hook = {
"payloadVersion": "2020-04-01",
"targetArn": "arn:aws:lambda:us-east-1:000000000000:function:hook",
}
iot_client.create_provisioning_template(
templateName=name,
templateBody=_provisioning_template_body(),
provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning",
preProvisioningHook=hook,
)
try:
assert iot_client.describe_provisioning_template(
templateName=name
)["preProvisioningHook"] == hook
iot_client.update_provisioning_template(
templateName=name, removePreProvisioningHook=True
)
desc = iot_client.describe_provisioning_template(templateName=name)
assert "preProvisioningHook" not in desc
iot_client.update_provisioning_template(
templateName=name, preProvisioningHook=hook
)
assert iot_client.describe_provisioning_template(
templateName=name
)["preProvisioningHook"] == hook
finally:
iot_client.delete_provisioning_template(templateName=name)
# ---------------------------------------------------------------------------
# Fleet indexing (indexing configuration + SearchIndex)
# ---------------------------------------------------------------------------
def _enable_fleet_indexing(
client, mode: str = "REGISTRY_AND_SHADOW", connectivity: str = "STATUS"
) -> None:
"""Turn the AWS_Things index on, as every fleet stack has to on AWS."""
thing_cfg = {"thingIndexingMode": mode}
if mode != "OFF":
thing_cfg["thingConnectivityIndexingMode"] = connectivity
client.update_indexing_configuration(thingIndexingConfiguration=thing_cfg)
def _iot_client_for_fresh_account():
"""An IoT client on an account of its own, so its index starts OFF."""
import os
import boto3
from botocore.config import Config
return boto3.client(
"iot",
endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
aws_access_key_id=f"{uuid.uuid4().int % 10**12:012d}",
aws_secret_access_key="test",
region_name="us-east-1",
config=Config(retries={"mode": "standard"}),
)
def test_iot_indexing_configuration_round_trip():
client = _iot_client_for_fresh_account()
# AWS's default for an account that never configured indexing.
default = client.get_indexing_configuration()
assert default["thingIndexingConfiguration"]["thingIndexingMode"] == "OFF"
assert client.list_indices()["indexNames"] == []
with pytest.raises(ClientError) as ei:
client.describe_index(indexName="AWS_Things")
assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
client.update_indexing_configuration(
thingIndexingConfiguration={"thingIndexingMode": "REGISTRY_AND_SHADOW"},
thingGroupIndexingConfiguration={"thingGroupIndexingMode": "ON"},
)
stored = client.get_indexing_configuration()
assert stored["thingIndexingConfiguration"]["thingIndexingMode"] == (
"REGISTRY_AND_SHADOW"
)
assert stored["thingGroupIndexingConfiguration"]["thingGroupIndexingMode"] == "ON"
assert client.list_indices()["indexNames"] == ["AWS_Things"]
index = client.describe_index(indexName="AWS_Things")
# The registry *is* the index, so it is never BUILDING.
assert index["indexStatus"] == "ACTIVE"
assert index["schema"] == "REGISTRY_AND_SHADOW"
# Registry-only indexing narrows the schema back.
_enable_fleet_indexing(client, "REGISTRY", connectivity="OFF")
assert client.describe_index(indexName="AWS_Things")["schema"] == "REGISTRY"
# Connectivity status widens it again, the way AWS's schema strings do.
_enable_fleet_indexing(client, "REGISTRY")
assert (
client.describe_index(indexName="AWS_Things")["schema"]
== "REGISTRY_AND_CONNECTIVITY_STATUS"
)
# ...and turning it off retires the index.
_enable_fleet_indexing(client, "OFF")
assert client.list_indices()["indexNames"] == []
def test_iot_indexing_configuration_rejects_impossible_modes():
client = _iot_client_for_fresh_account()
for kwargs in (
{"thingIndexingConfiguration": {"thingIndexingMode": "REGISTRY_AND_LOGS"}},
# AWS: connectivity indexing requires thing indexing to be on.
{
"thingIndexingConfiguration": {
"thingIndexingMode": "OFF",
"thingConnectivityIndexingMode": "STATUS",
}
},
{"thingGroupIndexingConfiguration": {"thingGroupIndexingMode": "SOMETIMES"}},
):
with pytest.raises(ClientError) as ei:
client.update_indexing_configuration(**kwargs)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException", kwargs
# A rejected update leaves the configuration untouched.
assert client.get_indexing_configuration()["thingIndexingConfiguration"][
"thingIndexingMode"
] == "OFF"
_EVENT_TYPES = (
"THING", "THING_GROUP", "THING_TYPE", "THING_GROUP_MEMBERSHIP",
"THING_GROUP_HIERARCHY", "THING_TYPE_ASSOCIATION", "JOB", "JOB_EXECUTION",
"POLICY", "CERTIFICATE", "CA_CERTIFICATE",
)
def _enabled_event_types(client) -> set:
configs = client.describe_event_configurations()["eventConfigurations"]
assert set(configs) == set(_EVENT_TYPES)
return {t for t, c in configs.items() if c["Enabled"]}
def test_iot_event_configurations_default_all_disabled():
client = _iot_client_for_fresh_account()
resp = client.describe_event_configurations()
assert resp["eventConfigurations"] == {t: {"Enabled": False} for t in _EVENT_TYPES}
assert "creationDate" not in resp and "lastModifiedDate" not in resp
def test_iot_update_event_configurations_changes_only_named_types():
client = _iot_client_for_fresh_account()
client.update_event_configurations(eventConfigurations={"THING": {"Enabled": True}})
first = client.describe_event_configurations()
assert _enabled_event_types(client) == {"THING"}
client.update_event_configurations(
eventConfigurations={"THING_GROUP": {"Enabled": True}}
)
assert _enabled_event_types(client) == {"THING", "THING_GROUP"}
second = client.describe_event_configurations()
assert second["creationDate"] == first["creationDate"]
assert second["lastModifiedDate"] >= first["lastModifiedDate"]
# A type named without Enabled is turned off, as on AWS.
client.update_event_configurations(eventConfigurations={"THING": {}})
assert _enabled_event_types(client) == {"THING_GROUP"}
def test_iot_update_event_configurations_rejects_bad_requests():
client = _iot_client_for_fresh_account()
with pytest.raises(ClientError) as ei:
client.update_event_configurations()
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
assert ei.value.response["Error"]["Message"] == "Configuration cannot be null"
with pytest.raises(ClientError) as ei:
client.update_event_configurations(
eventConfigurations={"THING": {"Enabled": True}, "BOGUS": {"Enabled": True}}
)
assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
# A refused update changes nothing.
assert _enabled_event_types(client) == set()
assert "creationDate" not in client.describe_event_configurations()
def test_iot_search_index_requires_indexing_enabled():
"""Searching an account that never enabled indexing is a 404 on AWS."""
client = _iot_client_for_fresh_account()
name = _unique("unindexed")