Debian Codegraph @

tests/test_plugin_bluesky.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 from datetime import datetime, timezone
29 import json
30 import logging
31 import os
32 from unittest.mock import Mock, patch
33
34 from helpers import AppriseURLTester
35 import pytest
36 import requests
37
38 from apprise import Apprise, AppriseAsset, AppriseAttachment, NotifyType
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.bluesky import NotifyBlueSky
41
42 # Disable logging for a cleaner testing output
43 logging.disable(logging.CRITICAL)
44
45 # Attachment Directory
46 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
47
48 TWITTER_SCREEN_NAME = "apprise"
49
50
51 # Our Testing URLs
52 apprise_url_tests = (
53 ##################################
54 # NotifyBlueSky
55 ##################################
56 (
57 "bluesky://",
58 {
59 # Missing user and app_pass
60 "instance": AppriseImproperlyConfigured,
61 },
62 ),
63 (
64 "bluesky://:@/",
65 {
66 "instance": AppriseImproperlyConfigured,
67 },
68 ),
69 (
70 "bluesky://app-pw",
71 {
72 # Missing User
73 "instance": AppriseImproperlyConfigured,
74 },
75 ),
76 (
77 "bluesky://user@app-pw",
78 {
79 "instance": NotifyBlueSky,
80 # Expected notify() response False (because we won't be able
81 # to detect our user)
82 "notify_response": False,
83 # Our expected url(privacy=True) startswith() response:
84 "privacy_url": "bsky://user@****",
85 },
86 ),
87 (
88 "bluesky://user@app-pw1?cache=no",
89 {
90 "instance": NotifyBlueSky,
91 # At minimum we need an access token and did; below has no did
92 "requests_response_text": {
93 "accessJwt": "abcd",
94 "refreshJwt": "abcd",
95 },
96 "notify_response": False,
97 },
98 ),
99 (
100 "bluesky://user@app-pw2?cache=no",
101 {
102 "instance": NotifyBlueSky,
103 # valid payload
104 "requests_response_text": {
105 "accessJwt": "abcd",
106 "refreshJwt": "abcd",
107 "did": "did:plc:1234",
108 # Support plc response
109 "service": [
110 {
111 "type": "AtprotoPersonalDataServer",
112 "serviceEndpoint": "https://example.pds.io",
113 }
114 ],
115 },
116 },
117 ),
118 (
119 "bluesky://user@app-pw3",
120 {
121 # no cache; so we store our results
122 "instance": NotifyBlueSky,
123 # valid payload
124 "requests_response_text": {
125 "accessJwt": "abcd",
126 "refreshJwt": "abcd",
127 "did": "did:plc:1234",
128 # For handling attachments
129 "blob": "content",
130 # Support plc response
131 "service": [
132 {
133 "type": "AtprotoPersonalDataServer",
134 "serviceEndpoint": "https://example.pds.io",
135 }
136 ],
137 },
138 },
139 ),
140 (
141 "bluesky://user.example.ca@app-pw3",
142 {
143 # no cache; so we store our results
144 "instance": NotifyBlueSky,
145 # valid payload
146 "requests_response_text": {
147 "accessJwt": "abcd",
148 "refreshJwt": "abcd",
149 "did": "did:plc:1234",
150 # For handling attachments
151 "blob": "content",
152 # Support plc response
153 "service": [
154 {
155 "type": "AtprotoPersonalDataServer",
156 "serviceEndpoint": "https://example.pds.io",
157 }
158 ],
159 },
160 },
161 ),
162 # A duplicate of the entry above, this will cause cache to be referenced
163 (
164 "bluesky://user@app-pw3",
165 {
166 # no cache; so we store our results
167 "instance": NotifyBlueSky,
168 # valid payload
169 "requests_response_text": {
170 "accessJwt": "abcd",
171 "refreshJwt": "abcd",
172 "did": "did:plc:1234",
173 # For handling attachments
174 "blob": "content",
175 # Support plc response
176 "service": [
177 {
178 "type": "AtprotoPersonalDataServer",
179 "serviceEndpoint": "https://example.pds.io",
180 }
181 ],
182 },
183 },
184 ),
185 (
186 "bluesky://user@app-pw",
187 {
188 "instance": NotifyBlueSky,
189 # throw a bizarre code forcing us to fail to look it up
190 "response": False,
191 "requests_response_code": 999,
192 "requests_response_text": {
193 "accessJwt": "abcd",
194 "refreshJwt": "abcd",
195 "did": "did:plc:1234",
196 # Support plc response
197 "service": [
198 {
199 "type": "AtprotoPersonalDataServer",
200 "serviceEndpoint": "https://example.pds.io",
201 }
202 ],
203 },
204 },
205 ),
206 (
207 "bluesky://user@app-pw",
208 {
209 "instance": NotifyBlueSky,
210 # Throws a series of i/o exceptions with this flag
211 # is set and tests that we gracefully handle them
212 "test_requests_exceptions": True,
213 "requests_response_text": {
214 "accessJwt": "abcd",
215 "refreshJwt": "abcd",
216 "did": "did:plc:1234",
217 # Support plc response
218 "service": [
219 {
220 "type": "AtprotoPersonalDataServer",
221 "serviceEndpoint": "https://example.pds.io",
222 }
223 ],
224 },
225 },
226 ),
227 )
228
229
230 def _chunked(response):
231 """Let a mocked response be read in chunks, the way requests does."""
232
233 def iter_content(chunk_size=None):
234 content = response.content
235 if isinstance(content, str):
236 content = content.encode("utf-8")
237
238 return iter([content] if content else [])
239
240 response.iter_content.side_effect = iter_content
241 return response
242
243
244 def good_response(data=None):
245 """Prepare a good response."""
246 response = Mock()
247 response.content = json.dumps(
248 {
249 "accessJwt": "abcd",
250 "refreshJwt": "abcd",
251 "did": "did:plc:1234",
252 # Support plc response
253 "service": [
254 {
255 "type": "AtprotoPersonalDataServer",
256 "serviceEndpoint": "https://example.pds.io",
257 }
258 ],
259 "ratelimit-reset": str(
260 int(datetime.now(timezone.utc).timestamp()) + 3600
261 ),
262 "ratelimit-remaining": "10",
263 }
264 if data is None
265 else data
266 )
267
268 response.status_code = requests.codes.ok
269
270 # Epoch time:
271 epoch = datetime.fromtimestamp(0, timezone.utc)
272
273 # Generate a very large rate-limit header window
274 response.headers = {
275 "ratelimit-reset": (
276 (datetime.now(timezone.utc) - epoch).total_seconds() + 86400
277 ),
278 "ratelimit-remaining": "1000",
279 }
280
281 return _chunked(response)
282
283
284 def bad_response(data=None):
285 """Prepare a bad response."""
286 response = Mock()
287 response.content = json.dumps(
288 {
289 "error": "InvalidRequest",
290 "message": "Something failed",
291 }
292 if data is None
293 else data
294 )
295 response.headers = {}
296 response.status_code = requests.codes.internal_server_error
297 return _chunked(response)
298
299
300 @pytest.fixture
301 def bluesky_url():
302 url = "bluesky://user@app-key"
303 return url
304
305
306 @pytest.fixture
307 def good_message_response():
308 """Prepare a good response."""
309 response = good_response()
310 return response
311
312
313 @pytest.fixture
314 def bad_message_response():
315 """Prepare a bad message response."""
316 response = bad_response()
317 return response
318
319
320 @pytest.fixture
321 def good_media_response():
322 """Prepare a good media response."""
323 response = Mock()
324 response.content = json.dumps(
325 {
326 "blob": {
327 "$type": "blob",
328 "mimeType": "image/jpeg",
329 "ref": {"$link": "baf124idksduabcjkaa3iey4bfyq"},
330 "size": 73667,
331 }
332 }
333 )
334 response.headers = {}
335 response.status_code = requests.codes.ok
336 return response
337
338
339 def test_plugin_bluesky_urls():
340 """NotifyBlueSky() Apprise URLs."""
341
342 # Run our general tests
343 AppriseURLTester(tests=apprise_url_tests).run_all()
344
345
346 def test_plugin_bluesky_general(mocker):
347 """NotifyBlueSky() General Tests."""
348
349 mock_get = mocker.patch("requests.get")
350 mock_post = mocker.patch("requests.post")
351
352 # Epoch time:
353 epoch = datetime.fromtimestamp(0, timezone.utc)
354
355 request = good_response()
356 request.headers = {
357 "ratelimit-reset": (
358 (datetime.now(timezone.utc) - epoch).total_seconds()
359 ),
360 "ratelimit-remaining": "1",
361 }
362
363 # Prepare Mock
364 mock_get.return_value = request
365 mock_post.return_value = request
366
367 # Variation Initializations
368 obj = NotifyBlueSky(user="handle", password="app-password")
369
370 assert isinstance(obj, NotifyBlueSky) is True
371 assert isinstance(obj.url(), str) is True
372
373 # apprise room was found
374 assert obj.send(body="test") is True
375
376 # Change our status code and try again
377 request.status_code = 403
378 assert obj.send(body="test") is False
379 assert obj.ratelimit_remaining == 1
380
381 # Return the status
382 request.status_code = requests.codes.ok
383 # Force a reset
384 request.headers["ratelimit-remaining"] = 0
385 # behind the scenes, it should cause us to update our rate limit
386 assert obj.send(body="test") is True
387 assert obj.ratelimit_remaining == 0
388
389 # This should cause us to block
390 request.headers["ratelimit-remaining"] = 10
391 assert obj.send(body="test") is True
392 assert obj.ratelimit_remaining == 10
393
394 # Handle cases where we simply couldn't get this field
395 del request.headers["ratelimit-remaining"]
396 assert obj.send(body="test") is True
397 # It remains set to the last value
398 assert obj.ratelimit_remaining == 10
399
400 # Reset our variable back to 1
401 request.headers["ratelimit-remaining"] = 1
402
403 # Handle cases where our epoch time is wrong
404 del request.headers["ratelimit-reset"]
405 assert obj.send(body="test") is True
406
407 # Return our object, but place it in the future forcing us to block
408 request.headers["ratelimit-reset"] = (
409 datetime.now(timezone.utc) - epoch
410 ).total_seconds() + 1
411 request.headers["ratelimit-remaining"] = 0
412 obj.ratelimit_remaining = 0
413 assert obj.send(body="test") is True
414
415 # Return our object, but place it in the future forcing us to block
416 request.headers["ratelimit-reset"] = (
417 datetime.now(timezone.utc) - epoch
418 ).total_seconds() - 1
419 request.headers["ratelimit-remaining"] = 0
420 obj.ratelimit_remaining = 0
421 assert obj.send(body="test") is True
422
423 # Return our limits to always work
424 request.headers["ratelimit-reset"] = (
425 datetime.now(timezone.utc) - epoch
426 ).total_seconds()
427 request.headers["ratelimit-remaining"] = 1
428 obj.ratelimit_remaining = 1
429
430 assert obj.send(body="test") is True
431
432 # Flush our cache forcing it is re-creating
433 NotifyBlueSky._user_cache = {}
434 assert obj.send(body="test") is True
435
436 # Cause content response to be None
437 request.content = None
438 assert obj.send(body="test") is True
439
440 # Invalid JSON
441 request.content = "{"
442 assert obj.send(body="test") is True
443
444 # Return it to a parseable string
445 request.content = "{}"
446
447 results = NotifyBlueSky.parse_url("bluesky://handle@app-pass-word")
448 assert isinstance(results, dict) is True
449
450 # cause a json parsing issue now
451 response_obj = None
452 assert obj.send(body="test") is True
453
454 response_obj = "{"
455 assert obj.send(body="test") is True
456
457 # Flush out our cache
458 NotifyBlueSky._user_cache = {}
459
460 response_obj = {
461 "accessJwt": "abcd",
462 "refreshJwt": "abcd",
463 "did": "did:plc:1234",
464 # Support plc response
465 "service": [
466 {
467 "type": "AtprotoPersonalDataServer",
468 "serviceEndpoint": "https://example.pds.io",
469 }
470 ],
471 }
472 request.content = json.dumps(response_obj)
473
474 obj = NotifyBlueSky(user="handle", password="app-pass-word")
475 assert obj.send(body="test") is True
476
477 # Alter the key forcing us to look up a new value of ourselves again
478 NotifyBlueSky._user_cache = {}
479 NotifyBlueSky._whoami_cache = None
480 obj.ckey = "different.then.it.was"
481 assert obj.send(body="test") is True
482
483 NotifyBlueSky._whoami_cache = None
484 obj.ckey = "different.again"
485 assert obj.send(body="test") is True
486
487
488 def test_plugin_bluesky_edge_cases():
489 """NotifyBlueSky() Edge Cases."""
490
491 with pytest.raises(AppriseImproperlyConfigured):
492 NotifyBlueSky()
493
494
495 @patch("requests.post")
496 @patch("requests.get")
497 def test_plugin_bluesky_attachments_basic(
498 mock_get,
499 mock_post,
500 bluesky_url,
501 good_message_response,
502 good_media_response,
503 ):
504 """
505 NotifyBlueSky() Attachment Checks - Basic
506 """
507
508 mock_get.return_value = good_message_response
509 mock_post.side_effect = [
510 good_message_response,
511 good_media_response,
512 good_message_response,
513 ]
514
515 # Create application objects.
516 obj = Apprise.instantiate(bluesky_url)
517 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
518
519 # Send our notification
520 assert (
521 bool(
522 obj.notify(
523 body="body",
524 title="title",
525 notify_type=NotifyType.INFO,
526 attach=attach,
527 )
528 )
529 is True
530 )
531
532 # Verify API calls.
533 assert mock_get.call_count == 2
534 assert (
535 mock_get.call_args_list[0][0][0]
536 == "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle"
537 )
538 assert (
539 mock_get.call_args_list[1][0][0]
540 == "https://plc.directory/did:plc:1234"
541 )
542
543 assert mock_post.call_count == 3
544 assert (
545 mock_post.call_args_list[0][0][0]
546 == "https://example.pds.io/xrpc/com.atproto.server.createSession"
547 )
548 assert (
549 mock_post.call_args_list[1][0][0]
550 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
551 )
552 assert (
553 mock_post.call_args_list[2][0][0]
554 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
555 )
556
557
558 @patch("requests.post")
559 @patch("requests.get")
560 def test_plugin_bluesky_attachments_bad_message_response(
561 mock_get,
562 mock_post,
563 bluesky_url,
564 good_media_response,
565 good_message_response,
566 bad_message_response,
567 ):
568 """Verify a failed message response fails attachment delivery."""
569
570 mock_get.return_value = good_message_response
571 mock_post.side_effect = [
572 good_message_response,
573 bad_message_response,
574 good_message_response,
575 ]
576
577 # Create application objects.
578 obj = Apprise.instantiate(bluesky_url)
579 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
580
581 # Our notification will fail now since our message will error out.
582 assert (
583 bool(
584 obj.notify(
585 body="body",
586 title="title",
587 notify_type=NotifyType.INFO,
588 attach=attach,
589 )
590 )
591 is False
592 )
593
594 # Verify API calls.
595 assert mock_get.call_count == 2
596 assert (
597 mock_get.call_args_list[0][0][0]
598 == "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle"
599 )
600 assert (
601 mock_get.call_args_list[1][0][0]
602 == "https://plc.directory/did:plc:1234"
603 )
604
605 assert mock_post.call_count == 2
606 assert (
607 mock_post.call_args_list[0][0][0]
608 == "https://example.pds.io/xrpc/com.atproto.server.createSession"
609 )
610 assert (
611 mock_post.call_args_list[1][0][0]
612 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
613 )
614
615
616 @patch("requests.post")
617 @patch("requests.get")
618 def test_plugin_bluesky_attachments_upload_fails(
619 mock_get,
620 mock_post,
621 bluesky_url,
622 good_media_response,
623 good_message_response,
624 ):
625 """Verify a failed media upload fails attachment delivery."""
626
627 # Test case where upload fails.
628 mock_get.return_value = good_message_response
629 mock_post.side_effect = [good_message_response, OSError]
630
631 # Create application objects.
632 obj = Apprise.instantiate(bluesky_url)
633 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
634
635 # Send our notification; it will fail because of the message response.
636 assert (
637 bool(
638 obj.notify(
639 body="body",
640 title="title",
641 notify_type=NotifyType.INFO,
642 attach=attach,
643 )
644 )
645 is False
646 )
647
648 # Verify API calls.
649 assert mock_get.call_count == 2
650 assert (
651 mock_get.call_args_list[0][0][0]
652 == "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle"
653 )
654 assert (
655 mock_get.call_args_list[1][0][0]
656 == "https://plc.directory/did:plc:1234"
657 )
658
659 assert mock_post.call_count == 2
660 assert (
661 mock_post.call_args_list[0][0][0]
662 == "https://example.pds.io/xrpc/com.atproto.server.createSession"
663 )
664 assert (
665 mock_post.call_args_list[1][0][0]
666 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
667 )
668
669
670 @patch("requests.post")
671 @patch("requests.get")
672 def test_plugin_bluesky_attachments_invalid_attachment(
673 mock_get,
674 mock_post,
675 bluesky_url,
676 good_message_response,
677 good_media_response,
678 ):
679 """Verify an invalid attachment is rejected cleanly."""
680
681 mock_get.return_value = good_message_response
682 mock_post.side_effect = [good_message_response, good_media_response]
683
684 # Create application objects.
685 obj = Apprise.instantiate(bluesky_url)
686 attach = AppriseAttachment(
687 os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
688 )
689
690 # An invalid attachment will cause a failure.
691 assert (
692 bool(
693 obj.notify(
694 body="body",
695 title="title",
696 notify_type=NotifyType.INFO,
697 attach=attach,
698 )
699 )
700 is False
701 )
702
703 # Verify API calls.
704 assert mock_get.call_count == 2
705 assert (
706 mock_get.call_args_list[0][0][0]
707 == "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle"
708 )
709 assert (
710 mock_get.call_args_list[1][0][0]
711 == "https://plc.directory/did:plc:1234"
712 )
713
714 # No post request as attachment is not good.
715 assert mock_post.call_count == 1
716 assert (
717 mock_post.call_args_list[0][0][0]
718 == "https://example.pds.io/xrpc/com.atproto.server.createSession"
719 )
720
721
722 @patch("requests.post")
723 @patch("requests.get")
724 def test_plugin_bluesky_attachments_multiple_batch(
725 mock_get,
726 mock_post,
727 bluesky_url,
728 good_message_response,
729 good_media_response,
730 ):
731 """Verify multiple attachments are uploaded and sent as one batch."""
732
733 mock_get.return_value = good_message_response
734 mock_post.side_effect = [
735 good_message_response,
736 good_media_response,
737 good_media_response,
738 good_media_response,
739 good_media_response,
740 good_message_response,
741 good_message_response,
742 good_message_response,
743 good_message_response,
744 ]
745
746 # instantiate our object
747 obj = Apprise.instantiate(bluesky_url)
748
749 # 4 images are produced
750 attach = [
751 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
752 os.path.join(TEST_VAR_DIR, "apprise-test.gif"),
753 os.path.join(TEST_VAR_DIR, "apprise-test.jpeg"),
754 os.path.join(TEST_VAR_DIR, "apprise-test.png"),
755 # This one is not supported, so it's ignored gracefully
756 os.path.join(TEST_VAR_DIR, "apprise-test.mp4"),
757 ]
758
759 assert (
760 bool(
761 obj.notify(
762 body="body",
763 title="title",
764 notify_type=NotifyType.INFO,
765 attach=attach,
766 )
767 )
768 is True
769 )
770
771 # Verify API calls.
772 assert mock_get.call_count == 2
773 assert (
774 mock_get.call_args_list[0][0][0]
775 == "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle"
776 )
777 assert (
778 mock_get.call_args_list[1][0][0]
779 == "https://plc.directory/did:plc:1234"
780 )
781 assert mock_post.call_count == 9
782 assert (
783 mock_post.call_args_list[0][0][0]
784 == "https://example.pds.io/xrpc/com.atproto.server.createSession"
785 )
786 assert (
787 mock_post.call_args_list[1][0][0]
788 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
789 )
790 assert (
791 mock_post.call_args_list[2][0][0]
792 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
793 )
794 assert (
795 mock_post.call_args_list[3][0][0]
796 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
797 )
798 assert (
799 mock_post.call_args_list[4][0][0]
800 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
801 )
802 assert (
803 mock_post.call_args_list[5][0][0]
804 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
805 )
806 assert (
807 mock_post.call_args_list[6][0][0]
808 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
809 )
810 assert (
811 mock_post.call_args_list[7][0][0]
812 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
813 )
814 assert (
815 mock_post.call_args_list[8][0][0]
816 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
817 )
818
819 # If we call the functions again, the only difference is
820 # we no longer need to resolve the handle or create a session
821 # as the previous one is fine.
822 mock_get.reset_mock()
823 mock_post.reset_mock()
824
825 mock_get.return_value = good_message_response
826 mock_post.side_effect = [
827 good_media_response,
828 good_media_response,
829 good_media_response,
830 good_media_response,
831 good_message_response,
832 good_message_response,
833 good_message_response,
834 good_message_response,
835 ]
836
837 assert (
838 bool(
839 obj.notify(
840 body="body",
841 title="title",
842 notify_type=NotifyType.INFO,
843 attach=attach,
844 )
845 )
846 is True
847 )
848
849 # Verify API calls.
850 assert mock_get.call_count == 0
851 assert mock_post.call_count == 8
852 assert (
853 mock_post.call_args_list[0][0][0]
854 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
855 )
856 assert (
857 mock_post.call_args_list[1][0][0]
858 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
859 )
860 assert (
861 mock_post.call_args_list[2][0][0]
862 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
863 )
864 assert (
865 mock_post.call_args_list[3][0][0]
866 == "https://example.pds.io/xrpc/com.atproto.repo.uploadBlob"
867 )
868 assert (
869 mock_post.call_args_list[4][0][0]
870 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
871 )
872 assert (
873 mock_post.call_args_list[5][0][0]
874 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
875 )
876 assert (
877 mock_post.call_args_list[6][0][0]
878 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
879 )
880 assert (
881 mock_post.call_args_list[7][0][0]
882 == "https://example.pds.io/xrpc/com.atproto.repo.createRecord"
883 )
884
885
886 @patch("requests.post")
887 @patch("requests.get")
888 def test_plugin_bluesky_auth_failure(
889 mock_get,
890 mock_post,
891 bluesky_url,
892 good_message_response,
893 bad_message_response,
894 ):
895 """Verify authentication failures prevent message delivery."""
896
897 mock_get.return_value = good_message_response
898 mock_post.return_value = bad_message_response
899
900 # instantiate our object
901 obj = Apprise.instantiate(bluesky_url)
902
903 assert (
904 bool(
905 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
906 )
907 is False
908 )
909
910 # Verify API calls.
911 assert mock_get.call_count == 2
912 assert (
913 mock_get.call_args_list[0][0][0]
914 == "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle"
915 )
916 assert (
917 mock_get.call_args_list[1][0][0]
918 == "https://plc.directory/did:plc:1234"
919 )
920 assert mock_post.call_count == 1
921 assert (
922 mock_post.call_args_list[0][0][0]
923 == "https://example.pds.io/xrpc/com.atproto.server.createSession"
924 )
925
926
927 @patch("requests.post")
928 @patch("requests.get")
929 def test_plugin_bluesky_did_web_and_plc_resolution(
930 mock_get, mock_post, bluesky_url, good_message_response
931 ):
932 """
933 NotifyBlueSky() - Full coverage of did:web and did:plc path
934 """
935
936 # Step 1: Identity resolution response (public.api.bsky.app)
937 identity_response = good_response({"did": "did:plc:abcdefg1234567"})
938
939 # Step 2: PLC Directory lookup
940 plc_response = good_response(
941 {
942 "service": [
943 {
944 "type": "AtprotoPersonalDataServer",
945 "serviceEndpoint": "https://example.pds.io",
946 }
947 ]
948 }
949 )
950
951 # Step 3: Auth session
952 session_response = good_response()
953
954 # Step 4: Create post
955 post_response = good_response()
956
957 mock_get.side_effect = [identity_response, plc_response]
958 mock_post.side_effect = [session_response, post_response]
959
960 obj = Apprise.instantiate(bluesky_url)
961 assert bool(obj.notify(body="Resolved PLC Flow")) is True
962
963 # Reset for did:web test
964 identity_response = good_response({"did": "did:web:example.com"})
965
966 web_did_response = good_response(
967 {
968 "service": [
969 {
970 "type": "AtprotoPersonalDataServer",
971 "serviceEndpoint": "https://example.com",
972 }
973 ]
974 }
975 )
976
977 mock_get.side_effect = [identity_response, web_did_response]
978 mock_post.side_effect = [session_response, post_response]
979
980 obj = Apprise.instantiate(bluesky_url)
981 assert bool(obj.notify(body="Resolved WEB Flow")) is True
982
983 # Invalid DID scheme
984 bad_did_response = good_response({"did": "did:unsupported:scheme"})
985
986 mock_get.side_effect = [bad_did_response]
987 obj = Apprise.instantiate(bluesky_url)
988 assert bool(obj.notify(body="fail due to bad scheme")) is False
989
990
991 @patch("requests.get")
992 def test_plugin_bluesky_pds_resolution_failures(mock_get):
993 """
994 NotifyBlueSky() - Missing service field or invalid service endpoint
995 """
996 identity_response = good_response({"did": "did:plc:missing-service"})
997 plc_no_service = good_response({"foo": "bar"})
998
999 mock_get.side_effect = [identity_response, plc_no_service]
1000 obj = NotifyBlueSky(user="handle", password="pass")
1001 did, endpoint = obj.get_identifier()
1002 assert (did, endpoint) == (False, False)
1003
1004 identity_response = good_response({"did": "did:web:example.com"})
1005 web_did_no_service = good_response({"foo": "bar"})
1006
1007 mock_get.side_effect = [identity_response, web_did_no_service]
1008 obj = NotifyBlueSky(user="handle", password="pass")
1009 did, endpoint = obj.get_identifier()
1010 assert (did, endpoint) == (False, False)
1011
1012
1013 @patch("requests.get")
1014 def test_plugin_bluesky_missing_pds_endpoint(mock_get):
1015 """
1016 NotifyBlueSky() - test case where endpoint is missing from DID document
1017 """
1018 # Return a valid DID resolution
1019 identity_response = good_response({"did": "did:plc:abcdefg1234567"})
1020
1021 # Return DID document with a service list, but no matching PDS type
1022 incomplete_pds_response = good_response(
1023 {
1024 "service": [
1025 {
1026 "type": "SomeOtherService",
1027 "serviceEndpoint": "https://unrelated.example.com",
1028 }
1029 ]
1030 }
1031 )
1032
1033 mock_get.side_effect = [identity_response, incomplete_pds_response]
1034 obj = NotifyBlueSky(user="handle", password="app-pw")
1035 assert obj.get_identifier() == (False, False)
1036
1037
1038 @patch("requests.post")
1039 @patch("requests.get")
1040 def test_plugin_bluesky_rejects_unsafe_pds(mock_get, mock_post):
1041 """Reject unsafe PDS addresses from a DID document."""
1042 for endpoint in (
1043 # An unencrypted address
1044 "http://evil.example.com",
1045 # Embedded credentials
1046 "https://attacker:[email protected]",
1047 # Not a host we can make sense of
1048 "https://-nope-.example.com",
1049 ):
1050 identity_response = good_response({"did": "did:plc:abcdefg1234567"})
1051 plc_response = good_response(
1052 {
1053 "service": [
1054 {
1055 "type": "AtprotoPersonalDataServer",
1056 "serviceEndpoint": endpoint,
1057 }
1058 ]
1059 }
1060 )
1061
1062 mock_get.side_effect = [identity_response, plc_response]
1063 obj = NotifyBlueSky(user="handle", password="app-pw")
1064 assert obj.get_identifier() == (False, False)
1065
1066 # Our login details were never sent anywhere
1067 assert mock_post.call_count == 0
1068
1069
1070 @patch("requests.post")
1071 @patch("requests.get")
1072 def test_plugin_bluesky_malformed_did_document(mock_get, mock_post):
1073 """Reject malformed DID documents without raising exceptions."""
1074 # The DID document could not be fetched at all
1075 mock_get.side_effect = [
1076 good_response({"did": "did:plc:abcdefg1234567"}),
1077 bad_response(),
1078 ]
1079 obj = NotifyBlueSky(user="handle", password="app-pw")
1080 assert obj.get_identifier() == (False, False)
1081
1082 # The identity lookup did not hand us an object
1083 mock_get.side_effect = [good_response(["not", "an", "object"])]
1084 obj = NotifyBlueSky(user="handle", password="app-pw")
1085 assert obj.get_identifier() == (False, False)
1086
1087 # The DID itself is not a string
1088 mock_get.side_effect = [good_response({"did": {"nested": "object"}})]
1089 obj = NotifyBlueSky(user="handle", password="app-pw")
1090 assert obj.get_identifier() == (False, False)
1091
1092 # The service entry is not shaped the way we expect
1093 for service in (
1094 # Not a list
1095 "AtprotoPersonalDataServer",
1096 # Entries that are not objects
1097 ["string", 42, None],
1098 # An entry with no type at all
1099 [{"serviceEndpoint": "https://example.pds.io"}],
1100 # Our type, but nothing to reach
1101 [{"type": "AtprotoPersonalDataServer"}],
1102 ):
1103 mock_get.side_effect = [
1104 good_response({"did": "did:plc:abcdefg1234567"}),
1105 good_response({"service": service}),
1106 ]
1107 obj = NotifyBlueSky(user="handle", password="app-pw")
1108 assert obj.get_identifier() == (False, False)
1109
1110 # Our login details were never sent anywhere
1111 assert mock_post.call_count == 0
1112
1113
1114 @patch("requests.post")
1115 @patch("requests.get")
1116 def test_plugin_bluesky_login_protects_password(mock_get, mock_post):
1117 """Keep the login password out of logs and redirected requests."""
1118 mock_get.side_effect = [
1119 good_response({"did": "did:plc:abcdefg1234567"}),
1120 good_response(
1121 {
1122 "service": [
1123 {
1124 "type": "AtprotoPersonalDataServer",
1125 "serviceEndpoint": "https://example.pds.io",
1126 }
1127 ]
1128 }
1129 ),
1130 ]
1131 mock_post.return_value = good_response()
1132
1133 obj = NotifyBlueSky(user="handle", password="app-pw")
1134 assert obj.login() is True
1135
1136 # A redirect is never followed while our password is in flight
1137 assert mock_post.call_args[1]["allow_redirects"] is False
1138
1139
1140 @patch("requests.post")
1141 @patch("requests.get")
1142 def test_plugin_bluesky_discovery_is_unauthenticated(mock_get, mock_post):
1143 """
1144 NotifyBlueSky() - our session token is not handed to a lookup service
1145 """
1146 mock_get.side_effect = [
1147 good_response({"did": "did:web:someone-elses.host"}),
1148 good_response(
1149 {
1150 "service": [
1151 {
1152 "type": "AtprotoPersonalDataServer",
1153 "serviceEndpoint": "https://example.pds.io",
1154 }
1155 ]
1156 }
1157 ),
1158 ]
1159 mock_post.return_value = good_response()
1160
1161 # Pretend we already hold a session from an earlier notification
1162 obj = NotifyBlueSky(user="handle", password="app-pw")
1163 obj._NotifyBlueSky__access_token = "secret-token"
1164
1165 assert obj.get_identifier() != (False, False)
1166
1167 # Neither lookup carried our token
1168 for call in mock_get.call_args_list:
1169 assert "Authorization" not in call[1]["headers"]
1170
1171 # ...but a call to our own server still does
1172 obj._fetch("https://example.pds.io/xrpc/test", payload="{}")
1173 assert "Authorization" in mock_post.call_args[1]["headers"]
1174
1175
1176 @patch("requests.post")
1177 def test_plugin_bluesky_secure_logging_controls_payload(mock_post):
1178 """
1179 NotifyBlueSky() - hiding the login payload follows secure_logging
1180 """
1181 mock_post.return_value = good_response()
1182
1183 obj = NotifyBlueSky(user="handle", password="app-pw")
1184 with patch.object(obj, "logger") as logger:
1185 obj._fetch("https://example.pds.io/x", payload="pw", credentials=True)
1186
1187 logged = [
1188 str(c) for c in logger.debug.call_args_list if "Payload" in str(c)
1189 ]
1190 assert "<hidden>" in logged[0]
1191
1192 # Turning secure logging off puts it back for troubleshooting
1193 obj = NotifyBlueSky(
1194 user="handle",
1195 password="app-pw",
1196 asset=AppriseAsset(secure_logging=False),
1197 )
1198 with patch.object(obj, "logger") as logger:
1199 obj._fetch("https://example.pds.io/x", payload="pw", credentials=True)
1200
1201 logged = [
1202 str(c) for c in logger.debug.call_args_list if "Payload" in str(c)
1203 ]
1204 assert "<hidden>" not in logged[0]
1205
1206
1207 @patch("requests.get")
1208 def test_plugin_bluesky_oversized_lookup(mock_get):
1209 """Discard an oversized lookup response and close its stream."""
1210 flood = Mock()
1211 flood.status_code = requests.codes.ok
1212 flood.headers = {}
1213 flood.iter_content.return_value = iter([b"x" * 600000, b"x" * 600000])
1214 mock_get.return_value = flood
1215
1216 obj = NotifyBlueSky(user="handle", password="app-pw")
1217 assert obj.get_identifier() == (False, False)
1218
1219 # We stopped reading rather than holding on to all of it
1220 flood.close.assert_called_once()