Repository navigation
Expand file tree
/
Copy pathtest_sns.py
More file actions
2321 lines (1945 loc) · 87.5 KB
/
Copy pathtest_sns.py
File metadata and controls
2321 lines (1945 loc) · 87.5 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
import io
import json
import os
import time
import urllib.error
import urllib.request
import uuid as _uuid_mod
import zipfile
from urllib.parse import urlencode
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
from conftest import sqs_policy_allow_sns
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
def _regional_client(service: str, region: str):
return boto3.client(
service,
endpoint_url=ENDPOINT,
aws_access_key_id="test",
aws_secret_access_key="test",
region_name=region,
config=Config(region_name=region, retries={"mode": "standard"}),
)
def _make_zip(code: str) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", code)
return buf.getvalue()
_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
def test_sns_create_topic(sns):
resp = sns.create_topic(Name="intg-sns-create")
assert "TopicArn" in resp
assert "intg-sns-create" in resp["TopicArn"]
def test_sns_delete_topic(sns):
arn = sns.create_topic(Name="intg-sns-delete")["TopicArn"]
sns.delete_topic(TopicArn=arn)
topics = sns.list_topics()["Topics"]
assert not any(t["TopicArn"] == arn for t in topics)
def test_sns_list_topics(sns):
sns.create_topic(Name="intg-sns-list-1")
sns.create_topic(Name="intg-sns-list-2")
topics = sns.list_topics()["Topics"]
arns = [t["TopicArn"] for t in topics]
assert any("intg-sns-list-1" in a for a in arns)
assert any("intg-sns-list-2" in a for a in arns)
def test_sns_get_topic_attributes(sns):
arn = sns.create_topic(Name="intg-sns-getattr")["TopicArn"]
resp = sns.get_topic_attributes(TopicArn=arn)
assert resp["Attributes"]["TopicArn"] == arn
assert resp["Attributes"]["DisplayName"] == "" # AWS default is empty, not topic name
def test_sns_topics_are_region_scoped_by_name(sns):
name = f"mr-sns-same-name-{_uuid_mod.uuid4().hex[:8]}"
west = _regional_client("sns", "us-west-2")
east_arn = sns.create_topic(Name=name)["TopicArn"]
west_arn = west.create_topic(Name=name)["TopicArn"]
assert east_arn == f"arn:aws:sns:us-east-1:000000000000:{name}"
assert west_arn == f"arn:aws:sns:us-west-2:000000000000:{name}"
east_arns = [t["TopicArn"] for t in sns.list_topics()["Topics"]]
west_arns = [t["TopicArn"] for t in west.list_topics()["Topics"]]
assert east_arn in east_arns
assert west_arn not in east_arns
assert west_arn in west_arns
assert east_arn not in west_arns
with pytest.raises(ClientError) as exc:
sns.get_topic_attributes(TopicArn=west_arn)
assert exc.value.response["Error"]["Code"] == "NotFound"
def test_sns_set_topic_attributes(sns):
arn = sns.create_topic(Name="intg-sns-setattr")["TopicArn"]
sns.set_topic_attributes(
TopicArn=arn,
AttributeName="DisplayName",
AttributeValue="New Display Name",
)
resp = sns.get_topic_attributes(TopicArn=arn)
assert resp["Attributes"]["DisplayName"] == "New Display Name"
def test_sns_subscribe_email(sns):
arn = sns.create_topic(Name="intg-sns-subemail")["TopicArn"]
resp = sns.subscribe(
TopicArn=arn,
Protocol="email",
)
assert "SubscriptionArn" in resp
def test_sns_subscribe_pending_arn_is_lowercase_with_space(sns):
"""For protocols that require confirmation, AWS returns the literal
lowercase string 'pending confirmation' (with a space) as the
SubscriptionArn until the subscriber confirms — NOT PascalCase
'PendingConfirmation'."""
arn = sns.create_topic(Name="intg-sns-pending-arn")["TopicArn"]
resp = sns.subscribe(
TopicArn=arn,
Protocol="http",
Endpoint="http://example.com/sns-callback",
)
assert resp["SubscriptionArn"] == "pending confirmation", resp["SubscriptionArn"]
def test_sns_unsubscribe(sns):
arn = sns.create_topic(Name="intg-sns-unsub")["TopicArn"]
sub = sns.subscribe(
TopicArn=arn,
Protocol="email",
)
sub_arn = sub["SubscriptionArn"]
sns.unsubscribe(SubscriptionArn=sub_arn)
subs = sns.list_subscriptions_by_topic(TopicArn=arn)["Subscriptions"]
assert not any(s["SubscriptionArn"] == sub_arn for s in subs)
def test_sns_list_subscriptions(sns):
arn = sns.create_topic(Name="intg-sns-listsubs")["TopicArn"]
subs = sns.list_subscriptions()["Subscriptions"]
topic_subs = [s for s in subs if s["TopicArn"] == arn]
assert len(topic_subs) >= 2
def test_sns_list_subscriptions_by_topic(sns):
arn = sns.create_topic(Name="intg-sns-listbytopic")["TopicArn"]
sns.subscribe(
TopicArn=arn,
Protocol="email",
)
subs = sns.list_subscriptions_by_topic(TopicArn=arn)["Subscriptions"]
assert len(subs) >= 1
assert all(s["TopicArn"] == arn for s in subs)
def test_sns_subscription_attributes_are_region_scoped(sns):
west = _regional_client("sns", "us-west-2")
name = f"mr-sns-sub-region-{_uuid_mod.uuid4().hex[:8]}"
east_arn = sns.create_topic(Name=name)["TopicArn"]
west_arn = west.create_topic(Name=name)["TopicArn"]
east_sub = sns.subscribe(
)["SubscriptionArn"]
west_sub = west.subscribe(
)["SubscriptionArn"]
assert sns.get_subscription_attributes(
SubscriptionArn=east_sub,
)["Attributes"]["TopicArn"] == east_arn
assert west.get_subscription_attributes(
SubscriptionArn=west_sub,
)["Attributes"]["TopicArn"] == west_arn
east_subs = [sub["SubscriptionArn"] for sub in sns.list_subscriptions()["Subscriptions"]]
west_subs = [sub["SubscriptionArn"] for sub in west.list_subscriptions()["Subscriptions"]]
assert east_sub in east_subs
assert west_sub not in east_subs
assert west_sub in west_subs
assert east_sub not in west_subs
with pytest.raises(ClientError) as exc:
sns.get_subscription_attributes(SubscriptionArn=west_sub)
assert exc.value.response["Error"]["Code"] == "NotFound"
def test_sns_publish(sns):
arn = sns.create_topic(Name="intg-sns-publish")["TopicArn"]
resp = sns.publish(
TopicArn=arn,
Message="hello sns",
Subject="Test Subject",
)
assert "MessageId" in resp
def test_sns_publish_nonexistent_topic(sns):
fake_arn = "arn:aws:sns:us-east-1:000000000000:intg-sns-nonexist"
with pytest.raises(ClientError) as exc:
sns.publish(TopicArn=fake_arn, Message="fail")
assert exc.value.response["Error"]["Code"] == "NotFound"
def test_sns_sqs_fanout(sns, sqs):
topic_arn = sns.create_topic(Name="intg-sns-fanout")["TopicArn"]
q_url = sqs.create_queue(QueueName="intg-sns-fanout-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
sns.publish(TopicArn=topic_arn, Message="fanout msg", Subject="Fan")
msgs = sqs.receive_message(
QueueUrl=q_url,
MaxNumberOfMessages=1,
WaitTimeSeconds=1,
)
assert len(msgs.get("Messages", [])) == 1
body = json.loads(msgs["Messages"][0]["Body"])
assert body["Message"] == "fanout msg"
assert body["TopicArn"] == topic_arn
@pytest.mark.parametrize("protocol, endpoint", [
("sqs", "not-an-arn"),
("sqs", "arn:aws:rds:us-east-1:000000000000:db:wrong-service"),
("lambda", "arn:aws:sqs:us-east-1:000000000000:wrong-service-q"),
("lambda", "arn:aws:lambda:us-east-1:000000000000:not-function-resource"),
])
def test_sns_subscribe_rejects_invalid_sqs_and_lambda_endpoint_arns(sns, protocol, endpoint):
topic_arn = sns.create_topic(Name=f"intg-sns-invalid-endpoint-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
with pytest.raises(ClientError) as exc:
sns.subscribe(TopicArn=topic_arn, Protocol=protocol, Endpoint=endpoint)
assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
def test_sns_sqs_fanout_does_not_tail_match_foreign_account_endpoint(sns, sqs):
queue_name = f"intg-sns-foreign-tail-{_uuid_mod.uuid4().hex[:8]}"
q_url = sqs.create_queue(QueueName=queue_name)["QueueUrl"]
topic_arn = sns.create_topic(Name=f"intg-sns-foreign-tail-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
sns.subscribe(
TopicArn=topic_arn,
Protocol="sqs",
Endpoint=f"arn:aws:sqs:us-east-1:111111111111:{queue_name}",
)
sns.publish(TopicArn=topic_arn, Message="must-not-tail-match")
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
assert "Messages" not in msgs
def test_sns_sqs_fanout_delivers_to_matching_cross_region_queue_arn(sns):
west_sqs = _regional_client("sqs", "us-west-2")
queue_name = f"intg-sns-cross-region-ok-{_uuid_mod.uuid4().hex[:8]}"
q_url = west_sqs.create_queue(QueueName=queue_name)["QueueUrl"]
q_arn = west_sqs.get_queue_attributes(
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
assert ":us-west-2:" in q_arn
topic_arn = sns.create_topic(Name=f"intg-sns-cross-region-ok-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
west_sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
sns.publish(TopicArn=topic_arn, Message="cross-region-delivery")
msgs = west_sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
assert len(msgs.get("Messages", [])) == 1
body = json.loads(msgs["Messages"][0]["Body"])
assert body["Message"] == "cross-region-delivery"
assert body["TopicArn"] == topic_arn
def test_sns_sqs_fanout_does_not_tail_match_foreign_region_endpoint(sns, sqs):
queue_name = f"intg-sns-cross-region-{_uuid_mod.uuid4().hex[:8]}"
q_url = sqs.create_queue(QueueName=queue_name)["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
west_q_arn = q_arn.replace(":us-east-1:", ":us-west-2:")
topic_arn = sns.create_topic(Name=f"intg-sns-cross-region-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=west_q_arn)
sns.publish(TopicArn=topic_arn, Message="must-not-tail-match-region")
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
assert "Messages" not in msgs
def test_sns_tags(sns):
arn = sns.create_topic(Name="intg-sns-tags")["TopicArn"]
sns.tag_resource(
ResourceArn=arn,
Tags=[
{"Key": "env", "Value": "staging"},
{"Key": "team", "Value": "infra"},
],
)
resp = sns.list_tags_for_resource(ResourceArn=arn)
tags = {t["Key"]: t["Value"] for t in resp["Tags"]}
assert tags["env"] == "staging"
assert tags["team"] == "infra"
sns.untag_resource(ResourceArn=arn, TagKeys=["team"])
resp = sns.list_tags_for_resource(ResourceArn=arn)
tags = {t["Key"]: t["Value"] for t in resp["Tags"]}
assert "team" not in tags
assert tags["env"] == "staging"
def test_sns_create_topic_keeps_its_tags(sns):
arn = sns.create_topic(Name="intg-sns-create-tags", Tags=[{"Key": "env", "Value": "dev"}])["TopicArn"]
assert sns.list_tags_for_resource(ResourceArn=arn)["Tags"] == [{"Key": "env", "Value": "dev"}]
def test_sns_tag_resource_accepts_empty_account_topic_arn(sns):
arn = sns.create_topic(Name=f"intg-sns-empty-account-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
empty_account_arn = arn.replace(":000000000000:", "::")
sns.tag_resource(ResourceArn=empty_account_arn, Tags=[{"Key": "env", "Value": "test"}])
resp = sns.list_tags_for_resource(ResourceArn=arn)
tags = {t["Key"]: t["Value"] for t in resp["Tags"]}
assert tags["env"] == "test"
def test_sns_topic_tag_apis_reject_invalid_arns(sns):
arn = sns.create_topic(Name=f"intg-sns-invalid-tags-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
invalid_cases = [
("not-an-arn", "InvalidParameterException"),
("arn:aws:sns:us-east-1", "InvalidParameterException"),
(arn.replace(":sns:", ":sqs:"), "InvalidParameterException"),
(arn.replace(":000000000000:", ":111111111111:"), "ResourceNotFoundException"),
(arn.replace(":us-east-1:", ":us-west-2:"), "ResourceNotFoundException"),
("arn:aws:sns:us-east-1:000000000000:app/APNS/example", "InvalidParameterException"),
]
for bad_arn, expected_code in invalid_cases:
with pytest.raises(ClientError) as exc:
sns.tag_resource(ResourceArn=bad_arn, Tags=[{"Key": "bad", "Value": "value"}])
assert exc.value.response["Error"]["Code"] == expected_code
resp = sns.list_tags_for_resource(ResourceArn=arn)
assert resp["Tags"] == []
def test_sns_topic_list_and_untag_reject_invalid_arns(sns):
for operation, kwargs in [
(sns.list_tags_for_resource, {}),
(sns.untag_resource, {"TagKeys": ["missing"]}),
]:
with pytest.raises(ClientError) as exc:
operation(ResourceArn="arn:aws:sqs:us-east-1:000000000000:not-a-topic", **kwargs)
assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
def test_sns_subscription_attributes(sns):
arn = sns.create_topic(Name="intg-sns-subattr")["TopicArn"]
sub = sns.subscribe(
TopicArn=arn,
Protocol="email",
)
sub_arn = sub["SubscriptionArn"]
resp = sns.get_subscription_attributes(SubscriptionArn=sub_arn)
assert resp["Attributes"]["Protocol"] == "email"
assert resp["Attributes"]["TopicArn"] == arn
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="RawMessageDelivery",
AttributeValue="true",
)
resp = sns.get_subscription_attributes(SubscriptionArn=sub_arn)
assert resp["Attributes"]["RawMessageDelivery"] == "true"
def test_sns_subscribe_with_raw_message_delivery(sns):
arn = sns.create_topic(Name="intg-sns-sub-raw")["TopicArn"]
sub = sns.subscribe(
TopicArn=arn,
Protocol="email",
Attributes={"RawMessageDelivery": "true"},
)
sub_arn = sub["SubscriptionArn"]
attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
assert attrs["RawMessageDelivery"] == "true"
def test_sns_subscribe_with_subscription_role_arn(sns):
"""SubscriptionRoleArn is a Subscribe and SetSubscriptionAttributes
attribute (the role Firehose subscriptions write with); both calls keep it."""
arn = sns.create_topic(Name="intg-sns-sub-role")["TopicArn"]
sub_arn = sns.subscribe(
Attributes={"SubscriptionRoleArn": "arn:aws:iam::000000000000:role/sub-role-a"},
)["SubscriptionArn"]
attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
assert attrs["SubscriptionRoleArn"] == "arn:aws:iam::000000000000:role/sub-role-a"
sns.set_subscription_attributes(
SubscriptionArn=sub_arn, AttributeName="SubscriptionRoleArn",
AttributeValue="arn:aws:iam::000000000000:role/sub-role-b")
attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
assert attrs["SubscriptionRoleArn"] == "arn:aws:iam::000000000000:role/sub-role-b"
def test_sns_subscribe_with_filter_policy(sns):
arn = sns.create_topic(Name="intg-sns-sub-filter")["TopicArn"]
filter_policy = json.dumps({"event": ["MyEvent"]})
sub = sns.subscribe(
TopicArn=arn,
Protocol="email",
Attributes={"FilterPolicy": filter_policy},
)
sub_arn = sub["SubscriptionArn"]
attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
assert attrs["FilterPolicy"] == filter_policy
def test_sns_sqs_fanout_raw_message_delivery(sns, sqs):
topic_arn = sns.create_topic(Name="intg-sns-fanout-raw")["TopicArn"]
q_url = sqs.create_queue(QueueName="intg-sns-fanout-raw-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(
TopicArn=topic_arn,
Protocol="sqs",
Endpoint=q_arn,
Attributes={"RawMessageDelivery": "true"},
)
message_attrs = {
"type": {"DataType": "String", "StringValue": "user.created"},
}
sns.publish(
TopicArn=topic_arn,
Message='{"user_id": "123"}',
MessageAttributes=message_attrs,
)
msgs = sqs.receive_message(
QueueUrl=q_url,
MaxNumberOfMessages=1,
WaitTimeSeconds=1,
MessageAttributeNames=["All"],
)
assert len(msgs.get("Messages", [])) == 1
msg = msgs["Messages"][0]
assert msg["Body"] == '{"user_id": "123"}'
assert msg["MessageAttributes"] == message_attrs
assert msg["MessageAttributes"]["type"]["StringValue"] == "user.created"
def test_sns_publish_batch(sns):
arn = sns.create_topic(Name="intg-sns-batch")["TopicArn"]
resp = sns.publish_batch(
TopicArn=arn,
PublishBatchRequestEntries=[
{"Id": "msg1", "Message": "batch message 1"},
{"Id": "msg2", "Message": "batch message 2"},
{"Id": "msg3", "Message": "batch message 3"},
],
)
assert len(resp["Successful"]) == 3
assert len(resp.get("Failed", [])) == 0
def test_sns_to_lambda_fanout(lam, sns):
"""SNS publish with lambda protocol delivers to the function."""
import uuid as _uuid_mod
fn = f"intg-sns-lam-{_uuid_mod.uuid4().hex[:8]}"
# Handler records the event on a module-level list so we can inspect it
code = "received = []\ndef handler(event, context):\n received.append(event)\n return {'ok': True}\n"
lam.create_function(
FunctionName=fn,
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
func_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"
topic_arn = sns.create_topic(Name=f"intg-sns-lam-topic-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
sns.subscribe(TopicArn=topic_arn, Protocol="lambda", Endpoint=func_arn)
# Publish — should not raise; Lambda invoked synchronously
resp = sns.publish(TopicArn=topic_arn, Message="hello-lambda")
assert "MessageId" in resp
def test_sns_to_lambda_delivery_is_async(lam, sns, sqs):
"""SNS→Lambda delivery must not block Publish on the subscriber.
Regression: lambda fanout invoked the subscriber synchronously inside
Publish, so a slow (or hung) subscriber Lambda stalled the Publish call and
its upstream caller (e.g. a Step Functions task that publishes a
notification). AWS delivers SNS→Lambda asynchronously: Publish returns
immediately and the subscriber runs in the background.
"""
import time
import uuid as _uuid
qname = f"sns-async-signal-{_uuid.uuid4().hex[:8]}"
q_url = sqs.create_queue(QueueName=qname)["QueueUrl"]
fn = f"intg-sns-async-{_uuid.uuid4().hex[:8]}"
# The subscriber simulates a slow handler (sleep) and then signals receipt
# out-of-band via SQS so the test can confirm eventual delivery.
code = (
"import os, time, boto3\n"
f"QNAME = {qname!r}\n"
"def handler(event, context):\n"
" time.sleep(5)\n"
" sqs = boto3.client('sqs', endpoint_url=os.environ['AWS_ENDPOINT_URL'])\n"
" url = sqs.get_queue_url(QueueName=QNAME)['QueueUrl']\n"
" sqs.send_message(QueueUrl=url, MessageBody='delivered')\n"
" return {'ok': True}\n"
)
lam.create_function(
FunctionName=fn,
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Timeout=30,
Code={"ZipFile": _make_zip(code)},
)
func_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"
topic_arn = sns.create_topic(
Name=f"intg-sns-async-topic-{_uuid.uuid4().hex[:8]}"
)["TopicArn"]
sns.subscribe(TopicArn=topic_arn, Protocol="lambda", Endpoint=func_arn)
start = time.time()
resp = sns.publish(TopicArn=topic_arn, Message="async-check")
elapsed = time.time() - start
assert "MessageId" in resp
# Publish must return well before the subscriber's 5s sleep completes; a
# synchronous fanout would block here for the cold start plus the sleep.
assert elapsed < 3.0, f"Publish blocked on the subscriber ({elapsed:.1f}s)"
# The subscriber still runs in the background and eventually signals.
deadline = time.time() + 30
received = False
while time.time() < deadline:
msgs = sqs.receive_message(
QueueUrl=q_url, WaitTimeSeconds=1, MaxNumberOfMessages=1
).get("Messages", [])
if msgs:
received = True
break
assert received, "subscriber Lambda was never delivered the SNS message"
def test_sns_to_lambda_event_subscription_arn(lam, sns):
"""SNS→Lambda fanout must set EventSubscriptionArn to the real subscription ARN."""
import uuid as _uuid_mod
fn = f"intg-sns-suborn-{_uuid_mod.uuid4().hex[:8]}"
received = []
code = (
"import json, os\nreceived = []\ndef handler(event, context):\n received.append(event)\n return event\n"
)
lam.create_function(
FunctionName=fn,
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
func_arn = f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"
topic_arn = sns.create_topic(Name=f"intg-sns-suborn-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
sub_resp = sns.subscribe(TopicArn=topic_arn, Protocol="lambda", Endpoint=func_arn)
sub_arn = sub_resp["SubscriptionArn"]
sns.publish(TopicArn=topic_arn, Message="test-sub-arn")
# Invoke the function directly and check what event it last received
import json
result = lam.invoke(FunctionName=fn, Payload=json.dumps({"ping": True}).encode())
# The subscription ARN should be a real ARN, not "{topic}:subscription"
assert sub_arn != f"{topic_arn}:subscription"
assert sub_arn.startswith(topic_arn)
def test_sns_filter_policy_blocks_non_matching(sns, sqs):
"""SNS filter policy prevents delivery when message attributes don't match."""
topic_arn = sns.create_topic(Name="qa-sns-filter")["TopicArn"]
q_url = sqs.create_queue(QueueName="qa-sns-filter-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sub_arn = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)["SubscriptionArn"]
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="FilterPolicy",
AttributeValue=json.dumps({"color": ["blue"]}),
)
sns.publish(
TopicArn=topic_arn,
Message="red message",
MessageAttributes={"color": {"DataType": "String", "StringValue": "red"}},
)
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)
assert len(msgs.get("Messages", [])) == 0, "Filtered message must not be delivered"
sns.publish(
TopicArn=topic_arn,
Message="blue message",
MessageAttributes={"color": {"DataType": "String", "StringValue": "blue"}},
)
msgs2 = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
assert len(msgs2.get("Messages", [])) == 1
body = json.loads(msgs2["Messages"][0]["Body"])
assert body["Message"] == "blue message"
def test_sns_filter_policy_or_operator(sns, sqs):
"""A top-level $or matches when any of its member policies matches; a
message satisfying neither is filtered out (AWS $or operator)."""
topic_arn = sns.create_topic(Name="qa-sns-or")["TopicArn"]
q_url = sqs.create_queue(QueueName="qa-sns-or-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sub_arn = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)["SubscriptionArn"]
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="FilterPolicy",
AttributeValue=json.dumps({
"$or": [
{"operation": ["event-broadcast"], "environment": ["ENV1"]},
{"operation": ["session-operation"], "environment": ["ENV1"],
"session_id": ["abc-123"]},
]
}),
)
def _attrs(**kv):
return {k: {"DataType": "String", "StringValue": v} for k, v in kv.items()}
# Matches the first $or member.
sns.publish(TopicArn=topic_arn, Message="first",
MessageAttributes=_attrs(operation="event-broadcast", environment="ENV1"))
# Matches the second $or member.
sns.publish(TopicArn=topic_arn, Message="second",
MessageAttributes=_attrs(operation="session-operation", environment="ENV1",
session_id="abc-123"))
# Matches neither (wrong environment).
sns.publish(TopicArn=topic_arn, Message="third",
MessageAttributes=_attrs(operation="event-broadcast", environment="ENV2"))
received = []
for _ in range(3):
resp = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=10, WaitTimeSeconds=1)
received.extend(json.loads(m["Body"])["Message"] for m in resp.get("Messages", []))
assert sorted(received) == ["first", "second"]
def test_sns_raw_message_delivery(sns, sqs):
"""RawMessageDelivery=true delivers raw message body, not SNS envelope."""
topic_arn = sns.create_topic(Name="qa-sns-raw")["TopicArn"]
q_url = sqs.create_queue(QueueName="qa-sns-raw-q")["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sub_arn = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)["SubscriptionArn"]
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="RawMessageDelivery",
AttributeValue="true",
)
sns.publish(TopicArn=topic_arn, Message="raw-body")
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=1)
assert len(msgs["Messages"]) == 1
assert msgs["Messages"][0]["Body"] == "raw-body"
def test_sns_publish_batch_distinct_ids(sns):
"""PublishBatch with duplicate IDs must fail with BatchEntryIdsNotDistinct."""
arn = sns.create_topic(Name="qa-sns-batch-dup")["TopicArn"]
with pytest.raises(ClientError) as exc:
sns.publish_batch(
TopicArn=arn,
PublishBatchRequestEntries=[
{"Id": "same", "Message": "msg1"},
{"Id": "same", "Message": "msg2"},
],
)
assert exc.value.response["Error"]["Code"] == "BatchEntryIdsNotDistinct"
def test_sns_fifo_dedup_passthrough(sns, sqs):
"""SNS FIFO topic passes MessageGroupId through to the SQS FIFO subscriber."""
topic_arn = sns.create_topic(
Name="intg-sns-fifo-dedup.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "false"},
)["TopicArn"]
q_url = sqs.create_queue(
QueueName="intg-sns-fifo-dedup-q.fifo",
Attributes={"FifoQueue": "true"},
)["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
sns.publish(
TopicArn=topic_arn,
Message="fifo-dedup-test",
MessageGroupId="grp-1",
MessageDeduplicationId="dedup-001",
)
msgs = sqs.receive_message(
QueueUrl=q_url,
MaxNumberOfMessages=1,
WaitTimeSeconds=2,
AttributeNames=["All"],
)
assert len(msgs.get("Messages", [])) == 1
msg = msgs["Messages"][0]
body = json.loads(msg["Body"])
assert body["Message"] == "fifo-dedup-test"
attrs = msg.get("Attributes", {})
assert attrs.get("MessageGroupId") == "grp-1"
def test_sns_to_sqs_fanout(sns, sqs):
"""SNS publish fans out to multiple SQS subscribers."""
topic_arn = sns.create_topic(Name="intg-fanout-topic")["TopicArn"]
q1_url = sqs.create_queue(QueueName="intg-fanout-q1")["QueueUrl"]
q2_url = sqs.create_queue(QueueName="intg-fanout-q2")["QueueUrl"]
q1_arn = sqs.get_queue_attributes(QueueUrl=q1_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
q2_arn = sqs.get_queue_attributes(QueueUrl=q2_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
for _q_url, _q_arn in ((q1_url, q1_arn), (q2_url, q2_arn)):
sqs.set_queue_attributes(
QueueUrl=_q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(_q_arn, topic_arn))})
sub1 = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q1_arn)
sub2 = sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q2_arn)
assert sub1["SubscriptionArn"] != "PendingConfirmation"
assert sub2["SubscriptionArn"] != "PendingConfirmation"
sns.publish(TopicArn=topic_arn, Message="fanout-test-msg", Subject="IntgTest")
# Both queues should receive the message
for q_url, q_name in [(q1_url, "q1"), (q2_url, "q2")]:
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=2)
assert len(msgs.get("Messages", [])) == 1, f"{q_name} should have received the message"
body = json.loads(msgs["Messages"][0]["Body"])
assert body["Message"] == "fanout-test-msg"
assert body["TopicArn"] == topic_arn
assert body["Subject"] == "IntgTest"
assert body["Type"] == "Notification"
# ---------------------------------------------------------------------------
# FIFO Topic Creation Tests
# ---------------------------------------------------------------------------
def test_sns_fifo_create_topic_with_fifo_suffix_and_attribute(sns):
"""Creating a FIFO topic with .fifo suffix and FifoTopic=true succeeds."""
resp = sns.create_topic(
Name="intg-fifo-create.fifo",
Attributes={"FifoTopic": "true"},
)
arn = resp["TopicArn"]
assert arn.endswith("intg-fifo-create.fifo")
attrs = sns.get_topic_attributes(TopicArn=arn)["Attributes"]
assert attrs["FifoTopic"] == "true"
def test_sns_fifo_create_topic_without_fifo_suffix_returns_error(sns):
"""Creating a topic with FifoTopic=true but no .fifo suffix returns InvalidParameterException."""
with pytest.raises(ClientError) as exc:
sns.create_topic(
Name="intg-fifo-no-suffix",
Attributes={"FifoTopic": "true"},
)
assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
def test_sns_fifo_auto_detect_from_suffix(sns):
"""Creating a topic with .fifo suffix auto-detects as FIFO even without explicit FifoTopic attribute."""
resp = sns.create_topic(Name="intg-fifo-autodetect.fifo")
arn = resp["TopicArn"]
attrs = sns.get_topic_attributes(TopicArn=arn)["Attributes"]
assert attrs["FifoTopic"] == "true"
def test_sns_fifo_content_based_dedup_defaults_to_false(sns):
"""ContentBasedDeduplication defaults to 'false' for FIFO topics when not explicitly provided."""
resp = sns.create_topic(
Name="intg-fifo-cbd-default.fifo",
Attributes={"FifoTopic": "true"},
)
arn = resp["TopicArn"]
attrs = sns.get_topic_attributes(TopicArn=arn)["Attributes"]
assert attrs["ContentBasedDeduplication"] == "false"
def test_sns_fifo_content_based_dedup_set_to_true(sns):
"""ContentBasedDeduplication can be set to 'true' at creation time."""
resp = sns.create_topic(
Name="intg-fifo-cbd-true.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "true"},
)
arn = resp["TopicArn"]
attrs = sns.get_topic_attributes(TopicArn=arn)["Attributes"]
assert attrs["ContentBasedDeduplication"] == "true"
def test_sns_fifo_get_topic_attributes_returns_fifo_attrs(sns):
"""GetTopicAttributes returns all FIFO-related attributes correctly."""
resp = sns.create_topic(
Name="intg-fifo-getattrs.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "true"},
)
arn = resp["TopicArn"]
attrs = sns.get_topic_attributes(TopicArn=arn)["Attributes"]
assert attrs["TopicArn"] == arn
assert attrs["FifoTopic"] == "true"
assert attrs["ContentBasedDeduplication"] == "true"
# Standard attributes should still be present
assert "Owner" in attrs
assert "Policy" in attrs
# ---------------------------------------------------------------------------
# FIFO Publish Validation Tests
# ---------------------------------------------------------------------------
def test_sns_fifo_publish_without_message_group_id_returns_error(sns):
"""Publishing to a FIFO topic without MessageGroupId returns InvalidParameterException."""
arn = sns.create_topic(
Name="intg-fifo-pub-no-grp.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "true"},
)["TopicArn"]
with pytest.raises(ClientError) as exc:
sns.publish(TopicArn=arn, Message="missing group id")
assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
def test_sns_fifo_publish_without_dedup_id_cbd_false_returns_error(sns):
"""Publishing to a FIFO topic (CBD=false) without MessageDeduplicationId returns error."""
arn = sns.create_topic(
Name="intg-fifo-pub-no-dedup.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "false"},
)["TopicArn"]
with pytest.raises(ClientError) as exc:
sns.publish(
TopicArn=arn,
Message="missing dedup id",
MessageGroupId="grp-1",
)
assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
def test_sns_standard_topic_publish_without_message_group_id_succeeds(sns):
"""Publishing to a standard topic without MessageGroupId succeeds normally."""
arn = sns.create_topic(Name="intg-std-pub-no-grp")["TopicArn"]
resp = sns.publish(TopicArn=arn, Message="standard topic message")
assert "MessageId" in resp
def test_sns_fifo_publish_with_valid_params_returns_sequence_number(sns):
"""Publishing to a FIFO topic with valid params succeeds and returns SequenceNumber."""
arn = sns.create_topic(
Name="intg-fifo-pub-seq.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "false"},
)["TopicArn"]
resp = sns.publish(
TopicArn=arn,
Message="fifo message with seq",
MessageGroupId="grp-1",
MessageDeduplicationId="dedup-seq-001",
)
assert "MessageId" in resp
assert "SequenceNumber" in resp
# Sequence number should be a zero-padded numeric string
assert resp["SequenceNumber"].isdigit()
assert len(resp["SequenceNumber"]) == 20
def test_sns_standard_topic_publish_response_omits_sequence_number(sns):
"""Standard topic publish response does not include SequenceNumber."""
arn = sns.create_topic(Name="intg-std-pub-no-seq")["TopicArn"]
resp = sns.publish(TopicArn=arn, Message="standard topic no seq")
assert "MessageId" in resp
assert "SequenceNumber" not in resp
# ---------------------------------------------------------------------------
# FIFO Deduplication and Sequence Number Tests
# ---------------------------------------------------------------------------
def test_sns_fifo_explicit_dedup_id_returns_same_result_on_duplicate(sns):
"""Publishing the same MessageDeduplicationId twice returns the same MessageId and SequenceNumber."""
arn = sns.create_topic(
Name="intg-fifo-dedup-same.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "false"},
)["TopicArn"]
resp1 = sns.publish(
TopicArn=arn,
Message="first publish",
MessageGroupId="grp-1",
MessageDeduplicationId="dedup-same-001",
)
resp2 = sns.publish(
TopicArn=arn,
Message="second publish different body",
MessageGroupId="grp-1",
MessageDeduplicationId="dedup-same-001",
)
assert resp1["MessageId"] == resp2["MessageId"]
assert resp1["SequenceNumber"] == resp2["SequenceNumber"]
def test_sns_fifo_cbd_dedup_subscriber_gets_one_message(sns, sqs):
"""CBD=true with same body twice deduplicates — subscriber receives only one message."""
topic_arn = sns.create_topic(
Name="intg-fifo-cbd-dedup.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "true"},
)["TopicArn"]
q_url = sqs.create_queue(
QueueName="intg-fifo-cbd-dedup-q.fifo",
Attributes={"FifoQueue": "true"},
)["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
sqs.set_queue_attributes(
QueueUrl=q_url,
Attributes={"Policy": json.dumps(sqs_policy_allow_sns(q_arn, topic_arn))})
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=q_arn)
# Publish the same body twice — CBD will generate the same dedup ID
resp1 = sns.publish(
TopicArn=topic_arn,
Message="identical body for cbd",
MessageGroupId="grp-cbd",
)
resp2 = sns.publish(
TopicArn=topic_arn,
Message="identical body for cbd",
MessageGroupId="grp-cbd",
)
# Both responses should return the same MessageId (dedup hit)
assert resp1["MessageId"] == resp2["MessageId"]
# Subscriber should only receive one message
msgs = sqs.receive_message(
QueueUrl=q_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=2,
)
assert len(msgs.get("Messages", [])) == 1
body = json.loads(msgs["Messages"][0]["Body"])
assert body["Message"] == "identical body for cbd"
def test_sns_fifo_explicit_dedup_id_overrides_cbd(sns):
"""Explicit MessageDeduplicationId is used regardless of CBD setting."""
arn = sns.create_topic(
Name="intg-fifo-dedup-override.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "true"},
)["TopicArn"]
# Publish two messages with the same body but different explicit dedup IDs
resp1 = sns.publish(