Debian Codegraph @

tests/test_plugin_sogs.py

raw symbols SCIP
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.plugins.sogs import (
39 NotifySessionOGS,
40 _build_session_message,
41 _encode_varint,
42 _ld_field,
43 )
44
45 logging.disable(logging.CRITICAL)
46
47 # A valid 64-hex-char Ed25519 seed used as the bot seed.
48 SEED = "a" * 64
49
50 # A valid 64-hex-char server Curve25519 public key (from Session join URL).
51 PUBLIC_KEY = "b" * 64
52
53 # An invalid key: 63 chars (too short).
54 BAD_KEY = "c" * 63
55
56 # A valid room token.
57 ROOM = "test-room"
58
59 # Second room token for multi-room tests.
60 ROOM2 = "another-room"
61
62 # Canonical base URL used throughout the tests.
63 BASE_URL = f"sessions://{PUBLIC_KEY}:{SEED}@open.getsession.org/{ROOM}"
64
65 # Apprise URL tester entries; requires cryptography to run functionally.
66 apprise_url_tests = (
67 # Missing public_key and seed (only hostname + room, no credentials)
68 (
69 f"sessions://host/{ROOM}",
70 {
71 "instance": TypeError,
72 },
73 ),
74 # Missing seed (user field present, no password)
75 (
76 f"sessions://{PUBLIC_KEY}@host/{ROOM}",
77 {
78 "instance": TypeError,
79 },
80 ),
81 # Missing public_key (bad key in user field, too short)
82 (
83 f"sessions://{BAD_KEY}:{SEED}@host/{ROOM}",
84 {
85 "instance": TypeError,
86 },
87 ),
88 # Missing room token (no path segments)
89 (
90 f"sessions://{PUBLIC_KEY}:{SEED}@host",
91 {
92 "instance": TypeError,
93 },
94 ),
95 # Invalid seed (too short, in password field)
96 (
97 f"sessions://{PUBLIC_KEY}:{BAD_KEY}@host/{ROOM}",
98 {
99 "instance": TypeError,
100 },
101 ),
102 # Valid HTTPS URL - single room
103 (
104 BASE_URL,
105 {
106 "instance": NotifySessionOGS,
107 "privacy_url": (
108 f"sessions://{PUBLIC_KEY}:[email protected]/{ROOM}"
109 ),
110 "requests_response_code": requests.codes.created,
111 },
112 ),
113 # Valid HTTPS URL via ?to= alias (public_key:seed in authority field)
114 (
115 f"sessions://{PUBLIC_KEY}:{SEED}@open.getsession.org?to={ROOM}",
116 {
117 "instance": NotifySessionOGS,
118 "requests_response_code": requests.codes.created,
119 },
120 ),
121 # Valid HTTPS URL with custom port
122 (
123 f"sessions://{PUBLIC_KEY}:{SEED}@open.getsession.org:8443/{ROOM}",
124 {
125 "instance": NotifySessionOGS,
126 "requests_response_code": requests.codes.created,
127 },
128 ),
129 # Valid HTTP (insecure) URL
130 (
131 f"session://{PUBLIC_KEY}:{SEED}@open.getsession.org/{ROOM}",
132 {
133 "instance": NotifySessionOGS,
134 "requests_response_code": requests.codes.created,
135 },
136 ),
137 # sogs:// alias for sessions:// (HTTPS)
138 (
139 f"sogs://{PUBLIC_KEY}:{SEED}@open.getsession.org/{ROOM}",
140 {
141 "instance": NotifySessionOGS,
142 "requests_response_code": requests.codes.created,
143 },
144 ),
145 # Multiple rooms as path segments
146 (
147 f"sessions://{PUBLIC_KEY}:{SEED}@open.getsession.org/{ROOM}/{ROOM2}",
148 {
149 "instance": NotifySessionOGS,
150 "requests_response_code": requests.codes.created,
151 },
152 ),
153 # Query-string form: ?key= and ?seed= instead of authority field
154 (
155 f"sessions://open.getsession.org/{ROOM}?key={PUBLIC_KEY}&seed={SEED}",
156 {
157 "instance": NotifySessionOGS,
158 "requests_response_code": requests.codes.created,
159 },
160 ),
161 # Query-string form using Session-native ?public_key= alias
162 (
163 f"sessions://open.getsession.org/{ROOM}"
164 f"?public_key={PUBLIC_KEY}&seed={SEED}",
165 {
166 "instance": NotifySessionOGS,
167 "requests_response_code": requests.codes.created,
168 },
169 ),
170 # HTTP 403 Forbidden
171 (
172 BASE_URL,
173 {
174 "instance": NotifySessionOGS,
175 "response": False,
176 "requests_response_code": requests.codes.forbidden,
177 },
178 ),
179 # HTTP 500 Internal Server Error
180 (
181 BASE_URL,
182 {
183 "instance": NotifySessionOGS,
184 "response": False,
185 "requests_response_code": requests.codes.internal_server_error,
186 },
187 ),
188 # Unknown HTTP status code
189 (
190 BASE_URL,
191 {
192 "instance": NotifySessionOGS,
193 "response": False,
194 "requests_response_code": 999,
195 },
196 ),
197 # RequestException
198 (
199 BASE_URL,
200 {
201 "instance": NotifySessionOGS,
202 "test_requests_exceptions": True,
203 },
204 ),
205 )
206
207
208 @pytest.mark.skipif(
209 "cryptography" not in sys.modules,
210 reason="Requires cryptography",
211 )
212 def test_plugin_sogs_urls():
213 """Run the Apprise URL test suite against SOGS URLs."""
214 helper = AppriseURLTester(tests=apprise_url_tests)
215 helper.run_all()
216
217
218 @pytest.mark.skipif(
219 "cryptography" in sys.modules,
220 reason="Requires that cryptography NOT be installed",
221 )
222 def test_plugin_sogs_no_cryptography():
223 """Plugin is disabled when cryptography is not installed."""
224 # Apprise.instantiate() returns None for disabled plugins.
225 obj = Apprise.instantiate(BASE_URL)
226 assert obj is None
227
228 # Direct instantiation must raise ImportError with a helpful message,
229 # not the confusing AttributeError from None.from_private_bytes().
230 with pytest.raises(ImportError, match="cryptography"):
231 NotifySessionOGS(public_key=PUBLIC_KEY, seed=SEED, targets=[ROOM])
232
233
234 @pytest.mark.skipif(
235 "cryptography" not in sys.modules,
236 reason="Requires cryptography",
237 )
238 @mock.patch("requests.post")
239 def test_plugin_sogs_init(mock_post):
240 """Test basic initialization and URL round-trip."""
241
242 def _mk_resp(code=requests.codes.created):
243 r = mock.Mock()
244 r.status_code = code
245 r.content = b'{"id": 1}'
246 return r
247
248 mock_post.return_value = _mk_resp()
249
250 # Basic construction.
251 obj = NotifySessionOGS(
252 public_key=PUBLIC_KEY,
253 seed=SEED,
254 targets=[ROOM],
255 host="open.getsession.org",
256 )
257 assert obj.rooms == [ROOM]
258 assert obj.public_key == PUBLIC_KEY
259 assert obj.seed == SEED
260
261 # Round-trip invariant.
262 url = obj.url()
263 parsed = NotifySessionOGS.parse_url(url)
264 obj2 = NotifySessionOGS(**parsed)
265 assert obj.url_identifier == obj2.url_identifier
266 assert len(obj.rooms) == len(obj2.rooms)
267
268
269 @pytest.mark.skipif(
270 "cryptography" not in sys.modules,
271 reason="Requires cryptography",
272 )
273 @mock.patch("requests.post")
274 def test_plugin_sogs_missing_public_key(mock_post):
275 """TypeError is raised when public_key is absent or invalid."""
276 with pytest.raises(TypeError):
277 NotifySessionOGS(
278 public_key=None,
279 seed=SEED,
280 targets=[ROOM],
281 host="host",
282 )
283 with pytest.raises(TypeError):
284 NotifySessionOGS(
285 public_key=BAD_KEY,
286 seed=SEED,
287 targets=[ROOM],
288 host="host",
289 )
290
291
292 @pytest.mark.skipif(
293 "cryptography" not in sys.modules,
294 reason="Requires cryptography",
295 )
296 @mock.patch("requests.post")
297 def test_plugin_sogs_missing_seed(mock_post):
298 """TypeError is raised when seed is absent or invalid."""
299 with pytest.raises(TypeError):
300 NotifySessionOGS(
301 public_key=PUBLIC_KEY,
302 seed=None,
303 targets=[ROOM],
304 host="host",
305 )
306 with pytest.raises(TypeError):
307 NotifySessionOGS(
308 public_key=PUBLIC_KEY,
309 seed=BAD_KEY,
310 targets=[ROOM],
311 host="host",
312 )
313
314
315 @pytest.mark.skipif(
316 "cryptography" not in sys.modules,
317 reason="Requires cryptography",
318 )
319 @mock.patch("requests.post")
320 def test_plugin_sogs_missing_rooms(mock_post):
321 """TypeError is raised when no valid room token is provided."""
322 with pytest.raises(TypeError):
323 NotifySessionOGS(
324 public_key=PUBLIC_KEY,
325 seed=SEED,
326 targets=None,
327 host="host",
328 )
329 with pytest.raises(TypeError):
330 NotifySessionOGS(
331 public_key=PUBLIC_KEY,
332 seed=SEED,
333 targets=["!!invalid!!"],
334 host="host",
335 )
336
337
338 @pytest.mark.skipif(
339 "cryptography" not in sys.modules,
340 reason="Requires cryptography",
341 )
342 @mock.patch("requests.post")
343 def test_plugin_sogs_send_success(mock_post):
344 """A 201 Created response is treated as success."""
345
346 def _mk_resp(code=requests.codes.created):
347 r = mock.Mock()
348 r.status_code = code
349 r.content = b'{"id": 1}'
350 return r
351
352 mock_post.return_value = _mk_resp()
353
354 obj = NotifySessionOGS(
355 public_key=PUBLIC_KEY,
356 seed=SEED,
357 targets=[ROOM],
358 host="open.getsession.org",
359 )
360 assert obj.notify(body="Hello SOGS") is True
361 assert mock_post.call_count == 1
362
363 # HTTP 200 (OK) is also treated as success.
364 mock_post.return_value = _mk_resp(requests.codes.ok)
365 assert obj.notify(body="Hello SOGS") is True
366
367
368 @pytest.mark.skipif(
369 "cryptography" not in sys.modules,
370 reason="Requires cryptography",
371 )
372 @mock.patch("requests.post")
373 def test_plugin_sogs_send_multi_room(mock_post):
374 """Sending to two rooms makes two POST requests."""
375
376 def _mk_resp(code=requests.codes.created):
377 r = mock.Mock()
378 r.status_code = code
379 r.content = b'{"id": 1}'
380 return r
381
382 mock_post.return_value = _mk_resp()
383
384 obj = NotifySessionOGS(
385 public_key=PUBLIC_KEY,
386 seed=SEED,
387 targets=[ROOM, ROOM2],
388 host="open.getsession.org",
389 )
390 assert obj.notify(body="Multi") is True
391 assert mock_post.call_count == 2
392
393
394 @pytest.mark.skipif(
395 "cryptography" not in sys.modules,
396 reason="Requires cryptography",
397 )
398 @mock.patch("requests.post")
399 def test_plugin_sogs_send_partial_failure(mock_post):
400 """Failure on any room causes the overall notify() to return False."""
401
402 def _mk_resp(code):
403 r = mock.Mock()
404 r.status_code = code
405 r.content = b""
406 return r
407
408 mock_post.side_effect = [
409 _mk_resp(requests.codes.created),
410 _mk_resp(requests.codes.forbidden),
411 ]
412
413 obj = NotifySessionOGS(
414 public_key=PUBLIC_KEY,
415 seed=SEED,
416 targets=[ROOM, ROOM2],
417 host="open.getsession.org",
418 )
419 assert obj.notify(body="Partial") is False
420 assert mock_post.call_count == 2
421
422
423 @pytest.mark.skipif(
424 "cryptography" not in sys.modules,
425 reason="Requires cryptography",
426 )
427 @mock.patch("requests.post")
428 def test_plugin_sogs_http_error(mock_post):
429 """Non-2xx responses cause send() to return False."""
430
431 def _mk_resp(code):
432 r = mock.Mock()
433 r.status_code = code
434 r.content = b""
435 return r
436
437 obj = NotifySessionOGS(
438 public_key=PUBLIC_KEY,
439 seed=SEED,
440 targets=[ROOM],
441 host="open.getsession.org",
442 )
443
444 for code in (
445 requests.codes.bad_request,
446 requests.codes.unauthorized,
447 requests.codes.forbidden,
448 requests.codes.not_found,
449 requests.codes.internal_server_error,
450 999,
451 ):
452 mock_post.reset_mock()
453 mock_post.return_value = _mk_resp(code)
454 assert obj.notify(body="Error") is False
455
456
457 @pytest.mark.skipif(
458 "cryptography" not in sys.modules,
459 reason="Requires cryptography",
460 )
461 @mock.patch("requests.post")
462 def test_plugin_sogs_request_exception(mock_post):
463 """requests.RequestException causes send() to return False."""
464 mock_post.side_effect = requests.RequestException("network error")
465
466 obj = NotifySessionOGS(
467 public_key=PUBLIC_KEY,
468 seed=SEED,
469 targets=[ROOM],
470 host="open.getsession.org",
471 )
472 assert obj.notify(body="Error") is False
473
474
475 @pytest.mark.skipif(
476 "cryptography" not in sys.modules,
477 reason="Requires cryptography",
478 )
479 @mock.patch("requests.post")
480 def test_plugin_sogs_http_insecure(mock_post):
481 """session:// sends over plain HTTP."""
482
483 def _mk_resp():
484 r = mock.Mock()
485 r.status_code = requests.codes.created
486 r.content = b'{"id": 1}'
487 return r
488
489 mock_post.return_value = _mk_resp()
490
491 obj = Apprise()
492 assert obj.add(f"session://{PUBLIC_KEY}:{SEED}@open.getsession.org/{ROOM}")
493 assert obj.notify(body="Plain HTTP") is True
494
495 # Confirm the request was sent to http:// not https://.
496 url_called = mock_post.call_args[0][0]
497 assert url_called.startswith("http://")
498 assert "https://" not in url_called
499
500
501 @pytest.mark.skipif(
502 "cryptography" not in sys.modules,
503 reason="Requires cryptography",
504 )
505 @mock.patch("requests.post")
506 def test_plugin_sogs_url_and_privacy(mock_post):
507 """url() round-trips and masks seed in privacy mode."""
508
509 def _mk_resp():
510 r = mock.Mock()
511 r.status_code = requests.codes.created
512 r.content = b'{"id": 1}'
513 return r
514
515 mock_post.return_value = _mk_resp()
516
517 obj = NotifySessionOGS(
518 public_key=PUBLIC_KEY,
519 seed=SEED,
520 targets=[ROOM],
521 host="open.getsession.org",
522 )
523
524 full_url = obj.url(privacy=False)
525 assert SEED in full_url
526 assert PUBLIC_KEY in full_url
527
528 priv_url = obj.url(privacy=True)
529 assert SEED not in priv_url
530 assert PUBLIC_KEY in priv_url
531
532 # Round-trip.
533 parsed = NotifySessionOGS.parse_url(full_url)
534 obj2 = NotifySessionOGS(**parsed)
535 assert obj.url_identifier == obj2.url_identifier
536
537
538 @pytest.mark.skipif(
539 "cryptography" not in sys.modules,
540 reason="Requires cryptography",
541 )
542 @mock.patch("requests.post")
543 def test_plugin_sogs_custom_port(mock_post):
544 """Custom port is encoded in the URL and used in requests."""
545
546 def _mk_resp():
547 r = mock.Mock()
548 r.status_code = requests.codes.created
549 r.content = b'{"id": 1}'
550 return r
551
552 mock_post.return_value = _mk_resp()
553
554 obj = NotifySessionOGS(
555 public_key=PUBLIC_KEY,
556 seed=SEED,
557 targets=[ROOM],
558 host="open.getsession.org",
559 port=8443,
560 )
561 assert ":8443" in obj.url()
562 assert obj.notify(body="custom port") is True
563
564 url_called = mock_post.call_args[0][0]
565 assert ":8443" in url_called
566
567
568 def test_plugin_sogs_sogs_alias():
569 """sogs:// is accepted as an alias for sessions:// (HTTPS)."""
570
571 # parse_url must recognise the sogs:// schema.
572 url = f"sogs://{PUBLIC_KEY}:{SEED}@open.getsession.org/{ROOM}"
573 results = NotifySessionOGS.parse_url(url)
574 assert results is not None
575 assert results["public_key"] == PUBLIC_KEY
576 assert results["seed"] == SEED
577 assert ROOM in results["targets"]
578
579 # The parsed schema must be "sogs" (the alias used in the input URL).
580 assert results["schema"] == "sogs"
581
582
583 def test_plugin_sogs_parse_url():
584 """parse_url extracts all expected fields."""
585
586 # Canonical format: public_key:seed in authority, rooms in path.
587 url = f"sessions://{PUBLIC_KEY}:{SEED}@open.getsession.org/{ROOM}/{ROOM2}"
588 results = NotifySessionOGS.parse_url(url)
589 assert results["public_key"] == PUBLIC_KEY
590 assert results["seed"] == SEED
591 assert ROOM in results["targets"]
592 assert ROOM2 in results["targets"]
593
594 # ?key= query param provides the public key (no user in URL).
595 url2 = (
596 f"sessions://open.getsession.org/{ROOM}?key={PUBLIC_KEY}&seed={SEED}"
597 )
598 results2 = NotifySessionOGS.parse_url(url2)
599 assert results2["public_key"] == PUBLIC_KEY
600 assert results2["seed"] == SEED
601
602 # ?public_key= is the Session-native alias and overrides ?key= when both
603 # are present.
604 url2b = (
605 f"sessions://open.getsession.org/{ROOM}"
606 f"?public_key={PUBLIC_KEY}&seed={SEED}"
607 )
608 results2b = NotifySessionOGS.parse_url(url2b)
609 assert results2b["public_key"] == PUBLIC_KEY
610 assert results2b["seed"] == SEED
611
612 # ?to= alias populates targets (no room in path).
613 url3 = f"sessions://{PUBLIC_KEY}:{SEED}@open.getsession.org?to={ROOM}"
614 results3 = NotifySessionOGS.parse_url(url3)
615 assert ROOM in results3["targets"]
616
617 # No password field -> seed is None.
618 url4 = f"sessions://{PUBLIC_KEY}@open.getsession.org/{ROOM}"
619 results4 = NotifySessionOGS.parse_url(url4)
620 assert results4["seed"] is None
621
622 # Empty URL -> None (host is required; verify_host=True is the default).
623 assert NotifySessionOGS.parse_url("sessions://") is None
624
625
626 @pytest.mark.skipif(
627 "cryptography" not in sys.modules,
628 reason="Requires cryptography",
629 )
630 @mock.patch("requests.post")
631 def test_plugin_sogs_invalid_room_token(mock_post):
632 """Invalid room tokens are stored in invalid_rooms and survive url()."""
633
634 def _mk_resp():
635 r = mock.Mock()
636 r.status_code = requests.codes.created
637 r.content = b'{"id": 1}'
638 return r
639
640 mock_post.return_value = _mk_resp()
641
642 # One valid + one invalid: must succeed with at least one valid room.
643 obj = NotifySessionOGS(
644 public_key=PUBLIC_KEY,
645 seed=SEED,
646 targets=[ROOM, "!!!bad!!!"],
647 host="open.getsession.org",
648 )
649 assert obj.rooms == [ROOM]
650 assert len(obj.invalid_rooms) == 1
651
652 # Invalid rooms survive url() round-trip (no silent data loss).
653 full_url = obj.url()
654 parsed = NotifySessionOGS.parse_url(full_url)
655 obj2 = NotifySessionOGS(**parsed)
656 assert obj.url_identifier == obj2.url_identifier
657
658
659 @pytest.mark.skipif(
660 "cryptography" not in sys.modules,
661 reason="Requires cryptography",
662 )
663 @mock.patch("requests.post")
664 def test_plugin_sogs_url_identifier(mock_post):
665 """url_identifier distinguishes connections by public_key and host."""
666
667 def _mk_obj(host, public_key=PUBLIC_KEY):
668 return NotifySessionOGS(
669 public_key=public_key,
670 seed=SEED,
671 targets=[ROOM],
672 host=host,
673 )
674
675 obj_a = _mk_obj("server-a.example.com")
676 obj_b = _mk_obj("server-b.example.com")
677 obj_c = _mk_obj("server-a.example.com", public_key="d" * 64)
678
679 # Same host + same public_key -> same identifier.
680 obj_a2 = _mk_obj("server-a.example.com")
681 assert obj_a.url_identifier == obj_a2.url_identifier
682
683 # Different host -> different identifier.
684 assert obj_a.url_identifier != obj_b.url_identifier
685
686 # Same host, different public_key -> different identifier.
687 assert obj_a.url_identifier != obj_c.url_identifier
688
689
690 @pytest.mark.skipif(
691 "cryptography" not in sys.modules,
692 reason="Requires cryptography",
693 )
694 @mock.patch("requests.post")
695 def test_plugin_sogs_auth_headers(mock_post):
696 """X-SOGS-* headers are present and well-formed on every request."""
697
698 def _mk_resp():
699 r = mock.Mock()
700 r.status_code = requests.codes.created
701 r.content = b'{"id": 1}'
702 return r
703
704 mock_post.return_value = _mk_resp()
705
706 obj = NotifySessionOGS(
707 public_key=PUBLIC_KEY,
708 seed=SEED,
709 targets=[ROOM],
710 host="open.getsession.org",
711 )
712 assert obj.notify(body="Auth test") is True
713
714 call_kwargs = mock_post.call_args[1]
715 headers = call_kwargs.get("headers", {})
716
717 # All four X-SOGS-* headers must be present.
718 assert "X-SOGS-Pubkey" in headers
719 assert "X-SOGS-Nonce" in headers
720 assert "X-SOGS-Timestamp" in headers
721 assert "X-SOGS-Signature" in headers
722
723 # Pubkey starts with "00" (unblinded) then 64 hex chars.
724 pk = headers["X-SOGS-Pubkey"]
725 assert pk.startswith("00")
726 assert len(pk) == 66 # "00" + 32-byte pubkey hex = 2 + 64
727
728 # Timestamp is a digit string.
729 assert headers["X-SOGS-Timestamp"].isdigit()
730
731 # Verify the no-body branch of _sogs_auth_headers (body_bytes=None
732 # skips the blake2b step; the returned dict must still be well-formed).
733 obj2 = NotifySessionOGS(
734 public_key=PUBLIC_KEY,
735 seed=SEED,
736 targets=[ROOM],
737 host="open.getsession.org",
738 )
739 no_body_headers = obj2._sogs_auth_headers("GET", "/room/test")
740 assert "X-SOGS-Pubkey" in no_body_headers
741 assert "X-SOGS-Nonce" in no_body_headers
742 assert "X-SOGS-Timestamp" in no_body_headers
743 assert "X-SOGS-Signature" in no_body_headers
744
745
746 @pytest.mark.skipif(
747 "cryptography" not in sys.modules,
748 reason="Requires cryptography",
749 )
750 @mock.patch("requests.post")
751 def test_plugin_sogs_response_unparseable_json(mock_post):
752 """Unparseable response body is handled gracefully."""
753 r = mock.Mock()
754 r.status_code = requests.codes.created
755 r.content = b"not-json"
756 mock_post.return_value = r
757
758 obj = NotifySessionOGS(
759 public_key=PUBLIC_KEY,
760 seed=SEED,
761 targets=[ROOM],
762 host="open.getsession.org",
763 )
764 assert obj.notify(body="Hello") is True
765
766
767 def test_plugin_sogs_build_session_message():
768 """_build_session_message produces valid padded protobuf bytes."""
769 msg = _build_session_message("hello")
770
771 # Must be bytes and non-empty.
772 assert isinstance(msg, bytes)
773 assert len(msg) > 0
774
775 # Ends with the Session padding marker 0x80.
776 assert msg[-1] == 0x80
777
778 # Starts with protobuf tag 0x0A (field 1, wire type 2).
779 assert msg[0] == 0x0A
780
781
782 def test_plugin_sogs_encode_varint():
783 """_encode_varint encodes small and multi-byte integers correctly."""
784 assert _encode_varint(0) == b"\x00"
785 assert _encode_varint(1) == b"\x01"
786 assert _encode_varint(127) == b"\x7f"
787 assert _encode_varint(128) == b"\x80\x01"
788 assert _encode_varint(300) == b"\xac\x02"
789
790
791 def test_plugin_sogs_ld_field():
792 """_ld_field encodes a length-delimited protobuf field."""
793 encoded = _ld_field(1, b"hi")
794 assert encoded == b"\x0a\x02hi"
795
796
797 def test_plugin_sogs_runtime_deps():
798 """runtime_deps() returns the cryptography package name."""
799 deps = NotifySessionOGS.runtime_deps()
800 assert "cryptography" in deps
801
802
803 @pytest.mark.skipif(
804 "cryptography" not in sys.modules,
805 reason="Requires cryptography",
806 )
807 @mock.patch("requests.post")
808 def test_plugin_sogs_apprise_integration(mock_post):
809 """Apprise.add() and Apprise.notify() work end-to-end."""
810
811 def _mk_resp():
812 r = mock.Mock()
813 r.status_code = requests.codes.created
814 r.content = b'{"id": 1}'
815 return r
816
817 mock_post.return_value = _mk_resp()
818
819 app = Apprise()
820 assert app.add(BASE_URL)
821 assert app.notify(title="Title", body="Body") is True
822 assert mock_post.call_count == 1