Debian Codegraph @

tests/test_plugin_bark.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 base64
30 import json
31 import logging
32 import re
33 from unittest import mock
34
35 from helpers import AppriseURLTester
36 import pytest
37 import requests
38
39 from apprise import Apprise, NotifyFormat
40 from apprise.exception import (
41 AppriseImproperlyConfigured,
42 ApprisePluginException,
43 )
44 import apprise.plugins.bark as bark_module
45 from apprise.plugins.bark import NotifyBark
46
47 logging.disable(logging.CRITICAL)
48
49 # Our Testing URLs
50 apprise_url_tests = (
51 (
52 "bark://",
53 {
54 # No no host
55 "instance": None,
56 },
57 ),
58 (
59 "bark://:@/",
60 {
61 # just invalid all around
62 "instance": None,
63 },
64 ),
65 (
66 "bark://localhost",
67 {
68 # No Device Key specified
69 "instance": NotifyBark,
70 # Expected notify() response False (because we won't be able
71 # to actually notify anything if no device_key was specified
72 "notify_response": False,
73 },
74 ),
75 (
76 "bark://192.168.0.6:8081/device_key",
77 {
78 # Everything is okay
79 "instance": NotifyBark,
80 # Our expected url(privacy=True) startswith() response:
81 "privacy_url": "bark://192.168.0.6:8081/",
82 },
83 ),
84 (
85 "bark://[email protected]:8081/device_key",
86 {
87 # Everything is okay (test with user)
88 "instance": NotifyBark,
89 # Our expected url(privacy=True) startswith() response:
90 "privacy_url": "bark://[email protected]:8081/",
91 },
92 ),
93 (
94 "bark://192.168.0.6:8081/device_key/?sound=invalid",
95 {
96 # bad sound, but we go ahead anyway
97 "instance": NotifyBark,
98 },
99 ),
100 (
101 "bark://192.168.0.6:8081/device_key/?sound=alarm",
102 {
103 # alarm.caf sound loaded
104 "instance": NotifyBark,
105 },
106 ),
107 (
108 "bark://192.168.0.6:8081/device_key/?sound=NOiR.cAf",
109 {
110 # noir.caf sound loaded
111 "instance": NotifyBark,
112 },
113 ),
114 (
115 "bark://192.168.0.6:8081/device_key/?badge=100",
116 {
117 # set badge
118 "instance": NotifyBark,
119 },
120 ),
121 (
122 "barks://192.168.0.6:8081/device_key/?badge=invalid",
123 {
124 # set invalid badge
125 "instance": NotifyBark,
126 },
127 ),
128 (
129 "barks://192.168.0.6:8081/device_key/?badge=-12",
130 {
131 # set invalid badge
132 "instance": NotifyBark,
133 },
134 ),
135 (
136 "bark://192.168.0.6:8081/device_key/?category=apprise",
137 {
138 # set category
139 "instance": NotifyBark,
140 },
141 ),
142 (
143 "bark://192.168.0.6:8081/device_key/?image=no",
144 {
145 # do not display image
146 "instance": NotifyBark,
147 },
148 ),
149 (
150 "bark://192.168.0.6:8081/device_key/?group=apprise",
151 {
152 # set group
153 "instance": NotifyBark,
154 },
155 ),
156 (
157 "bark://192.168.0.6:8081/device_key/?level=invalid",
158 {
159 # bad level, but we go ahead anyway
160 "instance": NotifyBark,
161 },
162 ),
163 (
164 "bark://192.168.0.6:8081/?to=device_key",
165 {
166 # test use of to= argument
167 "instance": NotifyBark,
168 },
169 ),
170 (
171 "bark://192.168.0.6:8081/device_key/?click=http://localhost",
172 {
173 # Our click link
174 "instance": NotifyBark,
175 },
176 ),
177 (
178 "bark://192.168.0.6:8081/device_key/?level=active",
179 {
180 # active level
181 "instance": NotifyBark,
182 },
183 ),
184 (
185 "bark://192.168.0.6:8081/device_key/?level=critical",
186 {
187 # critical level
188 "instance": NotifyBark,
189 },
190 ),
191 (
192 "bark://192.168.0.6:8081/device_key/?level=critical&volume=10",
193 {
194 # critical level with volume 10
195 "instance": NotifyBark,
196 },
197 ),
198 (
199 "bark://192.168.0.6:8081/device_key/?level=critical&volume=invalid",
200 {
201 # critical level with invalid volume
202 "instance": NotifyBark,
203 },
204 ),
205 (
206 "bark://192.168.0.6:8081/device_key/?level=critical&volume=11",
207 {
208 # volume > 10
209 "instance": NotifyBark,
210 },
211 ),
212 (
213 "bark://192.168.0.6:8081/device_key/?level=critical&volume=-1",
214 {
215 # volume < 0
216 "instance": NotifyBark,
217 },
218 ),
219 (
220 "bark://192.168.0.6:8081/device_key/?level=critical&volume=",
221 {
222 # volume None
223 "instance": NotifyBark,
224 },
225 ),
226 (
227 "bark://user:[email protected]:8086/device_key/device_key2/",
228 {
229 # Everything is okay
230 "instance": NotifyBark,
231 # Our expected url(privacy=True) startswith() response:
232 "privacy_url": "bark://user:****@192.168.0.5:8086/",
233 },
234 ),
235 (
236 "barks://192.168.0.7/device_key/",
237 {
238 "instance": NotifyBark,
239 # throw a bizarre code forcing us to fail to look it up
240 "response": False,
241 "requests_response_code": 999,
242 # Our expected url(privacy=True) startswith() response:
243 "privacy_url": "barks://192.168.0.7/****",
244 },
245 ),
246 (
247 "bark://192.168.0.7/device_key",
248 {
249 "instance": NotifyBark,
250 # Throws a series of i/o exceptions with this flag
251 # is set and tests that we gracefully handle them
252 "test_requests_exceptions": True,
253 },
254 ),
255 (
256 "bark://192.168.0.6:8081/device_key/?icon=https://example.com/icon.png",
257 {
258 # set custom icon
259 "instance": NotifyBark,
260 },
261 ),
262 (
263 "bark://192.168.0.6:8081/device_key/?icon=https://example.com/icon.png&image=no",
264 {
265 # set custom icon and disable default image
266 "instance": NotifyBark,
267 },
268 ),
269 (
270 "bark://192.168.0.6:8081/device_key/?call=1",
271 {
272 # set call parameter to repeat ringtone
273 "instance": NotifyBark,
274 },
275 ),
276 (
277 "bark://192.168.0.6:8081/device_key/?call=1&sound=alarm&level=critical",
278 {
279 # set call parameter with other parameters
280 "instance": NotifyBark,
281 },
282 ),
283 (
284 "bark://192.168.0.6:8081/device_key/?format=markdown",
285 {
286 # enable markdown mode via global format parameter
287 "instance": NotifyBark,
288 },
289 ),
290 (
291 "bark://192.168.0.6:8081/device_key/?format=text",
292 {
293 # explicitly set text format (default behavior)
294 "instance": NotifyBark,
295 },
296 ),
297 )
298
299
300 def test_plugin_bark_urls():
301 """NotifyBark() Apprise URLs."""
302
303 # Run our general tests
304 AppriseURLTester(tests=apprise_url_tests).run_all()
305
306
307 @mock.patch("requests.post")
308 def test_plugin_bark_html_to_markdown_format(mock_post):
309 """NotifyBark(): HTML body is converted to Markdown."""
310
311 # Prepare Mock
312 mock_post.return_value = requests.Request()
313 mock_post.return_value.status_code = requests.codes.ok
314
315 # Load via Apprise URL with markdown format enabled
316 aobj = Apprise()
317 assert aobj.add("bark://192.168.0.6:8081/device_key/?format=markdown")
318
319 # Notify with an HTML body; the framework converts it to Markdown
320 # before dispatching to the Bark plugin
321 assert (
322 bool(
323 aobj.notify(
324 body="<b>hello</b> <i>world</i>",
325 body_format=NotifyFormat.HTML,
326 )
327 )
328 is True
329 )
330 assert mock_post.call_count == 1
331
332 # The body must arrive as Markdown, not stripped plain text
333 payload = json.loads(mock_post.call_args_list[0][1]["data"])
334 assert payload["markdown"] == "**hello** *world*"
335
336
337 @pytest.mark.parametrize(
338 ("key", "expected_ciphertext"),
339 (
340 (
341 "k" * 16,
342 "M31imDGJqdEEszZWcWfgiMTooJniyhmvnRIIrUSrWDVi3FxcD9cl1Dyre2wQ8a5I2bhFyBrGPeMEwp1+Uw==",
343 ),
344 (
345 "k" * 24,
346 "QyuvztP2Yktq2khUWXw6hYrjLnhuc+kC44lyGOaVYBRJC4vsYaB6RewayvX+4ZKjUUIifRWDtIiVFq/KgA==",
347 ),
348 (
349 "k" * 32,
350 "a9CkBbe9d0qkskyAzKyb4pV/WjH6D1J/JLm0EOUTMcoTpJEs10gqANkkLKaOPqVXL0yo0AaxElYjmLmynw==",
351 ),
352 ),
353 )
354 def test_plugin_bark_aesgcm_wire_format(
355 key,
356 expected_ciphertext,
357 monkeypatch,
358 ):
359 """NotifyBark() matches Bark's AES-GCM combined wire format."""
360 pytest.importorskip("cryptography")
361 monkeypatch.setattr(
362 bark_module.secrets,
363 "token_urlsafe",
364 lambda length: "fixed-iv-123",
365 )
366 instance = NotifyBark(
367 host="localhost",
368 targets=("device-key",),
369 secure=True,
370 encryption_key=key,
371 )
372
373 ciphertext, iv = instance._encrypt_payload(
374 {"body": "Encrypted weather", "level": "active"}
375 )
376
377 assert iv == "fixed-iv-123"
378 assert ciphertext == expected_ciphertext
379
380
381 @pytest.mark.parametrize(
382 "key",
383 (
384 pytest.param("short", id="too-short"),
385 pytest.param("k" * 17, id="unsupported-length"),
386 pytest.param("🔒" * 16, id="non-ascii-unicode-probe"),
387 pytest.param(b"k" * 16, id="non-string"),
388 ),
389 )
390 def test_plugin_bark_rejects_invalid_encryption_keys(key):
391 """NotifyBark() rejects keys Bark cannot use as raw AES keys."""
392 with pytest.raises(
393 AppriseImproperlyConfigured, match="Bark encryption key"
394 ):
395 NotifyBark(
396 host="localhost",
397 targets=("device-key",),
398 secure=True,
399 encryption_key=key,
400 )
401
402
403 def test_plugin_bark_encryption_fails_closed_without_cryptography(monkeypatch):
404 """NotifyBark() never downgrades requested encryption to plaintext."""
405 monkeypatch.setattr(bark_module, "BARK_AESGCM_SUPPORT", False)
406
407 with pytest.raises(
408 AppriseImproperlyConfigured,
409 match="requires the 'cryptography' package",
410 ):
411 NotifyBark(
412 host="localhost",
413 targets=("device-key",),
414 secure=True,
415 encryption_key="k" * 32,
416 )
417
418 instance = NotifyBark(
419 host="localhost",
420 targets=("device-key",),
421 secure=True,
422 )
423 assert instance.encryption_key is None
424
425
426 def test_plugin_bark_encryption_url_roundtrip_and_privacy():
427 """NotifyBark() preserves encryption config without exposing secrets."""
428 pytest.importorskip("cryptography")
429 device_key = "private-device-key"
430 encryption_key = "k" * 32
431 instance = NotifyBark(
432 host="localhost",
433 targets=(device_key,),
434 secure=True,
435 encryption_key=encryption_key,
436 )
437
438 generated_url = instance.url(privacy=False)
439 assert device_key in generated_url
440 assert encryption_key in generated_url
441
442 private_url = instance.url(privacy=True)
443 assert device_key not in private_url
444 assert encryption_key not in private_url
445 assert private_url.startswith("barks://localhost/****?")
446 assert "key=" in private_url
447
448 parsed = NotifyBark.parse_url(generated_url)
449 rebuilt = NotifyBark(**parsed)
450 assert rebuilt.encryption_key == encryption_key
451 assert rebuilt.targets == [device_key]
452 assert rebuilt.url_identifier == instance.url_identifier
453
454 different_key = NotifyBark(
455 host="localhost",
456 targets=(device_key,),
457 secure=True,
458 encryption_key="x" * 32,
459 )
460 assert different_key.url_identifier != instance.url_identifier
461
462
463 @mock.patch("requests.post")
464 def test_plugin_bark_encrypts_complete_payload_with_fresh_iv_per_target(
465 mock_post,
466 monkeypatch,
467 ):
468 """NotifyBark() encrypts all parameters and rotates IVs per request."""
469 aesgcm = pytest.importorskip(
470 "cryptography.hazmat.primitives.ciphers.aead"
471 ).AESGCM
472 generated_ivs = iter(("abcdefghijkl", "mnopqrstuvwx"))
473 token_urlsafe = mock.Mock(side_effect=lambda length: next(generated_ivs))
474 monkeypatch.setattr(
475 bark_module.secrets,
476 "token_urlsafe",
477 token_urlsafe,
478 )
479 response = mock.Mock()
480 response.status_code = requests.codes.ok
481 mock_post.return_value = response
482 key = "k" * 32
483 private_body = "Private encrypted body"
484 private_title = "Private encrypted title"
485 targets = ("private-device-one", "private-device-two")
486 instance = NotifyBark(
487 host="localhost",
488 targets=targets,
489 secure=True,
490 encryption_key=key,
491 include_image=False,
492 sound="alarm",
493 category="private-category",
494 group="private-group",
495 level="active",
496 click="https://private.example.invalid",
497 badge=3,
498 volume=4,
499 icon="https://private.example.invalid/icon.png",
500 call=True,
501 )
502 instance.logger = mock.Mock()
503
504 assert instance.send(body=private_body, title=private_title) is True
505 assert mock_post.call_count == 2
506
507 request_payloads = [
508 json.loads(call.kwargs["data"]) for call in mock_post.call_args_list
509 ]
510 assert {payload["device_key"] for payload in request_payloads} == set(
511 targets
512 )
513 assert [payload["iv"] for payload in request_payloads] == [
514 "abcdefghijkl",
515 "mnopqrstuvwx",
516 ]
517 assert token_urlsafe.call_args_list == [
518 mock.call(bark_module.BARK_GCM_IV_RANDOM_BYTES),
519 mock.call(bark_module.BARK_GCM_IV_RANDOM_BYTES),
520 ]
521 assert all(
522 re.fullmatch(r"[A-Za-z0-9_-]{12}", payload["iv"])
523 for payload in request_payloads
524 )
525 assert all(
526 set(payload) == {"device_key", "ciphertext", "iv"}
527 for payload in request_payloads
528 )
529
530 expected_parameters = {
531 "title": private_title,
532 "body": private_body,
533 "sound": "alarm.caf",
534 "url": "https://private.example.invalid",
535 "badge": 3,
536 "level": "active",
537 "category": "private-category",
538 "group": "private-group",
539 "volume": 4,
540 "icon": "https://private.example.invalid/icon.png",
541 "call": 1,
542 }
543 for request_payload in request_payloads:
544 plaintext = aesgcm(key.encode("ascii")).decrypt(
545 request_payload["iv"].encode("ascii"),
546 base64.b64decode(request_payload["ciphertext"]),
547 None,
548 )
549 assert json.loads(plaintext) == expected_parameters
550
551 logged = repr(instance.logger.method_calls)
552 for private_value in (
553 key,
554 private_body,
555 private_title,
556 *targets,
557 "private-category",
558 "private-group",
559 "private.example.invalid",
560 ):
561 assert private_value not in logged
562
563
564 @mock.patch("requests.post")
565 def test_plugin_bark_encrypts_markdown_payload(mock_post, monkeypatch):
566 """NotifyBark() encrypts Markdown and does not add a plaintext body."""
567 aesgcm = pytest.importorskip(
568 "cryptography.hazmat.primitives.ciphers.aead"
569 ).AESGCM
570 monkeypatch.setattr(
571 bark_module.secrets,
572 "token_urlsafe",
573 lambda length: "fixed-iv-123",
574 )
575 response = mock.Mock()
576 response.status_code = requests.codes.ok
577 mock_post.return_value = response
578 key = "k" * 32
579 instance = NotifyBark(
580 host="localhost",
581 targets=("device-key",),
582 secure=True,
583 encryption_key=key,
584 include_image=False,
585 format=NotifyFormat.MARKDOWN,
586 )
587
588 assert instance.send(body="**encrypted**", title="Title") is True
589
590 request_payload = json.loads(mock_post.call_args.kwargs["data"])
591 plaintext = aesgcm(key.encode("ascii")).decrypt(
592 request_payload["iv"].encode("ascii"),
593 base64.b64decode(request_payload["ciphertext"]),
594 None,
595 )
596 assert json.loads(plaintext) == {
597 "title": "Title",
598 "markdown": "**encrypted**",
599 }
600
601
602 @mock.patch("requests.post")
603 def test_plugin_bark_rotates_iv_across_repeated_sends(
604 mock_post,
605 monkeypatch,
606 ):
607 """NotifyBark() generates a fresh IV for every repeated request."""
608 pytest.importorskip("cryptography")
609 generated_ivs = iter(("abcdefghijkl", "mnopqrstuvwx"))
610 monkeypatch.setattr(
611 bark_module.secrets,
612 "token_urlsafe",
613 lambda length: next(generated_ivs),
614 )
615 response = mock.Mock()
616 response.status_code = requests.codes.ok
617 mock_post.return_value = response
618 instance = NotifyBark(
619 host="localhost",
620 targets=("device-key",),
621 secure=True,
622 encryption_key="k" * 32,
623 include_image=False,
624 )
625
626 assert instance.send(body="same body", title="same title") is True
627 assert instance.send(body="same body", title="same title") is True
628
629 payloads = [
630 json.loads(call.kwargs["data"]) for call in mock_post.call_args_list
631 ]
632 assert [payload["iv"] for payload in payloads] == [
633 "abcdefghijkl",
634 "mnopqrstuvwx",
635 ]
636 assert payloads[0]["ciphertext"] != payloads[1]["ciphertext"]
637
638
639 def test_plugin_bark_rejects_incompatible_generated_iv(monkeypatch):
640 """NotifyBark() rejects RNG output Bark cannot decrypt."""
641 pytest.importorskip("cryptography")
642 monkeypatch.setattr(
643 bark_module.secrets,
644 "token_urlsafe",
645 lambda length: "too-short",
646 )
647 instance = NotifyBark(
648 host="localhost",
649 targets=("device-key",),
650 secure=True,
651 encryption_key="k" * 32,
652 )
653
654 with pytest.raises(
655 ApprisePluginException, match="incompatible AES-GCM IV"
656 ) as exc_info:
657 instance._encrypt_payload({"body": "private body"})
658 assert exc_info.value.error_code == 600
659
660
661 @mock.patch("requests.post")
662 def test_plugin_bark_encryption_failure_prevents_network_io(mock_post):
663 """NotifyBark() fails closed when payload encryption fails."""
664 pytest.importorskip("cryptography")
665 instance = NotifyBark(
666 host="localhost",
667 targets=("private-device",),
668 secure=True,
669 encryption_key="k" * 32,
670 include_image=False,
671 )
672 instance.logger = mock.Mock()
673 instance._encrypt_payload = mock.Mock(
674 side_effect=ValueError("private encryption detail")
675 )
676
677 assert instance.send(body="private body", title="private title") is False
678 mock_post.assert_not_called()
679 logged = repr(instance.logger.method_calls)
680 assert "private encryption detail" not in logged
681 assert "private body" not in logged
682 assert "private title" not in logged
683 assert "private-device" not in logged
684
685
686 @mock.patch("requests.post")
687 def test_plugin_bark_encrypted_send_http_error(mock_post, monkeypatch):
688 """NotifyBark() suppresses response details when encrypted."""
689 pytest.importorskip("cryptography")
690 monkeypatch.setattr(
691 bark_module.secrets,
692 "token_urlsafe",
693 lambda length: "fixed-iv-123",
694 )
695 response = mock.Mock()
696 response.status_code = requests.codes.internal_server_error
697 response.content = b"private response body"
698 mock_post.return_value = response
699 instance = NotifyBark(
700 host="localhost",
701 targets=("private-device",),
702 secure=True,
703 encryption_key="k" * 32,
704 include_image=False,
705 )
706 instance.logger = mock.Mock()
707
708 assert instance.send(body="private body", title="private title") is False
709 # The encrypted request still went out; it's the server's response
710 # that failed, not the encryption step
711 assert mock_post.call_count == 1
712
713 # A failure warning must still surface, just without the response
714 # body attached to it
715 instance.logger.warning.assert_called_once()
716 logged = repr(instance.logger.method_calls)
717 assert "private response body" not in logged
718 assert "private body" not in logged
719 assert "private title" not in logged
720 assert "private-device" not in logged
721
722
723 @mock.patch("requests.post")
724 def test_plugin_bark_encrypted_send_connection_error(mock_post, monkeypatch):
725 """NotifyBark() suppresses socket exception details when encrypted."""
726 pytest.importorskip("cryptography")
727 monkeypatch.setattr(
728 bark_module.secrets,
729 "token_urlsafe",
730 lambda length: "fixed-iv-123",
731 )
732 mock_post.side_effect = requests.RequestException("private socket detail")
733 instance = NotifyBark(
734 host="localhost",
735 targets=("private-device",),
736 secure=True,
737 encryption_key="k" * 32,
738 include_image=False,
739 )
740 instance.logger = mock.Mock()
741
742 assert instance.send(body="private body", title="private title") is False
743 assert mock_post.call_count == 1
744
745 # A failure warning must still surface, just without the raw
746 # exception text attached to it
747 instance.logger.warning.assert_called_once()
748 logged = repr(instance.logger.method_calls)
749 assert "private socket detail" not in logged
750 assert "private body" not in logged
751 assert "private title" not in logged
752 assert "private-device" not in logged
753
754
755 def test_plugin_bark_runtime_dependencies():
756 """NotifyBark() declares its optional cryptography dependency."""
757 assert NotifyBark.runtime_deps() == ("cryptography",)