Debian Codegraph @

tests/test_plugin_sns.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 # Disable logging for a cleaner testing output
29 import logging
30 import sys
31 from unittest import mock
32
33 from helpers import AppriseURLTester
34 import pytest
35 import requests
36
37 from apprise import Apprise
38 from apprise.exception import AppriseImproperlyConfigured
39 from apprise.plugins.base import _delivery_tracker
40 from apprise.plugins.sns import NotifySNS, SNSMode
41
42 logging.disable(logging.CRITICAL)
43
44
45 TEST_ACCESS_KEY_ID = "AHIAJGNT76XIMXDBIJYA"
46 TEST_ACCESS_KEY_SECRET = "bu1dHSdO22pfaaVy/wmNsdljF4C07D3bndi9PQJ9"
47 TEST_REGION = "us-east-2"
48
49 # A realistic-looking (but fake) AWS session token
50 TEST_SESSION_TOKEN = "FwoGZXIvYXdz+SESSION/TOKENABCDEFGHIJKLMNOPQRS="
51
52 # Our Testing URLs
53 apprise_url_tests = (
54 (
55 "sns://",
56 {
57 "instance": AppriseImproperlyConfigured,
58 },
59 ),
60 (
61 "sns://:@/",
62 {
63 "instance": AppriseImproperlyConfigured,
64 },
65 ),
66 (
67 "sns://T1JJ3T3L2",
68 {
69 # Just Token 1 provided
70 "instance": AppriseImproperlyConfigured,
71 },
72 ),
73 (
74 "sns://T1JJ3TD4JD/TIiajkdnlazk7FQ/",
75 {
76 # Missing a region
77 "instance": AppriseImproperlyConfigured,
78 },
79 ),
80 (
81 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
82 {
83 # we have a valid URL and one number to text
84 "instance": NotifySNS,
85 },
86 ),
87 (
88 (
89 "sns://?access=T1JJ3T3L2&secret=A1BRTD4JD/TIiajkdnlazkcevi7FQ"
90 "&region=us-west-2&to=12223334444"
91 ),
92 {
93 # Initialize using get parameters instead
94 "instance": NotifySNS,
95 },
96 ),
97 (
98 "sns://T1JJ3TD4JD/TIiajkdnlazk7FQ/us-west-2/12223334444/12223334445",
99 {
100 # Multi SNS Suppport
101 "instance": NotifySNS,
102 # Our expected url(privacy=True) startswith() response:
103 "privacy_url": "sns://T...D/****/us-west-2",
104 },
105 ),
106 (
107 (
108 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcOXrIdevi7FQ/us-east-1"
109 "?to=12223334444"
110 ),
111 {
112 # Missing a topic and/or phone No
113 "instance": NotifySNS,
114 },
115 ),
116 (
117 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
118 {
119 "instance": NotifySNS,
120 # throw a bizarre code forcing us to fail to look it up
121 "response": False,
122 "requests_response_code": 999,
123 },
124 ),
125 (
126 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/15556667777",
127 {
128 "instance": NotifySNS,
129 # Throws a series of i/o exceptions with this flag
130 # is set and tests that we gracefully handle them
131 "test_requests_exceptions": True,
132 },
133 ),
134 (
135 # Session token in userinfo position (temporary/IAM credentials)
136 "sns://SESSIONTOKEN@T1JJ3T3L2"
137 "/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
138 {
139 "instance": NotifySNS,
140 },
141 ),
142 (
143 # Session token via ?token= query parameter
144 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
145 "/us-west-2/12223334444?token=SESSIONTOKEN",
146 {
147 "instance": NotifySNS,
148 },
149 ),
150 (
151 # Access key via ?key= alias
152 "sns://?key=T1JJ3T3L2&secret=A1BRTD4JD/TIiajkdnlazkcevi7FQ"
153 "&region=us-west-2&to=12223334444",
154 {
155 "instance": NotifySNS,
156 },
157 ),
158 (
159 # Session token + HTTP error
160 "sns://SESSIONTOKEN@T1JJ3T3L2"
161 "/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/12223334444",
162 {
163 "instance": NotifySNS,
164 "response": False,
165 "requests_response_code": 999,
166 },
167 ),
168 (
169 # Session token + request exceptions
170 "sns://SESSIONTOKEN@T1JJ3T3L2"
171 "/A1BRTD4JD/TIiajkdnlazkcevi7FQ/us-west-2/15556667777",
172 {
173 "instance": NotifySNS,
174 "test_requests_exceptions": True,
175 },
176 ),
177 (
178 # Explicit SMS mode
179 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
180 "/us-west-2/12223334444?mode=sms",
181 {
182 "instance": NotifySNS,
183 },
184 ),
185 (
186 # Forced topic mode on a phone target
187 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
188 "/us-west-2/12223334444?mode=topic",
189 {
190 "instance": NotifySNS,
191 },
192 ),
193 (
194 # Invalid mode
195 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkcevi7FQ"
196 "/us-west-2/12223334444?mode=invalid",
197 {
198 "instance": AppriseImproperlyConfigured,
199 },
200 ),
201 )
202
203
204 def test_plugin_sns_urls():
205 """NotifySNS() Apprise URLs."""
206
207 # Run our general tests
208 AppriseURLTester(tests=apprise_url_tests).run_all()
209
210
211 # We initialize a post object just incase a test fails below
212 # we don't want it sending any notifications upstream
213 @mock.patch("requests.post")
214 def test_plugin_sns_edge_cases(mock_post):
215 """NotifySNS() Edge Cases."""
216 target = "+1800555999"
217 # Initializes the plugin with a valid access, but invalid access key
218 with pytest.raises(AppriseImproperlyConfigured):
219 # No access_key_id specified
220 NotifySNS(
221 access_key_id=None,
222 secret_access_key=TEST_ACCESS_KEY_SECRET,
223 region_name=TEST_REGION,
224 targets=target,
225 )
226
227 with pytest.raises(AppriseImproperlyConfigured):
228 # No secret_access_key specified
229 NotifySNS(
230 access_key_id=TEST_ACCESS_KEY_ID,
231 secret_access_key=None,
232 region_name=TEST_REGION,
233 targets=target,
234 )
235
236 with pytest.raises(AppriseImproperlyConfigured):
237 # No region_name specified
238 NotifySNS(
239 access_key_id=TEST_ACCESS_KEY_ID,
240 secret_access_key=TEST_ACCESS_KEY_SECRET,
241 region_name=None,
242 targets=target,
243 )
244
245 # No recipients
246 obj = NotifySNS(
247 access_key_id=TEST_ACCESS_KEY_ID,
248 secret_access_key=TEST_ACCESS_KEY_SECRET,
249 region_name=TEST_REGION,
250 targets=None,
251 )
252
253 # The object initializes properly but would not be able to send anything
254 assert bool(obj.notify(body="test", title="test")) is False
255
256 # The phone number is invalid, and without it, there is nothing
257 # to notify
258 obj = NotifySNS(
259 access_key_id=TEST_ACCESS_KEY_ID,
260 secret_access_key=TEST_ACCESS_KEY_SECRET,
261 region_name=TEST_REGION,
262 targets="+1809",
263 )
264
265 # The object initializes properly but would not be able to send anything
266 assert bool(obj.notify(body="test", title="test")) is False
267
268 # The phone number is invalid, and without it, there is nothing
269 # to notify; we
270 obj = NotifySNS(
271 access_key_id=TEST_ACCESS_KEY_ID,
272 secret_access_key=TEST_ACCESS_KEY_SECRET,
273 region_name=TEST_REGION,
274 targets="#(invalid-topic-because-of-the-brackets)",
275 )
276
277 # The object initializes properly but would not be able to send anything
278 assert bool(obj.notify(body="test", title="test")) is False
279
280
281 def test_plugin_sns_url_parsing():
282 """NotifySNS() URL Parsing."""
283
284 # No recipients
285 results = NotifySNS.parse_url(
286 f"sns://{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}/{TEST_REGION}/"
287 )
288
289 # Confirm that there were no recipients found
290 assert len(results["targets"]) == 0
291 assert "region_name" in results
292 assert results["region_name"] == TEST_REGION
293 assert "access_key_id" in results
294 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
295 assert "secret_access_key" in results
296 assert results["secret_access_key"] == TEST_ACCESS_KEY_SECRET
297
298 target = "+18001234567"
299 topic = "MyTopic"
300
301 # Detect recipients
302 results = NotifySNS.parse_url(
303 f"sns://{TEST_ACCESS_KEY_ID}/"
304 f"{TEST_ACCESS_KEY_SECRET}/"
305 f"{TEST_REGION.upper()}/"
306 f"{target}/"
307 f"{topic}/"
308 )
309
310 # Confirm that our recipients were found
311 assert len(results["targets"]) == 2
312 assert target in results["targets"]
313 assert topic in results["targets"]
314 assert "region_name" in results
315 assert results["region_name"] == TEST_REGION
316 assert "access_key_id" in results
317 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
318 assert "secret_access_key" in results
319 assert results["secret_access_key"] == TEST_ACCESS_KEY_SECRET
320
321
322 def test_plugin_sns_object_parsing():
323 """NotifySNS() Object Parsing."""
324
325 # Create our object
326 a = Apprise()
327
328 # Now test failing variations of our URL
329 assert a.add("sns://") is False
330 assert a.add("sns://nosecret") is False
331 assert a.add("sns://nosecret/noregion/") is False
332
333 # This is valid but without valid recipients; while it's still a valid URL
334 # it won't do much when the user goes to send a notification
335 assert a.add("sns://norecipient/norecipient/us-west-2") is True
336 assert len(a) == 1
337
338 # Parse a good one
339 assert a.add("sns://oh/yeah/us-west-2/abcdtopic/+12223334444") is True
340 assert len(a) == 2
341
342 assert a.add("sns://oh/yeah/us-west-2/12223334444") is True
343 assert len(a) == 3
344
345
346 def test_plugin_sns_aws_response_handling():
347 """NotifySNS() AWS Response Handling."""
348 # Not a string
349 response = NotifySNS.aws_response_to_dict(None)
350 assert response["type"] is None
351 assert response["request_id"] is None
352
353 # Invalid XML
354 response = NotifySNS.aws_response_to_dict(
355 '<Bad Response xmlns="http://sns.amazonaws.com/doc/2010-03-31/">'
356 )
357 assert response["type"] is None
358 assert response["request_id"] is None
359
360 # Single Element in XML
361 response = NotifySNS.aws_response_to_dict(
362 "<SingleElement></SingleElement>"
363 )
364 assert response["type"] == "SingleElement"
365 assert response["request_id"] is None
366
367 # Empty String
368 response = NotifySNS.aws_response_to_dict("")
369 assert response["type"] is None
370 assert response["request_id"] is None
371
372 response = NotifySNS.aws_response_to_dict("""
373 <PublishResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
374 <PublishResult>
375 <MessageId>5e16935a-d1fb-5a31-a716-c7805e5c1d2e</MessageId>
376 </PublishResult>
377 <ResponseMetadata>
378 <RequestId>dc258024-d0e6-56bb-af1b-d4fe5f4181a4</RequestId>
379 </ResponseMetadata>
380 </PublishResponse>
381 """)
382 assert response["type"] == "PublishResponse"
383 assert response["request_id"] == "dc258024-d0e6-56bb-af1b-d4fe5f4181a4"
384 assert response["message_id"] == "5e16935a-d1fb-5a31-a716-c7805e5c1d2e"
385
386 response = NotifySNS.aws_response_to_dict("""
387 <CreateTopicResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
388 <CreateTopicResult>
389 <TopicArn>arn:aws:sns:us-east-1:000000000000:abcd</TopicArn>
390 </CreateTopicResult>
391 <ResponseMetadata>
392 <RequestId>604bef0f-369c-50c5-a7a4-bbd474c83d6a</RequestId>
393 </ResponseMetadata>
394 </CreateTopicResponse>
395 """)
396 assert response["type"] == "CreateTopicResponse"
397 assert response["request_id"] == "604bef0f-369c-50c5-a7a4-bbd474c83d6a"
398 assert response["topic_arn"] == "arn:aws:sns:us-east-1:000000000000:abcd"
399
400 response = NotifySNS.aws_response_to_dict("""
401 <ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
402 <Error>
403 <Type>Sender</Type>
404 <Code>InvalidParameter</Code>
405 <Message>Invalid parameter: TopicArn or TargetArn Reason:
406 no value for required parameter</Message>
407 </Error>
408 <RequestId>b5614883-babe-56ca-93b2-1c592ba6191e</RequestId>
409 </ErrorResponse>
410 """)
411 assert response["type"] == "ErrorResponse"
412 assert response["request_id"] == "b5614883-babe-56ca-93b2-1c592ba6191e"
413 assert response["error_type"] == "Sender"
414 assert response["error_code"] == "InvalidParameter"
415 assert response["error_message"].startswith("Invalid parameter:")
416 assert response["error_message"].endswith("required parameter")
417
418 # An empty known element (no text at all) doesn't blow up; it's
419 # just treated as blank
420 response = NotifySNS.aws_response_to_dict("""
421 <ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
422 <Error>
423 <Type>Sender</Type>
424 <Code>InvalidParameter</Code>
425 <Message/>
426 </Error>
427 <RequestId>b5614883-babe-56ca-93b2-1c592ba6191e</RequestId>
428 </ErrorResponse>
429 """)
430 assert response["type"] == "ErrorResponse"
431 assert response["error_message"] == ""
432
433 # A response nested far deeper than Python's recursion limit still
434 # parses instead of raising a RecursionError
435 depth = sys.getrecursionlimit() + 1000
436 response = NotifySNS.aws_response_to_dict(
437 ("<RequestId>" * depth)
438 + "b5614883-babe-56ca-93b2-1c592ba6191e"
439 + ("</RequestId>" * depth)
440 )
441 assert response["type"] == "RequestId"
442 assert response["request_id"] == "b5614883-babe-56ca-93b2-1c592ba6191e"
443
444
445 @mock.patch("requests.post")
446 def test_plugin_sns_aws_topic_handling(mock_post):
447 """NotifySNS() AWS Topic Handling."""
448
449 arn_response = """
450 <CreateTopicResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
451 <CreateTopicResult>
452 <TopicArn>arn:aws:sns:us-east-1:000000000000:abcd</TopicArn>
453 </CreateTopicResult>
454 <ResponseMetadata>
455 <RequestId>604bef0f-369c-50c5-a7a4-bbd474c83d6a</RequestId>
456 </ResponseMetadata>
457 </CreateTopicResponse>
458 """
459
460 def post(url, data, **kwargs):
461 """Since Publishing a token requires 2 posts, we need to return our
462 response depending on what step we're on."""
463
464 # A request
465 robj = mock.Mock()
466 robj.text = ""
467 robj.status_code = requests.codes.ok
468
469 if data.find("=CreateTopic") >= 0:
470 # Topic Post Failure
471 robj.status_code = requests.codes.bad_request
472
473 return robj
474
475 # Assign ourselves a new function
476 mock_post.side_effect = post
477
478 # Create our object
479 a = Apprise()
480
481 a.add(
482 [
483 # Single Topic
484 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnl/us-west-2/TopicA",
485 # Multi-Topic
486 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnl/us-east-1/TopicA/TopicB/"
487 # Topic-Mix
488 "sns://T1JJ3T3L2/A1BRTD4JD/TIiajkdnlazkce/us-west-2/"
489 "12223334444/TopicA",
490 ]
491 )
492
493 # CreateTopic fails
494 assert bool(a.notify(title="", body="test")) is False
495
496 def post(url, data, **kwargs):
497 """Since Publishing a token requires 2 posts, we need to return our
498 response depending on what step we're on."""
499
500 # A request
501 robj = mock.Mock()
502 robj.text = ""
503 robj.status_code = requests.codes.ok
504
505 if data.find("=CreateTopic") >= 0:
506 robj.text = arn_response
507
508 # Manipulate Topic Publishing only (not phone)
509 elif data.find("=Publish") >= 0 and data.find("TopicArn=") >= 0:
510 # Topic Post Failure
511 robj.status_code = requests.codes.bad_request
512
513 return robj
514
515 # Assign ourselves a new function
516 mock_post.side_effect = post
517
518 # Publish fails
519 assert bool(a.notify(title="", body="test")) is False
520
521 # Disable our side effect
522 mock_post.side_effect = None
523
524 # Handle case where TopicArn is missing:
525 robj = mock.Mock()
526 robj.text = "<CreateTopicResponse></CreateTopicResponse>"
527 robj.status_code = requests.codes.ok
528
529 # Assign ourselves a new function
530 mock_post.return_value = robj
531 assert bool(a.notify(title="", body="test")) is False
532
533 # Handle case where we fails get a bad response
534 robj = mock.Mock()
535 robj.text = ""
536 robj.status_code = requests.codes.bad_request
537 mock_post.return_value = robj
538 assert bool(a.notify(title="", body="test")) is False
539
540 # Handle case where we get a valid response and TopicARN
541 robj = mock.Mock()
542 robj.text = arn_response
543 robj.status_code = requests.codes.ok
544 mock_post.return_value = robj
545 # We would have failed to make Post
546 assert bool(a.notify(title="", body="test")) is True
547
548
549 @mock.patch("requests.post")
550 def test_plugin_sns_session_token(mock_post):
551 """NotifySNS() session token for temporary/IAM credentials."""
552
553 response = mock.MagicMock()
554 response.status_code = requests.codes.ok
555 response.text = ""
556 mock_post.return_value = response
557
558 # Init with session token
559 obj = NotifySNS(
560 access_key_id=TEST_ACCESS_KEY_ID,
561 secret_access_key=TEST_ACCESS_KEY_SECRET,
562 region_name=TEST_REGION,
563 targets="+18001234567",
564 session_token=TEST_SESSION_TOKEN,
565 )
566 assert obj.aws_session_token == TEST_SESSION_TOKEN
567
568 # send() must include X-Amz-Security-Token in request headers
569 assert bool(obj.notify(body="test")) is True
570 call_kwargs = mock_post.call_args[1]
571 assert "X-Amz-Security-Token" in call_kwargs["headers"]
572 assert call_kwargs["headers"]["X-Amz-Security-Token"] == TEST_SESSION_TOKEN
573
574 # x-amz-security-token must also appear in the Authorization header
575 # (it is listed in SignedHeaders)
576 auth = call_kwargs["headers"]["Authorization"]
577 assert "x-amz-security-token" in auth
578
579 # URL round-trip via userinfo position; + and = stay unencoded
580 # (safe in userinfo); / is encoded since it terminates the netloc
581 url = obj.url()
582 assert "@" in url
583 assert NotifySNS.quote(TEST_SESSION_TOKEN, safe="+=") in url
584
585 results = NotifySNS.parse_url(url)
586 assert results["session_token"] == TEST_SESSION_TOKEN
587 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
588
589 obj2 = NotifySNS(**results)
590 assert obj2.aws_session_token == TEST_SESSION_TOKEN
591 assert obj2.url_identifier == obj.url_identifier
592
593 # Privacy URL must mask the token but keep the @ separator
594 priv_url = obj.url(privacy=True)
595 assert TEST_SESSION_TOKEN not in priv_url
596 assert "@" in priv_url
597
598 # Without a session token no X-Amz-Security-Token header is sent
599 mock_post.reset_mock()
600 obj_plain = NotifySNS(
601 access_key_id=TEST_ACCESS_KEY_ID,
602 secret_access_key=TEST_ACCESS_KEY_SECRET,
603 region_name=TEST_REGION,
604 targets="+18001234567",
605 )
606 assert obj_plain.aws_session_token is None
607 assert bool(obj_plain.notify(body="test")) is True
608 call_kwargs = mock_post.call_args[1]
609 assert "X-Amz-Security-Token" not in call_kwargs["headers"]
610
611 # url() without token has no @ separator
612 plain_url = obj_plain.url()
613 assert "@" not in plain_url
614
615
616 @mock.patch("requests.post")
617 def test_plugin_sns_session_token_via_kwarg(mock_post):
618 """NotifySNS() session token parsed from ?token= kwarg."""
619
620 response = mock.MagicMock()
621 response.status_code = requests.codes.ok
622 response.text = ""
623 mock_post.return_value = response
624
625 url = (
626 f"sns://{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}"
627 f"/{TEST_REGION}/+18001234567?token={TEST_SESSION_TOKEN}"
628 )
629 results = NotifySNS.parse_url(url)
630 assert results["session_token"] == TEST_SESSION_TOKEN
631
632 obj = NotifySNS(**results)
633 assert obj.aws_session_token == TEST_SESSION_TOKEN
634 assert bool(obj.notify(body="test")) is True
635
636 call_kwargs = mock_post.call_args[1]
637 assert call_kwargs["headers"]["X-Amz-Security-Token"] == TEST_SESSION_TOKEN
638
639 # ?token= overrides userinfo when both are present
640 url_both = (
641 f"sns://OTHERTOKEN@{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}"
642 f"/{TEST_REGION}/+18001234567?token={TEST_SESSION_TOKEN}"
643 )
644 results2 = NotifySNS.parse_url(url_both)
645 assert results2["session_token"] == TEST_SESSION_TOKEN
646
647
648 def test_plugin_sns_key_alias():
649 """NotifySNS() ?key= alias for access_key_id."""
650
651 # ?key= resolves to access_key_id
652 url = (
653 f"sns://?key={TEST_ACCESS_KEY_ID}"
654 f"&secret={TEST_ACCESS_KEY_SECRET}"
655 f"&region={TEST_REGION}&to=+18001234567"
656 )
657 results = NotifySNS.parse_url(url)
658 assert results["access_key_id"] == TEST_ACCESS_KEY_ID
659
660 obj = NotifySNS(**results)
661 assert obj.aws_access_key_id == TEST_ACCESS_KEY_ID
662
663 # ?key= takes priority over ?access= when both appear
664 url_both = (
665 f"sns://?key={TEST_ACCESS_KEY_ID}&access=OTHERID"
666 f"&secret={TEST_ACCESS_KEY_SECRET}"
667 f"&region={TEST_REGION}&to=+18001234567"
668 )
669 results2 = NotifySNS.parse_url(url_both)
670 assert results2["access_key_id"] == TEST_ACCESS_KEY_ID
671
672
673 def test_plugin_sns_detailed_failures(mocker):
674 """
675 Test specific failure modes (HTTP 400) for SMS, Topic Creation,
676 and Topic Publishing to ensure error counters are incremented.
677 """
678 from apprise.plugins.sns import NotifySNS
679
680 # Mock requests.post
681 mock_post = mocker.patch("requests.post")
682
683 # --- Scenario 1: SMS (Phone) Failure ---
684 obj_sms = NotifySNS(
685 access_key_id="key",
686 secret_access_key="secret",
687 region_name="us-east-1",
688 targets=["+15555555555"],
689 )
690
691 # Force a 400 Bad Request
692 mock_response_bad = mocker.Mock()
693 mock_response_bad.status_code = 400
694 mock_response_bad.text = (
695 "<ErrorResponse><Error><Message>Fail</Message></Error></ErrorResponse>"
696 )
697
698 mock_response_bad.content = mock_response_bad.text.encode("utf-8")
699 mock_post.return_value = mock_response_bad
700
701 # Should return False because the SMS failed
702 assert bool(obj_sms.notify(body="test")) is False
703
704 # --- Scenario 2: Topic Creation Failure ---
705 obj_topic = NotifySNS(
706 access_key_id="key",
707 secret_access_key="secret",
708 region_name="us-east-1",
709 targets=["#MyTopic"],
710 )
711
712 # Force 400 on ANY request (which includes the first one: CreateTopic)
713 mock_post.return_value = mock_response_bad
714
715 # Should return False because CreateTopic failed
716 assert bool(obj_topic.notify(body="test")) is False
717
718 # --- Scenario 3: CreateTopic Success, but Publish Failure ---
719 # We need a side_effect to return 200 for the first call (CreateTopic)
720 # and 400 for the second (Publish)
721
722 mock_response_ok = mocker.Mock()
723 mock_response_ok.status_code = 200
724 mock_response_ok.text = """
725 <CreateTopicResponse>
726 <CreateTopicResult>
727 <TopicArn>arn:aws:sns:us-east-1:123456789012:MyTopic</TopicArn>
728 </CreateTopicResult>
729 </CreateTopicResponse>
730 """
731 mock_response_ok.content = mock_response_ok.text.encode("utf-8")
732
733 def side_effect(*args, **kwargs):
734 data = kwargs.get("data", "")
735 if "Action=CreateTopic" in data:
736 return mock_response_ok
737 if "Action=Publish" in data:
738 return mock_response_bad
739 return mock_response_ok
740
741 mock_post.side_effect = side_effect
742
743 # Should return False because Publish failed
744 assert bool(obj_topic.notify(body="test")) is False
745
746
747 def test_plugin_sns_failed_publish_is_retried():
748 """A failed topic publish is not recorded as delivered."""
749
750 obj = NotifySNS(
751 access_key_id="key",
752 secret_access_key="secret",
753 region_name="us-east-1",
754 targets=["#MyTopic"],
755 )
756 topic = obj.topics[0]
757
758 tracker_token = _delivery_tracker.set(set())
759 try:
760 with mock.patch.object(
761 obj,
762 "_post",
763 side_effect=[
764 (True, {"topic_arn": "arn:test"}),
765 (False, {}),
766 ],
767 ):
768 assert obj.send(body="test") is False
769
770 assert obj.is_delivered(topic) is False
771
772 with mock.patch.object(
773 obj,
774 "_post",
775 side_effect=[
776 (True, {"topic_arn": "arn:test"}),
777 (True, {}),
778 ],
779 ):
780 assert obj.send(body="test") is True
781
782 assert obj.is_delivered(topic) is True
783 finally:
784 _delivery_tracker.reset(tracker_token)
785
786
787 def test_plugin_sns_mode_detection():
788 """NotifySNS() auto-detects and validates operating mode."""
789
790 # Topic-only targets -> TOPIC mode auto-detected
791 obj = NotifySNS(
792 access_key_id=TEST_ACCESS_KEY_ID,
793 secret_access_key=TEST_ACCESS_KEY_SECRET,
794 region_name=TEST_REGION,
795 targets=["#MyTopic"],
796 )
797 assert obj.mode == SNSMode.TOPIC
798 assert obj.title_maxlen == 100
799 assert obj.body_maxlen == 256000
800
801 # Phone targets -> SMS mode auto-detected
802 obj = NotifySNS(
803 access_key_id=TEST_ACCESS_KEY_ID,
804 secret_access_key=TEST_ACCESS_KEY_SECRET,
805 region_name=TEST_REGION,
806 targets=["+18001234567"],
807 )
808 assert obj.mode == SNSMode.SMS
809 assert obj.title_maxlen == 0
810 assert obj.body_maxlen == 160
811
812 # Mixed targets -> SMS mode (safe default)
813 obj = NotifySNS(
814 access_key_id=TEST_ACCESS_KEY_ID,
815 secret_access_key=TEST_ACCESS_KEY_SECRET,
816 region_name=TEST_REGION,
817 targets=["+18001234567", "#MyTopic"],
818 )
819 assert obj.mode == SNSMode.SMS
820
821 # No targets -> SMS mode (safe default)
822 obj = NotifySNS(
823 access_key_id=TEST_ACCESS_KEY_ID,
824 secret_access_key=TEST_ACCESS_KEY_SECRET,
825 region_name=TEST_REGION,
826 targets=[],
827 )
828 assert obj.mode == SNSMode.SMS
829
830 # Explicit mode=topic overrides auto-detection for phone-only URL
831 obj = NotifySNS(
832 access_key_id=TEST_ACCESS_KEY_ID,
833 secret_access_key=TEST_ACCESS_KEY_SECRET,
834 region_name=TEST_REGION,
835 targets=["+18001234567"],
836 mode=SNSMode.TOPIC,
837 )
838 assert obj.mode == SNSMode.TOPIC
839
840 # Explicit mode=sms overrides auto-detection for topic-only URL
841 obj = NotifySNS(
842 access_key_id=TEST_ACCESS_KEY_ID,
843 secret_access_key=TEST_ACCESS_KEY_SECRET,
844 region_name=TEST_REGION,
845 targets=["#MyTopic"],
846 mode=SNSMode.SMS,
847 )
848 assert obj.mode == SNSMode.SMS
849
850 # Prefix matching: "to" -> "topic"
851 obj = NotifySNS(
852 access_key_id=TEST_ACCESS_KEY_ID,
853 secret_access_key=TEST_ACCESS_KEY_SECRET,
854 region_name=TEST_REGION,
855 targets=["#MyTopic"],
856 mode="to",
857 )
858 assert obj.mode == SNSMode.TOPIC
859
860 # An invalid mode is rejected.
861 with pytest.raises(AppriseImproperlyConfigured):
862 NotifySNS(
863 access_key_id=TEST_ACCESS_KEY_ID,
864 secret_access_key=TEST_ACCESS_KEY_SECRET,
865 region_name=TEST_REGION,
866 targets=["#MyTopic"],
867 mode="invalid",
868 )
869
870
871 @mock.patch("requests.post")
872 def test_plugin_sns_topic_mode_send(mock_post):
873 """NotifySNS() TOPIC mode sets Subject field on topic payloads."""
874
875 arn_response = (
876 "<CreateTopicResponse>"
877 "<CreateTopicResult>"
878 "<TopicArn>"
879 "arn:aws:sns:us-east-2:000000000000:MyTopic"
880 "</TopicArn>"
881 "</CreateTopicResult>"
882 "</CreateTopicResponse>"
883 )
884
885 # Capture the most recent Publish payload for inspection
886 publish_data = {}
887
888 def side_effect(url, data, **kwargs):
889 """Return ARN on CreateTopic; record payload on Publish."""
890 robj = mock.Mock()
891 robj.status_code = requests.codes.ok
892 if "Action=CreateTopic" in data:
893 robj.text = arn_response
894 elif "Action=Publish" in data:
895 publish_data["data"] = data
896 robj.text = ""
897 else:
898 robj.text = ""
899 return robj
900
901 mock_post.side_effect = side_effect
902
903 # Topic-only -> TOPIC mode auto-detected; title goes to Subject
904 obj = NotifySNS(
905 access_key_id=TEST_ACCESS_KEY_ID,
906 secret_access_key=TEST_ACCESS_KEY_SECRET,
907 region_name=TEST_REGION,
908 targets=["#MyTopic"],
909 )
910 assert obj.mode == SNSMode.TOPIC
911
912 # With title: Subject must appear in the Publish payload
913 assert bool(obj.notify(title="My Title", body="My Body")) is True
914 # urlencode() uses %20 for spaces
915 assert "Subject=My%20Title" in publish_data["data"]
916 assert "Message=My%20Body" in publish_data["data"]
917
918 # With no title: Subject must not appear in the Publish payload
919 publish_data.clear()
920 assert bool(obj.notify(title="", body="My Body")) is True
921 assert "Subject=" not in publish_data.get("data", "")
922
923
924 @mock.patch("requests.post")
925 def test_plugin_sns_topic_mode_phone_forced(mock_post):
926 """NotifySNS() TOPIC mode forced on phone target prepends title."""
927
928 response = mock.MagicMock()
929 response.status_code = requests.codes.ok
930 response.text = ""
931 mock_post.return_value = response
932
933 # Force TOPIC mode on a phone target
934 obj = NotifySNS(
935 access_key_id=TEST_ACCESS_KEY_ID,
936 secret_access_key=TEST_ACCESS_KEY_SECRET,
937 region_name=TEST_REGION,
938 targets=["+18001234567"],
939 mode=SNSMode.TOPIC,
940 )
941 assert obj.mode == SNSMode.TOPIC
942
943 # With a title: it must be prepended to the body in the SMS payload
944 assert bool(obj.notify(title="My Title", body="My Body")) is True
945 data = mock_post.call_args[1]["data"]
946 # urlencode() uses %20 for spaces; \r\n becomes %0D%0A
947 assert "My%20Title" in data
948 assert "My%20Body" in data
949
950 # With no title: body is sent as-is without modification
951 mock_post.reset_mock()
952 assert bool(obj.notify(title="", body="My Body")) is True
953 data = mock_post.call_args[1]["data"]
954 assert "My%20Body" in data
955
956
957 def test_plugin_sns_mode_url_round_trip():
958 """NotifySNS() mode is preserved through url() and parse_url()."""
959
960 # TOPIC mode round-trip
961 obj = NotifySNS(
962 access_key_id=TEST_ACCESS_KEY_ID,
963 secret_access_key=TEST_ACCESS_KEY_SECRET,
964 region_name=TEST_REGION,
965 targets=["#MyTopic"],
966 mode=SNSMode.TOPIC,
967 )
968 url = obj.url()
969 assert "mode=topic" in url
970
971 results = NotifySNS.parse_url(url)
972 assert results["mode"] == SNSMode.TOPIC
973
974 obj2 = NotifySNS(**results)
975 assert obj2.mode == SNSMode.TOPIC
976 assert obj2.url_identifier == obj.url_identifier
977
978 # SMS mode round-trip
979 obj = NotifySNS(
980 access_key_id=TEST_ACCESS_KEY_ID,
981 secret_access_key=TEST_ACCESS_KEY_SECRET,
982 region_name=TEST_REGION,
983 targets=["+18001234567"],
984 mode=SNSMode.SMS,
985 )
986 url = obj.url()
987 assert "mode=sms" in url
988
989 results = NotifySNS.parse_url(url)
990 assert results["mode"] == SNSMode.SMS
991
992 obj2 = NotifySNS(**results)
993 assert obj2.mode == SNSMode.SMS
994
995 # No mode in URL -> auto-detection runs on re-instantiation
996 url_no_mode = (
997 f"sns://{TEST_ACCESS_KEY_ID}/{TEST_ACCESS_KEY_SECRET}"
998 f"/{TEST_REGION}/+18001234567"
999 )
1000 results = NotifySNS.parse_url(url_no_mode)
1001 assert results["mode"] is None
1002 obj3 = NotifySNS(**results)
1003 # Auto-detected from phone target
1004 assert obj3.mode == SNSMode.SMS