Debian Codegraph @

tests/test_plugin_matrix.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 from json import dumps, loads
29
30 # Disable logging for a cleaner testing output
31 import logging
32 import os
33 from typing import Union
34 from unittest import mock
35
36 from helpers import AppriseURLTester
37 import pytest
38 import requests
39
40 from apprise import (
41 Apprise,
42 AppriseAsset,
43 AppriseAttachment,
44 NotifyFormat,
45 NotifyType,
46 OverflowMode,
47 PersistentStoreMode,
48 )
49 from apprise.plugins.matrix import MatrixDiscoveryException, NotifyMatrix
50
51 # Use Matrix's internal limit and mode names for exact boundary assertions.
52 from apprise.plugins.matrix.base import (
53 MATRIX_CONTENT_BYTE_LIMIT,
54 MatrixWebhookMode,
55 )
56
57 logging.disable(logging.CRITICAL)
58
59 MATRIX_GOOD_RESPONSE = dumps(
60 {
61 "room_id": "!abc123:localhost",
62 "room_alias": "#abc123:localhost",
63 "joined_rooms": ["!abc123:localhost", "!def456:localhost"],
64 "access_token": "abcd1234",
65 "home_server": "localhost",
66 # user_id is returned by /login and /account/whoami; including it
67 # here ensures self.user_id is set after login so _whoami() is not
68 # called unnecessarily (it only fires when user_id is still absent).
69 "user_id": "@apprise:localhost",
70 # Simulate .well-known
71 "m.homeserver": {"base_url": "https://matrix.example.com"},
72 "m.identity_server": {"base_url": "https://vector.im"},
73 }
74 )
75
76 # Attachment Directory
77 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
78
79 # Our Testing URLs
80 apprise_url_tests = (
81 ##################################
82 # NotifyMatrix
83 ##################################
84 (
85 "matrix://",
86 {
87 "instance": None,
88 },
89 ),
90 (
91 "matrixs://",
92 {
93 "instance": None,
94 },
95 ),
96 (
97 "matrix://localhost?mode=off",
98 {
99 # treats it as a anonymous user to register
100 "instance": NotifyMatrix,
101 # response is false because we have nothing to notify
102 "response": False,
103 },
104 ),
105 (
106 "matrix://localhost",
107 {
108 # response is TypeError because we'll try to initialize as
109 # a t2bot and fail (localhost is too short of a api key)
110 "instance": TypeError
111 },
112 ),
113 (
114 "matrix://user:pass@localhost/#room1/#room2/#room3",
115 {
116 "instance": NotifyMatrix,
117 "response": False,
118 "requests_response_code": requests.codes.internal_server_error,
119 },
120 ),
121 (
122 "matrix://user:pass@localhost/#room1/#room2/!room1",
123 {
124 "instance": NotifyMatrix,
125 # throw a bizarre code forcing us to fail to look it up
126 "response": False,
127 "requests_response_code": 999,
128 },
129 ),
130 (
131 "matrix://user:pass@localhost:1234/#room",
132 {
133 "instance": NotifyMatrix,
134 # Throws a series of i/o exceptions with this flag
135 # is set and tests that we gracefully handle them
136 "test_requests_exceptions": True,
137 # Our expected url(privacy=True) startswith() response:
138 "privacy_url": "matrix://user:****@localhost:1234/",
139 },
140 ),
141 # Matrix supports webhooks too; the following tests this now:
142 (
143 "matrix://user:token@localhost?mode=matrix&format=text",
144 {
145 # user and token correctly specified with webhook
146 "instance": NotifyMatrix,
147 "response": False,
148 },
149 ),
150 (
151 "matrix://user:token@localhost?mode=matrix&format=html",
152 {
153 # user and token correctly specified with webhook
154 "instance": NotifyMatrix,
155 },
156 ),
157 (
158 "matrix://user:token@localhost:123/#general/?version=3",
159 {
160 # Provide version over-ride (using version=)
161 "instance": NotifyMatrix,
162 # Our response expected server response
163 "requests_response_text": MATRIX_GOOD_RESPONSE,
164 "privacy_url": "matrix://user:****@localhost:123",
165 },
166 ),
167 (
168 "matrixs://user:token@localhost/#general?v=2",
169 {
170 # Provide version over-ride (using v=)
171 "instance": NotifyMatrix,
172 # Our response expected server response
173 "requests_response_text": MATRIX_GOOD_RESPONSE,
174 "privacy_url": "matrixs://user:****@localhost",
175 },
176 ),
177 (
178 "matrix://user:token@localhost:123/#general/?v=invalid",
179 {
180 # Invalid version specified
181 "instance": TypeError
182 },
183 ),
184 (
185 "matrix://user:token@localhost?mode=slack&format=text",
186 {
187 # user and token correctly specified with webhook
188 "instance": NotifyMatrix,
189 },
190 ),
191 (
192 "matrixs://user:token@localhost?mode=SLACK&format=markdown",
193 {
194 # user and token specified; slack webhook still detected
195 # despite uppercase characters
196 "instance": NotifyMatrix,
197 },
198 ),
199 (
200 "matrix://user@localhost?mode=SLACK&format=markdown&token=mytoken",
201 {
202 # user and token specified; slack webhook still detected
203 # despite uppercase characters; token also set on URL as arg
204 "instance": NotifyMatrix,
205 },
206 ),
207 (
208 "matrix://_?mode=t2bot&token={}".format("b" * 64),
209 {
210 # Testing t2bot initialization and setting the password using the
211 # token directive
212 "instance": NotifyMatrix,
213 # Our expected url(privacy=True) startswith() response:
214 "privacy_url": "matrix://b...b/",
215 },
216 ),
217 (
218 (
219 "matrixs://hookuser:[email protected]"
220 "?mode=hookshot&path=%2Fpublic-hooks"
221 ),
222 {
223 "instance": NotifyMatrix,
224 "privacy_url": (
225 "matrixs://hookuser:****@hookshot.example/"
226 "?image=no&mode=hookshot"
227 ),
228 },
229 ),
230 (
231 (
232 "matrixs://hookuser:[email protected]"
233 "?mode=hookshot&path=public-hooks"
234 ),
235 {
236 "instance": NotifyMatrix,
237 },
238 ),
239 # Image Reference
240 (
241 "matrixs://user:token@localhost?mode=slack&format=markdown&image=True",
242 {
243 # user and token specified; image set to True
244 "instance": NotifyMatrix,
245 },
246 ),
247 (
248 (
249 "matrixs://user:token@localhost?mode=slack"
250 "&format=markdown&image=False"
251 ),
252 {
253 # user and token specified; image set to True
254 "instance": NotifyMatrix,
255 },
256 ),
257 # A Bunch of bad ports
258 (
259 "matrixs://user:pass@hostname:port/#room_alias",
260 {
261 # Invalid Port specified (was a string)
262 "instance": TypeError,
263 },
264 ),
265 (
266 "matrixs://user:pass@hostname:0/#room_alias",
267 {
268 # Invalid Port specified (was a string)
269 "instance": TypeError,
270 },
271 ),
272 (
273 "matrixs://user:pass@hostname:65536/#room_alias",
274 {
275 # Invalid Port specified (was a string)
276 "instance": TypeError,
277 },
278 ),
279 # More general testing...
280 (
281 "matrixs://user@{}?mode=t2bot&format=markdown&image=True".format(
282 "a" * 64
283 ),
284 {
285 # user and token specified; image set to True
286 "instance": NotifyMatrix
287 },
288 ),
289 (
290 "matrix://user@{}?mode=t2bot&format=html&image=False".format("z" * 64),
291 {
292 # user and token specified; image set to True
293 "instance": NotifyMatrix
294 },
295 ),
296 # This will default to t2bot because no targets were specified and no
297 # password
298 (
299 "matrixs://{}".format("c" * 64),
300 {
301 "instance": NotifyMatrix,
302 # Throws a series of i/o exceptions with this flag
303 # is set and tests that we gracefully handle them
304 "test_requests_exceptions": True,
305 },
306 ),
307 # Test Native URL
308 (
309 "https://webhooks.t2bot.io/api/v1/matrix/hook/{}/".format("d" * 64),
310 {
311 # user and token specified; image set to True
312 "instance": NotifyMatrix,
313 },
314 ),
315 (
316 "matrix://user:token@localhost?mode=On",
317 {
318 # invalid webhook specified (unexpected boolean)
319 "instance": TypeError,
320 },
321 ),
322 (
323 "matrix://token@localhost/?mode=Matrix",
324 {
325 "instance": NotifyMatrix,
326 "response": False,
327 "requests_response_code": requests.codes.internal_server_error,
328 },
329 ),
330 (
331 "matrix://user:token@localhost/mode=matrix",
332 {
333 "instance": NotifyMatrix,
334 # throw a bizarre code forcing us to fail to look it up
335 "response": False,
336 "requests_response_code": 999,
337 },
338 ),
339 (
340 "matrix://token@localhost:8080/?mode=slack",
341 {
342 "instance": NotifyMatrix,
343 # Throws a series of i/o exceptions with this flag
344 # is set and tests that we gracefully handle them
345 "test_requests_exceptions": True,
346 },
347 ),
348 (
349 "matrix://{}/?mode=t2bot".format("b" * 64),
350 {
351 "instance": NotifyMatrix,
352 # Throws a series of i/o exceptions with this flag
353 # is set and tests that we gracefully handle them
354 "test_requests_exceptions": True,
355 },
356 ),
357 )
358
359
360 def test_plugin_matrix_urls():
361 """NotifyMatrix() Apprise URLs."""
362
363 # Run our general tests
364 AppriseURLTester(tests=apprise_url_tests).run_all()
365
366
367 @mock.patch("requests.put")
368 @mock.patch("requests.get")
369 @mock.patch("requests.post")
370 def test_plugin_matrix_general(mock_post, mock_get, mock_put):
371 """NotifyMatrix() General Tests."""
372
373 response_obj = {
374 "room_id": "!abc123:localhost",
375 "room_alias": "#abc123:localhost",
376 "joined_rooms": ["!abc123:localhost", "!def456:localhost"],
377 "access_token": "abcd1234",
378 "home_server": "localhost",
379 }
380 request = mock.Mock()
381 request.content = dumps(response_obj)
382 request.status_code = requests.codes.ok
383
384 # Prepare Mock
385 mock_get.return_value = request
386 mock_post.return_value = request
387 mock_put.return_value = request
388
389 # Variation Initializations
390 obj = NotifyMatrix(host="host", targets="#abcd")
391 assert isinstance(obj, NotifyMatrix)
392 assert isinstance(obj.url(), str)
393 # Registration successful
394 assert obj.send(body="test") is True
395 del obj
396
397 obj = NotifyMatrix(host="host", user="user", targets="#abcd")
398 assert isinstance(obj, NotifyMatrix)
399 assert isinstance(obj.url(), str)
400 # Registration successful
401 assert obj.send(body="test") is True
402 del obj
403
404 obj = NotifyMatrix(host="host", password="passwd", targets="#abcd")
405 assert isinstance(obj, NotifyMatrix)
406 assert isinstance(obj.url(), str)
407 # A username gets automatically generated in these cases
408 assert obj.send(body="test") is True
409 del obj
410
411 obj = NotifyMatrix(
412 host="host", user="user", password="passwd", targets="#abcd"
413 )
414 assert isinstance(obj.url(), str)
415 assert isinstance(obj, NotifyMatrix)
416 # Registration Successful
417 assert obj.send(body="test") is True
418 del obj
419
420 # Test sending other format types
421 kwargs = NotifyMatrix.parse_url(
422 "matrix://user:passwd@hostname/#abcd?format=html"
423 )
424 obj = NotifyMatrix(**kwargs)
425 assert isinstance(obj.url(), str)
426 assert isinstance(obj, NotifyMatrix)
427 assert obj.send(body="test") is True
428 assert obj.send(title="title", body="test") is True
429 del obj
430
431 kwargs = NotifyMatrix.parse_url(
432 "matrix://user:passwd@hostname/#abcd/#abcd:localhost?format=markdown"
433 )
434 obj = NotifyMatrix(**kwargs)
435 assert isinstance(obj.url(), str)
436 assert isinstance(obj, NotifyMatrix)
437 assert obj.send(body="test") is True
438 assert obj.send(title="title", body="test") is True
439 del obj
440
441 kwargs = NotifyMatrix.parse_url(
442 "matrix://user:passwd@hostname/#abcd/!abcd:localhost?format=text"
443 )
444 obj = NotifyMatrix(**kwargs)
445 assert isinstance(obj.url(), str)
446 assert isinstance(obj, NotifyMatrix) is True
447 assert obj.send(body="test") is True
448 assert obj.send(title="title", body="test") is True
449 del obj
450
451 # Test notice type notifications
452 kwargs = NotifyMatrix.parse_url(
453 "matrix://user:passwd@hostname/#abcd?msgtype=notice"
454 )
455 obj = NotifyMatrix(**kwargs)
456 assert isinstance(obj.url(), str) is True
457 assert isinstance(obj, NotifyMatrix) is True
458 assert obj.send(body="test") is True
459 assert obj.send(title="title", body="test") is True
460
461 with pytest.raises(TypeError):
462 # invalid message type specified
463 kwargs = NotifyMatrix.parse_url(
464 "matrix://user:passwd@hostname/#abcd?msgtype=invalid"
465 )
466 NotifyMatrix(**kwargs)
467
468 # Force a failed login
469 ro = response_obj.copy()
470 del ro["access_token"]
471 request.content = dumps(ro)
472 request.status_code = 404
473
474 # Fails because we couldn't register because of 404 errors
475 assert obj.send(body="test") is False
476 del obj
477
478 obj = NotifyMatrix(host="host", user="test", targets="#abcd")
479 assert isinstance(obj, NotifyMatrix) is True
480 # Fails because we still couldn't register
481 assert obj.send(user="test", password="passwd", body="test") is False
482 del obj
483
484 obj = NotifyMatrix(
485 host="host", user="test", password="passwd", targets="#abcd"
486 )
487 assert isinstance(obj, NotifyMatrix) is True
488 # Fails because we still couldn't register
489 assert obj.send(body="test") is False
490 del obj
491
492 obj = NotifyMatrix(host="host", password="passwd", targets="#abcd")
493 # Fails because we still couldn't register
494 assert isinstance(obj, NotifyMatrix) is True
495 assert obj.send(body="test") is False
496
497 # Force a empty joined list response
498 ro = response_obj.copy()
499 ro["joined_rooms"] = []
500 request.content = dumps(ro)
501 assert obj.send(user="test", password="passwd", body="test") is False
502
503 # Fall back to original template
504 request.content = dumps(response_obj)
505 request.status_code = requests.codes.ok
506
507 # update our response object so logins now succeed
508 response_obj["user_id"] = "@apprise:localhost"
509
510 # Login was successful but not get a room_id
511 ro = response_obj.copy()
512 del ro["room_id"]
513 request.content = dumps(ro)
514 assert obj.send(user="test", password="passwd", body="test") is False
515
516 # Fall back to original template
517 request.content = dumps(response_obj)
518 request.status_code = requests.codes.ok
519 del obj
520
521 obj = NotifyMatrix(host="host", targets=None)
522 assert isinstance(obj, NotifyMatrix) is True
523
524 # Force a empty joined list response
525 ro = response_obj.copy()
526 ro["joined_rooms"] = []
527 request.content = dumps(ro)
528 assert obj.send(user="test", password="passwd", body="test") is False
529
530 # Fall back to original template
531 request.content = dumps(response_obj)
532 request.status_code = requests.codes.ok
533
534 # our room list is empty so we'll have retrieved the joined_list
535 # as our backup
536 assert obj.send(user="test", password="passwd", body="test") is True
537 del obj
538
539
540 @mock.patch("requests.put")
541 @mock.patch("requests.get")
542 @mock.patch("requests.post")
543 def test_plugin_matrix_fetch(mock_post, mock_get, mock_put):
544 """NotifyMatrix() Server Fetch/API Tests."""
545
546 response_obj = {
547 "room_id": "!abc123:localhost",
548 "room_alias": "#abc123:localhost",
549 "joined_rooms": ["!abc123:localhost", "!def456:localhost"],
550 # Login details
551 "access_token": "abcd1234",
552 "user_id": "@apprise:localhost",
553 "home_server": "localhost",
554 }
555
556 def fetch_failed(url, *args, **kwargs):
557
558 # Default configuration
559 request = mock.Mock()
560 request.status_code = requests.codes.ok
561 request.content = dumps(response_obj)
562
563 if url.find("/rooms/") > -1:
564 # over-ride on room query
565 request.status_code = 403
566 request.content = dumps(
567 {
568 "errcode": "M_UNKNOWN",
569 "error": "Internal server error",
570 }
571 )
572
573 return request
574
575 mock_put.side_effect = fetch_failed
576 mock_get.side_effect = fetch_failed
577 mock_post.side_effect = fetch_failed
578
579 obj = NotifyMatrix(
580 host="host", user="user", password="passwd", include_image=True
581 )
582 assert isinstance(obj, NotifyMatrix) is True
583 # We would hve failed to send our image notification
584 assert obj.send(user="test", password="passwd", body="test") is False
585 del obj
586
587 # Do the same query with no images to fetch
588 asset = AppriseAsset(image_path_mask=False, image_url_mask=False)
589 obj = NotifyMatrix(
590 host="host", user="user", password="passwd", asset=asset
591 )
592 assert isinstance(obj, NotifyMatrix) is True
593 # We would hve failed to send our notification
594 assert obj.send(user="test", password="passwd", body="test") is False
595 del obj
596
597 response_obj = {
598 # Registration
599 "access_token": "abcd1234",
600 "user_id": "@apprise:localhost",
601 "home_server": "localhost",
602 # For room joining
603 "room_id": "!abc123:localhost",
604 }
605
606 # Default configuration
607 mock_get.side_effect = None
608 mock_post.side_effect = None
609 mock_put.side_effect = None
610
611 request = mock.Mock()
612 request.status_code = requests.codes.ok
613 request.content = dumps(response_obj)
614 mock_post.return_value = request
615 mock_get.return_value = request
616 mock_put.return_value = request
617
618 obj = NotifyMatrix(host="host", include_image=True)
619 assert isinstance(obj, NotifyMatrix) is True
620 assert obj.access_token is None
621 assert obj._register() is True
622 assert obj.access_token is not None
623
624 # Cause retries
625 request.status_code = 429
626 request.content = dumps(
627 {
628 "retry_after_ms": 1,
629 }
630 )
631
632 postokay, _response, _ = obj._fetch("/retry/apprise/unit/test")
633 assert postokay is False
634
635 request.content = dumps(
636 {
637 "error": {
638 "retry_after_ms": 1,
639 }
640 }
641 )
642 postokay, _response, _ = obj._fetch("/retry/apprise/unit/test")
643 assert postokay is False
644
645 request.content = dumps({"error": {}})
646 postokay, _response, _ = obj._fetch("/retry/apprise/unit/test")
647 assert postokay is False
648 del obj
649
650
651 @mock.patch("requests.put")
652 @mock.patch("requests.get")
653 @mock.patch("requests.post")
654 def test_plugin_matrix_auth(mock_post, mock_get, mock_put):
655 """NotifyMatrix() Server Authentication."""
656
657 response_obj = {
658 # Registration
659 "access_token": "abcd1234",
660 "user_id": "@apprise:localhost",
661 "home_server": "localhost",
662 }
663
664 # Default configuration
665 request = mock.Mock()
666 request.status_code = requests.codes.ok
667 request.content = dumps(response_obj)
668 mock_post.return_value = request
669 mock_get.return_value = request
670 mock_put.return_value = request
671
672 obj = NotifyMatrix(host="localhost")
673 assert isinstance(obj, NotifyMatrix) is True
674 assert obj.access_token is None
675 # logging out without an access_token is silently a success
676 assert obj._logout() is True
677 assert obj.access_token is None
678
679 assert obj._register() is True
680 assert obj.access_token is not None
681
682 # Logging in is silently treated as a success because we
683 # already had success registering
684 assert obj._login() is True
685 assert obj.access_token is not None
686
687 # However if we log out
688 assert obj._logout() is True
689 assert obj.access_token is None
690
691 # And set ourselves up for failure
692 request.status_code = 403
693 assert obj._login() is False
694 assert obj.access_token is None
695
696 # Reset our token
697 obj.access_token = None
698
699 # Adjust our response to be invalid - missing access_token in response
700 request.status_code = requests.codes.ok
701 ro = response_obj.copy()
702 del ro["access_token"]
703 request.content = dumps(ro)
704 # Our registration will fail now
705 assert obj._register() is False
706 assert obj.access_token is None
707 del obj
708
709 # So will login
710 obj = NotifyMatrix(host="host", user="user", password="password")
711 assert isinstance(obj, NotifyMatrix) is True
712 assert obj._login() is False
713 assert obj.access_token is None
714
715 # Adjust our response to be invalid - invalid json response
716 request.content = "{"
717 # Our registration will fail now
718 assert obj._register() is False
719 assert obj.access_token is None
720
721 request.status_code = requests.codes.ok
722 request.content = dumps(response_obj)
723 assert obj._register() is True
724 assert obj.access_token is not None
725 # Test logoff when getting a 403 error
726 request.status_code = 403
727 assert obj._logout() is False
728 assert obj.access_token is not None
729
730 request.status_code = requests.codes.ok
731 request.content = dumps(response_obj)
732 assert obj._register() is True
733 assert obj.access_token is not None
734 request.status_code = 403
735 request.content = dumps(
736 {
737 "errcode": "M_UNKNOWN_TOKEN",
738 "error": "Access Token unknown or expired",
739 }
740 )
741 # Test logoff when getting a 403 error; but if we have the right error
742 # code in the response, then we return a True
743 assert obj._logout() is True
744 assert obj.access_token is None
745 del obj
746
747 # Modern Matrix servers omit home_server from login/register responses.
748 # Apprise must derive it from user_id so room-alias resolution works.
749 modern_resp = {
750 "access_token": "tok99",
751 "user_id": "@bot:matrix.org",
752 "device_id": "DEVXYZ",
753 # no "home_server" key -- matches real matrix.org behaviour
754 }
755 request.status_code = requests.codes.ok
756 request.content = dumps(modern_resp)
757
758 # No home_server in response + no prior home_server -> derive from user_id
759 obj2 = NotifyMatrix(host="matrix.org", user="bot", password="pass")
760 assert obj2._login() is True
761 assert obj2.home_server == "matrix.org"
762
763 obj3 = NotifyMatrix(host="matrix.org", user="bot", password="pass")
764 assert obj3._register() is True
765 assert obj3.home_server == "matrix.org"
766
767 # No home_server in response + home_server already set -> not overwritten
768 obj4 = NotifyMatrix(host="matrix.org", user="bot", password="pass")
769 obj4.home_server = "already.set"
770 assert obj4._login() is True
771 assert obj4.home_server == "already.set"
772
773 obj5 = NotifyMatrix(host="matrix.org", user="bot", password="pass")
774 obj5.home_server = "already.set"
775 assert obj5._register() is True
776 assert obj5.home_server == "already.set"
777
778 # No home_server in response + user_id has no colon ->
779 # home_server stays None
780 no_colon_resp = {
781 "access_token": "tok88",
782 "user_id": "@nocoilon",
783 "device_id": "DEV88",
784 }
785 request.content = dumps(no_colon_resp)
786 obj6 = NotifyMatrix(host="matrix.org", user="bot", password="pass")
787 assert obj6._login() is True
788 assert obj6.home_server is None
789
790 obj7 = NotifyMatrix(host="matrix.org", user="bot", password="pass")
791 assert obj7._register() is True
792 assert obj7.home_server is None
793 del obj2, obj3, obj4, obj5, obj6, obj7
794
795
796 @mock.patch("requests.put")
797 @mock.patch("requests.get")
798 @mock.patch("requests.post")
799 def test_plugin_matrix_rooms(mock_post, mock_get, mock_put):
800 """NotifyMatrix() Room Testing."""
801
802 response_obj = {
803 # Registration
804 "access_token": "abcd1234",
805 "user_id": "@apprise:localhost",
806 "home_server": "localhost",
807 # For joined_room response
808 "joined_rooms": ["!abc123", "!def456:localhost"],
809 # For room joining
810 "room_id": "!abc123",
811 }
812
813 # Default configuration
814 request = mock.Mock()
815 request.status_code = requests.codes.ok
816 request.content = dumps(response_obj)
817 mock_post.return_value = request
818 mock_get.return_value = request
819 mock_put.return_value = request
820
821 obj = NotifyMatrix(host="host")
822 assert isinstance(obj, NotifyMatrix) is True
823 assert obj.access_token is None
824
825 # Can't get room listing if we're not connnected
826 assert obj._room_join("#abc123") is None
827
828 assert obj._register() is True
829 assert obj.access_token is not None
830
831 assert obj._room_join("!abc123") == response_obj["room_id"]
832 # Use cache to get same results
833 assert obj.store.get("!abc123") is None
834 # However this is how the cache entry gets stored
835 assert obj.store.get("!abc123:localhost") is not None
836 assert obj.store.get("!abc123:localhost")["id"] == response_obj["room_id"]
837
838 # When hsreq=yes, legacy behaviour is restored and a homeserver is
839 # automatically appended to room IDs that omit it.
840 obj.store.clear()
841 obj.hsreq = True
842 mock_post.reset_mock()
843 assert obj._room_join("!abc123") == response_obj["room_id"]
844 assert mock_post.call_count == 1
845 assert (
846 mock_post.call_args_list[0][0][0]
847 == "http://host/_matrix/client/v3/join/%21abc123%3Alocalhost"
848 )
849
850 # When hsreq=no, we honour the raw !room identifier exactly as provided
851 # and do not suffix it with :homeserver.
852 obj.store.clear()
853 obj.hsreq = False
854
855 def _join_side_effect(url, *args, **kwargs):
856 r = mock.Mock()
857
858 # With hsreq disabled, only the raw form should be attempted:
859 if url.endswith("/_matrix/client/v3/join/%21abc123"):
860 r.status_code = requests.codes.ok
861 r.content = dumps(response_obj).encode("utf-8")
862 return r
863
864 # Default ok for any other unexpected call
865 r.status_code = requests.codes.ok
866 r.content = dumps(response_obj).encode("utf-8")
867 return r
868
869 mock_post.reset_mock()
870 mock_post.side_effect = _join_side_effect
871 assert obj._room_join("!abc123") == response_obj["room_id"]
872 assert mock_post.call_count == 1
873 assert (
874 mock_post.call_args_list[0][0][0]
875 == "http://host/_matrix/client/v3/join/%21abc123"
876 )
877
878 mock_post.reset_mock()
879 assert obj._room_join("!abc123") == response_obj["room_id"]
880 # Cache is used
881 assert mock_post.call_count == 0
882
883 # Still using cache
884 assert obj._room_join("!abc123:localhost") == response_obj["room_id"]
885 assert mock_post.call_count == 0
886
887 # Toggle our settings back
888 obj.hsreq = True
889 mock_post.reset_mock()
890 mock_post.side_effect = _join_side_effect
891 assert obj._room_join("!abc123") == response_obj["room_id"]
892 # We still no longer need to fetch as we know the info already
893 assert mock_post.call_count == 0
894
895 # Restore defaults for remaining tests
896 mock_post.side_effect = None
897 obj.hsreq = True
898
899 # Use cache to get same results (no additional HTTP call)
900 mock_post.reset_mock()
901 assert obj._room_join("!abc123") == response_obj["room_id"]
902 assert mock_post.call_count == 0
903
904 obj.store.clear()
905 assert obj._room_join("!abc123:localhost") == response_obj["room_id"]
906 assert obj.store.get("!abc123:localhost") is not None
907 assert obj.store.get("!abc123:localhost")["id"] == response_obj["room_id"]
908 # Use cache to get same results
909 assert obj._room_join("!abc123:localhost") == response_obj["room_id"]
910
911 obj.store.clear()
912 assert obj._room_join("abc123") == response_obj["room_id"]
913 # Use cache to get same results
914 assert obj.store.get("#abc123:localhost") is not None
915 assert obj.store.get("#abc123:localhost")["id"] == response_obj["room_id"]
916 assert obj._room_join("abc123") == response_obj["room_id"]
917
918 # If home_server is missing, recover it from user_id so we never try
919 # to join a '#room:None' alias.
920 obj.store.clear()
921 obj.home_server = None
922 obj.user_id = "@apprise:localhost"
923 mock_post.reset_mock()
924 assert obj._room_join("abc123") == response_obj["room_id"]
925 assert mock_post.call_count == 1
926 assert (
927 mock_post.call_args_list[0][0][0]
928 == "http://host/_matrix/client/v3/join/%23abc123%3Alocalhost"
929 )
930
931 obj.store.clear()
932 assert obj._room_join("abc123:localhost") == response_obj["room_id"]
933 # Use cache to get same results
934 assert obj.store.get("#abc123:localhost") is not None
935 assert obj.store.get("#abc123:localhost")["id"] == response_obj["room_id"]
936 assert obj._room_join("abc123:localhost") == response_obj["room_id"]
937
938 obj.store.clear()
939 assert obj._room_join("#abc123:localhost") == response_obj["room_id"]
940 # Use cache to get same results
941 assert obj.store.get("#abc123:localhost") is not None
942 assert obj.store.get("#abc123:localhost")["id"] == response_obj["room_id"]
943 assert obj._room_join("#abc123:localhost") == response_obj["room_id"]
944
945 obj.store.clear()
946 assert obj._room_join("%") is None
947 assert obj._room_join(None) is None
948
949 obj.store.clear()
950 obj.home_server = None
951 obj.user_id = "@apprise"
952 mock_post.reset_mock()
953 assert obj._room_join("abc123") is None
954 assert mock_post.call_count == 0
955
956 # 403 response; this will push for a room creation for alias based rooms
957 # and these will fail
958 request.status_code = 403
959 obj.store.clear()
960 assert obj._room_join("!abc123") is None
961 obj.store.clear()
962 assert obj._room_join("!abc123:localhost") is None
963 obj.store.clear()
964 assert obj._room_join("abc123") is None
965 obj.store.clear()
966 assert obj._room_join("abc123:localhost") is None
967 obj.store.clear()
968 assert obj._room_join("#abc123:localhost") is None
969 del obj
970
971 # Room creation
972 request.status_code = requests.codes.ok
973 obj = NotifyMatrix(host="host")
974 assert isinstance(obj, NotifyMatrix) is True
975 assert obj.access_token is None
976
977 # Can't get room listing if we're not connnected
978 assert obj._room_create("#abc123") is None
979
980 assert obj._register() is True
981 assert obj.access_token is not None
982
983 # You can't add room_id's, they must be aliases
984 assert obj._room_create("!abc123") is None
985 assert obj._room_create("!abc123:localhost") is None
986 obj.store.clear()
987 assert obj._room_create("abc123") == response_obj["room_id"]
988 obj.store.clear()
989 assert obj._room_create("abc123:localhost") == response_obj["room_id"]
990 obj.store.clear()
991 assert obj._room_create("#abc123:localhost") == response_obj["room_id"]
992 obj.store.clear()
993 assert obj._room_create("%") is None
994 assert obj._room_create(None) is None
995
996 # 403 response; this will push for a room creation for alias based rooms
997 # and these will fail
998 request.status_code = 403
999 obj.store.clear()
1000 assert obj._room_create("abc123") is None
1001 obj.store.clear()
1002 assert obj._room_create("abc123:localhost") is None
1003 obj.store.clear()
1004 assert obj._room_create("#abc123:localhost") is None
1005
1006 request.status_code = 403
1007 request.content = dumps(
1008 {
1009 "errcode": "M_ROOM_IN_USE",
1010 "error": "Room alias already taken",
1011 }
1012 )
1013 obj.store.clear()
1014 # This causes us to look up a channel ID if we get a ROOM_IN_USE response
1015 assert obj._room_create("#abc123:localhost") is None
1016 del obj
1017
1018 # Room detection
1019 request.status_code = requests.codes.ok
1020 request.content = dumps(response_obj)
1021 obj = NotifyMatrix(host="localhost")
1022 assert isinstance(obj, NotifyMatrix) is True
1023 assert obj.access_token is None
1024
1025 # No rooms if we're not connected
1026 response = obj._joined_rooms()
1027 assert isinstance(response, list) is True
1028 assert len(response) == 0
1029
1030 # register our account
1031 assert obj._register() is True
1032 assert obj.access_token is not None
1033
1034 response = obj._joined_rooms()
1035 assert isinstance(response, list) is True
1036 assert len(response) == len(response_obj["joined_rooms"])
1037 for r in response:
1038 assert r in response_obj["joined_rooms"]
1039
1040 request.status_code = 403
1041 response = obj._joined_rooms()
1042 assert isinstance(response, list) is True
1043 assert len(response) == 0
1044 del obj
1045
1046 # Room id lookup
1047 request.status_code = requests.codes.ok
1048 obj = NotifyMatrix(host="localhost")
1049 assert isinstance(obj, NotifyMatrix) is True
1050 assert obj.access_token is None
1051
1052 # Can't get room listing if we're not connnected
1053 assert obj._room_id("#abc123") is None
1054
1055 assert obj._register() is True
1056 assert obj.access_token is not None
1057
1058 # You can't add room_id's, they must be aliases
1059 assert obj._room_id("!abc123") is None
1060 assert obj._room_id("!abc123:localhost") is None
1061 obj.store.clear()
1062 assert obj._room_id("abc123") == response_obj["room_id"]
1063 obj.store.clear()
1064 assert obj._room_id("abc123:localhost") == response_obj["room_id"]
1065 obj.store.clear()
1066 assert obj._room_id("#abc123:localhost") == response_obj["room_id"]
1067 obj.store.clear()
1068 assert obj._room_id("%") is None
1069 assert obj._room_id(None) is None
1070
1071 # If we can't look the code up, we return None
1072 request.status_code = 403
1073 obj.store.clear()
1074 assert obj._room_id("#abc123:localhost") is None
1075
1076 # Force a object removal (thus a logout call)
1077 del obj
1078
1079
1080 def test_plugin_matrix_url_parsing():
1081 """NotifyMatrix() URL Testing."""
1082 result = NotifyMatrix.parse_url("matrix://user:token@localhost?to=#room")
1083 assert isinstance(result, dict) is True
1084 assert len(result["targets"]) == 1
1085 assert "#room" in result["targets"]
1086
1087 result = NotifyMatrix.parse_url(
1088 "matrix://user:token@localhost?to=#room&hsreq=yes"
1089 )
1090 assert isinstance(result, dict) is True
1091 assert result.get("hsreq") is True
1092
1093 result = NotifyMatrix.parse_url(
1094 "matrix://user:token@localhost?to=#room1,#room2,#room3"
1095 )
1096 assert isinstance(result, dict) is True
1097 assert len(result["targets"]) == 3
1098 assert "#room1" in result["targets"]
1099 assert "#room2" in result["targets"]
1100 assert "#room3" in result["targets"]
1101
1102 # Mixed-case alias with underscore should parse
1103 result = NotifyMatrix.parse_url(
1104 "matrix://user:token@localhost?to=#Dev_Room:localhost"
1105 )
1106 assert isinstance(result, dict) is True
1107 assert len(result["targets"]) == 1
1108 assert "#Dev_Room:localhost" in result["targets"]
1109
1110 # Mixed-case room id with underscore should be accepted by _room_join
1111 from apprise.plugins.matrix import IS_ROOM_ID # local alias
1112
1113 nm = NotifyMatrix(host="localhost")
1114 nm.access_token = "abc" # simulate logged-in
1115 nm.home_server = "localhost"
1116 # this should NOT be rejected by the regex
1117 assert IS_ROOM_ID.match("!Jm_LvU1nas_8KJPBmN9n:nginx.eu")
1118
1119
1120 @mock.patch("requests.put")
1121 @mock.patch("requests.get")
1122 @mock.patch("requests.post")
1123 def test_plugin_matrix_image_errors(mock_post, mock_get, mock_put):
1124 """NotifyMatrix() Image Error Handling."""
1125
1126 def mock_function_handing(url, data, **kwargs):
1127 """Dummy function for handling image posts (as a failure)"""
1128 response_obj = {
1129 "room_id": "!abc123:localhost",
1130 "room_alias": "#abc123:localhost",
1131 "joined_rooms": ["!abc123:localhost", "!def456:localhost"],
1132 "access_token": "abcd1234",
1133 "home_server": "localhost",
1134 }
1135
1136 request = mock.Mock()
1137 request.content = dumps(response_obj)
1138 request.status_code = requests.codes.ok
1139
1140 if "m.image" in data:
1141 # Fail for images
1142 request.status_code = 400
1143
1144 return request
1145
1146 # Prepare Mock
1147 mock_get.side_effect = mock_function_handing
1148 mock_post.side_effect = mock_function_handing
1149 mock_put.side_effect = mock_function_handing
1150
1151 obj = NotifyMatrix(host="host", include_image=True, version="2")
1152 assert isinstance(obj, NotifyMatrix) is True
1153 assert obj.access_token is None
1154
1155 # Notification was successful, however we could not post image and since
1156 # we had post errors (of any kind) we still report a failure.
1157 assert obj.notify("test", "test") is False
1158 del obj
1159
1160 obj = NotifyMatrix(host="host", include_image=False, version="2")
1161 assert isinstance(obj, NotifyMatrix) is True
1162 assert obj.access_token is None
1163
1164 # We didn't post an image (which was set to fail) and therefore our
1165 # post was okay
1166 assert obj.notify("test", "test") is True
1167
1168 # Force a object removal (thus a logout call)
1169 del obj
1170
1171 def mock_function_handing(url, data, **kwargs):
1172 """Dummy function for handling image posts (successfully)"""
1173 response_obj = {
1174 "room_id": "!abc123:localhost",
1175 "room_alias": "#abc123:localhost",
1176 "joined_rooms": ["!abc123:localhost", "!def456:localhost"],
1177 "access_token": "abcd1234",
1178 "home_server": "localhost",
1179 }
1180
1181 request = mock.Mock()
1182 request.content = dumps(response_obj)
1183 request.status_code = requests.codes.ok
1184
1185 return request
1186
1187 # Prepare Mock
1188 mock_get.side_effect = mock_function_handing
1189 mock_put.side_effect = mock_function_handing
1190 mock_post.side_effect = mock_function_handing
1191 obj = NotifyMatrix(host="host", include_image=True)
1192 assert isinstance(obj, NotifyMatrix) is True
1193 assert obj.access_token is None
1194
1195 assert obj.notify("test", "test") is True
1196 del obj
1197
1198 obj = NotifyMatrix(host="host", include_image=False)
1199 assert isinstance(obj, NotifyMatrix) is True
1200 assert obj.access_token is None
1201
1202 assert obj.notify("test", "test") is True
1203
1204 # Force a object removal (thus a logout call)
1205 del obj
1206
1207
1208 @mock.patch("requests.put")
1209 @mock.patch("requests.post")
1210 def test_plugin_matrix_attachments_api_v3(mock_post, mock_put):
1211 """NotifyMatrix() Attachment Checks (v3)"""
1212
1213 # Prepare a good response
1214 response = mock.Mock()
1215 response.status_code = requests.codes.ok
1216 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1217
1218 # Prepare a bad response
1219 bad_response = mock.Mock()
1220 bad_response.status_code = requests.codes.internal_server_error
1221
1222 # Prepare Mock return object
1223 mock_post.return_value = response
1224 mock_put.return_value = response
1225
1226 # Instantiate our object
1227 obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=3")
1228
1229 # attach our content
1230 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1231
1232 assert (
1233 obj.notify(
1234 body="body",
1235 title="title",
1236 notify_type=NotifyType.INFO,
1237 attach=attach,
1238 )
1239 is True
1240 )
1241
1242 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1243
1244 # Test our call count
1245 assert mock_put.call_count == 2
1246 assert mock_post.call_count == 3
1247 assert (
1248 mock_post.call_args_list[0][0][0]
1249 == "http://localhost/_matrix/client/v3/login"
1250 )
1251 assert (
1252 mock_post.call_args_list[1][0][0]
1253 == "http://localhost/_matrix/client/v3/join/%23general%3Alocalhost"
1254 )
1255 assert (
1256 mock_post.call_args_list[2][0][0]
1257 == "http://localhost/_matrix/media/v3/upload"
1258 )
1259 assert (
1260 mock_put.call_args_list[0][0][0]
1261 == "http://localhost/_matrix/client/v3/rooms/%21abc123%3Alocalhost/"
1262 "send/m.room.message/0"
1263 )
1264 assert (
1265 mock_put.call_args_list[1][0][0]
1266 == "http://localhost/_matrix/client/v3/rooms/%21abc123%3Alocalhost/"
1267 "send/m.room.message/1"
1268 )
1269
1270 # Attach a zip file type
1271 attach = AppriseAttachment(
1272 os.path.join(TEST_VAR_DIR, "apprise-archive.zip")
1273 )
1274 assert (
1275 obj.notify(
1276 body="body",
1277 title="title",
1278 notify_type=NotifyType.INFO,
1279 attach=attach,
1280 )
1281 is True
1282 )
1283
1284 # An invalid attachment will cause a failure
1285 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
1286 attach = AppriseAttachment(path)
1287 assert (
1288 obj.notify(
1289 body="body",
1290 title="title",
1291 notify_type=NotifyType.INFO,
1292 attach=path,
1293 )
1294 is False
1295 )
1296
1297 # update our attachment to be valid
1298 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1299
1300 mock_put.return_value = None
1301 mock_post.return_value = None
1302
1303 # Throw an exception on the first call to requests.post()
1304 for side_effect in (requests.RequestException(), OSError(), bad_response):
1305 # Reset our value
1306 mock_put.reset_mock()
1307 mock_post.reset_mock()
1308
1309 mock_post.side_effect = [side_effect]
1310
1311 assert obj.send(body="test", attach=attach) is False
1312
1313 # Throw an exception on the second call to requests.post()
1314 for side_effect in (requests.RequestException(), OSError(), bad_response):
1315 # Reset our value
1316 mock_put.reset_mock()
1317 mock_post.reset_mock()
1318
1319 mock_put.side_effect = [side_effect, response]
1320 mock_post.side_effect = [response, side_effect, response]
1321
1322 # We'll fail now because of our error handling
1323 assert obj.send(body="test", attach=attach) is False
1324
1325 # handle a bad response
1326 mock_put.side_effect = [bad_response, response]
1327 mock_post.side_effect = [response, bad_response, response]
1328
1329 # We'll fail now because of an internal exception
1330 assert obj.send(body="test", attach=attach) is False
1331
1332 # Force a object removal (thus a logout call)
1333 del obj
1334
1335
1336 @mock.patch("requests.put")
1337 @mock.patch("requests.get")
1338 @mock.patch("requests.post")
1339 def test_plugin_matrix_discovery_service(mock_post, mock_get, mock_put):
1340 """NotifyMatrix() Discovery Service."""
1341
1342 # Prepare a good response
1343 response = mock.Mock()
1344 response.status_code = requests.codes.ok
1345 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1346
1347 # Prepare a good response
1348 bad_response = mock.Mock()
1349 bad_response.status_code = requests.codes.unauthorized
1350 bad_response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1351
1352 # Prepare Mock return object
1353 mock_post.return_value = response
1354 mock_get.return_value = response
1355 mock_put.return_value = response
1356
1357 # Instantiate our object
1358 obj = Apprise.instantiate(
1359 "matrixs://user:[email protected]/#general?v=2&discovery=yes"
1360 )
1361 assert obj.notify("body") is True
1362
1363 response = mock.Mock()
1364 response.status_code = requests.codes.unavailable
1365 resp = loads(MATRIX_GOOD_RESPONSE)
1366
1367 mock_get.return_value = response
1368 mock_post.return_value = response
1369 obj = Apprise.instantiate(
1370 "matrixs://user:[email protected]/#general?v=2&discovery=yes"
1371 )
1372 obj.store.clear(
1373 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1374 )
1375
1376 # Invalid host / fallback is to resolve our own host
1377 with pytest.raises(MatrixDiscoveryException):
1378 _ = obj.base_url
1379
1380 # Verify cache is not saved
1381 assert NotifyMatrix.discovery_base_key not in obj.store
1382 assert NotifyMatrix.discovery_identity_key not in obj.store
1383
1384 response.status_code = requests.codes.ok
1385 obj.store.clear(
1386 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1387 )
1388
1389 # bad data
1390 resp["m.homeserver"] = "!garbage!:303"
1391 response.content = dumps(resp).encode("utf-8")
1392 obj.store.clear(
1393 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1394 )
1395
1396 with pytest.raises(MatrixDiscoveryException):
1397 _ = obj.base_url
1398
1399 # Verify cache is not saved
1400 assert NotifyMatrix.discovery_base_key not in obj.store
1401 assert NotifyMatrix.discovery_identity_key not in obj.store
1402
1403 # We fail our discovery and therefore can't send our notification
1404 assert obj.notify("hello world") is False
1405
1406 # bad key
1407 resp["m.homeserver"] = {}
1408 response.content = dumps(resp).encode("utf-8")
1409 obj.store.clear(
1410 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1411 )
1412 with pytest.raises(MatrixDiscoveryException):
1413 _ = obj.base_url
1414
1415 # Verify cache is not saved
1416 assert NotifyMatrix.discovery_base_key not in obj.store
1417 assert NotifyMatrix.discovery_identity_key not in obj.store
1418
1419 resp["m.homeserver"] = {"base_url": "https://nuxref.com/base"}
1420 response.content = dumps(resp).encode("utf-8")
1421 obj.store.clear(
1422 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1423 )
1424 assert obj.base_url == "https://nuxref.com/base"
1425 assert obj.identity_url == "https://vector.im"
1426
1427 # Verify cache saved
1428 assert NotifyMatrix.discovery_base_key in obj.store
1429 assert NotifyMatrix.discovery_identity_key in obj.store
1430
1431 # Discovery passes so notifications work too
1432 assert obj.notify("hello world") is True
1433
1434 # bad data
1435 resp["m.identity_server"] = "!garbage!:303"
1436 response.content = dumps(resp).encode("utf-8")
1437 obj.store.clear(
1438 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1439 )
1440
1441 with pytest.raises(MatrixDiscoveryException):
1442 _ = obj.base_url
1443
1444 # Verify cache is not saved
1445 assert NotifyMatrix.discovery_base_key not in obj.store
1446 assert NotifyMatrix.discovery_identity_key not in obj.store
1447
1448 # no key
1449 resp["m.identity_server"] = {}
1450 response.content = dumps(resp).encode("utf-8")
1451 obj.store.clear(
1452 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1453 )
1454
1455 with pytest.raises(MatrixDiscoveryException):
1456 _ = obj.base_url
1457
1458 # Verify cache is not saved
1459 assert NotifyMatrix.discovery_base_key not in obj.store
1460 assert NotifyMatrix.discovery_identity_key not in obj.store
1461
1462 # remove
1463 del resp["m.identity_server"]
1464 response.content = dumps(resp).encode("utf-8")
1465
1466 obj.store.clear(
1467 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1468 )
1469 assert obj.base_url == "https://nuxref.com/base"
1470 assert obj.identity_url == "https://nuxref.com/base"
1471
1472 # restore
1473 resp["m.identity_server"] = {"base_url": '"https://vector.im'}
1474 response.content = dumps(resp).encode("utf-8")
1475
1476 # Not found is an acceptable response (no exceptions thrown)
1477 response.status_code = requests.codes.not_found
1478 obj.store.clear(
1479 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1480 )
1481 assert obj.base_url == "https://example.com"
1482 assert obj.identity_url == "https://example.com"
1483
1484 # Verify cache saved
1485 assert NotifyMatrix.discovery_base_key in obj.store
1486 assert NotifyMatrix.discovery_identity_key in obj.store
1487
1488 # Discovery passes so notifications work too
1489 response.status_code = requests.codes.ok
1490 assert obj.notify("hello world") is True
1491
1492 response.status_code = requests.codes.ok
1493 mock_get.return_value = None
1494 mock_get.side_effect = (response, bad_response)
1495 obj.store.clear(
1496 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1497 )
1498
1499 with pytest.raises(MatrixDiscoveryException):
1500 _ = obj.base_url
1501
1502 # Verify cache is not saved
1503 assert NotifyMatrix.discovery_base_key not in obj.store
1504 assert NotifyMatrix.discovery_identity_key not in obj.store
1505
1506 # Test case where ourIdentity URI fails to do it's check
1507 mock_get.side_effect = (response, response, bad_response)
1508 obj.store.clear(
1509 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1510 )
1511
1512 with pytest.raises(MatrixDiscoveryException):
1513 _ = obj.base_url
1514
1515 # Verify cache is not saved
1516 assert NotifyMatrix.discovery_base_key not in obj.store
1517 assert NotifyMatrix.discovery_identity_key not in obj.store
1518
1519 # Test an empty block response
1520 response.status_code = requests.codes.ok
1521 response.content = ""
1522 mock_get.return_value = response
1523 mock_get.side_effect = None
1524 mock_post.return_value = response
1525 mock_post.side_effect = None
1526 obj.store.clear(
1527 NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key
1528 )
1529
1530 assert obj.base_url == "https://example.com"
1531 assert obj.identity_url == "https://example.com"
1532
1533 # Verify cache saved
1534 assert NotifyMatrix.discovery_base_key in obj.store
1535 assert NotifyMatrix.discovery_identity_key in obj.store
1536
1537 del obj
1538
1539
1540 @mock.patch("requests.put")
1541 @mock.patch("requests.get")
1542 @mock.patch("requests.post")
1543 def test_plugin_matrix_attachments_api_v2(mock_post, mock_get, mock_put):
1544 """NotifyMatrix() Attachment Checks (v2)"""
1545
1546 # Prepare a good response
1547 response = mock.Mock()
1548 response.status_code = requests.codes.ok
1549 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1550
1551 # Prepare a bad response
1552 bad_response = mock.Mock()
1553 bad_response.status_code = requests.codes.internal_server_error
1554
1555 # Prepare Mock return object
1556 mock_post.return_value = response
1557 mock_get.return_value = response
1558 mock_put.return_value = response
1559
1560 # Instantiate our object
1561 obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=2")
1562
1563 # attach our content
1564 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1565
1566 assert (
1567 obj.notify(
1568 body="body",
1569 title="title",
1570 notify_type=NotifyType.INFO,
1571 attach=attach,
1572 )
1573 is True
1574 )
1575
1576 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1577
1578 # Attach an unsupported file
1579 mock_post.return_value = response
1580 mock_get.return_value = response
1581 mock_post.side_effect = None
1582 mock_get.side_effect = None
1583
1584 # Force a object removal (thus a logout call)
1585 del obj
1586
1587 # Instantiate our object
1588 obj = Apprise.instantiate("matrixs://user:pass@localhost/#general?v=2")
1589
1590 # Reset our object
1591 mock_post.reset_mock()
1592 mock_get.reset_mock()
1593 mock_put.reset_mock()
1594
1595 assert (
1596 obj.notify(
1597 body="body",
1598 title="title",
1599 notify_type=NotifyType.INFO,
1600 attach=attach,
1601 )
1602 is True
1603 )
1604
1605 # Test our call count -- login, join, upload use POST; sends use PUT
1606 assert mock_post.call_count == 3
1607 assert (
1608 mock_post.call_args_list[0][0][0]
1609 == "https://matrix.example.com/_matrix/client/r0/login"
1610 )
1611 assert (
1612 mock_post.call_args_list[1][0][0]
1613 == "https://matrix.example.com/_matrix/client/r0/"
1614 "join/%23general%3Alocalhost"
1615 )
1616 assert (
1617 mock_post.call_args_list[2][0][0]
1618 == "https://matrix.example.com/_matrix/media/r0/upload"
1619 )
1620 assert mock_put.call_count == 2
1621 assert (
1622 mock_put.call_args_list[0][0][0]
1623 == "https://matrix.example.com/_matrix/client/r0"
1624 "/rooms/%21abc123%3Alocalhost/send/m.room.message/0"
1625 )
1626 assert (
1627 mock_put.call_args_list[1][0][0]
1628 == "https://matrix.example.com/_matrix/client/r0/"
1629 "rooms/%21abc123%3Alocalhost/send/m.room.message/1"
1630 )
1631
1632 # Attach an unsupported file type; these are skipped
1633 attach = AppriseAttachment(
1634 os.path.join(TEST_VAR_DIR, "apprise-archive.zip")
1635 )
1636 assert (
1637 obj.notify(
1638 body="body",
1639 title="title",
1640 notify_type=NotifyType.INFO,
1641 attach=attach,
1642 )
1643 is True
1644 )
1645
1646 # An invalid attachment will cause a failure
1647 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
1648 attach = AppriseAttachment(path)
1649 assert (
1650 obj.notify(
1651 body="body",
1652 title="title",
1653 notify_type=NotifyType.INFO,
1654 attach=path,
1655 )
1656 is False
1657 )
1658
1659 # update our attachment to be valid
1660 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1661
1662 mock_post.return_value = None
1663 mock_get.return_value = None
1664
1665 # Throw an exception on the first call to requests.post()
1666 for side_effect in (requests.RequestException(), OSError(), bad_response):
1667 # Reset our value
1668 mock_post.reset_mock()
1669 mock_get.reset_mock()
1670
1671 mock_post.side_effect = [side_effect, response]
1672 mock_get.side_effect = [side_effect, response]
1673
1674 assert obj.send(body="test", attach=attach) is False
1675
1676 # Throw an exception on the attachment send (now uses PUT)
1677 for side_effect in (requests.RequestException(), OSError(), bad_response):
1678 # Reset our value
1679 mock_post.reset_mock()
1680 mock_get.reset_mock()
1681 mock_put.reset_mock()
1682
1683 mock_post.side_effect = [response] # upload ok
1684 mock_put.side_effect = [side_effect, side_effect] # sends fail
1685
1686 # We'll fail now because of our error handling
1687 assert obj.send(body="test", attach=attach) is False
1688
1689 # handle a bad response on the attachment send (now PUT)
1690 mock_post.side_effect = [response] # upload ok
1691 mock_put.side_effect = [bad_response, response] # attachment fails
1692 mock_get.side_effect = None
1693
1694 # We'll fail now because of an internal exception
1695 assert obj.send(body="test", attach=attach) is False
1696
1697 # Force a object removal (thus a logout call)
1698 del obj
1699
1700 # Instantiate our object (no discovery required)
1701 obj = Apprise.instantiate(
1702 "matrixs://user:pass@localhost/#general?v=2&discovery=no&image=y"
1703 )
1704
1705 # Reset our object
1706 mock_post.reset_mock()
1707 mock_get.reset_mock()
1708 mock_put.reset_mock()
1709
1710 # login + join succeed; image inline send (now PUT) fails
1711 mock_post.side_effect = [response, response]
1712 mock_get.side_effect = None
1713 mock_put.side_effect = [bad_response]
1714
1715 # image attachment didn't succeed
1716 assert (
1717 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1718 is False
1719 )
1720
1721 # All calls now succeed
1722 mock_post.return_value = response
1723 mock_get.return_value = response
1724 mock_put.return_value = response
1725 mock_post.side_effect = None
1726 mock_get.side_effect = None
1727 mock_put.side_effect = None
1728
1729 # We'll fail now because of an internal exception
1730 assert obj.send(body="test", attach=attach) is True
1731
1732 # Force __del__() call
1733 del obj
1734
1735
1736 @mock.patch("requests.put")
1737 @mock.patch("requests.post")
1738 def test_plugin_matrix_v2_compliance(mock_post, mock_put):
1739 """NotifyMatrix() Verify V2 uses PUT and TID for standard messages."""
1740 # Setup compliant response
1741 response = mock.Mock()
1742 response.status_code = requests.codes.ok
1743 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1744 mock_post.return_value = response
1745 mock_put.return_value = response
1746
1747 # Instantiate as V2
1748 obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=2")
1749
1750 # Send a standard notification
1751 assert obj.notify(body="test message") is True
1752
1753 # Confirm the fix:
1754 # 1. Path contains the transaction ID '0'
1755 # 2. Method is PUT
1756 assert mock_put.call_count == 1
1757 assert "/_matrix/client/r0/rooms/" in mock_put.call_args_list[0][0][0]
1758 assert "/send/m.room.message/0" in mock_put.call_args_list[0][0][0]
1759
1760
1761 @mock.patch("requests.put")
1762 @mock.patch("requests.get")
1763 @mock.patch("requests.post")
1764 def test_plugin_matrix_v2_token_mode_no_txn_increment(
1765 mock_post, mock_get, mock_put
1766 ):
1767 """Token mode (access_token == password) skips transaction ID increment."""
1768 response = mock.Mock()
1769 response.status_code = requests.codes.ok
1770 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1771 mock_post.return_value = response
1772 mock_get.return_value = response
1773 mock_put.return_value = response
1774
1775 # Token mode: user omitted, password treated as access token
1776 # (parse_url swaps user->password when no password supplied)
1777 obj = Apprise.instantiate(
1778 "matrixs://my_access_token@localhost/#general?v=2&image=y"
1779 )
1780 assert obj is not None
1781
1782 # Send with image inline enabled
1783 assert obj.notify(body="token mode image test") is True
1784
1785 # Send with an attachment
1786 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1787 assert obj.send(body="token mode attach test", attach=attach) is True
1788
1789
1790 def test_plugin_matrix_parse_native_url_no_match():
1791 """parse_native_url returns None for non-t2bot URLs."""
1792 assert (
1793 NotifyMatrix.parse_native_url("https://not-a-t2bot-url.com/some/path")
1794 is None
1795 )
1796
1797
1798 @mock.patch("requests.post")
1799 def test_plugin_matrix_hookshot_webhook(mock_post):
1800 """matrix-hookshot webhook mode uses hookshot URL/payload conventions."""
1801
1802 response = mock.Mock()
1803 response.status_code = requests.codes.ok
1804 response.content = b"{}"
1805 mock_post.return_value = response
1806
1807 obj = Apprise.instantiate(
1808 "matrixs://apprise:[email protected]"
1809 "?mode=hookshot&format=html&path=%2Fpublic-hooks"
1810 )
1811 assert obj is not None
1812
1813 assert obj.notify(title="Title", body="<b>Body</b>") is True
1814
1815 assert mock_post.call_args.args[0] == (
1816 "https://hookshot.example/public-hooks/supersecret"
1817 )
1818
1819 payload = loads(mock_post.call_args.kwargs["data"])
1820 assert payload["username"] == "apprise"
1821 # An omitted input format preserves v1's pass-through behavior.
1822 assert payload["text"] == "Title\r\n<b>Body</b>"
1823 assert payload["html"] == "<h1>Title</h1><b>Body</b>"
1824
1825
1826 @mock.patch("requests.post")
1827 def test_plugin_matrix_hookshot_webhook_empty_title(mock_post):
1828 """Hookshot webhook mode avoids extra separators for empty titles."""
1829
1830 response = mock.Mock()
1831 response.status_code = requests.codes.ok
1832 response.content = b"{}"
1833 mock_post.return_value = response
1834
1835 obj = Apprise.instantiate(
1836 "matrixs://apprise:[email protected]"
1837 "?mode=hookshot&format=markdown&path=%2Fpublic-hooks"
1838 )
1839 assert obj is not None
1840
1841 assert obj.notify(body="**Body**") is True
1842
1843 payload = loads(mock_post.call_args.kwargs["data"])
1844 assert payload["username"] == "apprise"
1845 assert payload["text"] == "**Body**"
1846 assert payload["html"] == "<p><strong>Body</strong></p>"
1847
1848
1849 def test_plugin_matrix_hookshot_path_normalization():
1850 """Hookshot webhook paths normalize missing leading slashes."""
1851
1852 obj = Apprise.instantiate(
1853 "matrixs://apprise:[email protected]"
1854 "?mode=hookshot&path=public-hooks"
1855 )
1856 assert obj is not None
1857 assert obj.webhook_path == "/public-hooks"
1858
1859
1860 @mock.patch("requests.post")
1861 def test_plugin_matrix_hookshot_root_path_text(mock_post):
1862 """Hookshot root paths and text mode stay literal."""
1863
1864 response = mock.Mock()
1865 response.status_code = requests.codes.ok
1866 response.content = b"{}"
1867 mock_post.return_value = response
1868
1869 obj = Apprise.instantiate(
1870 "matrixs://apprise:[email protected]"
1871 "?mode=hookshot&format=text&path=%2F"
1872 )
1873 assert obj is not None
1874 assert obj.notify(body="<b>Body</b>") is True
1875
1876 assert mock_post.call_args.args[0] == (
1877 "https://hookshot.example/supersecret"
1878 )
1879 assert loads(mock_post.call_args.kwargs["data"])["html"] == (
1880 "&lt;b&gt;Body&lt;/b&gt;"
1881 )
1882
1883
1884 @mock.patch("requests.put")
1885 @mock.patch("requests.get")
1886 @mock.patch("requests.post")
1887 def test_plugin_matrix_transaction_ids_api_v3_no_cache(
1888 mock_post, mock_get, mock_put
1889 ):
1890 """NotifyMatrix() Transaction ID Checks (v3)"""
1891
1892 # Prepare a good response
1893 response = mock.Mock()
1894 response.status_code = requests.codes.ok
1895 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1896
1897 # Prepare a bad response
1898 bad_response = mock.Mock()
1899 bad_response.status_code = requests.codes.internal_server_error
1900
1901 # Prepare Mock return object
1902 mock_post.return_value = response
1903 mock_get.return_value = response
1904 mock_put.return_value = response
1905
1906 # For each element is 1 batch that is ran
1907 # the number defined is the number of notifications to send
1908 batch = [10, 1, 5]
1909
1910 for notifications in batch:
1911 # Instantiate our object
1912 obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=3")
1913
1914 # Ensure mode is memory
1915 assert obj.store.mode == PersistentStoreMode.MEMORY
1916
1917 # Performs a login
1918 assert (
1919 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
1920 is True
1921 )
1922 assert mock_get.call_count == 0
1923 assert mock_post.call_count == 2
1924 assert (
1925 mock_post.call_args_list[0][0][0]
1926 == "http://localhost/_matrix/client/v3/login"
1927 )
1928 assert (
1929 mock_post.call_args_list[1][0][0]
1930 == "http://localhost/_matrix/client/v3/join/%23general%3Alocalhost"
1931 )
1932 assert mock_put.call_count == 1
1933 assert (
1934 mock_put.call_args_list[0][0][0]
1935 == "http://localhost/_matrix/client/v3/rooms/"
1936 + "%21abc123%3Alocalhost/send/m.room.message/0"
1937 )
1938
1939 for no, _ in enumerate(range(notifications), start=1):
1940 # Clean our slate
1941 mock_post.reset_mock()
1942 mock_get.reset_mock()
1943 mock_put.reset_mock()
1944
1945 assert (
1946 obj.notify(
1947 body="body", title="title", notify_type=NotifyType.INFO
1948 )
1949 is True
1950 )
1951
1952 assert mock_get.call_count == 0
1953 assert mock_post.call_count == 0
1954 assert mock_put.call_count == 1
1955 assert (
1956 mock_put.call_args_list[0][0][0]
1957 == "http://localhost/_matrix/client/v3/rooms/"
1958 + f"%21abc123%3Alocalhost/send/m.room.message/{no}"
1959 )
1960
1961 mock_post.reset_mock()
1962 mock_get.reset_mock()
1963 mock_put.reset_mock()
1964
1965 # Force a object removal (thus a logout call)
1966 del obj
1967
1968 assert mock_get.call_count == 0
1969 assert mock_post.call_count == 1
1970 assert (
1971 mock_post.call_args_list[0][0][0]
1972 == "http://localhost/_matrix/client/v3/logout"
1973 )
1974 mock_post.reset_mock()
1975 assert mock_put.call_count == 0
1976
1977
1978 @mock.patch("requests.put")
1979 @mock.patch("requests.get")
1980 @mock.patch("requests.post")
1981 def test_plugin_matrix_transaction_ids_api_v3_w_cache(
1982 mock_post, mock_get, mock_put, tmpdir
1983 ):
1984 """NotifyMatrix() Transaction ID Checks (v3)"""
1985
1986 # Prepare a good response
1987 response = mock.Mock()
1988 response.status_code = requests.codes.ok
1989 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
1990
1991 # Prepare a bad response
1992 bad_response = mock.Mock()
1993 bad_response.status_code = requests.codes.internal_server_error
1994
1995 # Prepare Mock return object
1996 mock_post.return_value = response
1997 mock_get.return_value = response
1998 mock_put.return_value = response
1999
2000 # For each element is 1 batch that is ran
2001 # the number defined is the number of notifications to send
2002 batch = [10, 1, 5]
2003
2004 mock_post.reset_mock()
2005 mock_get.reset_mock()
2006 mock_put.reset_mock()
2007
2008 asset = AppriseAsset(
2009 storage_mode=PersistentStoreMode.FLUSH,
2010 storage_path=str(tmpdir),
2011 )
2012
2013 # Message Counter
2014 transaction_id = 1
2015
2016 for no, notifications in enumerate(batch):
2017 # Instantiate our object
2018 obj = Apprise.instantiate(
2019 "matrix://user:pass@localhost/#general?v=3", asset=asset
2020 )
2021
2022 # Ensure mode is flush
2023 assert obj.store.mode == PersistentStoreMode.FLUSH
2024
2025 # Performs a login
2026 assert (
2027 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
2028 is True
2029 )
2030 assert mock_get.call_count == 0
2031 if no == 0:
2032 # first entry
2033 assert mock_post.call_count == 2
2034 assert (
2035 mock_post.call_args_list[0][0][0]
2036 == "http://localhost/_matrix/client/v3/login"
2037 )
2038 assert (
2039 mock_post.call_args_list[1][0][0]
2040 == "http://localhost/_matrix/client/v3/"
2041 "join/%23general%3Alocalhost"
2042 )
2043 assert mock_put.call_count == 1
2044 assert (
2045 mock_put.call_args_list[0][0][0]
2046 == "http://localhost/_matrix/client/v3/rooms/"
2047 + "%21abc123%3Alocalhost/send/m.room.message/0"
2048 )
2049
2050 for no, _ in enumerate(range(notifications), start=transaction_id):
2051 # Clean our slate
2052 mock_post.reset_mock()
2053 mock_get.reset_mock()
2054 mock_put.reset_mock()
2055
2056 assert (
2057 obj.notify(
2058 body="body", title="title", notify_type=NotifyType.INFO
2059 )
2060 is True
2061 )
2062
2063 # Increment transaction counter
2064 transaction_id += 1
2065
2066 assert mock_get.call_count == 0
2067 assert mock_post.call_count == 0
2068 assert mock_put.call_count == 1
2069 assert (
2070 mock_put.call_args_list[0][0][0]
2071 == "http://localhost/_matrix/client/v3/rooms/"
2072 + f"%21abc123%3Alocalhost/send/m.room.message/{no}"
2073 )
2074
2075 # Increment transaction counter
2076 transaction_id += 1
2077
2078 mock_post.reset_mock()
2079 mock_get.reset_mock()
2080 mock_put.reset_mock()
2081
2082 # Force a object removal
2083 # Biggest takeaway is that a logout no longer happens
2084 del obj
2085
2086 assert mock_get.call_count == 0
2087 assert mock_post.call_count == 0
2088 assert mock_put.call_count == 0
2089
2090
2091 @mock.patch("requests.put")
2092 @mock.patch("requests.get")
2093 @mock.patch("requests.post")
2094 def test_plugin_matrix_v3_url_with_port_assembly(
2095 mock_post, mock_get, mock_put, tmpdir
2096 ):
2097 """NotifyMatrix() URL with Port Assembly Checks (v3)"""
2098
2099 # Prepare a good response
2100 response = mock.Mock()
2101 response.status_code = requests.codes.ok
2102 response.content = MATRIX_GOOD_RESPONSE.encode("utf-8")
2103
2104 # Prepare Mock return object
2105 mock_post.return_value = response
2106 mock_get.return_value = response
2107 mock_put.return_value = response
2108
2109 asset = AppriseAsset(
2110 storage_mode=PersistentStoreMode.FLUSH,
2111 storage_path=str(tmpdir),
2112 )
2113
2114 # Instantiate our object
2115 obj = Apprise.instantiate(
2116 "matrixs://user1:[email protected]:8080/#general?v=3", asset=asset
2117 )
2118 # Performs a login
2119 assert (
2120 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
2121 is True
2122 )
2123
2124 # Secure Connections have a bit of additional overhead to verify
2125 # the authenticity of the server through discovery
2126 assert mock_get.call_count == 3
2127 assert (
2128 mock_get.call_args_list[0][0][0]
2129 == "https://example.ca:8080/.well-known/matrix/client"
2130 )
2131 assert (
2132 mock_get.call_args_list[1][0][0]
2133 == "https://matrix.example.com/_matrix/client/versions"
2134 )
2135 assert (
2136 mock_get.call_args_list[2][0][0]
2137 == "https://vector.im/_matrix/identity/v2"
2138 )
2139
2140 assert mock_post.call_count == 2
2141 # matrix.example.com comes from our MATRIX_GOOD_RESPONSE
2142 # response which defines wht our .well-known returned to us
2143 assert (
2144 mock_post.call_args_list[0][0][0]
2145 == "https://matrix.example.com/_matrix/client/v3/login"
2146 )
2147 assert (
2148 mock_post.call_args_list[1][0][0]
2149 == "https://matrix.example.com/_matrix/client/v3/"
2150 "join/%23general%3Alocalhost"
2151 )
2152 assert mock_put.call_count == 1
2153 assert (
2154 mock_put.call_args_list[0][0][0]
2155 == "https://matrix.example.com/_matrix/client/v3/rooms/"
2156 + "%21abc123%3Alocalhost/send/m.room.message/0"
2157 )
2158
2159 mock_post.reset_mock()
2160 mock_get.reset_mock()
2161 mock_put.reset_mock()
2162
2163 assert obj.base_url == "https://matrix.example.com"
2164
2165 # Cache is used under the hood; no second discover is performed
2166 assert mock_put.call_count == 0
2167 assert mock_get.call_count == 0
2168 assert mock_post.call_count == 0
2169
2170 # Cleanup
2171 del obj
2172
2173
2174 @mock.patch("requests.put")
2175 @mock.patch("requests.get")
2176 @mock.patch("requests.post")
2177 def test_plugin_matrix_no_room_create_on_non_not_found_join(
2178 mock_post: mock.Mock,
2179 mock_get: mock.Mock,
2180 mock_put: mock.Mock,
2181 ) -> None:
2182 """No room creation when join fails with 400 (or other non-404).
2183
2184 A join failure can occur for many reasons, such as auth failure or invite
2185 required. In these cases, attempting to create the room is incorrect and
2186 produces misleading follow-up errors like M_ROOM_IN_USE.
2187 """
2188
2189 def _resp(status_code: int, content: Union[str, bytes]) -> mock.Mock:
2190 r = mock.Mock()
2191 r.status_code = status_code
2192 if isinstance(content, str):
2193 r.content = content.encode("utf-8")
2194 else:
2195 r.content = content
2196 return r
2197
2198 login = dumps(
2199 {
2200 "access_token": "t",
2201 "home_server": "hs",
2202 "user_id": "@u:hs",
2203 }
2204 )
2205
2206 # POST sequence:
2207 # 1. /login succeeds
2208 # 2. /join/#backup fails with 400 and an empty body
2209 # 3. /logout succeeds during object cleanup remembering token
2210 mock_post.side_effect = [
2211 _resp(requests.codes.ok, login),
2212 _resp(requests.codes.bad_request, b""),
2213 _resp(requests.codes.ok, dumps({})),
2214 ]
2215
2216 # No other requests should be needed (no createRoom, no directory lookup)
2217 mock_get.return_value = _resp(requests.codes.internal_server_error, b"")
2218 mock_put.return_value = _resp(requests.codes.ok, dumps({}))
2219
2220 ap = Apprise()
2221 ap.add("matrixs://user:[email protected]/#backup?discovery=no")
2222
2223 assert ap.notify(title="t", body="b") is False
2224
2225 # Cleanup explicitly to ensure __del__ executes while mocks are active.
2226 import gc
2227
2228 del ap
2229 gc.collect()
2230
2231 # login + join + logout
2232 assert mock_post.call_count == 3
2233 assert mock_get.call_count == 0
2234
2235
2236 @mock.patch("requests.put")
2237 @mock.patch("requests.get")
2238 @mock.patch("requests.post")
2239 def test_plugin_matrix_room_create_on_not_found_join(
2240 mock_post: mock.Mock,
2241 mock_get: mock.Mock,
2242 mock_put: mock.Mock,
2243 ) -> None:
2244 """Attempt room creation only when join reports 404 / M_NOT_FOUND."""
2245
2246 def _resp(status_code: int, content: Union[str, bytes]) -> mock.Mock:
2247 r = mock.Mock()
2248 r.status_code = status_code
2249 if isinstance(content, str):
2250 r.content = content.encode("utf-8")
2251 else:
2252 r.content = content
2253 return r
2254
2255 login = dumps(
2256 {
2257 "access_token": "t",
2258 "home_server": "hs",
2259 "user_id": "@u:hs",
2260 }
2261 )
2262
2263 # POST sequence:
2264 # 1. /login succeeds
2265 # 2. /join/#backup returns 404 not found
2266 # 3. /createRoom returns alias in use, triggering alias resolution
2267 # 4. /logout succeeds during object cleanup
2268 mock_post.side_effect = [
2269 _resp(requests.codes.ok, login),
2270 _resp(
2271 requests.codes.not_found,
2272 dumps({"errcode": "M_NOT_FOUND", "error": "Not found"}),
2273 ),
2274 _resp(
2275 requests.codes.bad_request,
2276 dumps(
2277 {
2278 "errcode": "M_ROOM_IN_USE",
2279 "error": "Room alias already taken",
2280 }
2281 ),
2282 ),
2283 _resp(requests.codes.ok, dumps({})),
2284 ]
2285
2286 # Directory lookup returns the room id
2287 mock_get.return_value = _resp(
2288 requests.codes.ok,
2289 dumps({"room_id": "!abc123:matrix.vip"}),
2290 )
2291
2292 # Sending the message succeeds (v3 uses PUT)
2293 mock_put.return_value = _resp(requests.codes.ok, dumps({}))
2294
2295 ap = Apprise()
2296 ap.add("matrixs://user:[email protected]/#backup?discovery=no")
2297
2298 assert ap.notify(title="t", body="b") is True
2299
2300 import gc
2301
2302 del ap
2303 gc.collect()
2304
2305 # login + join + createRoom + logout
2306 assert mock_post.call_count == 4
2307 assert mock_get.call_count == 1
2308 assert mock_put.call_count == 1
2309
2310
2311 # ---------------------------------------------------------------------------
2312 # E2EE unit tests (require the cryptography package)
2313 # ---------------------------------------------------------------------------
2314
2315 try:
2316 import cryptography # noqa: F401
2317
2318 CRYPTOGRAPHY_AVAILABLE = True
2319 except ImportError:
2320 CRYPTOGRAPHY_AVAILABLE = False
2321
2322
2323 @mock.patch("requests.put")
2324 @mock.patch("requests.get")
2325 @mock.patch("requests.post")
2326 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2327 def test_plugin_matrix_room_create_e2ee_initial_state(
2328 mock_post, mock_get, mock_put
2329 ):
2330 """_room_create with e2ee=True/secure=True embeds m.room.encryption in
2331 initial_state and pre-seeds the room encryption cache."""
2332 response_obj = {
2333 "access_token": "tok",
2334 "user_id": "@u:localhost",
2335 "home_server": "localhost",
2336 "room_id": "!abc123",
2337 }
2338 r = mock.Mock()
2339 r.status_code = requests.codes.ok
2340 r.content = dumps(response_obj).encode()
2341 mock_post.return_value = r
2342 mock_get.return_value = r
2343 mock_put.return_value = r
2344
2345 obj = NotifyMatrix(
2346 host="localhost",
2347 user="u",
2348 password="p",
2349 e2ee=True,
2350 secure=True,
2351 discovery=False,
2352 )
2353 obj.access_token = "tok"
2354 obj.home_server = "localhost"
2355
2356 captured_payloads = []
2357 _orig_fetch = obj._fetch
2358
2359 def _capture_fetch(path, payload=None, **kw):
2360 if path == "/createRoom":
2361 captured_payloads.append(payload)
2362 return _orig_fetch(path, payload=payload, **kw)
2363
2364 obj._fetch = _capture_fetch
2365 room_id = obj._room_create("e2ee_room")
2366 assert room_id == response_obj["room_id"]
2367 assert len(captured_payloads) == 1
2368 init_state = captured_payloads[0].get("initial_state", [])
2369 assert any(s.get("type") == "m.room.encryption" for s in init_state)
2370 assert obj.store.get("e2ee_room_enc_{}".format(room_id)) is True
2371
2372
2373 def _rand_b64_32():
2374 """32 bytes of random data encoded as unpadded base64."""
2375 import base64
2376
2377 return base64.b64encode(os.urandom(32)).decode()
2378
2379
2380 def _make_signed_otk(account, user_id, device_id, key_b64=None):
2381 """Return a signed_curve25519 OTK dict signed by *account*.
2382
2383 Produces {"key": ..., "signatures": {user_id: {"ed25519:DEV": ...}}}
2384 suitable for inclusion in a /keys/claim mock response.
2385 """
2386 from apprise.plugins.matrix.e2ee import _canonical_json
2387
2388 if key_b64 is None:
2389 key_b64 = _rand_b64_32()
2390 payload = {"key": key_b64}
2391 sig = account.sign(_canonical_json(payload))
2392 payload["signatures"] = {user_id: {"ed25519:{}".format(device_id): sig}}
2393 return payload
2394
2395
2396 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2397 def test_plugin_matrix_e2ee_helpers():
2398 """e2ee helper functions."""
2399 from apprise.plugins.matrix.e2ee import (
2400 _b64dec,
2401 _b64enc,
2402 _canonical_json,
2403 _hmac_sha256,
2404 _pb_bytes,
2405 _pb_varint_field,
2406 _varint,
2407 )
2408
2409 # _b64enc / _b64dec round-trip
2410 raw = b"\x00\x01\x02\x03"
2411 assert _b64dec(_b64enc(raw)) == raw
2412
2413 # _b64dec tolerates missing padding and URL-safe chars
2414 # "AA==" -> decode "AA" (2 chars, pad=2)
2415 assert _b64dec("AA") == b"\x00"
2416 # URL-safe chars are normalised
2417 assert _b64dec("AA--") == _b64dec("AA++")
2418
2419 # _hmac_sha256 returns 32 bytes
2420 mac = _hmac_sha256(b"\x00" * 32, b"data")
2421 assert isinstance(mac, bytes) and len(mac) == 32
2422
2423 # _varint: n==0 -> single zero byte
2424 assert _varint(0) == b"\x00"
2425 # n>0 is encoded as multi-byte varint
2426 assert _varint(128) == b"\x80\x01"
2427
2428 # _pb_bytes / _pb_varint_field produce bytes
2429 pb = _pb_bytes(1, b"hello")
2430 assert isinstance(pb, bytes) and len(pb) > 5
2431 pv = _pb_varint_field(2, 42)
2432 assert isinstance(pv, bytes)
2433
2434 # _canonical_json produces sorted-key JSON bytes
2435 data = {"z": 1, "a": 2}
2436 out = _canonical_json(data)
2437 assert out.startswith(b'{"a"')
2438
2439
2440 def test_plugin_matrix_e2ee_no_cryptography():
2441 """MATRIX_E2EE_SUPPORT is False when cryptography is unavailable."""
2442 import importlib
2443 import sys
2444
2445 # Block 'cryptography' so the ImportError branch is taken on reload
2446 saved = {
2447 k: v for k, v in sys.modules.items() if k.startswith("cryptography")
2448 }
2449 for key in list(saved):
2450 sys.modules[key] = None # type: ignore[assignment]
2451
2452 try:
2453 import apprise.plugins.matrix.e2ee as e2ee_mod
2454
2455 importlib.reload(e2ee_mod)
2456 assert e2ee_mod.MATRIX_E2EE_SUPPORT is False
2457 finally:
2458 # Restore everything so subsequent tests are not broken
2459 for key in list(saved):
2460 if saved[key] is None:
2461 del sys.modules[key]
2462 else:
2463 sys.modules[key] = saved[key]
2464 # Force a clean reload so MATRIX_E2EE_SUPPORT is True again
2465 importlib.reload(e2ee_mod)
2466
2467
2468 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2469 def test_plugin_matrix_e2ee_olm_account():
2470 """MatrixOlmAccount creation, signing, serialisation."""
2471 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
2472
2473 # Fresh account
2474 acct = MatrixOlmAccount()
2475 assert isinstance(acct.identity_key, str)
2476 assert isinstance(acct.signing_key, str)
2477
2478 # sign() accepts str and bytes
2479 sig = acct.sign("hello")
2480 assert isinstance(sig, str)
2481 sig2 = acct.sign(b"hello")
2482 assert isinstance(sig2, str)
2483
2484 # to_dict / from_dict round-trip
2485 d = acct.to_dict()
2486 assert "ik" in d and "sk" in d
2487 restored = MatrixOlmAccount.from_dict(d)
2488 assert restored.identity_key == acct.identity_key
2489 assert restored.signing_key == acct.signing_key
2490
2491 # Explicit key construction from stored keys
2492 acct2 = MatrixOlmAccount(
2493 ik_priv_b64=d["ik"],
2494 sk_priv_b64=d["sk"],
2495 )
2496 assert acct2.identity_key == acct.identity_key
2497
2498 # device_keys_payload produces a signed dict
2499 payload = acct.device_keys_payload("@u:h", "DEVID")
2500 assert "signatures" in payload
2501 assert "algorithms" in payload
2502
2503 # fallback_keys_payload
2504 fb1 = acct.fallback_keys_payload("@u:h", "DEVID")
2505 assert len(fb1) == 1
2506 fb_key_id1 = next(iter(fb1.keys()))
2507 assert fb_key_id1.startswith("signed_curve25519:")
2508 fb2 = acct.fallback_keys_payload("@u:h", "DEVID")
2509 # second call returns the same key id (key not regenerated)
2510 assert next(iter(fb2.keys())) == fb_key_id1
2511
2512
2513 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2514 def test_plugin_matrix_e2ee_olm_session():
2515 """MatrixOlmSession encrypts and produces correct wire format."""
2516 from apprise.plugins.matrix.e2ee import MatrixOlmAccount, _b64dec
2517
2518 acct = MatrixOlmAccount()
2519 # Create a second account to act as recipient
2520 recipient = MatrixOlmAccount()
2521
2522 session = acct.create_outbound_session(
2523 recipient.identity_key,
2524 recipient.identity_key, # reuse IK as a stand-in OTK
2525 )
2526
2527 assert session.their_identity_key == recipient.identity_key
2528
2529 # str plaintext
2530 result = session.encrypt("test plaintext")
2531 assert result["type"] == 0
2532 assert isinstance(result["body"], str)
2533
2534 # Decode and check the outer pre-key wire format.
2535 # Outer: version(0x03) | field1(OTK) | field2(EK) | field3(IK) |
2536 # field4(inner+mac) | outer_mac(8)
2537 # Inner (in field 4): version(0x03) | field1(ratchet_key) |
2538 # field2(chain_index) | field4(ciphertext,tag=0x22) | inner_mac(8)
2539 raw = _b64dec(result["body"])
2540 assert raw[0:1] == b"\x03", "outer version must be 0x03"
2541 # field 4, wire-type 2 -> tag = (4<<3)|2 = 0x22 -- ciphertext in inner msg
2542 assert b"\x22" in raw, "ciphertext field tag 0x22 must be present"
2543 # Outer field 1 (OTK, tag 0x0A), field 2 (EK, tag 0x12) must appear
2544 assert b"\x0a" in raw, "outer OTK field (tag 0x0A) must be present"
2545 assert b"\x12" in raw, "outer EK field (tag 0x12) must be present"
2546
2547 # bytes plaintext also accepted
2548 result2 = session.encrypt(b"bytes input")
2549 assert result2["type"] == 0
2550
2551
2552 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2553 def test_plugin_matrix_e2ee_olm_roundtrip():
2554 """Full Olm round-trip: Alice encrypts, Bob manually decrypts.
2555
2556 This test implements the Bob (inbound) side of the Olm X3DH and
2557 message-decryption protocol using the same cryptography primitives,
2558 verifying that our Alice-side implementation produces wire bytes that
2559 a conformant receiver can decrypt.
2560
2561 Critical invariant verified: the outer base-key (pre-key field 2)
2562 equals the inner ratchet-key (normal-message field 1). They MUST be
2563 the same ephemeral key E_A or the receiver cannot reconstruct the
2564 session and decryption fails.
2565 """
2566 import hmac as _hmac_stdlib
2567
2568 from cryptography.hazmat.backends import default_backend
2569 from cryptography.hazmat.primitives import hashes, hmac as _hmac_mod
2570 from cryptography.hazmat.primitives.asymmetric.x25519 import (
2571 X25519PrivateKey,
2572 )
2573 from cryptography.hazmat.primitives.ciphers import (
2574 Cipher,
2575 algorithms,
2576 modes,
2577 )
2578 from cryptography.hazmat.primitives.kdf.hkdf import HKDF
2579 from cryptography.hazmat.primitives.padding import PKCS7
2580 from cryptography.hazmat.primitives.serialization import (
2581 Encoding,
2582 PublicFormat,
2583 )
2584
2585 from apprise.plugins.matrix.e2ee import (
2586 MatrixOlmAccount,
2587 _b64dec,
2588 _b64enc,
2589 )
2590
2591 # -- helpers (Bob-side) -------------------------------------------
2592
2593 def _hmac(key, data):
2594 h = _hmac_mod.HMAC(key, hashes.SHA256(), backend=default_backend())
2595 h.update(data)
2596 return h.finalize()
2597
2598 def _hkdf(ikm, length, salt, info):
2599 return HKDF(
2600 algorithm=hashes.SHA256(),
2601 length=length,
2602 salt=salt,
2603 info=info,
2604 backend=default_backend(),
2605 ).derive(ikm)
2606
2607 def _aes_cbc_decrypt(key, iv, ciphertext):
2608 cipher = Cipher(
2609 algorithms.AES(key), modes.CBC(iv), backend=default_backend()
2610 )
2611 dec = cipher.decryptor()
2612 padded = dec.update(ciphertext) + dec.finalize()
2613 unpadder = PKCS7(128).unpadder()
2614 return unpadder.update(padded) + unpadder.finalize()
2615
2616 def _read_varint(data, pos):
2617 val, shift = 0, 0
2618 while True:
2619 b = data[pos]
2620 pos += 1
2621 val |= (b & 0x7F) << shift
2622 shift += 7
2623 if not (b & 0x80):
2624 return val, pos
2625
2626 def _parse_pb_fields(data):
2627 """Parse length-delimited protobuf body; return {field_num: bytes}."""
2628 fields = {}
2629 pos = 0
2630 while pos < len(data):
2631 tag, pos = _read_varint(data, pos)
2632 field_num = tag >> 3
2633 wire_type = tag & 0x07
2634 if wire_type == 2:
2635 length, pos = _read_varint(data, pos)
2636 fields[field_num] = data[pos : pos + length]
2637 pos += length
2638 elif wire_type == 0:
2639 val, pos = _read_varint(data, pos)
2640 fields[field_num] = val
2641 else:
2642 raise ValueError("Unexpected wire type {}".format(wire_type))
2643 return fields
2644
2645 # -- test setup ---------------------------------------------------
2646
2647 # Alice's account (sender)
2648 alice = MatrixOlmAccount()
2649
2650 # Bob's account: identity key + a separate one-time key
2651 bob = MatrixOlmAccount()
2652 bob_otk_priv = X25519PrivateKey.generate()
2653 bob_otk_pub = bob_otk_priv.public_key().public_bytes(
2654 Encoding.Raw, PublicFormat.Raw
2655 )
2656 bob_otk_pub_b64 = _b64enc(bob_otk_pub)
2657
2658 # Bob's identity-key private (for DH computation)
2659 bob_ik_priv = bob._ik
2660
2661 # Alice creates an outbound session to Bob using his real OTK
2662 session = alice.create_outbound_session(
2663 bob.identity_key, # Bob's Curve25519 identity key
2664 bob_otk_pub_b64, # Bob's one-time key
2665 )
2666
2667 plaintext = "hello from Alice"
2668 result = session.encrypt(plaintext)
2669 assert result["type"] == 0
2670
2671 # -- Bob-side decryption ------------------------------------------
2672
2673 raw = _b64dec(result["body"])
2674
2675 # Outer pre-key message format (Olm spec Section 5.2):
2676 # version(1) | protobuf(field1=OTK, field2=base_key,
2677 # field3=IK, field4=inner_message)
2678 #
2679 # There is NO outer MAC on the pre-key message. Only the inner
2680 # normal-message (field 4) has its own 8-byte MAC appended.
2681 # Reference: olm.md Section 5.2; libolm session.cpp
2682 # encode_one_time_key_message_length() (no MAC bytes allocated);
2683 # vodozemac src/olm/messages/pre_key.rs decode() (no MAC consumed).
2684 assert raw[0:1] == b"\x03", "outer version must be 0x03"
2685
2686 # Parse the full outer protobuf body (all bytes after the version byte)
2687 outer_fields = _parse_pb_fields(raw[1:])
2688 otk_pub_in_msg = outer_fields[1] # field 1: Bob's OTK public bytes
2689 base_key = outer_fields[2] # field 2: Alice's ephemeral E_A
2690 alice_ik_pub = outer_fields[3] # field 3: Alice's identity key
2691
2692 # The OTK bytes in the message must equal Bob's OTK public key
2693 assert otk_pub_in_msg == bob_otk_pub, (
2694 "OTK in pre-key message must match the OTK that was claimed"
2695 )
2696
2697 # Bob computes X3DH (mirroring Alice's DH operations)
2698 # DH1 = X25519(OTK_B_priv, IK_A_pub)
2699 # DH2 = X25519(IK_B_priv, E_A_pub)
2700 # DH3 = X25519(OTK_B_priv, E_A_pub)
2701 from cryptography.hazmat.primitives.asymmetric.x25519 import (
2702 X25519PublicKey,
2703 )
2704
2705 alice_ik = X25519PublicKey.from_public_bytes(alice_ik_pub)
2706 e_a = X25519PublicKey.from_public_bytes(base_key)
2707
2708 dh1 = bob_otk_priv.exchange(alice_ik)
2709 dh2 = bob_ik_priv.exchange(e_a)
2710 dh3 = bob_otk_priv.exchange(e_a)
2711
2712 ikm = dh1 + dh2 + dh3
2713 keys64 = _hkdf(ikm, 64, salt=None, info=b"OLM_ROOT")
2714 root_key = keys64[:32]
2715 chain_key = keys64[32:]
2716 del root_key # not needed for first-message decryption
2717
2718 # Derive message keys from the initial chain key
2719 msg_key = _hmac(chain_key, b"\x01")
2720 keys80 = _hkdf(msg_key, 80, salt=b"\x00" * 32, info=b"OLM_KEYS")
2721 aes_key = keys80[:32]
2722 mac_key = keys80[32:64]
2723 iv = keys80[64:80]
2724
2725 # Field 4 = inner_normal_message || 8-byte MAC.
2726 # The inner normal message itself starts with version byte 0x03 followed
2727 # by the protobuf body; the MAC covers the version + protobuf body.
2728 inner_with_mac = outer_fields[4]
2729 inner_body = inner_with_mac[:-8] # version(1) + pb_fields
2730 inner_mac_received = inner_with_mac[-8:]
2731
2732 # Verify the inner MAC (HMAC-SHA-256 of inner_body, truncated to 8 bytes)
2733 inner_mac_expected = _hmac(mac_key, inner_body)[:8]
2734 assert _hmac_stdlib.compare_digest(
2735 inner_mac_expected, inner_mac_received
2736 ), "inner MAC verification failed"
2737
2738 # Parse inner fields
2739 # inner_body = version(0x03) | pb_fields
2740 assert inner_body[0:1] == b"\x03", "inner version must be 0x03"
2741 inner_fields = _parse_pb_fields(inner_body[1:])
2742
2743 # CRITICAL invariant:
2744 # ratchet_key (inner field 1) == base_key (outer field 2)
2745 ratchet_key = inner_fields[1]
2746 assert ratchet_key == base_key, (
2747 "Olm invariant violated: inner ratchet_key must equal outer base_key "
2748 "(E_A must be used in BOTH positions per Olm spec Section 5.1). "
2749 "Got ratchet_key={} base_key={}".format(
2750 _b64enc(ratchet_key), _b64enc(base_key)
2751 )
2752 )
2753
2754 # Decrypt the AES-256-CBC ciphertext (inner field 4)
2755 ciphertext = inner_fields[4]
2756 decrypted = _aes_cbc_decrypt(aes_key, iv, ciphertext)
2757
2758 assert decrypted.decode("utf-8") == plaintext, (
2759 "round-trip decryption failed: got {!r}".format(decrypted)
2760 )
2761
2762
2763 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2764 def test_plugin_matrix_e2ee_verify_keys():
2765 """verify_device_keys and verify_signed_otk accept/reject signatures."""
2766 from apprise.plugins.matrix.e2ee import (
2767 MatrixOlmAccount,
2768 _canonical_json,
2769 verify_device_keys,
2770 verify_signed_otk,
2771 )
2772
2773 acct = MatrixOlmAccount()
2774 uid = "@alice:h"
2775 dev = "DEVID"
2776
2777 # --- verify_device_keys ---
2778
2779 # Valid self-signed device keys -> True
2780 dk = acct.device_keys_payload(uid, dev)
2781 assert verify_device_keys(dk, uid, dev) is True
2782
2783 # Payload user_id doesn't match -> False (identity binding check)
2784 mismatched_uid = {**dk, "user_id": "@other:h"}
2785 assert verify_device_keys(mismatched_uid, uid, dev) is False
2786
2787 # Payload device_id doesn't match -> False (identity binding check)
2788 mismatched_dev = {**dk, "device_id": "WRONGDEV"}
2789 assert verify_device_keys(mismatched_dev, uid, dev) is False
2790
2791 # Missing user_id in payload -> False
2792 no_user_id = {k: v for k, v in dk.items() if k != "user_id"}
2793 assert verify_device_keys(no_user_id, uid, dev) is False
2794
2795 # Missing signatures field -> False
2796 no_sig = {k: v for k, v in dk.items() if k != "signatures"}
2797 assert verify_device_keys(no_sig, uid, dev) is False
2798
2799 # Wrong user_id in signatures -> False
2800 wrong_uid = {
2801 **dk,
2802 "signatures": {"@wrong:h": dk["signatures"][uid]},
2803 }
2804 assert verify_device_keys(wrong_uid, uid, dev) is False
2805
2806 # Tampered key value -> False
2807 tampered = {**dk, "keys": {**dk["keys"], f"ed25519:{dev}": "bad"}}
2808 assert verify_device_keys(tampered, uid, dev) is False
2809
2810 # Missing ed25519 key entry -> False
2811 no_keys = {**dk, "keys": {f"curve25519:{dev}": acct.identity_key}}
2812 assert verify_device_keys(no_keys, uid, dev) is False
2813
2814 # --- verify_signed_otk ---
2815
2816 key_b64 = _rand_b64_32()
2817 otk_obj = {"key": key_b64}
2818 sig = acct.sign(_canonical_json(otk_obj))
2819 signed_otk = {
2820 **otk_obj,
2821 "signatures": {uid: {f"ed25519:{dev}": sig}},
2822 }
2823
2824 # Valid OTK -> True
2825 assert verify_signed_otk(signed_otk, uid, dev, acct.signing_key) is True
2826
2827 # Missing signatures -> False
2828 assert verify_signed_otk(otk_obj, uid, dev, acct.signing_key) is False
2829
2830 # Wrong signing key -> False
2831 other = MatrixOlmAccount()
2832 assert verify_signed_otk(signed_otk, uid, dev, other.signing_key) is False
2833
2834 # Tampered key value -> False
2835 tampered_otk = {**signed_otk, "key": _rand_b64_32()}
2836 assert verify_signed_otk(tampered_otk, uid, dev, acct.signing_key) is False
2837
2838
2839 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2840 def test_plugin_matrix_e2ee_megolm_session():
2841 """MatrixMegOlmSession encrypt, session_key, rotation, serialisation."""
2842 from apprise.plugins.matrix.e2ee import (
2843 MATRIX_MEGOLM_STORE_VERSION,
2844 MEGOLM_ROTATION_MSGS,
2845 MatrixMegOlmSession,
2846 )
2847
2848 s = MatrixMegOlmSession()
2849 assert isinstance(s.session_id, str)
2850
2851 # encrypt returns base64 ciphertext
2852 ct = s.encrypt({"type": "m.room.message", "content": {}})
2853 assert isinstance(ct, str)
2854
2855 # Verify MegOLM wire format (libolm message.cpp):
2856 # version(0x03) | field1_varint(msg_index,tag=0x08) |
2857 # field2_bytes(ciphertext,tag=0x12) | mac(8) | sig(64)
2858 from apprise.plugins.matrix.e2ee import _b64dec
2859
2860 raw = _b64dec(ct)
2861 assert raw[0:1] == b"\x03", "MegOLM version must be 0x03"
2862 assert raw[1:2] == b"\x08", "MegOLM field 1 tag must be 0x08 (varint)"
2863 # After tag 0x08: the varint counter value (0 -> single byte 0x00),
2864 # then the ciphertext tag 0x12.
2865 assert b"\x12" in raw, "MegOLM ciphertext field tag 0x12 must be present"
2866
2867 # session_key returns base64 -- verify wire format per libolm
2868 # outbound_group_session.c: version(1) + counter(4) + ratchet(128)
2869 # + ed25519_pub(32) + ed25519_sig(64) = 229 bytes raw = 308 base64 chars
2870 sk = s.session_key()
2871 assert isinstance(sk, str)
2872 sk_raw = _b64dec(sk)
2873 assert len(sk_raw) == 229, "session_key must be 229 bytes (sig included)"
2874 assert sk_raw[0:1] == b"\x02", "session_key version must be 0x02"
2875
2876 # to_dict / from_dict round-trip
2877 d = s.to_dict()
2878 assert d["version"] == MATRIX_MEGOLM_STORE_VERSION
2879 s2 = MatrixMegOlmSession.from_dict(d)
2880 assert s2.session_id == s.session_id
2881 assert s2._counter == s._counter
2882
2883 # should_rotate: explicit count threshold
2884 assert not s.should_rotate(msg_count=MEGOLM_ROTATION_MSGS - 1)
2885 assert s.should_rotate(msg_count=MEGOLM_ROTATION_MSGS)
2886
2887 # should_rotate: time threshold (old created_at)
2888 old = MatrixMegOlmSession(created_at=0.0)
2889 assert old.should_rotate()
2890
2891 # _advance branches -- cascade fires when (n+1) % threshold == 0,
2892 # i.e. when the counter is one less than a threshold multiple.
2893
2894 # -- normal step (else branch)
2895 s3 = MatrixMegOlmSession()
2896 s3._advance() # counter 0 -> 1 (1 % 256 != 0, else: R[3] only)
2897
2898 # -- %256 branch: next counter will be 256
2899 s4 = MatrixMegOlmSession()
2900 s4._counter = 255
2901 s4._advance()
2902
2903 # -- %65536 branch: next counter will be 65536
2904 s5 = MatrixMegOlmSession()
2905 s5._counter = 65535
2906 s5._advance()
2907
2908 # -- %2^24 branch: next counter will be 2^24
2909 s6 = MatrixMegOlmSession()
2910 s6._counter = (1 << 24) - 1
2911 s6._advance()
2912
2913
2914 # ---------------------------------------------------------------------------
2915 # E2EE integration tests -- URL parsing and send flow
2916 # ---------------------------------------------------------------------------
2917
2918
2919 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2920 def test_plugin_matrix_e2ee_url_roundtrip():
2921 """e2ee default is True; disabled state survives url() / parse_url()."""
2922 # Default (no e2ee param) is now True
2923 obj = NotifyMatrix(
2924 host="matrix.example.com",
2925 user="user",
2926 password="pass",
2927 targets=["#room"],
2928 )
2929 assert obj.e2ee is True
2930 # Enabled is the default -- not written to URL
2931 assert "e2ee" not in obj.url()
2932
2933 # Disabled survives round-trip
2934 obj2 = NotifyMatrix(
2935 host="matrix.example.com",
2936 user="user",
2937 password="pass",
2938 targets=["#room"],
2939 e2ee=False,
2940 )
2941 assert obj2.e2ee is False
2942 u2 = obj2.url()
2943 assert "e2ee=no" in u2
2944
2945 result = NotifyMatrix.parse_url(u2)
2946 assert result is not None
2947 assert result.get("e2ee") is False or str(result.get("e2ee")).lower() in (
2948 "false",
2949 "no",
2950 "0",
2951 )
2952
2953
2954 @mock.patch("requests.put")
2955 @mock.patch("requests.get")
2956 @mock.patch("requests.post")
2957 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2958 def test_plugin_matrix_e2ee_insecure_connection(mock_post, mock_get, mock_put):
2959 """e2ee=yes over insecure (matrix://) falls back to unencrypted."""
2960 resp = mock.Mock()
2961 resp.status_code = requests.codes.ok
2962 resp.content = dumps(
2963 {
2964 "access_token": "tok",
2965 "user_id": "@u:h",
2966 "home_server": "h",
2967 "device_id": "DEV",
2968 "room_id": "!r:h",
2969 }
2970 ).encode()
2971 mock_post.return_value = resp
2972 mock_get.return_value = resp
2973 mock_put.return_value = resp
2974
2975 # matrix:// (not matrixs://) -- E2EE silently skipped, plain delivery
2976 obj = NotifyMatrix(
2977 host="h",
2978 user="u",
2979 password="pass",
2980 targets=["#room"],
2981 e2ee=True,
2982 # secure=False is the default for matrix:// URLs
2983 )
2984 assert not obj.secure
2985 assert obj.send(body="test") is True
2986
2987
2988 @mock.patch("requests.put")
2989 @mock.patch("requests.get")
2990 @mock.patch("requests.post")
2991 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
2992 def test_plugin_matrix_e2ee_no_support(mock_post, mock_get, mock_put):
2993 """e2ee=yes with MATRIX_E2EE_SUPPORT=False sends unencrypted."""
2994 resp = mock.Mock()
2995 resp.status_code = requests.codes.ok
2996 resp.content = dumps(
2997 {
2998 "access_token": "tok",
2999 "user_id": "@u:h",
3000 "home_server": "h",
3001 "device_id": "DEV",
3002 "room_id": "!r:h",
3003 }
3004 ).encode()
3005 mock_post.return_value = resp
3006 mock_get.return_value = resp
3007 mock_put.return_value = resp
3008
3009 with mock.patch(
3010 "apprise.plugins.matrix.base.MATRIX_E2EE_SUPPORT",
3011 False,
3012 ):
3013 obj = NotifyMatrix(
3014 host="h",
3015 user="u",
3016 password="pass",
3017 targets=["#room"],
3018 e2ee=True,
3019 )
3020 # Should succeed (falls back to unencrypted)
3021 assert obj.send(body="test") is True
3022
3023
3024 @mock.patch("requests.put")
3025 @mock.patch("requests.get")
3026 @mock.patch("requests.post")
3027 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3028 def test_plugin_matrix_e2ee_send(mock_post, mock_get, mock_put):
3029 """Full E2EE send path via _send_server_notification."""
3030 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3031
3032 # Recipient device (acts as a room member)
3033 recipient = MatrixOlmAccount()
3034
3035 login_resp = {
3036 "access_token": "tok123",
3037 "user_id": "@sender:localhost",
3038 "home_server": "localhost",
3039 "device_id": "SENDERDEV",
3040 }
3041
3042 members_resp = {
3043 "joined": {"@other:localhost": {}},
3044 }
3045
3046 # Properly signed device keys (required by verify_device_keys)
3047 signed_dev = recipient.device_keys_payload("@other:localhost", "OTHERDEV")
3048 query_resp = {
3049 "device_keys": {"@other:localhost": {"OTHERDEV": signed_dev}}
3050 }
3051
3052 # Properly signed OTK (required by verify_signed_otk)
3053 signed_otk = _make_signed_otk(recipient, "@other:localhost", "OTHERDEV")
3054 claim_resp = {
3055 "one_time_keys": {
3056 "@other:localhost": {
3057 "OTHERDEV": {"signed_curve25519:KEYID": signed_otk}
3058 }
3059 }
3060 }
3061
3062 def _mk_resp(d):
3063 r = mock.Mock()
3064 r.status_code = requests.codes.ok
3065 r.content = dumps(d).encode()
3066 return r
3067
3068 # POST sequence:
3069 # login, keys/upload (with OTK count), join, keys/query, keys/claim,
3070 # keys/upload (OTK replenishment), logout
3071 mock_post.side_effect = [
3072 _mk_resp(login_resp),
3073 _mk_resp({"one_time_key_counts": {"signed_curve25519": 1}}),
3074 _mk_resp({"room_id": "!room:localhost"}), # join
3075 _mk_resp(query_resp), # keys/query
3076 _mk_resp(claim_resp), # keys/claim
3077 # Replenishment: remaining = 1 - 1 (built_count) = 0 < threshold
3078 _mk_resp(
3079 {
3080 "one_time_key_counts": {
3081 "signed_curve25519": NotifyMatrix.default_e2ee_otk_count,
3082 }
3083 }
3084 ),
3085 _mk_resp({}), # logout
3086 ]
3087 mock_get.return_value = _mk_resp(members_resp)
3088 mock_put.return_value = _mk_resp({})
3089
3090 obj = NotifyMatrix(
3091 host="localhost",
3092 user="sender",
3093 password="pass",
3094 targets=["#room"],
3095 e2ee=True,
3096 secure=True,
3097 discovery=False,
3098 )
3099 assert obj.send(body="hello", title="hi") is True
3100
3101 # PUT was called: sendToDevice + rooms/send/encrypted
3102 assert mock_put.call_count >= 2
3103
3104
3105 @mock.patch("requests.put")
3106 @mock.patch("requests.get")
3107 @mock.patch("requests.post")
3108 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3109 def test_plugin_matrix_e2ee_send_cached_session(mock_post, mock_get, mock_put):
3110 """E2EE send skips key-share when session key already shared."""
3111 login_resp = {
3112 "access_token": "tok",
3113 "user_id": "@u:h",
3114 "home_server": "h",
3115 "device_id": "DEV",
3116 }
3117
3118 def _mk_resp(d):
3119 r = mock.Mock()
3120 r.status_code = requests.codes.ok
3121 r.content = dumps(d).encode()
3122 return r
3123
3124 # POST: login, keys/upload, join, logout
3125 mock_post.side_effect = [
3126 _mk_resp(login_resp),
3127 _mk_resp({}), # keys/upload
3128 _mk_resp({"room_id": "!r:h"}), # join
3129 _mk_resp({}), # logout
3130 ]
3131 mock_put.return_value = _mk_resp({})
3132
3133 from apprise.plugins.matrix.e2ee import MatrixMegOlmSession
3134
3135 obj = NotifyMatrix(
3136 host="h",
3137 user="u",
3138 password="pass",
3139 targets=["!r:h"],
3140 e2ee=True,
3141 secure=True,
3142 discovery=False,
3143 )
3144 # Pre-seed room encryption state, MegOLM session, and key-shared flag
3145 # so that no additional GETs or key-exchange PUTs are issued.
3146 _sess = MatrixMegOlmSession()
3147 obj.store.set("e2ee_room_enc_!r:h", True)
3148 obj.store.set("e2ee_megolm_!r:h", _sess.to_dict())
3149 obj.store.set("e2ee_key_shared_!r:h", _sess.session_id)
3150 assert obj.send(body="silent") is True
3151 # Only one PUT for the encrypted message itself
3152 assert mock_put.call_count == 1
3153
3154
3155 @mock.patch("requests.put")
3156 @mock.patch("requests.get")
3157 @mock.patch("requests.post")
3158 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3159 def test_plugin_matrix_e2ee_send_legacy_shared_flag_rekeys(
3160 mock_post, mock_get, mock_put
3161 ):
3162 """Legacy boolean key-share cache forces a fresh room-key share."""
3163 from apprise.plugins.matrix.e2ee import (
3164 MatrixMegOlmSession,
3165 MatrixOlmAccount,
3166 )
3167
3168 obj = NotifyMatrix(
3169 host="h",
3170 user="u",
3171 password="pass",
3172 targets=["#r"],
3173 e2ee=True,
3174 )
3175 obj.access_token = "tok"
3176 obj.home_server = "h"
3177 obj.user_id = "@u:h"
3178 obj.device_id = "DEV"
3179 obj._e2ee_account = MatrixOlmAccount()
3180 session = MatrixMegOlmSession()
3181 obj.store.set("e2ee_megolm_!r:h", session.to_dict())
3182 obj.store.set("e2ee_key_shared_!r:h", True)
3183
3184 with (
3185 mock.patch.object(
3186 obj, "_e2ee_share_room_key", return_value=True
3187 ) as share,
3188 mock.patch.object(obj, "_fetch", return_value=(True, {}, 200)),
3189 ):
3190 assert (
3191 obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO) is True
3192 )
3193
3194 assert share.call_count == 1
3195 assert obj.store.get("e2ee_key_shared_!r:h") == session.session_id
3196
3197
3198 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3199 def test_plugin_matrix_e2ee_setup_restored():
3200 """E2EE account restores from store via _e2ee_setup and __init__."""
3201 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3202
3203 acct = MatrixOlmAccount()
3204
3205 obj = NotifyMatrix(
3206 host="h",
3207 user="u",
3208 password="pass",
3209 targets=["#r"],
3210 e2ee=True,
3211 )
3212 # Seed account + mark keys already uploaded
3213 obj.store.set("e2ee_account", acct.to_dict())
3214 obj.store.set("e2ee_keys_uploaded", True)
3215 obj.store.set(
3216 "e2ee_device_binding",
3217 "{}|{}|{}|{}".format(
3218 obj.user_id or "",
3219 obj.device_id or "",
3220 acct.identity_key,
3221 acct.signing_key,
3222 ),
3223 )
3224
3225 # Simulate state where account is not yet loaded in memory
3226 obj._e2ee_account = None
3227
3228 # _e2ee_setup should restore the account from the store
3229 assert obj._e2ee_setup() is True
3230 assert obj._e2ee_account is not None
3231 assert obj._e2ee_account.identity_key == acct.identity_key
3232
3233 # Bad account data in store -> _e2ee_setup creates a fresh account;
3234 # the try/except in _e2ee_setup is exercised when from_dict raises.
3235 obj._e2ee_account = None
3236 obj.store.set("e2ee_account", {"bad": "data"})
3237 obj.store.clear("e2ee_keys_uploaded")
3238 with mock.patch.object(obj, "_e2ee_upload_keys", return_value=True):
3239 result = obj._e2ee_setup()
3240 assert result is True
3241 assert obj._e2ee_account is not None
3242
3243 # Patch the store so __init__ sees a valid pre-existing account,
3244 # exercising the success path of the contextlib.suppress block.
3245 valid_data = obj._e2ee_account.to_dict()
3246 with mock.patch(
3247 "apprise.persistent_store.PersistentStore.get",
3248 return_value=valid_data,
3249 ):
3250 obj2 = NotifyMatrix(
3251 host="h",
3252 user="u",
3253 password="pass",
3254 targets=["#r"],
3255 e2ee=True,
3256 )
3257 assert obj2._e2ee_account is not None
3258
3259
3260 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3261 def test_plugin_matrix_e2ee_setup_reuploads_on_binding_change():
3262 """Changed device/account identity forces a fresh key upload."""
3263 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3264
3265 acct = MatrixOlmAccount()
3266 obj = NotifyMatrix(
3267 host="h",
3268 user="u",
3269 password="pass",
3270 targets=["#r"],
3271 e2ee=True,
3272 )
3273 obj.user_id = "@u:h"
3274 obj.device_id = "DEV_NEW"
3275 obj._e2ee_account = acct
3276 obj.store.set("e2ee_account", acct.to_dict())
3277 obj.store.set("e2ee_keys_uploaded", True)
3278 obj.store.set("e2ee_device_binding", "@u:h|DEV_OLD|oldik|oldsk")
3279
3280 with mock.patch.object(
3281 obj, "_e2ee_upload_keys", return_value=True
3282 ) as upload:
3283 assert obj._e2ee_setup() is True
3284
3285 assert upload.call_count == 1
3286
3287
3288 @mock.patch("requests.put")
3289 @mock.patch("requests.get")
3290 @mock.patch("requests.post")
3291 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3292 def test_plugin_matrix_e2ee_upload_keys_no_ids(mock_post, mock_get, mock_put):
3293 """_e2ee_upload_keys returns False when user_id/device_id missing."""
3294 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3295
3296 obj = NotifyMatrix(
3297 host="h",
3298 user="u",
3299 password="pass",
3300 targets=["#r"],
3301 e2ee=True,
3302 )
3303 obj._e2ee_account = MatrixOlmAccount()
3304 # No user_id / device_id set
3305 assert obj._e2ee_upload_keys() is False
3306
3307
3308 @mock.patch("requests.put")
3309 @mock.patch("requests.get")
3310 @mock.patch("requests.post")
3311 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3312 def test_plugin_matrix_e2ee_upload_keys_http_fail(
3313 mock_post, mock_get, mock_put
3314 ):
3315 """_e2ee_upload_keys returns False on HTTP error."""
3316 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3317
3318 resp = mock.Mock()
3319 resp.status_code = 500
3320 resp.content = dumps({}).encode()
3321 mock_post.return_value = resp
3322
3323 obj = NotifyMatrix(
3324 host="h",
3325 user="u",
3326 password="pass",
3327 targets=["#r"],
3328 e2ee=True,
3329 )
3330 obj._e2ee_account = MatrixOlmAccount()
3331 obj.access_token = "tok"
3332 obj.user_id = "@u:h"
3333 obj.device_id = "DEV"
3334 obj.home_server = "h"
3335 assert obj._e2ee_upload_keys() is False
3336
3337
3338 @mock.patch("requests.put")
3339 @mock.patch("requests.get")
3340 @mock.patch("requests.post")
3341 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3342 def test_plugin_matrix_e2ee_upload_keys_success_marks_published(
3343 mock_post, mock_get, mock_put
3344 ):
3345 """Successful upload clears the current unpublished OTK batch."""
3346 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3347
3348 resp = mock.Mock()
3349 resp.status_code = requests.codes.ok
3350 resp.content = dumps(
3351 {
3352 "one_time_key_counts": {
3353 "signed_curve25519": NotifyMatrix.default_e2ee_otk_count,
3354 }
3355 }
3356 ).encode()
3357 mock_post.return_value = resp
3358
3359 obj = NotifyMatrix(
3360 host="h",
3361 user="u",
3362 password="pass",
3363 targets=["#r"],
3364 e2ee=True,
3365 )
3366 obj._e2ee_account = MatrixOlmAccount()
3367 obj.access_token = "tok"
3368 obj.user_id = "@u:h"
3369 obj.device_id = "DEV"
3370 obj.home_server = "h"
3371
3372 # Pre-generate one-time keys so we can verify they are marked published.
3373 obj._e2ee_account.one_time_keys_payload(
3374 obj.user_id, obj.device_id, count=3
3375 )
3376 assert obj._e2ee_account._otks
3377 assert obj._e2ee_upload_keys() is True
3378 assert obj._e2ee_account._otks == {}
3379 # Server OTK count from the response is persisted for threshold checks.
3380 assert obj.store.get("e2ee_otk_server_count") == (
3381 NotifyMatrix.default_e2ee_otk_count
3382 )
3383
3384
3385 @mock.patch("requests.put")
3386 @mock.patch("requests.get")
3387 @mock.patch("requests.post")
3388 def test_plugin_matrix_whoami(mock_post, mock_get, mock_put):
3389 """_whoami() resolves user_id and device_id from GET /account/whoami."""
3390
3391 def _mk_resp(d, code=requests.codes.ok):
3392 r = mock.Mock()
3393 r.status_code = code
3394 r.content = dumps(d).encode()
3395 return r
3396
3397 obj = NotifyMatrix(
3398 host="h",
3399 password="rawtoken",
3400 targets=["#r"],
3401 e2ee=True,
3402 )
3403 obj.access_token = "rawtoken"
3404 obj.home_server = "h"
3405
3406 # Success: server returns user_id and device_id; home_server is
3407 # extracted from user_id so DM targets resolve correctly.
3408 mock_get.return_value = _mk_resp(
3409 {"user_id": "@tok:h", "device_id": "TOKDEV"}
3410 )
3411 assert obj._whoami() is True
3412 assert obj.user_id == "@tok:h"
3413 assert obj.device_id == "TOKDEV"
3414 assert obj.home_server == "h"
3415 assert obj.store.get("user_id") == "@tok:h"
3416 assert obj.store.get("device_id") == "TOKDEV"
3417 assert obj.store.get("home_server") == "h"
3418
3419 # user_id without homeserver component (@alice, no colon) -> home_server
3420 # is not extracted (branch where len(parts) != 2 is not taken).
3421 obj.user_id = None
3422 obj.home_server = None
3423 mock_get.return_value = _mk_resp(
3424 {"user_id": "@noserver", "device_id": "DEV2"}
3425 )
3426 assert obj._whoami() is True
3427 assert obj.user_id == "@noserver"
3428 assert obj.home_server is None # no colon -> not extracted
3429
3430 # home_server already known -> not overwritten
3431 obj.home_server = "existing.h"
3432 mock_get.return_value = _mk_resp(
3433 {"user_id": "@tok:other.h", "device_id": "DEV3"}
3434 )
3435 assert obj._whoami() is True
3436 assert obj.home_server == "existing.h"
3437
3438 # Failure: server returns non-200
3439 obj.user_id = None
3440 obj.device_id = None
3441 mock_get.return_value = _mk_resp({}, code=401)
3442 assert obj._whoami() is False
3443
3444
3445 @mock.patch("requests.put")
3446 @mock.patch("requests.get")
3447 @mock.patch("requests.post")
3448 def test_plugin_matrix_send_cached_token_recovers_home_server(
3449 mock_post, mock_get, mock_put
3450 ):
3451 """Cached auth without home_server should be repaired via _whoami()."""
3452
3453 obj = NotifyMatrix(
3454 host="matrix.org",
3455 user="apprise",
3456 password="pass",
3457 targets=["#general"],
3458 )
3459 obj.access_token = "cached-token"
3460 obj.user_id = None
3461 obj.device_id = None
3462 obj.home_server = None
3463
3464 whoami_called = {"count": 0}
3465
3466 def _fake_whoami():
3467 whoami_called["count"] += 1
3468 obj.user_id = "@apprise:matrix.org"
3469 obj.device_id = "DEV42"
3470 obj.home_server = "matrix.org"
3471 return True
3472
3473 with (
3474 mock.patch.object(obj, "_room_join", return_value="!room:matrix.org"),
3475 mock.patch.object(obj, "_whoami", side_effect=_fake_whoami),
3476 mock.patch.object(
3477 obj, "_fetch", return_value=(True, {"event_id": "$1"}, 200)
3478 ),
3479 ):
3480 assert obj.send("body", title="test") is True
3481
3482 assert whoami_called["count"] == 1
3483 assert obj.home_server == "matrix.org"
3484 assert obj.user_id == "@apprise:matrix.org"
3485
3486
3487 @mock.patch("requests.put")
3488 @mock.patch("requests.get")
3489 @mock.patch("requests.post")
3490 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3491 def test_plugin_matrix_e2ee_get_megolm_rotation(mock_post, mock_get, mock_put):
3492 """_e2ee_get_megolm rotates session after threshold."""
3493 from apprise.plugins.matrix.e2ee import (
3494 MEGOLM_ROTATION_MSGS,
3495 MatrixMegOlmSession,
3496 )
3497
3498 obj = NotifyMatrix(
3499 host="h",
3500 user="u",
3501 password="pass",
3502 targets=["#r"],
3503 e2ee=True,
3504 )
3505
3506 # Seed a session that is already past the rotation threshold
3507 stale = MatrixMegOlmSession()
3508 stale._counter = MEGOLM_ROTATION_MSGS
3509 obj.store.set("e2ee_megolm_!r:h", stale.to_dict())
3510 obj.store.set("e2ee_key_shared_!r:h", True)
3511
3512 new_session = obj._e2ee_get_megolm("!r:h")
3513 assert new_session.session_id != stale.session_id
3514
3515 # The shared flag should be cleared on rotation
3516 assert obj.store.get("e2ee_key_shared_!r:h") is None
3517
3518 # Legacy cached sessions without the current version marker are
3519 # invalidated and replaced with a fresh session.
3520 legacy = stale.to_dict()
3521 del legacy["version"]
3522 obj.store.set("e2ee_megolm_!r:h", legacy)
3523 obj.store.set("e2ee_key_shared_!r:h", stale.session_id)
3524 replaced = obj._e2ee_get_megolm("!r:h")
3525 assert replaced.session_id != stale.session_id
3526 assert obj.store.get("e2ee_key_shared_!r:h") is None
3527
3528
3529 @mock.patch("requests.put")
3530 @mock.patch("requests.get")
3531 @mock.patch("requests.post")
3532 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3533 def test_plugin_matrix_e2ee_room_encrypted(mock_post, mock_get, mock_put):
3534 """_e2ee_room_encrypted: cached, GET success, GET failure paths."""
3535
3536 def _mk_resp(d, code=requests.codes.ok):
3537 r = mock.Mock()
3538 r.status_code = code
3539 r.content = dumps(d).encode()
3540 return r
3541
3542 obj = NotifyMatrix(
3543 host="h",
3544 user="u",
3545 password="pass",
3546 targets=["#r"],
3547 e2ee=True,
3548 )
3549 obj.access_token = "tok"
3550 obj.home_server = "h"
3551
3552 # Cache hit -- no GET fired
3553 obj.store.set("e2ee_room_enc_!r:h", True)
3554 assert obj._e2ee_room_encrypted("!r:h") is True
3555 assert mock_get.call_count == 0
3556
3557 # Cache miss, GET returns 200 with content -> True
3558 obj.store.clear("e2ee_room_enc_!r:h")
3559 mock_get.return_value = _mk_resp({"algorithm": "m.megolm.v1.aes-sha2"})
3560 assert obj._e2ee_room_encrypted("!r:h") is True
3561 assert mock_get.call_count == 1
3562
3563 # Cache is now populated
3564 assert obj.store.get("e2ee_room_enc_!r:h") is True
3565
3566 # Cache miss, GET returns 404 -> False
3567 obj.store.clear("e2ee_room_enc_!r:h")
3568 mock_get.return_value = _mk_resp({}, code=404)
3569 assert obj._e2ee_room_encrypted("!r:h") is False
3570 assert obj.store.get("e2ee_room_enc_!r:h") is False
3571
3572
3573 @mock.patch("requests.put")
3574 @mock.patch("requests.get")
3575 @mock.patch("requests.post")
3576 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3577 def test_plugin_matrix_e2ee_room_members(mock_post, mock_get, mock_put):
3578 """_e2ee_room_members handles HTTP failures and empty rooms."""
3579
3580 def _mk_resp(d, code=requests.codes.ok):
3581 r = mock.Mock()
3582 r.status_code = code
3583 r.content = dumps(d).encode()
3584 return r
3585
3586 obj = NotifyMatrix(
3587 host="h",
3588 user="u",
3589 password="pass",
3590 targets=["#r"],
3591 e2ee=True,
3592 )
3593 obj.access_token = "tok"
3594 obj.home_server = "h"
3595
3596 # joined_members HTTP failure -> None
3597 mock_get.return_value = _mk_resp({}, code=500)
3598 assert obj._e2ee_room_members("!r:h") is None
3599
3600 # No joined members -> empty dict
3601 mock_get.return_value = _mk_resp({"joined": {}})
3602 assert obj._e2ee_room_members("!r:h") == {}
3603
3604 # keys/query failure -> None
3605 mock_get.return_value = _mk_resp({"joined": {"@u:h": {}}})
3606 mock_post.return_value = _mk_resp({}, code=500)
3607 assert obj._e2ee_room_members("!r:h") is None
3608
3609 # Unsigned device key -> device is rejected (empty result for that uid)
3610 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3611
3612 unsigned_resp = {
3613 "device_keys": {
3614 "@u:h": {
3615 "DEV": {
3616 "keys": {
3617 "curve25519:DEV": "IK",
3618 "ed25519:DEV": "SK",
3619 }
3620 # no "signatures" field
3621 }
3622 }
3623 }
3624 }
3625 mock_get.return_value = _mk_resp({"joined": {"@u:h": {}}})
3626 mock_post.return_value = _mk_resp(unsigned_resp)
3627 result = obj._e2ee_room_members("!r:h")
3628 assert result["@u:h"] == {}
3629
3630 # Properly signed device key -> device included
3631 acct = MatrixOlmAccount()
3632 signed_dev = acct.device_keys_payload("@u:h", "DEV")
3633 query_resp = {"device_keys": {"@u:h": {"DEV": signed_dev}}}
3634 mock_get.return_value = _mk_resp({"joined": {"@u:h": {}}})
3635 mock_post.return_value = _mk_resp(query_resp)
3636 result = obj._e2ee_room_members("!r:h")
3637 assert "@u:h" in result
3638 assert result["@u:h"]["DEV"]["curve25519"] == acct.identity_key
3639
3640
3641 @mock.patch("requests.put")
3642 @mock.patch("requests.get")
3643 @mock.patch("requests.post")
3644 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3645 def test_plugin_matrix_e2ee_share_room_key_branches(
3646 mock_post, mock_get, mock_put
3647 ):
3648 """_e2ee_share_room_key edge cases."""
3649 from apprise.plugins.matrix.e2ee import (
3650 MatrixMegOlmSession,
3651 MatrixOlmAccount,
3652 )
3653
3654 def _mk_resp(d, code=requests.codes.ok):
3655 r = mock.Mock()
3656 r.status_code = code
3657 r.content = dumps(d).encode()
3658 return r
3659
3660 obj = NotifyMatrix(
3661 host="h",
3662 user="u",
3663 password="pass",
3664 targets=["#r"],
3665 e2ee=True,
3666 )
3667 obj.access_token = "tok"
3668 obj.home_server = "h"
3669 obj.user_id = "@sender:h"
3670 obj.device_id = "SDEV"
3671 obj._e2ee_account = MatrixOlmAccount()
3672 session = MatrixMegOlmSession()
3673
3674 # members failure -> False
3675 with mock.patch.object(obj, "_e2ee_room_members", return_value=None):
3676 assert obj._e2ee_share_room_key("!r:h", session) is False
3677
3678 # empty members -> True (nothing to send)
3679 with mock.patch.object(obj, "_e2ee_room_members", return_value={}):
3680 assert obj._e2ee_share_room_key("!r:h", session) is True
3681
3682 # keys/claim failure -> False
3683 members = {"@other:h": {"DEV": {"curve25519": "IK", "ed25519": "SK"}}}
3684 mock_post.return_value = _mk_resp({}, code=500)
3685 with mock.patch.object(obj, "_e2ee_room_members", return_value=members):
3686 assert obj._e2ee_share_room_key("!r:h", session) is False
3687
3688 # keys/claim succeeds but server reports failures{} for remote servers
3689 failures_resp = {
3690 "one_time_keys": {},
3691 "failures": {"remote.example": {"errcode": "M_UNREACHABLE"}},
3692 }
3693 mock_post.return_value = _mk_resp(failures_resp)
3694 with mock.patch.object(obj, "_e2ee_room_members", return_value=members):
3695 assert obj._e2ee_share_room_key("!r:h", session) is True
3696
3697 # own device is skipped (sender uid + device match)
3698 own_members = {
3699 "@sender:h": {"SDEV": {"curve25519": "IK", "ed25519": "SK"}}
3700 }
3701 otk_resp = {
3702 "one_time_keys": {
3703 "@sender:h": {"SDEV": {"signed_curve25519:KID": _rand_b64_32()}}
3704 }
3705 }
3706 mock_post.return_value = _mk_resp(otk_resp)
3707 mock_put.return_value = _mk_resp({})
3708 with mock.patch.object(
3709 obj, "_e2ee_room_members", return_value=own_members
3710 ):
3711 # All devices skipped -> no PUT; still returns True
3712 assert obj._e2ee_share_room_key("!r:h", session) is True
3713
3714 # missing curve25519 key -> device skipped
3715 no_ik = {"@other:h": {"DEV": {"curve25519": "", "ed25519": "SK"}}}
3716 with mock.patch.object(obj, "_e2ee_room_members", return_value=no_ik):
3717 mock_post.return_value = _mk_resp(
3718 {"one_time_keys": {"@other:h": {"DEV": {}}}}
3719 )
3720 assert obj._e2ee_share_room_key("!r:h", session) is True
3721
3722 # dict-valued OTK with valid signature succeeds end-to-end
3723 recipient = MatrixOlmAccount()
3724 their_ik = recipient.identity_key
3725 their_otk_b64 = _rand_b64_32()
3726 signed_otk_dict = _make_signed_otk(
3727 recipient, "@other:h", "DEV", their_otk_b64
3728 )
3729 dict_members = {
3730 "@other:h": {
3731 "DEV": {
3732 "curve25519": their_ik,
3733 "ed25519": recipient.signing_key,
3734 }
3735 }
3736 }
3737 dict_otk = {
3738 "one_time_keys": {
3739 "@other:h": {"DEV": {"signed_curve25519:KID": signed_otk_dict}}
3740 }
3741 }
3742 mock_post.return_value = _mk_resp(dict_otk)
3743 mock_put.return_value = _mk_resp({})
3744 with mock.patch.object(
3745 obj, "_e2ee_room_members", return_value=dict_members
3746 ):
3747 assert obj._e2ee_share_room_key("!r:h", session) is True
3748 payload = loads(mock_put.call_args.kwargs["data"])
3749 dev_payload = payload["messages"]["@other:h"]["DEV"]
3750 assert dev_payload["sender_key"] == obj._e2ee_account.identity_key
3751 # recipient_key and org.matrix.msgid are non-standard fields
3752 # that were removed; verify they are absent
3753 assert "recipient_key" not in dev_payload
3754 assert "org.matrix.msgid" not in dev_payload
3755
3756 # dict-valued OTK with no signatures -> OTK rejected, device skipped
3757 unsigned_otk_dict = {"key": their_otk_b64} # no "signatures" field
3758 unsigned_otk_resp = {
3759 "one_time_keys": {
3760 "@other:h": {"DEV": {"signed_curve25519:KID": unsigned_otk_dict}}
3761 }
3762 }
3763 mock_post.return_value = _mk_resp(unsigned_otk_resp)
3764 with mock.patch.object(
3765 obj, "_e2ee_room_members", return_value=dict_members
3766 ):
3767 # No valid OTK -> no messages built -> True (nothing to send)
3768 assert obj._e2ee_share_room_key("!r:h", session) is True
3769
3770 # Plain-string OTK for signed_curve25519 -> rejected (not a KeyObject)
3771 str_members = {
3772 "@other:h": {
3773 "DEV": {
3774 "curve25519": their_ik,
3775 "ed25519": recipient.signing_key,
3776 }
3777 }
3778 }
3779 str_otk = {
3780 "one_time_keys": {
3781 "@other:h": {"DEV": {"signed_curve25519:KID": their_otk_b64}}
3782 }
3783 }
3784 mock_post.return_value = _mk_resp(str_otk)
3785 with mock.patch.object(
3786 obj, "_e2ee_room_members", return_value=str_members
3787 ):
3788 # No valid KeyObject OTK -> no messages built -> True (nothing sent)
3789 assert obj._e2ee_share_room_key("!r:h", session) is True
3790
3791 # OTK key not prefixed with "signed_curve25519:" -> skipped, no OTK found
3792 bad_key_otk = {
3793 "one_time_keys": {"@other:h": {"DEV": {"ed25519:KID": their_otk_b64}}}
3794 }
3795 mock_post.return_value = _mk_resp(bad_key_otk)
3796 with mock.patch.object(
3797 obj, "_e2ee_room_members", return_value=str_members
3798 ):
3799 assert obj._e2ee_share_room_key("!r:h", session) is True
3800
3801 # OTK entry is not a dict (unexpected server response format)
3802 non_dict_otk = {"one_time_keys": {"@other:h": {"DEV": "invalid_format"}}}
3803 mock_post.return_value = _mk_resp(non_dict_otk)
3804 with mock.patch.object(
3805 obj, "_e2ee_room_members", return_value=str_members
3806 ):
3807 assert obj._e2ee_share_room_key("!r:h", session) is True
3808
3809 # OTK value is an integer (unknown format) -> skipped
3810 non_str_otk = {
3811 "one_time_keys": {"@other:h": {"DEV": {"signed_curve25519:KID": 42}}}
3812 }
3813 mock_post.return_value = _mk_resp(non_str_otk)
3814 with mock.patch.object(
3815 obj, "_e2ee_room_members", return_value=str_members
3816 ):
3817 assert obj._e2ee_share_room_key("!r:h", session) is True
3818
3819 # create_outbound_session raises -> device is skipped gracefully
3820 # Use a properly signed OTK so verification passes and the Olm call
3821 # is actually reached.
3822 create_fail_signed = _make_signed_otk(
3823 recipient, "@other:h", "DEV", their_otk_b64
3824 )
3825 create_fail_otk = {
3826 "one_time_keys": {
3827 "@other:h": {"DEV": {"signed_curve25519:KID": create_fail_signed}}
3828 }
3829 }
3830 mock_post.return_value = _mk_resp(create_fail_otk)
3831 with (
3832 mock.patch.object(
3833 obj, "_e2ee_room_members", return_value=dict_members
3834 ),
3835 mock.patch.object(
3836 obj._e2ee_account,
3837 "create_outbound_session",
3838 side_effect=Exception("olm error"),
3839 ),
3840 ):
3841 assert obj._e2ee_share_room_key("!r:h", session) is True
3842
3843 # sendToDevice PUT fails -> returns False (key-shared flag not set)
3844 # Uses a signed OTK so the full Olm path is exercised before the PUT
3845 full_signed_otk = _make_signed_otk(
3846 recipient, "@other:h", "DEV", their_otk_b64
3847 )
3848 full_otk_resp = {
3849 "one_time_keys": {
3850 "@other:h": {"DEV": {"signed_curve25519:KID": full_signed_otk}}
3851 }
3852 }
3853 mock_post.return_value = _mk_resp(full_otk_resp)
3854 mock_put.return_value = _mk_resp({}, code=500)
3855 with mock.patch.object(
3856 obj, "_e2ee_room_members", return_value=dict_members
3857 ):
3858 assert obj._e2ee_share_room_key("!r:h", session) is False
3859
3860 # token-as-password mode: transaction_id is a UUID, not an int.
3861 # Previously, the unconditional `+= 1` raised TypeError (UUID + int).
3862 # With the guard in place the UUID is used as-is and the send succeeds.
3863 import uuid as _uuid_mod
3864
3865 uuid_obj = NotifyMatrix(
3866 host="h", password="rawtoken", targets=["#r"], e2ee=True
3867 )
3868 uuid_obj.access_token = "rawtoken"
3869 uuid_obj.password = "rawtoken"
3870 uuid_obj.transaction_id = _uuid_mod.uuid4() # UUID, not int
3871 uuid_obj.home_server = "h"
3872 uuid_obj.user_id = "@tok:h"
3873 uuid_obj.device_id = "TOKDEV"
3874 uuid_obj._e2ee_account = MatrixOlmAccount()
3875
3876 uuid_session = MatrixMegOlmSession()
3877 uuid_otk = _make_signed_otk(recipient, "@other:h", "DEV", their_otk_b64)
3878 uuid_claim = {
3879 "one_time_keys": {
3880 "@other:h": {"DEV": {"signed_curve25519:KID": uuid_otk}}
3881 }
3882 }
3883 mock_post.return_value = _mk_resp(uuid_claim)
3884 mock_put.return_value = _mk_resp({})
3885 with mock.patch.object(
3886 uuid_obj, "_e2ee_room_members", return_value=dict_members
3887 ):
3888 # Must not raise TypeError; transaction_id stays as UUID
3889 assert uuid_obj._e2ee_share_room_key("!r:h", uuid_session) is True
3890 assert isinstance(uuid_obj.transaction_id, _uuid_mod.UUID)
3891
3892
3893 @mock.patch("requests.post")
3894 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3895 def test_plugin_matrix_e2ee_replenish_otks(mock_post):
3896 """_e2ee_replenish_otks: threshold logic, diagnostics, and error paths."""
3897 from apprise.plugins.matrix.e2ee import MatrixOlmAccount
3898
3899 otk_count = NotifyMatrix.default_e2ee_otk_count
3900 otk_threshold = NotifyMatrix.default_e2ee_otk_replenish_threshold
3901
3902 def _mk_resp(d, code=requests.codes.ok):
3903 r = mock.Mock()
3904 r.status_code = code
3905 r.content = dumps(d).encode()
3906 return r
3907
3908 def _make_obj():
3909 obj = NotifyMatrix(
3910 host="h", user="u", password="pass", targets=["#r"], e2ee=True
3911 )
3912 obj.user_id = "@u:h"
3913 obj.device_id = "DEV"
3914 obj._e2ee_account = MatrixOlmAccount()
3915 return obj
3916
3917 # --- missing credentials: no network call, returns False ---
3918 obj = _make_obj()
3919 obj.user_id = None
3920 assert obj._e2ee_replenish_otks() is False
3921 assert mock_post.call_count == 0
3922
3923 obj = _make_obj()
3924 obj.device_id = None
3925 assert obj._e2ee_replenish_otks() is False
3926 assert mock_post.call_count == 0
3927
3928 # --- pool sufficient: skip upload ---
3929 # Store a count well above threshold; claimed_count=1 -> remaining is
3930 # above default_e2ee_otk_replenish_threshold so no upload should happen.
3931 obj = _make_obj()
3932 obj.store.set("e2ee_otk_server_count", otk_threshold + otk_count)
3933 result = obj._e2ee_replenish_otks(claimed_count=1, skipped_no_otk=0)
3934 assert result is True
3935 assert mock_post.call_count == 0
3936
3937 # --- pool low: remaining < threshold triggers upload ---
3938 obj = _make_obj()
3939 obj.store.set("e2ee_otk_server_count", otk_threshold - 1)
3940 mock_post.return_value = _mk_resp(
3941 {"one_time_key_counts": {"signed_curve25519": otk_count}}
3942 )
3943 assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is True
3944 assert mock_post.call_count == 1
3945 assert obj.store.get("e2ee_otk_server_count") == otk_count
3946 assert obj.store.get("e2ee_account") is not None
3947 mock_post.reset_mock()
3948
3949 # --- unknown server count (no store entry): replenish as precaution ---
3950 obj = _make_obj()
3951 # e2ee_otk_server_count not set -> unknown
3952 mock_post.return_value = _mk_resp(
3953 {"one_time_key_counts": {"signed_curve25519": otk_count}}
3954 )
3955 assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is True
3956 assert mock_post.call_count == 1
3957 mock_post.reset_mock()
3958
3959 # --- skipped_no_otk > 0: always replenishes regardless of count ---
3960 obj = _make_obj()
3961 obj.store.set("e2ee_otk_server_count", otk_threshold + otk_count)
3962 mock_post.return_value = _mk_resp(
3963 {"one_time_key_counts": {"signed_curve25519": otk_count}}
3964 )
3965 assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=2) is True
3966 assert mock_post.call_count == 1
3967 mock_post.reset_mock()
3968
3969 # --- upload failure: returns False, logs warning ---
3970 obj = _make_obj()
3971 obj.store.set("e2ee_otk_server_count", 0)
3972 mock_post.return_value = _mk_resp({}, code=500)
3973 assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is False
3974 mock_post.reset_mock()
3975
3976 # --- response missing one_time_key_counts: new count defaults to 0 ---
3977 obj = _make_obj()
3978 obj.store.set("e2ee_otk_server_count", 0)
3979 mock_post.return_value = _mk_resp({}) # no one_time_key_counts key
3980 assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is True
3981 assert obj.store.get("e2ee_otk_server_count") == 0
3982 mock_post.reset_mock()
3983
3984
3985 @mock.patch("requests.put")
3986 @mock.patch("requests.get")
3987 @mock.patch("requests.post")
3988 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
3989 def test_plugin_matrix_e2ee_send_to_room_formats(
3990 mock_post, mock_get, mock_put
3991 ):
3992 """_e2ee_send_to_room: HTML/Markdown format paths and key-share fail."""
3993 from apprise.common import NotifyFormat
3994 from apprise.plugins.matrix.e2ee import (
3995 MatrixMegOlmSession,
3996 MatrixOlmAccount,
3997 )
3998
3999 def _mk_resp(d):
4000 r = mock.Mock()
4001 r.status_code = requests.codes.ok
4002 r.content = dumps(d).encode()
4003 return r
4004
4005 mock_put.return_value = _mk_resp({})
4006
4007 def _make_obj(fmt):
4008 obj = NotifyMatrix(
4009 host="h",
4010 user="u",
4011 password="pass",
4012 targets=["#r"],
4013 e2ee=True,
4014 )
4015 obj.notify_format = fmt
4016 obj.access_token = "tok"
4017 obj.home_server = "h"
4018 obj.user_id = "@u:h"
4019 obj.device_id = "DEV"
4020 obj._e2ee_account = MatrixOlmAccount()
4021 return obj
4022
4023 # HTML format
4024 obj = _make_obj(NotifyFormat.HTML)
4025 session = MatrixMegOlmSession()
4026 obj.store.set("e2ee_megolm_!r:h", session.to_dict())
4027 obj.store.set("e2ee_key_shared_!r:h", session.session_id)
4028 assert (
4029 obj._e2ee_send_to_room(
4030 "!r:h", "<b>body</b>", "<h1>title</h1>", NotifyType.INFO
4031 )
4032 is True
4033 )
4034
4035 # Markdown format
4036 obj = _make_obj(NotifyFormat.MARKDOWN)
4037 session = MatrixMegOlmSession()
4038 obj.store.set("e2ee_megolm_!r:h", session.to_dict())
4039 obj.store.set("e2ee_key_shared_!r:h", session.session_id)
4040 assert (
4041 obj._e2ee_send_to_room("!r:h", "**bold**", "title", NotifyType.INFO)
4042 is True
4043 )
4044
4045 # key-share flags set after successful share (no pre-seeded flag)
4046 obj = _make_obj(NotifyFormat.TEXT)
4047 session = MatrixMegOlmSession()
4048 obj.store.set("e2ee_megolm_!r:h", session.to_dict())
4049 with mock.patch.object(obj, "_e2ee_share_room_key", return_value=True):
4050 assert (
4051 obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO) is True
4052 )
4053
4054 # token-as-password mode: access_token == password skips txn increment
4055 obj = _make_obj(NotifyFormat.TEXT)
4056 obj.access_token = "same"
4057 obj.password = "same"
4058 session2 = MatrixMegOlmSession()
4059 obj.store.set("e2ee_megolm_!r:h", session2.to_dict())
4060 obj.store.set("e2ee_key_shared_!r:h", session2.session_id)
4061 assert obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO) is True
4062
4063 # key-share failure aborts send
4064 obj = _make_obj(NotifyFormat.TEXT)
4065 obj.store.clear("e2ee_key_shared_!r:h")
4066 with mock.patch.object(obj, "_e2ee_share_room_key", return_value=False):
4067 assert (
4068 obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO)
4069 is False
4070 )
4071
4072
4073 @mock.patch("requests.put")
4074 @mock.patch("requests.get")
4075 @mock.patch("requests.post")
4076 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
4077 def test_plugin_matrix_e2ee_setup_failure(mock_post, mock_get, mock_put):
4078 """When E2EE setup fails, send falls back to unencrypted."""
4079 resp = mock.Mock()
4080 resp.status_code = requests.codes.ok
4081 resp.content = dumps(
4082 {
4083 "access_token": "tok",
4084 "user_id": "@u:h",
4085 "home_server": "h",
4086 "device_id": "DEV",
4087 "room_id": "!r:h",
4088 }
4089 ).encode()
4090 # upload keys call fails
4091 fail_resp = mock.Mock()
4092 fail_resp.status_code = 500
4093 fail_resp.content = dumps({}).encode()
4094 mock_put.return_value = resp
4095
4096 mock_post.side_effect = [
4097 resp, # login
4098 fail_resp, # keys/upload -> failure
4099 resp, # join
4100 resp, # logout
4101 ]
4102 mock_get.return_value = resp
4103
4104 obj = NotifyMatrix(
4105 host="h",
4106 user="u",
4107 password="pass",
4108 targets=["!r:h"],
4109 e2ee=True,
4110 secure=True,
4111 discovery=False,
4112 )
4113 # Falls back to unencrypted -> send succeeds
4114 assert obj.send(body="fallback") is True
4115
4116
4117 @mock.patch("requests.put")
4118 @mock.patch("requests.get")
4119 @mock.patch("requests.post")
4120 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
4121 def test_plugin_matrix_e2ee_attachment_encrypted(
4122 mock_post, mock_get, mock_put
4123 ):
4124 """E2EE mode encrypts and delivers attachments."""
4125 import tempfile
4126
4127 login_resp = {
4128 "access_token": "tok",
4129 "user_id": "@u:h",
4130 "home_server": "h",
4131 "device_id": "DEV",
4132 }
4133 upload_resp = {"content_uri": "mxc://h/enc123"}
4134
4135 def _mk_resp(d):
4136 r = mock.Mock()
4137 r.status_code = requests.codes.ok
4138 r.content = dumps(d).encode()
4139 return r
4140
4141 mock_post.side_effect = [
4142 _mk_resp(login_resp),
4143 _mk_resp({}), # keys/upload
4144 _mk_resp({"room_id": "!r:h"}), # join
4145 _mk_resp(upload_resp), # encrypted attachment upload
4146 _mk_resp({}), # logout
4147 ]
4148 mock_get.return_value = _mk_resp({"joined": {}})
4149 mock_put.return_value = _mk_resp({})
4150
4151 with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
4152 f.write(b"test attachment")
4153 attach_path = f.name
4154
4155 try:
4156 attach = AppriseAttachment()
4157 attach.add(attach_path)
4158
4159 obj = NotifyMatrix(
4160 host="h",
4161 user="u",
4162 password="pass",
4163 targets=["!r:h"],
4164 e2ee=True,
4165 secure=True,
4166 discovery=False,
4167 )
4168 from apprise.plugins.matrix.e2ee import MatrixMegOlmSession
4169
4170 _s = MatrixMegOlmSession()
4171 obj.store.set("e2ee_room_enc_!r:h", True)
4172 obj.store.set("e2ee_megolm_!r:h", _s.to_dict())
4173 obj.store.set("e2ee_key_shared_!r:h", _s.session_id)
4174 assert obj.send(body="body", attach=attach) is True
4175
4176 # Two PUTs: encrypted message + encrypted attachment event
4177 assert mock_put.call_count == 2
4178
4179 finally:
4180 os.unlink(attach_path)
4181
4182
4183 @mock.patch("requests.put")
4184 @mock.patch("requests.get")
4185 @mock.patch("requests.post")
4186 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
4187 def test_plugin_matrix_e2ee_send_attachment_errors(
4188 mock_post, mock_get, mock_put
4189 ):
4190 """_e2ee_send_attachment error branches: OSError, network, HTTP fail."""
4191 import tempfile
4192
4193 from apprise.plugins.matrix.e2ee import (
4194 MatrixMegOlmSession,
4195 MatrixOlmAccount,
4196 )
4197
4198 def _mk_resp(d, code=requests.codes.ok):
4199 r = mock.Mock()
4200 r.status_code = code
4201 r.content = dumps(d).encode()
4202 return r
4203
4204 obj = NotifyMatrix(
4205 host="h",
4206 user="u",
4207 password="pass",
4208 targets=["!r:h"],
4209 e2ee=True,
4210 secure=True,
4211 discovery=False,
4212 )
4213 obj.access_token = "tok"
4214 obj.home_server = "h"
4215 obj.user_id = "@u:h"
4216 obj.device_id = "DEV"
4217 obj._e2ee_account = MatrixOlmAccount()
4218 session = MatrixMegOlmSession()
4219
4220 # OSError reading file -> False
4221 with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
4222 f.write(b"data")
4223 tmp_path = f.name
4224
4225 try:
4226
4227 class _BadAttach:
4228 path = tmp_path
4229 name = "f.txt"
4230 mimetype = "text/plain"
4231
4232 def __len__(self):
4233 return 0
4234
4235 with mock.patch("builtins.open", side_effect=OSError("no read")):
4236 assert (
4237 obj._e2ee_send_attachment(_BadAttach(), "!r:h", session)
4238 is False
4239 )
4240
4241 # Network error during upload -> False
4242 with mock.patch(
4243 "requests.post",
4244 side_effect=requests.RequestException("boom"),
4245 ):
4246 assert (
4247 obj._e2ee_send_attachment(_BadAttach(), "!r:h", session)
4248 is False
4249 )
4250
4251 # HTTP error from media server -> False
4252 with mock.patch("requests.post", return_value=_mk_resp({}, code=500)):
4253 assert (
4254 obj._e2ee_send_attachment(_BadAttach(), "!r:h", session)
4255 is False
4256 )
4257
4258 # Upload succeeds but response body is not valid JSON -> treated as
4259 # missing content_uri -> False
4260 bad_json_resp = mock.Mock()
4261 bad_json_resp.status_code = requests.codes.ok
4262 bad_json_resp.content = b"not-json"
4263 with mock.patch("requests.post", return_value=bad_json_resp):
4264 assert (
4265 obj._e2ee_send_attachment(_BadAttach(), "!r:h", session)
4266 is False
4267 )
4268
4269 # base_url raises -> False
4270 with mock.patch(
4271 "apprise.plugins.matrix.base.NotifyMatrix.base_url",
4272 new_callable=mock.PropertyMock,
4273 side_effect=Exception("discovery fail"),
4274 ):
4275 assert (
4276 obj._e2ee_send_attachment(_BadAttach(), "!r:h", session)
4277 is False
4278 )
4279
4280 # No access_token -> Authorization header omitted, upload still works
4281 obj_noauth = NotifyMatrix(
4282 host="h",
4283 user="u",
4284 password="pass",
4285 targets=["!r:h"],
4286 e2ee=True,
4287 secure=True,
4288 discovery=False,
4289 )
4290 obj_noauth.access_token = None
4291 obj_noauth.home_server = "h"
4292 obj_noauth.user_id = "@u:h"
4293 obj_noauth.device_id = "DEV"
4294 obj_noauth._e2ee_account = MatrixOlmAccount()
4295 sess_noauth = MatrixMegOlmSession()
4296 with mock.patch(
4297 "requests.post",
4298 return_value=_mk_resp({"content_uri": "mxc://h/y"}),
4299 ):
4300 mock_put.return_value = _mk_resp({})
4301 assert (
4302 obj_noauth._e2ee_send_attachment(
4303 _BadAttach(), "!r:h", sess_noauth
4304 )
4305 is True
4306 )
4307
4308 # access_token == password -> transaction ID not incremented
4309 obj2 = NotifyMatrix(
4310 host="h",
4311 user="u",
4312 password="tok",
4313 targets=["!r:h"],
4314 e2ee=True,
4315 secure=True,
4316 discovery=False,
4317 )
4318 obj2.access_token = "tok"
4319 obj2.password = "tok"
4320 obj2.home_server = "h"
4321 obj2.user_id = "@u:h"
4322 obj2.device_id = "DEV"
4323 obj2._e2ee_account = MatrixOlmAccount()
4324 sess2 = MatrixMegOlmSession()
4325 txn_before = obj2.transaction_id
4326 upload_r = _mk_resp({"content_uri": "mxc://h/x"})
4327 put_r = _mk_resp({})
4328 with mock.patch("requests.post", return_value=upload_r):
4329 mock_put.return_value = put_r
4330 result = obj2._e2ee_send_attachment(_BadAttach(), "!r:h", sess2)
4331 assert result is True
4332 assert obj2.transaction_id == txn_before
4333
4334 # Image mimetype -> is_image branch (no 'filename' field added)
4335 class _ImageAttach:
4336 path = tmp_path
4337 name = "photo.png"
4338 mimetype = "image/png"
4339
4340 def __len__(self):
4341 return 4
4342
4343 with mock.patch("requests.post", return_value=upload_r):
4344 mock_put.return_value = put_r
4345 result = obj2._e2ee_send_attachment(_ImageAttach(), "!r:h", sess2)
4346 assert result is True
4347
4348 finally:
4349 os.unlink(tmp_path)
4350
4351
4352 @mock.patch("requests.put")
4353 @mock.patch("requests.get")
4354 @mock.patch("requests.post")
4355 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
4356 def test_plugin_matrix_e2ee_send_attachment_invalid(
4357 mock_post, mock_get, mock_put
4358 ):
4359 """Invalid attachment and _e2ee_send_attachment failure mark has_error."""
4360 import tempfile
4361
4362 login_resp = {
4363 "access_token": "tok",
4364 "user_id": "@u:h",
4365 "home_server": "h",
4366 "device_id": "DEV",
4367 }
4368
4369 def _mk_resp(d):
4370 r = mock.Mock()
4371 r.status_code = requests.codes.ok
4372 r.content = dumps(d).encode()
4373 return r
4374
4375 mock_post.side_effect = [
4376 _mk_resp(login_resp),
4377 _mk_resp({}), # keys/upload
4378 _mk_resp({"room_id": "!r:h"}), # join
4379 _mk_resp({}), # logout
4380 ]
4381 mock_get.return_value = _mk_resp({})
4382 mock_put.return_value = _mk_resp({})
4383
4384 with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
4385 f.write(b"data")
4386 attach_path = f.name
4387
4388 try:
4389 from apprise.plugins.matrix.e2ee import MatrixMegOlmSession
4390
4391 obj = NotifyMatrix(
4392 host="h",
4393 user="u",
4394 password="pass",
4395 targets=["!r:h"],
4396 e2ee=True,
4397 secure=True,
4398 discovery=False,
4399 )
4400 _s = MatrixMegOlmSession()
4401 obj.store.set("e2ee_room_enc_!r:h", True)
4402 obj.store.set("e2ee_megolm_!r:h", _s.to_dict())
4403 obj.store.set("e2ee_key_shared_!r:h", _s.session_id)
4404
4405 attach = AppriseAttachment()
4406 attach.add(attach_path)
4407
4408 # _e2ee_send_attachment fails -> send returns False
4409 with mock.patch.object(
4410 obj, "_e2ee_send_attachment", return_value=False
4411 ):
4412 assert obj.send(body="body", attach=attach) is False
4413
4414 # Invalid attachment (falsy) in list -> has_error set and loop breaks
4415 mock_post.reset_mock()
4416 mock_post.side_effect = [
4417 _mk_resp(login_resp),
4418 _mk_resp({}), # keys/upload
4419 _mk_resp({"room_id": "!r:h"}), # join
4420 _mk_resp({}), # logout
4421 ]
4422 obj2 = NotifyMatrix(
4423 host="h",
4424 user="u",
4425 password="pass",
4426 targets=["!r:h"],
4427 e2ee=True,
4428 secure=True,
4429 discovery=False,
4430 )
4431 _s2 = MatrixMegOlmSession()
4432 obj2.store.set("e2ee_room_enc_!r:h", True)
4433 obj2.store.set("e2ee_megolm_!r:h", _s2.to_dict())
4434 obj2.store.set("e2ee_key_shared_!r:h", _s2.session_id)
4435 # Add a non-existent file to get a falsy attachment
4436 bad_attach = AppriseAttachment()
4437 bad_attach.add("/nonexistent/path/file.txt")
4438 with mock.patch.object(obj2, "_e2ee_send_to_room", return_value=True):
4439 assert obj2.send(body="body", attach=bad_attach) is False
4440
4441 finally:
4442 os.unlink(attach_path)
4443
4444
4445 @mock.patch("requests.put")
4446 @mock.patch("requests.get")
4447 @mock.patch("requests.post")
4448 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
4449 def test_plugin_matrix_e2ee_send_room_failure(mock_post, mock_get, mock_put):
4450 """E2EE path returns False when _e2ee_send_to_room fails."""
4451 login_resp = {
4452 "access_token": "tok",
4453 "user_id": "@u:h",
4454 "home_server": "h",
4455 "device_id": "DEV",
4456 }
4457
4458 def _mk_resp(d):
4459 r = mock.Mock()
4460 r.status_code = requests.codes.ok
4461 r.content = dumps(d).encode()
4462 return r
4463
4464 mock_post.side_effect = [
4465 _mk_resp(login_resp),
4466 _mk_resp({}), # keys/upload
4467 _mk_resp({"room_id": "!r:h"}), # join
4468 _mk_resp({}), # logout
4469 ]
4470 mock_get.return_value = _mk_resp({})
4471 mock_put.return_value = _mk_resp({})
4472
4473 from apprise.plugins.matrix.e2ee import MatrixMegOlmSession
4474
4475 obj = NotifyMatrix(
4476 host="h",
4477 user="u",
4478 password="pass",
4479 targets=["!r:h"],
4480 e2ee=True,
4481 secure=True,
4482 discovery=False,
4483 )
4484 obj.store.set("e2ee_room_enc_!r:h", True)
4485 _s = MatrixMegOlmSession()
4486 obj.store.set("e2ee_megolm_!r:h", _s.to_dict())
4487 obj.store.set("e2ee_key_shared_!r:h", _s.session_id)
4488
4489 with mock.patch.object(obj, "_e2ee_send_to_room", return_value=False):
4490 assert obj.send(body="fail") is False
4491
4492
4493 @mock.patch("requests.put")
4494 @mock.patch("requests.get")
4495 @mock.patch("requests.post")
4496 def test_plugin_matrix_register_with_device_id(mock_post, mock_get, mock_put):
4497 """Registration response that includes device_id persists it."""
4498 r = mock.Mock()
4499 r.status_code = requests.codes.ok
4500 r.content = dumps(
4501 {
4502 "access_token": "tok",
4503 "user_id": "@u:h",
4504 "home_server": "h",
4505 "device_id": "REG_DEV",
4506 }
4507 ).encode()
4508 mock_post.return_value = r
4509
4510 obj = NotifyMatrix(host="h", discovery=False)
4511 assert obj._register() is True
4512 assert obj.device_id == "REG_DEV"
4513 assert obj.store.get("device_id") == "REG_DEV"
4514
4515
4516 @mock.patch("requests.put")
4517 @mock.patch("requests.get")
4518 @mock.patch("requests.post")
4519 def test_plugin_matrix_login_reuses_device_id(mock_post, mock_get, mock_put):
4520 """Login payload reuses the stored device ID when present."""
4521 r = mock.Mock()
4522 r.status_code = requests.codes.ok
4523 r.content = dumps(
4524 {
4525 "access_token": "tok",
4526 "user_id": "@u:h",
4527 "home_server": "h",
4528 "device_id": "DEV_REUSED",
4529 }
4530 ).encode()
4531 mock_post.return_value = r
4532
4533 obj = NotifyMatrix(host="h", user="u", password="pass", discovery=False)
4534 obj.device_id = "DEV_REUSED"
4535 assert obj._login() is True
4536
4537 payload = mock_post.call_args.kwargs["data"]
4538 assert '"device_id": "DEV_REUSED"' in payload
4539
4540
4541 @mock.patch("requests.put")
4542 @mock.patch("requests.get")
4543 @mock.patch("requests.post")
4544 def test_plugin_matrix_register_reuses_device_id(
4545 mock_post, mock_get, mock_put
4546 ):
4547 """Register payload reuses the stored device ID when present."""
4548 r = mock.Mock()
4549 r.status_code = requests.codes.ok
4550 r.content = dumps(
4551 {
4552 "access_token": "tok",
4553 "user_id": "@u:h",
4554 "home_server": "h",
4555 "device_id": "DEV_REUSED",
4556 }
4557 ).encode()
4558 mock_post.return_value = r
4559
4560 obj = NotifyMatrix(host="h", user="u", password="pass", discovery=False)
4561 obj.device_id = "DEV_REUSED"
4562 assert obj._register() is True
4563
4564 payload = mock_post.call_args.kwargs["data"]
4565 assert '"device_id": "DEV_REUSED"' in payload
4566
4567
4568 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
4569 def test_plugin_matrix_e2ee_account_bad_store_data():
4570 """Corrupt e2ee_account in store is silently ignored."""
4571 obj = NotifyMatrix(
4572 host="h",
4573 user="u",
4574 password="pass",
4575 targets=["#r"],
4576 e2ee=True,
4577 )
4578 obj.store.set("e2ee_account", {"ik": "NOTVALID", "sk": "NOTVALID"})
4579
4580 # Re-instantiate with the same store to trigger the restore path
4581 obj2 = NotifyMatrix(
4582 host="h",
4583 user="u",
4584 password="pass",
4585 targets=["#r"],
4586 e2ee=True,
4587 store=obj.store,
4588 )
4589 # Bad data is suppressed; account is None until setup is called
4590 assert obj2._e2ee_account is None
4591
4592
4593 def test_plugin_matrix_del_suppresses_logout_exceptions():
4594 """__del__ should never raise if logout fails during GC cleanup."""
4595 obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"])
4596 obj.access_token = "tok"
4597
4598 with mock.patch.object(obj, "_logout", side_effect=RuntimeError("boom")):
4599 obj.__del__()
4600
4601
4602 # ---------------------------------------------------------------------------
4603 # DM / direct-message tests
4604 # ---------------------------------------------------------------------------
4605
4606
4607 def test_plugin_matrix_dm_target_separation():
4608 """@user targets are separated from room targets at init time."""
4609 obj = NotifyMatrix(
4610 host="h",
4611 user="u",
4612 password="pass",
4613 targets=["#general", "@alice", "@bob:other.com", "!room:h"],
4614 discovery=False,
4615 )
4616 assert "#general" in obj.rooms
4617 assert "!room:h" in obj.rooms
4618 assert "@alice" in obj.users
4619 assert "@bob:other.com" in obj.users
4620 assert len(obj.rooms) == 2
4621 assert len(obj.users) == 2
4622
4623 # __len__ accounts for both rooms and users
4624 assert len(obj) == 4
4625
4626
4627 def test_plugin_matrix_dm_url_roundtrip():
4628 """@user targets survive a url() -> parse_url() -> NotifyMatrix cycle."""
4629 obj = NotifyMatrix(
4630 host="h",
4631 user="u",
4632 password="pass",
4633 targets=["#room", "@alice"],
4634 discovery=False,
4635 secure=True,
4636 )
4637 url = obj.url()
4638 # @ is URL-encoded to %40 inside the path segment
4639 assert "%40alice" in url
4640
4641 result = NotifyMatrix.parse_url(url)
4642 assert result is not None
4643 obj2 = NotifyMatrix(**result)
4644 assert "@alice" in obj2.users
4645 assert any("room" in r for r in obj2.rooms)
4646
4647
4648 @mock.patch("requests.put")
4649 @mock.patch("requests.get")
4650 @mock.patch("requests.post")
4651 def test_plugin_matrix_dm_room_find_cached(mock_post, mock_get, mock_put):
4652 """_dm_room_find_or_create returns cached room ID without HTTP calls."""
4653
4654 def _mk_resp(d, code=requests.codes.ok):
4655 r = mock.Mock()
4656 r.status_code = code
4657 r.content = dumps(d).encode()
4658 return r
4659
4660 mock_post.return_value = _mk_resp({})
4661 mock_get.return_value = _mk_resp({})
4662 mock_put.return_value = _mk_resp({})
4663
4664 obj = NotifyMatrix(
4665 host="h",
4666 user="u",
4667 password="pass",
4668 targets=["@alice"],
4669 discovery=False,
4670 )
4671 obj.access_token = "tok"
4672 obj.user_id = "@u:h"
4673 obj.home_server = "h"
4674
4675 # Seed the cache
4676 obj.store.set("dm_room_@alice:h", "!dm123:h")
4677
4678 room_id = obj._dm_room_find_or_create("@alice")
4679 assert room_id == "!dm123:h"
4680 # No HTTP calls should have been made
4681 assert mock_get.call_count == 0
4682 assert mock_post.call_count == 0
4683
4684
4685 @mock.patch("requests.put")
4686 @mock.patch("requests.get")
4687 @mock.patch("requests.post")
4688 def test_plugin_matrix_dm_room_find_via_mdirect(mock_post, mock_get, mock_put):
4689 """_dm_room_find_or_create finds existing room from m.direct data."""
4690
4691 def _mk_resp(d, code=requests.codes.ok):
4692 r = mock.Mock()
4693 r.status_code = code
4694 r.content = dumps(d).encode()
4695 return r
4696
4697 mdirect = {"@alice:h": ["!existing_dm:h"]}
4698 mock_get.return_value = _mk_resp(mdirect)
4699 mock_post.return_value = _mk_resp({})
4700 mock_put.return_value = _mk_resp({})
4701
4702 obj = NotifyMatrix(
4703 host="h",
4704 user="u",
4705 password="pass",
4706 targets=["@alice"],
4707 discovery=False,
4708 )
4709 obj.access_token = "tok"
4710 obj.user_id = "@u:h"
4711 obj.home_server = "h"
4712
4713 room_id = obj._dm_room_find_or_create("@alice")
4714 assert room_id == "!existing_dm:h"
4715
4716 # Result is now cached
4717 assert obj.store.get("dm_room_@alice:h") == "!existing_dm:h"
4718
4719 # No createRoom POST should have been made
4720 assert mock_post.call_count == 0
4721
4722
4723 @mock.patch("requests.put")
4724 @mock.patch("requests.get")
4725 @mock.patch("requests.post")
4726 def test_plugin_matrix_dm_room_create_new(mock_post, mock_get, mock_put):
4727 """_dm_room_find_or_create creates a new room when none exists."""
4728
4729 def _mk_resp(d, code=requests.codes.ok):
4730 r = mock.Mock()
4731 r.status_code = code
4732 r.content = dumps(d).encode()
4733 return r
4734
4735 # GET m.direct returns empty (no existing DM for alice)
4736 mock_get.return_value = _mk_resp({})
4737 # First POST = createRoom, second = (not called)
4738 mock_post.return_value = _mk_resp({"room_id": "!new_dm:h"})
4739 mock_put.return_value = _mk_resp({})
4740
4741 obj = NotifyMatrix(
4742 host="h",
4743 user="u",
4744 password="pass",
4745 targets=["@alice"],
4746 discovery=False,
4747 )
4748 obj.access_token = "tok"
4749 obj.user_id = "@u:h"
4750 obj.home_server = "h"
4751
4752 room_id = obj._dm_room_find_or_create("@alice")
4753 assert room_id == "!new_dm:h"
4754
4755 # Should be cached
4756 assert obj.store.get("dm_room_@alice:h") == "!new_dm:h"
4757
4758 # m.direct PUT should have been called to update the mapping
4759 assert mock_put.call_count >= 1
4760
4761
4762 @mock.patch("requests.put")
4763 @mock.patch("requests.get")
4764 @mock.patch("requests.post")
4765 def test_plugin_matrix_dm_room_create_failure(mock_post, mock_get, mock_put):
4766 """_dm_room_find_or_create returns None when createRoom fails."""
4767
4768 def _mk_resp(d, code=requests.codes.ok):
4769 r = mock.Mock()
4770 r.status_code = code
4771 r.content = dumps(d).encode()
4772 return r
4773
4774 mock_get.return_value = _mk_resp({})
4775 mock_post.return_value = _mk_resp(
4776 {"errcode": "M_FORBIDDEN"}, code=requests.codes.forbidden
4777 )
4778 mock_put.return_value = _mk_resp({})
4779
4780 obj = NotifyMatrix(
4781 host="h",
4782 user="u",
4783 password="pass",
4784 targets=["@alice"],
4785 discovery=False,
4786 )
4787 obj.access_token = "tok"
4788 obj.user_id = "@u:h"
4789 obj.home_server = "h"
4790
4791 assert obj._dm_room_find_or_create("@alice") is None
4792
4793
4794 @mock.patch("requests.put")
4795 @mock.patch("requests.get")
4796 @mock.patch("requests.post")
4797 def test_plugin_matrix_dm_room_create_no_room_id(
4798 mock_post, mock_get, mock_put
4799 ):
4800 """_dm_room_find_or_create returns None when createRoom omits room_id."""
4801
4802 def _mk_resp(d, code=requests.codes.ok):
4803 r = mock.Mock()
4804 r.status_code = code
4805 r.content = dumps(d).encode()
4806 return r
4807
4808 mock_get.return_value = _mk_resp({})
4809 # createRoom returns 200 but no room_id key
4810 mock_post.return_value = _mk_resp({})
4811 mock_put.return_value = _mk_resp({})
4812
4813 obj = NotifyMatrix(
4814 host="h",
4815 user="u",
4816 password="pass",
4817 targets=["@alice"],
4818 discovery=False,
4819 )
4820 obj.access_token = "tok"
4821 obj.user_id = "@u:h"
4822 obj.home_server = "h"
4823
4824 assert obj._dm_room_find_or_create("@alice") is None
4825
4826
4827 def test_plugin_matrix_dm_invalid_user():
4828 """_dm_room_find_or_create returns None for a malformed user target."""
4829 obj = NotifyMatrix(
4830 host="h",
4831 user="u",
4832 password="pass",
4833 targets=["#r"],
4834 discovery=False,
4835 )
4836 obj.access_token = "tok"
4837 obj.user_id = "@u:h"
4838 obj.home_server = "h"
4839
4840 # No @ prefix -- not a valid user target
4841 assert obj._dm_room_find_or_create("notauser") is None
4842
4843
4844 @mock.patch("requests.put")
4845 @mock.patch("requests.get")
4846 @mock.patch("requests.post")
4847 def test_plugin_matrix_dm_send_notification(mock_post, mock_get, mock_put):
4848 """Sending to @user target resolves DM room and delivers message."""
4849
4850 def _mk_resp(d, code=requests.codes.ok):
4851 r = mock.Mock()
4852 r.status_code = code
4853 r.content = dumps(d).encode()
4854 return r
4855
4856 mock_get.return_value = _mk_resp({})
4857 mock_put.return_value = _mk_resp({})
4858 mock_post.side_effect = [
4859 _mk_resp(
4860 {"access_token": "tok", "user_id": "@u:h", "home_server": "h"}
4861 ), # login
4862 _mk_resp({"room_id": "!new_dm:h"}), # createRoom
4863 _mk_resp({}), # logout
4864 ]
4865
4866 obj = NotifyMatrix(
4867 host="h",
4868 user="u",
4869 password="pass",
4870 targets=["@alice"],
4871 discovery=False,
4872 e2ee=False,
4873 )
4874
4875 # Pre-seed DM room so _room_join succeeds
4876 def _join_side(*a, **kw):
4877 return "!new_dm:h"
4878
4879 with (
4880 mock.patch.object(obj, "_room_join", side_effect=_join_side),
4881 mock.patch.object(
4882 obj, "_dm_room_find_or_create", return_value="!new_dm:h"
4883 ),
4884 ):
4885 assert obj.send(body="hello DM") is True
4886
4887
4888 @mock.patch("requests.put")
4889 @mock.patch("requests.get")
4890 @mock.patch("requests.post")
4891 def test_plugin_matrix_dm_only_users_no_rooms_skips_joined(
4892 mock_post, mock_get, mock_put
4893 ):
4894 """When only @user targets are present, _joined_rooms is not queried."""
4895
4896 def _mk_resp(d, code=requests.codes.ok):
4897 r = mock.Mock()
4898 r.status_code = code
4899 r.content = dumps(d).encode()
4900 return r
4901
4902 mock_get.return_value = _mk_resp({})
4903 mock_put.return_value = _mk_resp({})
4904 mock_post.side_effect = [
4905 _mk_resp(
4906 {"access_token": "tok", "user_id": "@u:h", "home_server": "h"}
4907 ), # login
4908 _mk_resp({}), # logout
4909 ]
4910
4911 obj = NotifyMatrix(
4912 host="h",
4913 user="u",
4914 password="pass",
4915 targets=["@alice"],
4916 discovery=False,
4917 e2ee=False,
4918 )
4919
4920 with (
4921 mock.patch.object(obj, "_joined_rooms", return_value=[]) as mock_jr,
4922 mock.patch.object(obj, "_dm_room_find_or_create", return_value=None),
4923 ):
4924 obj.send(body="hi")
4925 # _joined_rooms must NOT have been called
4926 assert mock_jr.call_count == 0
4927
4928
4929 @mock.patch("requests.put")
4930 @mock.patch("requests.get")
4931 @mock.patch("requests.post")
4932 def test_plugin_matrix_dm_room_create_mdirect_get_fails(
4933 mock_post, mock_get, mock_put
4934 ):
4935 """_dm_room_find_or_create still creates room if m.direct GET fails."""
4936
4937 def _mk_resp(d, code=requests.codes.ok):
4938 r = mock.Mock()
4939 r.status_code = code
4940 r.content = dumps(d).encode()
4941 return r
4942
4943 # GET fails (404)
4944 mock_get.return_value = _mk_resp({}, code=404)
4945 mock_post.return_value = _mk_resp({"room_id": "!fallback:h"})
4946 mock_put.return_value = _mk_resp({})
4947
4948 obj = NotifyMatrix(
4949 host="h",
4950 user="u",
4951 password="pass",
4952 targets=["@alice"],
4953 discovery=False,
4954 )
4955 obj.access_token = "tok"
4956 obj.user_id = "@u:h"
4957 obj.home_server = "h"
4958
4959 room_id = obj._dm_room_find_or_create("@alice")
4960 assert room_id == "!fallback:h"
4961
4962
4963 @mock.patch("requests.put")
4964 @mock.patch("requests.get")
4965 @mock.patch("requests.post")
4966 def test_plugin_matrix_dm_room_create_no_user_id(
4967 mock_post, mock_get, mock_put
4968 ):
4969 """_dm_room_find_or_create creates room when user_id is None (skips
4970 the m.direct GET and PUT)."""
4971
4972 def _mk_resp(d, code=requests.codes.ok):
4973 r = mock.Mock()
4974 r.status_code = code
4975 r.content = dumps(d).encode()
4976 return r
4977
4978 mock_get.return_value = _mk_resp({})
4979 mock_post.return_value = _mk_resp({"room_id": "!nodm:h"})
4980 mock_put.return_value = _mk_resp({})
4981
4982 obj = NotifyMatrix(
4983 host="h",
4984 user="u",
4985 password="pass",
4986 targets=["@alice"],
4987 discovery=False,
4988 )
4989 obj.access_token = "tok"
4990 # user_id intentionally left as None so the m.direct branch is skipped
4991 obj.home_server = "h"
4992
4993 room_id = obj._dm_room_find_or_create("@alice")
4994 assert room_id == "!nodm:h"
4995 # No GET and no PUT for m.direct since user_id is None
4996 assert mock_get.call_count == 0
4997
4998
4999 @mock.patch("requests.put")
5000 @mock.patch("requests.get")
5001 @mock.patch("requests.post")
5002 def test_plugin_matrix_dm_room_create_e2ee(mock_post, mock_get, mock_put):
5003 """_dm_room_find_or_create with e2ee=True/secure=True embeds
5004 initial_state and pre-seeds the room encryption cache."""
5005 from apprise.plugins.matrix.base import MATRIX_E2EE_SUPPORT
5006
5007 if not MATRIX_E2EE_SUPPORT:
5008 pytest.skip("cryptography package not installed")
5009
5010 def _mk_resp(d, code=requests.codes.ok):
5011 r = mock.Mock()
5012 r.status_code = code
5013 r.content = dumps(d).encode()
5014 return r
5015
5016 mock_get.return_value = _mk_resp({})
5017 mock_post.return_value = _mk_resp({"room_id": "!dm_e2ee:h"})
5018 mock_put.return_value = _mk_resp({})
5019
5020 obj = NotifyMatrix(
5021 host="h",
5022 user="u",
5023 password="pass",
5024 targets=["@alice"],
5025 e2ee=True,
5026 secure=True,
5027 discovery=False,
5028 )
5029 obj.access_token = "tok"
5030 obj.user_id = "@u:h"
5031 obj.home_server = "h"
5032
5033 captured_payloads = []
5034 _orig_fetch = obj._fetch
5035
5036 def _capture_fetch(path, payload=None, **kw):
5037 if path == "/createRoom":
5038 captured_payloads.append(payload or {})
5039 return _orig_fetch(path, payload=payload, **kw)
5040
5041 obj._fetch = _capture_fetch
5042
5043 room_id = obj._dm_room_find_or_create("@alice")
5044 assert room_id == "!dm_e2ee:h"
5045
5046 # Verify initial_state was sent with m.room.encryption
5047 assert len(captured_payloads) == 1
5048 init_state = captured_payloads[0].get("initial_state", [])
5049 assert any(s.get("type") == "m.room.encryption" for s in init_state)
5050
5051 # Room encryption cache must be pre-seeded
5052 assert obj.store.get("e2ee_room_enc_!dm_e2ee:h") is True
5053
5054
5055 # ---------------------------------------------------------------------------
5056 # home_server recovery-from-user_id coverage tests
5057 # ---------------------------------------------------------------------------
5058
5059
5060 def test_plugin_matrix_init_recovers_home_server_from_user_id(tmpdir):
5061 """__init__ extracts home_server from a cached user_id when home_server
5062 was not stored (older cache entries that predate the home_server field)."""
5063 # A disk-backed asset ensures two separate NotifyMatrix instances that
5064 # share the same url_id() also share the same persistent store file.
5065 asset = AppriseAsset(
5066 storage_mode=PersistentStoreMode.FLUSH,
5067 storage_path=str(tmpdir),
5068 )
5069
5070 # First instance: simulate a login that wrote user_id/access_token but
5071 # did NOT write home_server (older Apprise behaviour).
5072 obj = NotifyMatrix(
5073 host="h", user="u", password="pass", targets=["#r"], asset=asset
5074 )
5075 obj.store.set("user_id", "@u:recovered.com")
5076 obj.store.set("access_token", "tok")
5077 # Flush to disk before the second instance reads it.
5078 obj.store.flush()
5079
5080 # Second instance with the same credentials (same url_id) reads the store.
5081 # The recovery branch (lines 506-509) should derive home_server from
5082 # the stored user_id.
5083 obj2 = NotifyMatrix(
5084 host="h", user="u", password="pass", targets=["#r"], asset=asset
5085 )
5086 assert obj2.home_server == "recovered.com"
5087
5088
5089 def test_plugin_matrix_init_no_home_server_recovery_without_colon(tmpdir):
5090 """__init__ leaves home_server as None when the cached user_id has no
5091 colon -- the recovery split yields a single part and the assignment is
5092 skipped."""
5093 asset = AppriseAsset(
5094 storage_mode=PersistentStoreMode.FLUSH,
5095 storage_path=str(tmpdir),
5096 )
5097
5098 obj = NotifyMatrix(
5099 host="h", user="u", password="pass", targets=["#r"], asset=asset
5100 )
5101 # user_id with no colon -- split(":", 1) produces only one element.
5102 obj.store.set("user_id", "nocolon")
5103 obj.store.set("access_token", "tok")
5104 obj.store.flush()
5105
5106 obj2 = NotifyMatrix(
5107 host="h", user="u", password="pass", targets=["#r"], asset=asset
5108 )
5109 # No colon in user_id means home_server cannot be extracted.
5110 assert obj2.home_server is None
5111
5112
5113 @mock.patch("requests.put")
5114 @mock.patch("requests.get")
5115 @mock.patch("requests.post")
5116 def test_plugin_matrix_whoami_recovers_home_server_from_user_id(
5117 mock_post, mock_get, mock_put
5118 ):
5119 """_whoami() extracts home_server from user_id when the server does not
5120 return a home_server field and self.home_server is unset."""
5121 r = mock.Mock()
5122 r.status_code = requests.codes.ok
5123 r.content = dumps(
5124 {"user_id": "@u:whoami.example.com", "device_id": "DEVX"}
5125 ).encode()
5126 mock_get.return_value = r
5127
5128 obj = NotifyMatrix(host="h", user="u", password="pass", discovery=False)
5129 obj.access_token = "tok"
5130 obj.home_server = None
5131
5132 assert obj._whoami() is True
5133 assert obj.home_server == "whoami.example.com"
5134
5135
5136 def test_plugin_matrix_room_create_recovers_home_server_from_user_id():
5137 """_room_create() falls back to extracting home_server from user_id when
5138 both the room alias and self.home_server carry no homeserver part."""
5139 obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"])
5140 obj.access_token = "tok"
5141 obj.home_server = None
5142 obj.user_id = "@u:create.example.com"
5143
5144 # Capture the /createRoom POST so we can verify the room name used.
5145 captured = {}
5146
5147 def _fake_fetch(path, payload=None, **kw):
5148 if path == "/createRoom":
5149 captured["payload"] = payload
5150 return True, {"room_id": "!newroom:create.example.com"}, 200
5151 return False, {}, 404
5152
5153 with mock.patch.object(obj, "_fetch", side_effect=_fake_fetch):
5154 room_id = obj._room_create("#bare_alias")
5155
5156 assert room_id == "!newroom:create.example.com"
5157 # The room name in the request must use the homeserver from user_id.
5158 assert captured["payload"]["room_alias_name"] == "bare_alias"
5159
5160
5161 def test_plugin_matrix_room_create_returns_none_without_home_server():
5162 """_room_create() returns None when neither the alias, self.home_server,
5163 nor self.user_id can supply a homeserver component."""
5164 obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"])
5165 obj.access_token = "tok"
5166 obj.home_server = None
5167 # user_id with no colon -> extraction yields nothing.
5168 obj.user_id = "nocolon"
5169
5170 result = obj._room_create("#bare_alias")
5171 assert result is None
5172
5173
5174 def test_plugin_matrix_room_id_recovers_home_server_from_user_id():
5175 """_room_id() falls back to extracting home_server from user_id when both
5176 the alias and self.home_server carry no homeserver part."""
5177 obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"])
5178 obj.access_token = "tok"
5179 obj.home_server = None
5180 obj.user_id = "@u:lookup.example.com"
5181
5182 def _fake_fetch(path, payload=None, **kw):
5183 return True, {"room_id": "!found:lookup.example.com"}, 200
5184
5185 with mock.patch.object(obj, "_fetch", side_effect=_fake_fetch):
5186 room_id = obj._room_id("#bare_alias")
5187
5188 assert room_id == "!found:lookup.example.com"
5189
5190
5191 def test_plugin_matrix_room_id_returns_none_without_home_server():
5192 """_room_id() returns None when neither the alias, self.home_server,
5193 nor self.user_id can supply a homeserver component."""
5194 obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"])
5195 obj.access_token = "tok"
5196 obj.home_server = None
5197 obj.user_id = "nocolon"
5198
5199 result = obj._room_id("#bare_alias")
5200 assert result is None
5201
5202
5203 def test_plugin_matrix_enforce_byte_budget():
5204 """The byte budget shrinks Unicode without looping on empty text."""
5205
5206 # Give both Matrix body representations the same emoji-heavy content.
5207 payload = {
5208 "body": "\U0001f600" * 1000,
5209 "formatted_body": "\U0001f600" * 1000,
5210 }
5211 # Apply a deliberately small budget so both fields must shrink.
5212 NotifyMatrix._matrix_enforce_byte_budget(
5213 payload, 500, keys=("formatted_body", "body")
5214 )
5215
5216 # Measure the JSON exactly as Matrix serializes it.
5217 assert len(dumps(payload, ensure_ascii=False).encode("utf-8")) <= 500
5218
5219 # Empty candidates exercise the helper's no-progress exit path.
5220 empty_payload = {"body": "", "formatted_body": ""}
5221
5222 # A tiny impossible budget must return instead of looping forever.
5223 result = NotifyMatrix._matrix_enforce_byte_budget(
5224 empty_payload, 10, keys=("formatted_body", "body")
5225 )
5226 assert result == {"body": "", "formatted_body": ""}
5227
5228
5229 @mock.patch("requests.put")
5230 @mock.patch("requests.get")
5231 @mock.patch("requests.post")
5232 def test_plugin_matrix_emoji_byte_budget(mock_post, mock_get, mock_put):
5233 """Emoji-heavy messages remain within Matrix's byte limit."""
5234
5235 # Reuse a successful Matrix response for login, lookup, and room joins.
5236 response_obj = {
5237 "room_id": "!abc123:localhost",
5238 "room_alias": "#abc123:localhost",
5239 "joined_rooms": ["!abc123:localhost"],
5240 "access_token": "abcd1234",
5241 "home_server": "localhost",
5242 }
5243 # Every mocked Matrix request receives the same successful response.
5244 request = mock.Mock()
5245 request.content = dumps(response_obj)
5246 request.status_code = requests.codes.ok
5247
5248 # Cover each HTTP verb used by the direct Matrix send path.
5249 mock_get.return_value = request
5250 mock_post.return_value = request
5251 mock_put.return_value = request
5252
5253 # Configure rich output so the payload contains two body fields.
5254 kwargs = NotifyMatrix.parse_url(
5255 "matrix://user:passwd@hostname/#abcd?format=html"
5256 )
5257 obj = NotifyMatrix(**kwargs)
5258
5259 # Send directly to exercise the byte-budget safety net.
5260 assert obj.send(body="\U0001f600" * 20000) is True
5261
5262 # Inspect the final room event submitted through PUT.
5263 payload = loads(mock_put.call_args.kwargs["data"])
5264
5265 # Confirm the wire representation stays inside Matrix's safe allowance.
5266 encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8"))
5267 assert encoded_len <= MATRIX_CONTENT_BYTE_LIMIT
5268
5269 # Invalid Unicode is replaced instead of raising during serialization.
5270 assert obj.send(body="\ud800") is True
5271 # The invalid code point becomes a valid placeholder in the JSON body.
5272 wire_payload = mock_put.call_args.kwargs["data"]
5273 assert loads(wire_payload)["body"] == "?"
5274
5275
5276 def test_plugin_matrix_e2ee_body_limit():
5277 """Matrix selects limits for formatting, encryption, and webhooks."""
5278
5279 # Begin with an explicitly unencrypted direct Matrix connection.
5280 obj = NotifyMatrix(
5281 host="h",
5282 user="u",
5283 password="pass",
5284 targets=["#r"],
5285 e2ee=False,
5286 secure=True,
5287 )
5288 # Plain output receives the larger single-body allowance.
5289 assert obj.e2ee is False
5290 assert obj.body_maxlen == obj.body_maxlen_default
5291
5292 # Rich text carries a plain fallback beside its formatted body.
5293 obj.notify_format = NotifyFormat.HTML
5294 assert obj.body_maxlen == obj.body_maxlen_formatted
5295
5296 # Non-TLS connections cannot use encryption even when requested.
5297 obj = NotifyMatrix(
5298 host="h",
5299 user="u",
5300 password="pass",
5301 targets=["#r"],
5302 e2ee=True,
5303 secure=False,
5304 )
5305 # The setting remains visible, but the normal formatted limit is used.
5306 assert obj.e2ee is True
5307 obj.notify_format = NotifyFormat.HTML
5308 assert obj.body_maxlen == obj.body_maxlen_formatted
5309
5310 # A secure connection may use E2EE when crypto support is installed.
5311 obj = NotifyMatrix(
5312 host="h",
5313 user="u",
5314 password="pass",
5315 targets=["#r"],
5316 e2ee=True,
5317 secure=True,
5318 )
5319 assert obj.e2ee is True
5320 obj.notify_format = NotifyFormat.HTML
5321
5322 # Installed crypto support activates the smaller encrypted rich limit.
5323 if CRYPTOGRAPHY_AVAILABLE:
5324 assert obj.body_maxlen == obj.body_maxlen_e2ee_formatted
5325 assert obj.body_maxlen < obj.body_maxlen_formatted
5326
5327 # Plain encrypted content only needs one Matrix body field.
5328 obj.notify_format = NotifyFormat.TEXT
5329 assert obj.body_maxlen == obj.body_maxlen_e2ee
5330 else:
5331 # Encryption also requires the optional cryptography package.
5332 assert obj.body_maxlen == obj.body_maxlen_formatted
5333
5334 # Webhooks keep the original limit regardless of output format.
5335 obj.mode = MatrixWebhookMode.HOOKSHOT
5336 assert obj.body_maxlen == obj.body_maxlen_webhook
5337
5338
5339 @mock.patch("requests.put")
5340 @mock.patch("requests.get")
5341 @mock.patch("requests.post")
5342 def test_plugin_matrix_html_plain_fallback(mock_post, mock_get, mock_put):
5343 """HTML messages include plain text without repeating their markup."""
5344
5345 # Supply the minimum successful responses needed for a direct room send.
5346 response_obj = {
5347 "room_id": "!abc123:localhost",
5348 "room_alias": "#abc123:localhost",
5349 "joined_rooms": ["!abc123:localhost"],
5350 "access_token": "abcd1234",
5351 "home_server": "localhost",
5352 }
5353 # Return success for each mocked Matrix endpoint.
5354 request = mock.Mock()
5355 request.content = dumps(response_obj)
5356 request.status_code = requests.codes.ok
5357
5358 mock_get.return_value = request
5359 mock_post.return_value = request
5360 mock_put.return_value = request
5361
5362 # Select HTML as Matrix's single configured v1 output format.
5363 kwargs = NotifyMatrix.parse_url(
5364 "matrix://user:passwd@hostname/#abcd?format=html"
5365 )
5366 obj = NotifyMatrix(**kwargs)
5367
5368 # Known input provenance allows Matrix to build a plain fallback.
5369 assert (
5370 obj.send(
5371 title="Title",
5372 body="<b>Bold</b> text",
5373 body_format=NotifyFormat.HTML,
5374 )
5375 is True
5376 )
5377
5378 # Read the unencrypted Matrix event submitted to the room.
5379 payload = loads(mock_put.call_args.kwargs["data"])
5380
5381 # Preserve the original markup in Matrix's formatted representation.
5382 assert payload["formatted_body"] == "<h1>Title</h1><b>Bold</b> text"
5383 # The plain-text fallback must not carry the raw markup a second time.
5384 assert "<b>" not in payload["body"]
5385 assert "Bold text" in payload["body"]
5386
5387 # No input format is v1's pass-through signal.
5388 assert obj.send(body="<b>Upstream HTML</b>") is True
5389
5390 # Re-read the most recent PUT to verify pass-through behavior.
5391 payload = loads(mock_put.call_args.kwargs["data"])
5392 assert payload["body"] == "<b>Upstream HTML</b>"
5393
5394
5395 @mock.patch("requests.put")
5396 @mock.patch("requests.get")
5397 @mock.patch("requests.post")
5398 def test_plugin_matrix_html_split_preserves_body(
5399 mock_post, mock_get, mock_put
5400 ):
5401 """HTML overflow splits before payload sizing so content is preserved."""
5402
5403 # Make login, discovery, and room operations succeed for every chunk.
5404 response_obj = {
5405 "room_id": "!abc123:localhost",
5406 "room_alias": "#abc123:localhost",
5407 "joined_rooms": ["!abc123:localhost"],
5408 "access_token": "abcd1234",
5409 "home_server": "localhost",
5410 }
5411 # Share one stable mock response across all Matrix HTTP methods.
5412 request = mock.Mock()
5413 request.content = dumps(response_obj)
5414 request.status_code = requests.codes.ok
5415
5416 mock_get.return_value = request
5417 mock_post.return_value = request
5418 mock_put.return_value = request
5419
5420 # Disable E2EE so this test targets the unencrypted HTML tier.
5421 kwargs = NotifyMatrix.parse_url(
5422 "matrix://user:passwd@hostname/#abcd?format=html&e2ee=no"
5423 )
5424 # Build a body that requires exactly three framework chunks.
5425 obj = NotifyMatrix(**kwargs)
5426 body = "x" * (obj.body_maxlen * 2 + 100)
5427
5428 # Use the normal notification path so the framework performs the split.
5429 assert (
5430 obj.notify(
5431 body=body,
5432 body_format=NotifyFormat.HTML,
5433 overflow=OverflowMode.SPLIT,
5434 )
5435 is True
5436 )
5437
5438 # Every original character remains across the resulting Matrix events.
5439 payloads = [loads(call.kwargs["data"]) for call in mock_put.call_args_list]
5440 # The conservative formatted limit should produce three events.
5441 assert len(payloads) == 3
5442
5443 # Joining the formatted bodies must recreate the original input.
5444 assert "".join(payload["formatted_body"] for payload in payloads) == body
5445
5446 # Each individual room event must remain within the byte allowance.
5447 assert all(
5448 len(dumps(payload, ensure_ascii=False).encode("utf-8"))
5449 <= MATRIX_CONTENT_BYTE_LIMIT
5450 for payload in payloads
5451 )
5452
5453
5454 @mock.patch("requests.put")
5455 @mock.patch("requests.get")
5456 @mock.patch("requests.post")
5457 @pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography")
5458 def test_plugin_matrix_e2ee_html_plain_fallback(mock_post, mock_get, mock_put):
5459 """Encrypted HTML messages also provide a plain-text fallback."""
5460 from apprise.common import NotifyFormat
5461 from apprise.plugins.matrix.e2ee import (
5462 MatrixMegOlmSession,
5463 MatrixOlmAccount,
5464 )
5465
5466 def _mk_resp(d):
5467 # Build a successful Matrix response with JSON content.
5468 r = mock.Mock()
5469 r.status_code = requests.codes.ok
5470 r.content = dumps(d).encode()
5471 return r
5472
5473 # Room sends only need an empty successful response body here.
5474 mock_put.return_value = _mk_resp({})
5475
5476 # Prepare a logged-in Matrix object with E2EE enabled.
5477 obj = NotifyMatrix(
5478 host="h", user="u", password="pass", targets=["#r"], e2ee=True
5479 )
5480 # Force the rich-output branch being exercised by this regression.
5481 obj.notify_format = NotifyFormat.HTML
5482
5483 # Populate the identifiers normally learned during Matrix login.
5484 obj.access_token = "tok"
5485 obj.home_server = "h"
5486 obj.user_id = "@u:h"
5487 obj.device_id = "DEV"
5488 # Supply an Olm account so the outer event has a sender key.
5489 obj._e2ee_account = MatrixOlmAccount()
5490
5491 # Seed a MegOLM session that has already been shared with the room.
5492 session = MatrixMegOlmSession()
5493 obj.store.set("e2ee_megolm_!r:h", session.to_dict())
5494 obj.store.set("e2ee_key_shared_!r:h", session.session_id)
5495
5496 # Capture the event before encryption so its fallback can be checked.
5497 captured = {}
5498 # Retain the real encryption function after capturing its input.
5499 original_encrypt = MatrixMegOlmSession.encrypt
5500
5501 def _spy_encrypt(self, event):
5502 # Save the plaintext event immediately before MegOLM encryption.
5503 captured["event"] = event
5504 return original_encrypt(self, event)
5505
5506 with mock.patch.object(MatrixMegOlmSession, "encrypt", _spy_encrypt):
5507 assert (
5508 obj._e2ee_send_to_room(
5509 "!r:h",
5510 "<b>Bold</b> text",
5511 "Title",
5512 NotifyType.INFO,
5513 NotifyFormat.HTML,
5514 )
5515 is True
5516 )
5517
5518 # Inspect both representations inside the captured plaintext event.
5519 msg_content = captured["event"]["content"]
5520
5521 # The rich representation retains all supplied HTML.
5522 assert msg_content["formatted_body"] == "<h1>Title</h1><b>Bold</b> text"
5523
5524 # The fallback remains readable without carrying duplicate markup.
5525 assert "<b>" not in msg_content["body"]
5526 assert "Bold text" in msg_content["body"]
5527
5528 # Reject unexpected envelope growth before the homeserver returns a 413.
5529 # Record network activity before introducing an oversized device ID.
5530 put_count = mock_put.call_count
5531
5532 # Simulate unexpected server metadata that consumes the entire budget.
5533 obj.device_id = "d" * MATRIX_CONTENT_BYTE_LIMIT
5534 assert (
5535 obj._e2ee_send_to_room(
5536 "!r:h", "Body", "", NotifyType.INFO, NotifyFormat.HTML
5537 )
5538 is False
5539 )
5540 # Rejection must happen locally without another room request.
5541 assert mock_put.call_count == put_count