| 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 |
import errno |
| 29 |
import gc |
| 30 |
from json import dumps, loads |
| 31 |
|
| 32 |
# Disable logging for a cleaner testing output |
| 33 |
import logging |
| 34 |
import os |
| 35 |
from typing import Union |
| 36 |
from unittest import mock |
| 37 |
|
| 38 |
from helpers import AppriseURLTester |
| 39 |
import pytest |
| 40 |
import requests |
| 41 |
|
| 42 |
from apprise import ( |
| 43 |
Apprise, |
| 44 |
AppriseAsset, |
| 45 |
AppriseAttachment, |
| 46 |
NotifyType, |
| 47 |
PersistentStoreMode, |
| 48 |
) |
| 49 |
from apprise.exception import ( |
| 50 |
AppriseImproperlyConfigured, |
| 51 |
AppriseInvalidData, |
| 52 |
ApprisePluginException, |
| 53 |
) |
| 54 |
from apprise.plugins.base import _delivery_tracker |
| 55 |
from apprise.plugins.matrix import ( |
| 56 |
MatrixDiscoveryException, |
| 57 |
NotifyMatrix, |
| 58 |
sas as matrix_sas, |
| 59 |
) |
| 60 |
|
| 61 |
logging.disable(logging.CRITICAL) |
| 62 |
|
| 63 |
|
| 64 |
class _Response(mock.Mock): |
| 65 |
"""Mock an HTTP response that supports Requests-style chunked reads.""" |
| 66 |
|
| 67 |
def iter_content(self, chunk_size=None): |
| 68 |
content = self.content |
| 69 |
if isinstance(content, str): |
| 70 |
content = content.encode("utf-8") |
| 71 |
|
| 72 |
return iter([content] if content else []) |
| 73 |
|
| 74 |
|
| 75 |
MATRIX_GOOD_RESPONSE = dumps( |
| 76 |
{ |
| 77 |
"room_id": "!abc123:localhost", |
| 78 |
"room_alias": "#abc123:localhost", |
| 79 |
"joined_rooms": ["!abc123:localhost", "!def456:localhost"], |
| 80 |
"access_token": "abcd1234", |
| 81 |
"home_server": "localhost", |
| 82 |
# user_id is returned by /login and /account/whoami; including it |
| 83 |
# here ensures self.user_id is set after login so _whoami() is not |
| 84 |
# called unnecessarily (it only fires when user_id is still absent). |
| 85 |
"user_id": "@apprise:localhost", |
| 86 |
# Simulate .well-known |
| 87 |
"m.homeserver": {"base_url": "https://matrix.example.com"}, |
| 88 |
"m.identity_server": {"base_url": "https://vector.im"}, |
| 89 |
} |
| 90 |
) |
| 91 |
|
| 92 |
|
| 93 |
def test_plugin_matrix_discovery_exception(): |
| 94 |
"""Matrix discovery failures use the common plugin exception.""" |
| 95 |
exc = MatrixDiscoveryException("discovery failed") |
| 96 |
assert isinstance(exc, ApprisePluginException) |
| 97 |
assert exc.error_code == 600 |
| 98 |
|
| 99 |
|
| 100 |
# Attachment Directory |
| 101 |
TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var") |
| 102 |
|
| 103 |
|
| 104 |
def _force_del_cleanup(): |
| 105 |
"""Run a garbage collection pass right after `del obj`. |
| 106 |
|
| 107 |
This is required otherwise the timing of the systems garbage collection |
| 108 |
can cause issues with the testing |
| 109 |
""" |
| 110 |
gc.collect() |
| 111 |
|
| 112 |
|
| 113 |
# Our Testing URLs |
| 114 |
apprise_url_tests = ( |
| 115 |
################################## |
| 116 |
# NotifyMatrix |
| 117 |
################################## |
| 118 |
( |
| 119 |
"matrix://", |
| 120 |
{ |
| 121 |
"instance": None, |
| 122 |
}, |
| 123 |
), |
| 124 |
( |
| 125 |
"matrixs://", |
| 126 |
{ |
| 127 |
"instance": None, |
| 128 |
}, |
| 129 |
), |
| 130 |
( |
| 131 |
"matrix://localhost?mode=off", |
| 132 |
{ |
| 133 |
# treats it as a anonymous user to register |
| 134 |
"instance": NotifyMatrix, |
| 135 |
# response is false because we have nothing to notify |
| 136 |
"response": False, |
| 137 |
}, |
| 138 |
), |
| 139 |
( |
| 140 |
"matrix://localhost", |
| 141 |
{ |
| 142 |
# Initialization as t2bot fails because localhost is too short |
| 143 |
# to be an API key. |
| 144 |
"instance": AppriseImproperlyConfigured |
| 145 |
}, |
| 146 |
), |
| 147 |
( |
| 148 |
"matrix://user:pass@localhost/#room1/#room2/#room3", |
| 149 |
{ |
| 150 |
"instance": NotifyMatrix, |
| 151 |
"response": False, |
| 152 |
"requests_response_code": requests.codes.internal_server_error, |
| 153 |
}, |
| 154 |
), |
| 155 |
( |
| 156 |
"matrix://user:pass@localhost/#room1/#room2/!room1", |
| 157 |
{ |
| 158 |
"instance": NotifyMatrix, |
| 159 |
# throw a bizarre code forcing us to fail to look it up |
| 160 |
"response": False, |
| 161 |
"requests_response_code": 999, |
| 162 |
}, |
| 163 |
), |
| 164 |
( |
| 165 |
"matrix://user:pass@localhost:1234/#room", |
| 166 |
{ |
| 167 |
"instance": NotifyMatrix, |
| 168 |
# Throws a series of i/o exceptions with this flag |
| 169 |
# is set and tests that we gracefully handle them |
| 170 |
"test_requests_exceptions": True, |
| 171 |
# Our expected url(privacy=True) startswith() response: |
| 172 |
"privacy_url": "matrix://user:****@localhost:1234/", |
| 173 |
}, |
| 174 |
), |
| 175 |
# Matrix supports webhooks too; the following tests this now: |
| 176 |
( |
| 177 |
"matrix://user:token@localhost?mode=matrix&format=text", |
| 178 |
{ |
| 179 |
# user and token correctly specified with webhook |
| 180 |
"instance": NotifyMatrix, |
| 181 |
"response": False, |
| 182 |
}, |
| 183 |
), |
| 184 |
( |
| 185 |
"matrix://user:token@localhost?mode=matrix&format=html", |
| 186 |
{ |
| 187 |
# user and token correctly specified with webhook |
| 188 |
"instance": NotifyMatrix, |
| 189 |
}, |
| 190 |
), |
| 191 |
( |
| 192 |
"matrix://user:token@localhost:123/#general/?version=3", |
| 193 |
{ |
| 194 |
# Provide version over-ride (using version=) |
| 195 |
"instance": NotifyMatrix, |
| 196 |
# Our response expected server response |
| 197 |
"requests_response_text": MATRIX_GOOD_RESPONSE, |
| 198 |
"privacy_url": "matrix://user:****@localhost:123", |
| 199 |
}, |
| 200 |
), |
| 201 |
( |
| 202 |
"matrixs://user:token@localhost/#general?v=2", |
| 203 |
{ |
| 204 |
# Provide version over-ride (using v=) |
| 205 |
"instance": NotifyMatrix, |
| 206 |
# Our response expected server response |
| 207 |
"requests_response_text": MATRIX_GOOD_RESPONSE, |
| 208 |
"privacy_url": "matrixs://user:****@localhost", |
| 209 |
}, |
| 210 |
), |
| 211 |
( |
| 212 |
"matrix://user:token@localhost:123/#general/?v=invalid", |
| 213 |
{ |
| 214 |
# Invalid version specified |
| 215 |
"instance": AppriseImproperlyConfigured |
| 216 |
}, |
| 217 |
), |
| 218 |
( |
| 219 |
"matrix://user:token@localhost?mode=slack&format=text", |
| 220 |
{ |
| 221 |
# user and token correctly specified with webhook |
| 222 |
"instance": NotifyMatrix, |
| 223 |
}, |
| 224 |
), |
| 225 |
( |
| 226 |
"matrixs://user:token@localhost?mode=SLACK&format=markdown", |
| 227 |
{ |
| 228 |
# user and token specified; slack webhook still detected |
| 229 |
# despite uppercase characters |
| 230 |
"instance": NotifyMatrix, |
| 231 |
}, |
| 232 |
), |
| 233 |
( |
| 234 |
"matrix://user@localhost?mode=SLACK&format=markdown&token=mytoken", |
| 235 |
{ |
| 236 |
# user and token specified; slack webhook still detected |
| 237 |
# despite uppercase characters; token also set on URL as arg |
| 238 |
"instance": NotifyMatrix, |
| 239 |
}, |
| 240 |
), |
| 241 |
( |
| 242 |
"matrix://_?mode=t2bot&token={}".format("b" * 64), |
| 243 |
{ |
| 244 |
# Testing t2bot initialization and setting the password using the |
| 245 |
# token directive |
| 246 |
"instance": NotifyMatrix, |
| 247 |
# Our expected url(privacy=True) startswith() response: |
| 248 |
"privacy_url": "matrix://b...b/", |
| 249 |
}, |
| 250 |
), |
| 251 |
( |
| 252 |
( |
| 253 |
"matrixs://hookuser:[email protected]" |
| 254 |
"?mode=hookshot&path=%2Fpublic-hooks" |
| 255 |
), |
| 256 |
{ |
| 257 |
"instance": NotifyMatrix, |
| 258 |
"privacy_url": ( |
| 259 |
"matrixs://hookuser:****@hookshot.example/" |
| 260 |
"?image=no&mode=hookshot" |
| 261 |
), |
| 262 |
}, |
| 263 |
), |
| 264 |
( |
| 265 |
( |
| 266 |
"matrixs://hookuser:[email protected]" |
| 267 |
"?mode=hookshot&path=public-hooks" |
| 268 |
), |
| 269 |
{ |
| 270 |
"instance": NotifyMatrix, |
| 271 |
}, |
| 272 |
), |
| 273 |
# Image Reference |
| 274 |
( |
| 275 |
"matrixs://user:token@localhost?mode=slack&format=markdown&image=True", |
| 276 |
{ |
| 277 |
# user and token specified; image set to True |
| 278 |
"instance": NotifyMatrix, |
| 279 |
}, |
| 280 |
), |
| 281 |
( |
| 282 |
( |
| 283 |
"matrixs://user:token@localhost?mode=slack" |
| 284 |
"&format=markdown&image=False" |
| 285 |
), |
| 286 |
{ |
| 287 |
# user and token specified; image set to True |
| 288 |
"instance": NotifyMatrix, |
| 289 |
}, |
| 290 |
), |
| 291 |
# A Bunch of bad ports |
| 292 |
( |
| 293 |
"matrixs://user:pass@hostname:port/#room_alias", |
| 294 |
{ |
| 295 |
# Invalid Port specified (was a string) |
| 296 |
"instance": AppriseImproperlyConfigured, |
| 297 |
}, |
| 298 |
), |
| 299 |
( |
| 300 |
"matrixs://user:pass@hostname:0/#room_alias", |
| 301 |
{ |
| 302 |
# Invalid Port specified (was a string) |
| 303 |
"instance": AppriseImproperlyConfigured, |
| 304 |
}, |
| 305 |
), |
| 306 |
( |
| 307 |
"matrixs://user:pass@hostname:65536/#room_alias", |
| 308 |
{ |
| 309 |
# Invalid Port specified (was a string) |
| 310 |
"instance": AppriseImproperlyConfigured, |
| 311 |
}, |
| 312 |
), |
| 313 |
# More general testing... |
| 314 |
( |
| 315 |
"matrixs://user@{}?mode=t2bot&format=markdown&image=True".format( |
| 316 |
"a" * 64 |
| 317 |
), |
| 318 |
{ |
| 319 |
# user and token specified; image set to True |
| 320 |
"instance": NotifyMatrix |
| 321 |
}, |
| 322 |
), |
| 323 |
( |
| 324 |
"matrix://user@{}?mode=t2bot&format=html&image=False".format("z" * 64), |
| 325 |
{ |
| 326 |
# user and token specified; image set to True |
| 327 |
"instance": NotifyMatrix |
| 328 |
}, |
| 329 |
), |
| 330 |
# This will default to t2bot because no targets were specified and no |
| 331 |
# password |
| 332 |
( |
| 333 |
"matrixs://{}".format("c" * 64), |
| 334 |
{ |
| 335 |
"instance": NotifyMatrix, |
| 336 |
# Throws a series of i/o exceptions with this flag |
| 337 |
# is set and tests that we gracefully handle them |
| 338 |
"test_requests_exceptions": True, |
| 339 |
}, |
| 340 |
), |
| 341 |
# Test Native URL |
| 342 |
( |
| 343 |
"https://webhooks.t2bot.io/api/v1/matrix/hook/{}/".format("d" * 64), |
| 344 |
{ |
| 345 |
# user and token specified; image set to True |
| 346 |
"instance": NotifyMatrix, |
| 347 |
}, |
| 348 |
), |
| 349 |
( |
| 350 |
"matrix://user:token@localhost?mode=On", |
| 351 |
{ |
| 352 |
# invalid webhook specified (unexpected boolean) |
| 353 |
"instance": AppriseImproperlyConfigured, |
| 354 |
}, |
| 355 |
), |
| 356 |
( |
| 357 |
"matrix://token@localhost/?mode=Matrix", |
| 358 |
{ |
| 359 |
"instance": NotifyMatrix, |
| 360 |
"response": False, |
| 361 |
"requests_response_code": requests.codes.internal_server_error, |
| 362 |
}, |
| 363 |
), |
| 364 |
( |
| 365 |
"matrix://user:token@localhost/mode=matrix", |
| 366 |
{ |
| 367 |
"instance": NotifyMatrix, |
| 368 |
# throw a bizarre code forcing us to fail to look it up |
| 369 |
"response": False, |
| 370 |
"requests_response_code": 999, |
| 371 |
}, |
| 372 |
), |
| 373 |
( |
| 374 |
"matrix://token@localhost:8080/?mode=slack", |
| 375 |
{ |
| 376 |
"instance": NotifyMatrix, |
| 377 |
# Throws a series of i/o exceptions with this flag |
| 378 |
# is set and tests that we gracefully handle them |
| 379 |
"test_requests_exceptions": True, |
| 380 |
}, |
| 381 |
), |
| 382 |
( |
| 383 |
"matrix://{}/?mode=t2bot".format("b" * 64), |
| 384 |
{ |
| 385 |
"instance": NotifyMatrix, |
| 386 |
# Throws a series of i/o exceptions with this flag |
| 387 |
# is set and tests that we gracefully handle them |
| 388 |
"test_requests_exceptions": True, |
| 389 |
}, |
| 390 |
), |
| 391 |
) |
| 392 |
|
| 393 |
|
| 394 |
def test_plugin_matrix_urls(): |
| 395 |
"""NotifyMatrix() Apprise URLs.""" |
| 396 |
|
| 397 |
# Run our general tests |
| 398 |
AppriseURLTester(tests=apprise_url_tests).run_all() |
| 399 |
|
| 400 |
|
| 401 |
@mock.patch("requests.put") |
| 402 |
@mock.patch("requests.get") |
| 403 |
@mock.patch("requests.post") |
| 404 |
def test_plugin_matrix_general(mock_post, mock_get, mock_put): |
| 405 |
"""NotifyMatrix() General Tests.""" |
| 406 |
|
| 407 |
response_obj = { |
| 408 |
"room_id": "!abc123:localhost", |
| 409 |
"room_alias": "#abc123:localhost", |
| 410 |
"joined_rooms": ["!abc123:localhost", "!def456:localhost"], |
| 411 |
"access_token": "abcd1234", |
| 412 |
"home_server": "localhost", |
| 413 |
} |
| 414 |
request = _Response() |
| 415 |
request.content = dumps(response_obj) |
| 416 |
request.status_code = requests.codes.ok |
| 417 |
|
| 418 |
# Prepare Mock |
| 419 |
mock_get.return_value = request |
| 420 |
mock_post.return_value = request |
| 421 |
mock_put.return_value = request |
| 422 |
|
| 423 |
# Variation Initializations |
| 424 |
obj = NotifyMatrix(host="host", targets="#abcd") |
| 425 |
assert isinstance(obj, NotifyMatrix) |
| 426 |
assert isinstance(obj.url(), str) |
| 427 |
# Registration successful |
| 428 |
assert obj.send(body="test") is True |
| 429 |
del obj |
| 430 |
|
| 431 |
obj = NotifyMatrix(host="host", user="user", targets="#abcd") |
| 432 |
assert isinstance(obj, NotifyMatrix) |
| 433 |
assert isinstance(obj.url(), str) |
| 434 |
# Registration successful |
| 435 |
assert obj.send(body="test") is True |
| 436 |
del obj |
| 437 |
|
| 438 |
obj = NotifyMatrix(host="host", password="passwd", targets="#abcd") |
| 439 |
assert isinstance(obj, NotifyMatrix) |
| 440 |
assert isinstance(obj.url(), str) |
| 441 |
# A username gets automatically generated in these cases |
| 442 |
assert obj.send(body="test") is True |
| 443 |
del obj |
| 444 |
|
| 445 |
obj = NotifyMatrix( |
| 446 |
host="host", user="user", password="passwd", targets="#abcd" |
| 447 |
) |
| 448 |
assert isinstance(obj.url(), str) |
| 449 |
assert isinstance(obj, NotifyMatrix) |
| 450 |
# Registration Successful |
| 451 |
assert obj.send(body="test") is True |
| 452 |
del obj |
| 453 |
|
| 454 |
# Test sending other format types |
| 455 |
kwargs = NotifyMatrix.parse_url( |
| 456 |
"matrix://user:passwd@hostname/#abcd?format=html" |
| 457 |
) |
| 458 |
obj = NotifyMatrix(**kwargs) |
| 459 |
assert isinstance(obj.url(), str) |
| 460 |
assert isinstance(obj, NotifyMatrix) |
| 461 |
assert obj.send(body="test") is True |
| 462 |
assert obj.send(title="title", body="test") is True |
| 463 |
del obj |
| 464 |
|
| 465 |
kwargs = NotifyMatrix.parse_url( |
| 466 |
"matrix://user:passwd@hostname/#abcd/#abcd:localhost?format=markdown" |
| 467 |
) |
| 468 |
obj = NotifyMatrix(**kwargs) |
| 469 |
assert isinstance(obj.url(), str) |
| 470 |
assert isinstance(obj, NotifyMatrix) |
| 471 |
assert obj.send(body="test") is True |
| 472 |
assert obj.send(title="title", body="test") is True |
| 473 |
del obj |
| 474 |
|
| 475 |
kwargs = NotifyMatrix.parse_url( |
| 476 |
"matrix://user:passwd@hostname/#abcd/!abcd:localhost?format=text" |
| 477 |
) |
| 478 |
obj = NotifyMatrix(**kwargs) |
| 479 |
assert isinstance(obj.url(), str) |
| 480 |
assert isinstance(obj, NotifyMatrix) is True |
| 481 |
assert obj.send(body="test") is True |
| 482 |
assert obj.send(title="title", body="test") is True |
| 483 |
del obj |
| 484 |
|
| 485 |
# Test notice type notifications |
| 486 |
kwargs = NotifyMatrix.parse_url( |
| 487 |
"matrix://user:passwd@hostname/#abcd?msgtype=notice" |
| 488 |
) |
| 489 |
obj = NotifyMatrix(**kwargs) |
| 490 |
assert isinstance(obj.url(), str) is True |
| 491 |
assert isinstance(obj, NotifyMatrix) is True |
| 492 |
assert obj.send(body="test") is True |
| 493 |
assert obj.send(title="title", body="test") is True |
| 494 |
|
| 495 |
with pytest.raises(AppriseImproperlyConfigured): |
| 496 |
# invalid message type specified |
| 497 |
kwargs = NotifyMatrix.parse_url( |
| 498 |
"matrix://user:passwd@hostname/#abcd?msgtype=invalid" |
| 499 |
) |
| 500 |
NotifyMatrix(**kwargs) |
| 501 |
|
| 502 |
# Force a failed login |
| 503 |
ro = response_obj.copy() |
| 504 |
del ro["access_token"] |
| 505 |
request.content = dumps(ro) |
| 506 |
request.status_code = 404 |
| 507 |
|
| 508 |
# Fails because we couldn't register because of 404 errors |
| 509 |
assert obj.send(body="test") is False |
| 510 |
del obj |
| 511 |
|
| 512 |
obj = NotifyMatrix(host="host", user="test", targets="#abcd") |
| 513 |
assert isinstance(obj, NotifyMatrix) is True |
| 514 |
# Fails because we still couldn't register |
| 515 |
assert obj.send(user="test", password="passwd", body="test") is False |
| 516 |
del obj |
| 517 |
|
| 518 |
obj = NotifyMatrix( |
| 519 |
host="host", user="test", password="passwd", targets="#abcd" |
| 520 |
) |
| 521 |
assert isinstance(obj, NotifyMatrix) is True |
| 522 |
# Fails because we still couldn't register |
| 523 |
assert obj.send(body="test") is False |
| 524 |
del obj |
| 525 |
|
| 526 |
obj = NotifyMatrix(host="host", password="passwd", targets="#abcd") |
| 527 |
# Fails because we still couldn't register |
| 528 |
assert isinstance(obj, NotifyMatrix) is True |
| 529 |
assert obj.send(body="test") is False |
| 530 |
|
| 531 |
# Force a empty joined list response |
| 532 |
ro = response_obj.copy() |
| 533 |
ro["joined_rooms"] = [] |
| 534 |
request.content = dumps(ro) |
| 535 |
assert obj.send(user="test", password="passwd", body="test") is False |
| 536 |
|
| 537 |
# Fall back to original template |
| 538 |
request.content = dumps(response_obj) |
| 539 |
request.status_code = requests.codes.ok |
| 540 |
|
| 541 |
# update our response object so logins now succeed |
| 542 |
response_obj["user_id"] = "@apprise:localhost" |
| 543 |
|
| 544 |
# Login was successful but not get a room_id |
| 545 |
ro = response_obj.copy() |
| 546 |
del ro["room_id"] |
| 547 |
request.content = dumps(ro) |
| 548 |
assert obj.send(user="test", password="passwd", body="test") is False |
| 549 |
|
| 550 |
# Fall back to original template |
| 551 |
request.content = dumps(response_obj) |
| 552 |
request.status_code = requests.codes.ok |
| 553 |
del obj |
| 554 |
|
| 555 |
obj = NotifyMatrix(host="host", targets=None) |
| 556 |
assert isinstance(obj, NotifyMatrix) is True |
| 557 |
|
| 558 |
# Force a empty joined list response |
| 559 |
ro = response_obj.copy() |
| 560 |
ro["joined_rooms"] = [] |
| 561 |
request.content = dumps(ro) |
| 562 |
assert obj.send(user="test", password="passwd", body="test") is False |
| 563 |
|
| 564 |
# Fall back to original template |
| 565 |
request.content = dumps(response_obj) |
| 566 |
request.status_code = requests.codes.ok |
| 567 |
|
| 568 |
# our room list is empty so we'll have retrieved the joined_list |
| 569 |
# as our backup |
| 570 |
assert obj.send(user="test", password="passwd", body="test") is True |
| 571 |
del obj |
| 572 |
|
| 573 |
|
| 574 |
@mock.patch("requests.put") |
| 575 |
@mock.patch("requests.get") |
| 576 |
@mock.patch("requests.post") |
| 577 |
def test_plugin_matrix_fetch(mock_post, mock_get, mock_put): |
| 578 |
"""NotifyMatrix() Server Fetch/API Tests.""" |
| 579 |
|
| 580 |
response_obj = { |
| 581 |
"room_id": "!abc123:localhost", |
| 582 |
"room_alias": "#abc123:localhost", |
| 583 |
"joined_rooms": ["!abc123:localhost", "!def456:localhost"], |
| 584 |
# Login details |
| 585 |
"access_token": "abcd1234", |
| 586 |
"user_id": "@apprise:localhost", |
| 587 |
"home_server": "localhost", |
| 588 |
} |
| 589 |
|
| 590 |
def fetch_failed(url, *args, **kwargs): |
| 591 |
|
| 592 |
# Default configuration |
| 593 |
request = _Response() |
| 594 |
request.status_code = requests.codes.ok |
| 595 |
request.content = dumps(response_obj) |
| 596 |
|
| 597 |
if url.find("/rooms/") > -1: |
| 598 |
# over-ride on room query |
| 599 |
request.status_code = 403 |
| 600 |
request.content = dumps( |
| 601 |
{ |
| 602 |
"errcode": "M_UNKNOWN", |
| 603 |
"error": "Internal server error", |
| 604 |
} |
| 605 |
) |
| 606 |
|
| 607 |
return request |
| 608 |
|
| 609 |
mock_put.side_effect = fetch_failed |
| 610 |
mock_get.side_effect = fetch_failed |
| 611 |
mock_post.side_effect = fetch_failed |
| 612 |
|
| 613 |
obj = NotifyMatrix( |
| 614 |
host="host", user="user", password="passwd", include_image=True |
| 615 |
) |
| 616 |
assert isinstance(obj, NotifyMatrix) is True |
| 617 |
# We would hve failed to send our image notification |
| 618 |
assert obj.send(user="test", password="passwd", body="test") is False |
| 619 |
del obj |
| 620 |
|
| 621 |
# Do the same query with no images to fetch |
| 622 |
asset = AppriseAsset(image_path_mask=False, image_url_mask=False) |
| 623 |
obj = NotifyMatrix( |
| 624 |
host="host", user="user", password="passwd", asset=asset |
| 625 |
) |
| 626 |
assert isinstance(obj, NotifyMatrix) is True |
| 627 |
# We would hve failed to send our notification |
| 628 |
assert obj.send(user="test", password="passwd", body="test") is False |
| 629 |
del obj |
| 630 |
|
| 631 |
response_obj = { |
| 632 |
# Registration |
| 633 |
"access_token": "abcd1234", |
| 634 |
"user_id": "@apprise:localhost", |
| 635 |
"home_server": "localhost", |
| 636 |
# For room joining |
| 637 |
"room_id": "!abc123:localhost", |
| 638 |
} |
| 639 |
|
| 640 |
# Default configuration |
| 641 |
mock_get.side_effect = None |
| 642 |
mock_post.side_effect = None |
| 643 |
mock_put.side_effect = None |
| 644 |
|
| 645 |
request = _Response() |
| 646 |
request.status_code = requests.codes.ok |
| 647 |
request.content = dumps(response_obj) |
| 648 |
mock_post.return_value = request |
| 649 |
mock_get.return_value = request |
| 650 |
mock_put.return_value = request |
| 651 |
|
| 652 |
obj = NotifyMatrix(host="host", include_image=True) |
| 653 |
assert isinstance(obj, NotifyMatrix) is True |
| 654 |
assert obj.access_token is None |
| 655 |
assert obj._register() is True |
| 656 |
assert obj.access_token is not None |
| 657 |
|
| 658 |
# Cause retries |
| 659 |
request.status_code = 429 |
| 660 |
request.content = dumps( |
| 661 |
{ |
| 662 |
"retry_after_ms": 1, |
| 663 |
} |
| 664 |
) |
| 665 |
|
| 666 |
postokay, _response, _ = obj._fetch("/retry/apprise/unit/test") |
| 667 |
assert postokay is False |
| 668 |
|
| 669 |
request.content = dumps( |
| 670 |
{ |
| 671 |
"error": { |
| 672 |
"retry_after_ms": 1, |
| 673 |
} |
| 674 |
} |
| 675 |
) |
| 676 |
postokay, _response, _ = obj._fetch("/retry/apprise/unit/test") |
| 677 |
assert postokay is False |
| 678 |
|
| 679 |
request.content = dumps({"error": {}}) |
| 680 |
postokay, _response, _ = obj._fetch("/retry/apprise/unit/test") |
| 681 |
assert postokay is False |
| 682 |
|
| 683 |
# A caller with its own tight time budget can cap how long a 429's |
| 684 |
# own server-requested wait is allowed to throttle for. |
| 685 |
request.content = dumps({"retry_after_ms": 999999}) |
| 686 |
with mock.patch.object(obj, "throttle") as throttle: |
| 687 |
postokay, _response, _ = obj._fetch( |
| 688 |
"/retry/apprise/unit/test", max_retry_wait=1 |
| 689 |
) |
| 690 |
assert postokay is False |
| 691 |
# The second throttle uses the remaining shared 429 budget. |
| 692 |
second_call_wait = throttle.call_args_list[1].kwargs["wait"] |
| 693 |
assert second_call_wait == pytest.approx(1.0, abs=0.1) |
| 694 |
|
| 695 |
# Restore success so object cleanup does not honor the mocked long retry. |
| 696 |
request.status_code = requests.codes.ok |
| 697 |
request.content = dumps(response_obj) |
| 698 |
del obj |
| 699 |
|
| 700 |
|
| 701 |
@mock.patch("requests.put") |
| 702 |
@mock.patch("requests.get") |
| 703 |
@mock.patch("requests.post") |
| 704 |
def test_plugin_matrix_shared_retry_budget(mock_post, mock_get, mock_put): |
| 705 |
"""Every 429 response draws from one shared retry-wait budget.""" |
| 706 |
request = _Response() |
| 707 |
request.status_code = 429 |
| 708 |
request.content = dumps({"retry_after_ms": 999999}) |
| 709 |
mock_post.return_value = request |
| 710 |
|
| 711 |
obj = NotifyMatrix(host="host", user="user", password="passwd") |
| 712 |
obj.access_token = "token" |
| 713 |
|
| 714 |
waits = [] |
| 715 |
|
| 716 |
def fake_throttle(wait=None): |
| 717 |
if wait is not None: |
| 718 |
waits.append(wait) |
| 719 |
|
| 720 |
with ( |
| 721 |
mock.patch.object(obj, "throttle", side_effect=fake_throttle), |
| 722 |
mock.patch( |
| 723 |
"apprise.plugins.matrix.base.monotonic", |
| 724 |
# retry_deadline anchor, then each 429 draws a remaining-wait |
| 725 |
# check before sleeping and a deadline recheck right after. |
| 726 |
side_effect=[0, 0.5, 0.6, 1.8, 1.9], |
| 727 |
), |
| 728 |
): |
| 729 |
postokay, _response, _ = obj._fetch( |
| 730 |
"/retry/apprise/unit/test", max_retry_wait=2 |
| 731 |
) |
| 732 |
assert postokay is False |
| 733 |
# The two waits use the remaining portions of the same two-second budget. |
| 734 |
assert waits[0] == pytest.approx(1.5) |
| 735 |
assert waits[1] == pytest.approx(0.2) |
| 736 |
|
| 737 |
# Restore success so object cleanup does not honor the mocked long retry. |
| 738 |
request.status_code = requests.codes.ok |
| 739 |
request.content = dumps( |
| 740 |
{ |
| 741 |
"access_token": "abcd1234", |
| 742 |
"user_id": "@apprise:localhost", |
| 743 |
"home_server": "localhost", |
| 744 |
} |
| 745 |
) |
| 746 |
del obj |
| 747 |
|
| 748 |
|
| 749 |
@mock.patch("requests.put") |
| 750 |
@mock.patch("requests.get") |
| 751 |
@mock.patch("requests.post") |
| 752 |
def test_plugin_matrix_exhausted_retry_budget(mock_post, mock_get, mock_put): |
| 753 |
"""An exhausted retry-wait budget ends the attempt without a new request. |
| 754 |
|
| 755 |
Once no time remains, a 429 must not be followed by another sleep and |
| 756 |
another request; it must give up immediately instead. |
| 757 |
""" |
| 758 |
request = _Response() |
| 759 |
request.status_code = 429 |
| 760 |
request.content = dumps({"retry_after_ms": 999999}) |
| 761 |
mock_post.return_value = request |
| 762 |
|
| 763 |
obj = NotifyMatrix(host="host", user="user", password="passwd") |
| 764 |
obj.access_token = "token" |
| 765 |
|
| 766 |
with ( |
| 767 |
mock.patch.object(obj, "throttle") as throttle, |
| 768 |
mock.patch( |
| 769 |
"apprise.plugins.matrix.base.monotonic", |
| 770 |
# retry_deadline anchor, then the very first remaining-wait |
| 771 |
# check already finds the budget spent. |
| 772 |
side_effect=[0, 2.0], |
| 773 |
), |
| 774 |
): |
| 775 |
postokay, _response, _ = obj._fetch( |
| 776 |
"/retry/apprise/unit/test", max_retry_wait=2 |
| 777 |
) |
| 778 |
|
| 779 |
assert postokay is False |
| 780 |
# throttle() is always called once before the initial request; giving |
| 781 |
# up on the exhausted budget must not add a second, 429-driven wait. |
| 782 |
throttle.assert_called_once_with() |
| 783 |
assert mock_post.call_count == 1 |
| 784 |
|
| 785 |
# Restore success so object cleanup does not honor the mocked long retry. |
| 786 |
request.status_code = requests.codes.ok |
| 787 |
request.content = dumps( |
| 788 |
{ |
| 789 |
"access_token": "abcd1234", |
| 790 |
"user_id": "@apprise:localhost", |
| 791 |
"home_server": "localhost", |
| 792 |
} |
| 793 |
) |
| 794 |
del obj |
| 795 |
|
| 796 |
|
| 797 |
@mock.patch("requests.put") |
| 798 |
@mock.patch("requests.get") |
| 799 |
@mock.patch("requests.post") |
| 800 |
def test_plugin_matrix_retry_sleep_exhausts_budget( |
| 801 |
mock_post, mock_get, mock_put |
| 802 |
): |
| 803 |
"""A budget consumed by the sleep itself also stops the retry loop. |
| 804 |
|
| 805 |
The deadline is checked before sleeping and again right after -- a |
| 806 |
wait that lands exactly on (or past) the deadline must not be |
| 807 |
followed by one more request. |
| 808 |
""" |
| 809 |
request = _Response() |
| 810 |
request.status_code = 429 |
| 811 |
request.content = dumps({"retry_after_ms": 999999}) |
| 812 |
mock_post.return_value = request |
| 813 |
|
| 814 |
obj = NotifyMatrix(host="host", user="user", password="passwd") |
| 815 |
obj.access_token = "token" |
| 816 |
|
| 817 |
with ( |
| 818 |
mock.patch.object(obj, "throttle") as throttle, |
| 819 |
mock.patch( |
| 820 |
"apprise.plugins.matrix.base.monotonic", |
| 821 |
# retry_deadline anchor, a remaining-wait check that is still |
| 822 |
# positive (so the wait proceeds), then the post-sleep |
| 823 |
# recheck lands exactly on the deadline. |
| 824 |
side_effect=[0, 0.5, 1.0], |
| 825 |
), |
| 826 |
): |
| 827 |
postokay, _response, _ = obj._fetch( |
| 828 |
"/retry/apprise/unit/test", max_retry_wait=1 |
| 829 |
) |
| 830 |
|
| 831 |
assert postokay is False |
| 832 |
# The 429 wait happens once; no second request follows it. |
| 833 |
assert throttle.call_args_list[-1] == mock.call(wait=0.5) |
| 834 |
assert mock_post.call_count == 1 |
| 835 |
|
| 836 |
# Restore success so object cleanup does not honor the mocked long retry. |
| 837 |
request.status_code = requests.codes.ok |
| 838 |
request.content = dumps( |
| 839 |
{ |
| 840 |
"access_token": "abcd1234", |
| 841 |
"user_id": "@apprise:localhost", |
| 842 |
"home_server": "localhost", |
| 843 |
} |
| 844 |
) |
| 845 |
del obj |
| 846 |
|
| 847 |
|
| 848 |
@mock.patch("requests.put") |
| 849 |
@mock.patch("requests.get") |
| 850 |
@mock.patch("requests.post") |
| 851 |
def test_plugin_matrix_fetch_response_limit(mock_post, mock_get, mock_put): |
| 852 |
"""Discard and close a response that exceeds the caller's limit.""" |
| 853 |
request = mock.Mock() |
| 854 |
request.status_code = requests.codes.ok |
| 855 |
request.iter_content.return_value = iter([b"x" * 1000, b"x" * 1001]) |
| 856 |
mock_post.return_value = request |
| 857 |
|
| 858 |
obj = NotifyMatrix(host="host", user="user", password="passwd") |
| 859 |
obj.access_token = "token" |
| 860 |
|
| 861 |
postokay, response, status_code = obj._fetch( |
| 862 |
"/some/path", max_response_bytes=2000 |
| 863 |
) |
| 864 |
|
| 865 |
assert postokay is False |
| 866 |
assert response == {} |
| 867 |
assert status_code == requests.codes.ok |
| 868 |
request.close.assert_called_once() |
| 869 |
|
| 870 |
del obj |
| 871 |
|
| 872 |
|
| 873 |
@mock.patch("requests.put") |
| 874 |
@mock.patch("requests.get") |
| 875 |
@mock.patch("requests.post") |
| 876 |
def test_plugin_matrix_fetch_response_within_limit( |
| 877 |
mock_post, mock_get, mock_put |
| 878 |
): |
| 879 |
"""Parse a bounded response while ignoring empty stream chunks.""" |
| 880 |
request = mock.Mock() |
| 881 |
request.status_code = requests.codes.ok |
| 882 |
request.iter_content.return_value = iter( |
| 883 |
[b"", dumps({"ok": True}).encode()] |
| 884 |
) |
| 885 |
mock_post.return_value = request |
| 886 |
|
| 887 |
obj = NotifyMatrix(host="host", user="user", password="passwd") |
| 888 |
obj.access_token = "token" |
| 889 |
|
| 890 |
postokay, response, _status_code = obj._fetch( |
| 891 |
"/some/path", max_response_bytes=2000 |
| 892 |
) |
| 893 |
|
| 894 |
assert postokay is True |
| 895 |
assert response == {"ok": True} |
| 896 |
# The stream is closed either way, not just on the oversized path. |
| 897 |
request.close.assert_called_once() |
| 898 |
|
| 899 |
del obj |
| 900 |
|
| 901 |
|
| 902 |
@mock.patch("requests.put") |
| 903 |
@mock.patch("requests.get") |
| 904 |
@mock.patch("requests.post") |
| 905 |
def test_plugin_matrix_fetch_stream_error(mock_post, mock_get, mock_put): |
| 906 |
"""Handle streamed download errors and close the response.""" |
| 907 |
request = mock.Mock() |
| 908 |
request.status_code = requests.codes.ok |
| 909 |
|
| 910 |
def broken_iter_content(chunk_size=None): |
| 911 |
yield b"partial" |
| 912 |
raise requests.exceptions.ChunkedEncodingError("broken transfer") |
| 913 |
|
| 914 |
request.iter_content.side_effect = broken_iter_content |
| 915 |
mock_post.return_value = request |
| 916 |
|
| 917 |
obj = NotifyMatrix(host="host", user="user", password="passwd") |
| 918 |
obj.access_token = "token" |
| 919 |
|
| 920 |
postokay, response, status_code = obj._fetch( |
| 921 |
"/some/path", max_response_bytes=2000 |
| 922 |
) |
| 923 |
|
| 924 |
assert postokay is False |
| 925 |
assert response == {} |
| 926 |
assert status_code == requests.codes.ok |
| 927 |
request.close.assert_called_once() |
| 928 |
|
| 929 |
del obj |
| 930 |
|
| 931 |
|
| 932 |
@mock.patch("requests.put") |
| 933 |
@mock.patch("requests.get") |
| 934 |
@mock.patch("requests.post") |
| 935 |
def test_plugin_matrix_auth(mock_post, mock_get, mock_put): |
| 936 |
"""NotifyMatrix() Server Authentication.""" |
| 937 |
|
| 938 |
response_obj = { |
| 939 |
# Registration |
| 940 |
"access_token": "abcd1234", |
| 941 |
"user_id": "@apprise:localhost", |
| 942 |
"home_server": "localhost", |
| 943 |
} |
| 944 |
|
| 945 |
# Default configuration |
| 946 |
request = _Response() |
| 947 |
request.status_code = requests.codes.ok |
| 948 |
request.content = dumps(response_obj) |
| 949 |
mock_post.return_value = request |
| 950 |
mock_get.return_value = request |
| 951 |
mock_put.return_value = request |
| 952 |
|
| 953 |
obj = NotifyMatrix(host="localhost") |
| 954 |
assert isinstance(obj, NotifyMatrix) is True |
| 955 |
assert obj.access_token is None |
| 956 |
# logging out without an access_token is silently a success |
| 957 |
assert obj._logout() is True |
| 958 |
assert obj.access_token is None |
| 959 |
|
| 960 |
assert obj._register() is True |
| 961 |
assert obj.access_token is not None |
| 962 |
|
| 963 |
# Logging in is silently treated as a success because we |
| 964 |
# already had success registering |
| 965 |
assert obj._login() is True |
| 966 |
assert obj.access_token is not None |
| 967 |
|
| 968 |
# However if we log out |
| 969 |
assert obj._logout() is True |
| 970 |
assert obj.access_token is None |
| 971 |
|
| 972 |
# And set ourselves up for failure |
| 973 |
request.status_code = 403 |
| 974 |
assert obj._login() is False |
| 975 |
assert obj.access_token is None |
| 976 |
|
| 977 |
# Reset our token |
| 978 |
obj.access_token = None |
| 979 |
|
| 980 |
# Adjust our response to be invalid - missing access_token in response |
| 981 |
request.status_code = requests.codes.ok |
| 982 |
ro = response_obj.copy() |
| 983 |
del ro["access_token"] |
| 984 |
request.content = dumps(ro) |
| 985 |
# Our registration will fail now |
| 986 |
assert obj._register() is False |
| 987 |
assert obj.access_token is None |
| 988 |
del obj |
| 989 |
|
| 990 |
# So will login |
| 991 |
obj = NotifyMatrix(host="host", user="user", password="password") |
| 992 |
assert isinstance(obj, NotifyMatrix) is True |
| 993 |
assert obj._login() is False |
| 994 |
assert obj.access_token is None |
| 995 |
|
| 996 |
# Adjust our response to be invalid - invalid json response |
| 997 |
request.content = "{" |
| 998 |
# Our registration will fail now |
| 999 |
assert obj._register() is False |
| 1000 |
assert obj.access_token is None |
| 1001 |
|
| 1002 |
request.status_code = requests.codes.ok |
| 1003 |
request.content = dumps(response_obj) |
| 1004 |
assert obj._register() is True |
| 1005 |
assert obj.access_token is not None |
| 1006 |
# Test logoff when getting a 403 error |
| 1007 |
request.status_code = 403 |
| 1008 |
assert obj._logout() is False |
| 1009 |
assert obj.access_token is not None |
| 1010 |
|
| 1011 |
request.status_code = requests.codes.ok |
| 1012 |
request.content = dumps(response_obj) |
| 1013 |
assert obj._register() is True |
| 1014 |
assert obj.access_token is not None |
| 1015 |
request.status_code = 403 |
| 1016 |
request.content = dumps( |
| 1017 |
{ |
| 1018 |
"errcode": "M_UNKNOWN_TOKEN", |
| 1019 |
"error": "Access Token unknown or expired", |
| 1020 |
} |
| 1021 |
) |
| 1022 |
# Test logoff when getting a 403 error; but if we have the right error |
| 1023 |
# code in the response, then we return a True |
| 1024 |
assert obj._logout() is True |
| 1025 |
assert obj.access_token is None |
| 1026 |
del obj |
| 1027 |
|
| 1028 |
# Modern Matrix servers omit home_server from login/register responses. |
| 1029 |
# Apprise must derive it from user_id so room-alias resolution works. |
| 1030 |
modern_resp = { |
| 1031 |
"access_token": "tok99", |
| 1032 |
"user_id": "@bot:matrix.org", |
| 1033 |
"device_id": "DEVXYZ", |
| 1034 |
# no "home_server" key -- matches real matrix.org behaviour |
| 1035 |
} |
| 1036 |
request.status_code = requests.codes.ok |
| 1037 |
request.content = dumps(modern_resp) |
| 1038 |
|
| 1039 |
# No home_server in response + no prior home_server -> derive from user_id |
| 1040 |
obj2 = NotifyMatrix(host="matrix.org", user="bot", password="pass") |
| 1041 |
assert obj2._login() is True |
| 1042 |
assert obj2.home_server == "matrix.org" |
| 1043 |
|
| 1044 |
obj3 = NotifyMatrix(host="matrix.org", user="bot", password="pass") |
| 1045 |
assert obj3._register() is True |
| 1046 |
assert obj3.home_server == "matrix.org" |
| 1047 |
|
| 1048 |
# No home_server in response + home_server already set -> not overwritten |
| 1049 |
obj4 = NotifyMatrix(host="matrix.org", user="bot", password="pass") |
| 1050 |
obj4.home_server = "already.set" |
| 1051 |
assert obj4._login() is True |
| 1052 |
assert obj4.home_server == "already.set" |
| 1053 |
|
| 1054 |
obj5 = NotifyMatrix(host="matrix.org", user="bot", password="pass") |
| 1055 |
obj5.home_server = "already.set" |
| 1056 |
assert obj5._register() is True |
| 1057 |
assert obj5.home_server == "already.set" |
| 1058 |
|
| 1059 |
# No home_server in response + user_id has no colon -> |
| 1060 |
# home_server stays None |
| 1061 |
no_colon_resp = { |
| 1062 |
"access_token": "tok88", |
| 1063 |
"user_id": "@nocoilon", |
| 1064 |
"device_id": "DEV88", |
| 1065 |
} |
| 1066 |
request.content = dumps(no_colon_resp) |
| 1067 |
obj6 = NotifyMatrix(host="matrix.org", user="bot", password="pass") |
| 1068 |
assert obj6._login() is True |
| 1069 |
assert obj6.home_server is None |
| 1070 |
|
| 1071 |
obj7 = NotifyMatrix(host="matrix.org", user="bot", password="pass") |
| 1072 |
assert obj7._register() is True |
| 1073 |
assert obj7.home_server is None |
| 1074 |
del obj2, obj3, obj4, obj5, obj6, obj7 |
| 1075 |
|
| 1076 |
|
| 1077 |
@mock.patch("requests.put") |
| 1078 |
@mock.patch("requests.get") |
| 1079 |
@mock.patch("requests.post") |
| 1080 |
def test_plugin_matrix_rooms(mock_post, mock_get, mock_put): |
| 1081 |
"""NotifyMatrix() Room Testing.""" |
| 1082 |
|
| 1083 |
response_obj = { |
| 1084 |
# Registration |
| 1085 |
"access_token": "abcd1234", |
| 1086 |
"user_id": "@apprise:localhost", |
| 1087 |
"home_server": "localhost", |
| 1088 |
# For joined_room response |
| 1089 |
"joined_rooms": ["!abc123", "!def456:localhost"], |
| 1090 |
# For room joining |
| 1091 |
"room_id": "!abc123", |
| 1092 |
} |
| 1093 |
|
| 1094 |
# Default configuration |
| 1095 |
request = _Response() |
| 1096 |
request.status_code = requests.codes.ok |
| 1097 |
request.content = dumps(response_obj) |
| 1098 |
mock_post.return_value = request |
| 1099 |
mock_get.return_value = request |
| 1100 |
mock_put.return_value = request |
| 1101 |
|
| 1102 |
obj = NotifyMatrix(host="host") |
| 1103 |
assert isinstance(obj, NotifyMatrix) is True |
| 1104 |
assert obj.access_token is None |
| 1105 |
|
| 1106 |
# Can't get room listing if we're not connnected |
| 1107 |
assert obj._room_join("#abc123") is None |
| 1108 |
|
| 1109 |
assert obj._register() is True |
| 1110 |
assert obj.access_token is not None |
| 1111 |
|
| 1112 |
assert obj._room_join("!abc123") == response_obj["room_id"] |
| 1113 |
# Use cache to get same results |
| 1114 |
assert obj.store.get("!abc123") is None |
| 1115 |
# However this is how the cache entry gets stored |
| 1116 |
assert obj.store.get("!abc123:localhost") is not None |
| 1117 |
assert obj.store.get("!abc123:localhost")["id"] == response_obj["room_id"] |
| 1118 |
|
| 1119 |
# When hsreq=yes, legacy behaviour is restored and a homeserver is |
| 1120 |
# automatically appended to room IDs that omit it. |
| 1121 |
obj.store.clear() |
| 1122 |
obj.hsreq = True |
| 1123 |
mock_post.reset_mock() |
| 1124 |
assert obj._room_join("!abc123") == response_obj["room_id"] |
| 1125 |
assert mock_post.call_count == 1 |
| 1126 |
assert ( |
| 1127 |
mock_post.call_args_list[0][0][0] |
| 1128 |
== "http://host/_matrix/client/v3/join/%21abc123%3Alocalhost" |
| 1129 |
) |
| 1130 |
|
| 1131 |
# When hsreq=no, we honour the raw !room identifier exactly as provided |
| 1132 |
# and do not suffix it with :homeserver. |
| 1133 |
obj.store.clear() |
| 1134 |
obj.hsreq = False |
| 1135 |
|
| 1136 |
def _join_side_effect(url, *args, **kwargs): |
| 1137 |
r = _Response() |
| 1138 |
|
| 1139 |
# With hsreq disabled, only the raw form should be attempted: |
| 1140 |
if url.endswith("/_matrix/client/v3/join/%21abc123"): |
| 1141 |
r.status_code = requests.codes.ok |
| 1142 |
r.content = dumps(response_obj).encode("utf-8") |
| 1143 |
return r |
| 1144 |
|
| 1145 |
# Default ok for any other unexpected call |
| 1146 |
r.status_code = requests.codes.ok |
| 1147 |
r.content = dumps(response_obj).encode("utf-8") |
| 1148 |
return r |
| 1149 |
|
| 1150 |
mock_post.reset_mock() |
| 1151 |
mock_post.side_effect = _join_side_effect |
| 1152 |
assert obj._room_join("!abc123") == response_obj["room_id"] |
| 1153 |
assert mock_post.call_count == 1 |
| 1154 |
assert ( |
| 1155 |
mock_post.call_args_list[0][0][0] |
| 1156 |
== "http://host/_matrix/client/v3/join/%21abc123" |
| 1157 |
) |
| 1158 |
|
| 1159 |
mock_post.reset_mock() |
| 1160 |
assert obj._room_join("!abc123") == response_obj["room_id"] |
| 1161 |
# Cache is used |
| 1162 |
assert mock_post.call_count == 0 |
| 1163 |
|
| 1164 |
# Still using cache |
| 1165 |
assert obj._room_join("!abc123:localhost") == response_obj["room_id"] |
| 1166 |
assert mock_post.call_count == 0 |
| 1167 |
|
| 1168 |
# Toggle our settings back |
| 1169 |
obj.hsreq = True |
| 1170 |
mock_post.reset_mock() |
| 1171 |
mock_post.side_effect = _join_side_effect |
| 1172 |
assert obj._room_join("!abc123") == response_obj["room_id"] |
| 1173 |
# We still no longer need to fetch as we know the info already |
| 1174 |
assert mock_post.call_count == 0 |
| 1175 |
|
| 1176 |
# Restore defaults for remaining tests |
| 1177 |
mock_post.side_effect = None |
| 1178 |
obj.hsreq = True |
| 1179 |
|
| 1180 |
# Use cache to get same results (no additional HTTP call) |
| 1181 |
mock_post.reset_mock() |
| 1182 |
assert obj._room_join("!abc123") == response_obj["room_id"] |
| 1183 |
assert mock_post.call_count == 0 |
| 1184 |
|
| 1185 |
obj.store.clear() |
| 1186 |
assert obj._room_join("!abc123:localhost") == response_obj["room_id"] |
| 1187 |
assert obj.store.get("!abc123:localhost") is not None |
| 1188 |
assert obj.store.get("!abc123:localhost")["id"] == response_obj["room_id"] |
| 1189 |
# Use cache to get same results |
| 1190 |
assert obj._room_join("!abc123:localhost") == response_obj["room_id"] |
| 1191 |
|
| 1192 |
obj.store.clear() |
| 1193 |
assert obj._room_join("abc123") == response_obj["room_id"] |
| 1194 |
# Use cache to get same results |
| 1195 |
assert obj.store.get("#abc123:localhost") is not None |
| 1196 |
assert obj.store.get("#abc123:localhost")["id"] == response_obj["room_id"] |
| 1197 |
assert obj._room_join("abc123") == response_obj["room_id"] |
| 1198 |
|
| 1199 |
# If home_server is missing, recover it from user_id so we never try |
| 1200 |
# to join a '#room:None' alias. |
| 1201 |
obj.store.clear() |
| 1202 |
obj.home_server = None |
| 1203 |
obj.user_id = "@apprise:localhost" |
| 1204 |
mock_post.reset_mock() |
| 1205 |
assert obj._room_join("abc123") == response_obj["room_id"] |
| 1206 |
assert mock_post.call_count == 1 |
| 1207 |
assert ( |
| 1208 |
mock_post.call_args_list[0][0][0] |
| 1209 |
== "http://host/_matrix/client/v3/join/%23abc123%3Alocalhost" |
| 1210 |
) |
| 1211 |
|
| 1212 |
obj.store.clear() |
| 1213 |
assert obj._room_join("abc123:localhost") == response_obj["room_id"] |
| 1214 |
# Use cache to get same results |
| 1215 |
assert obj.store.get("#abc123:localhost") is not None |
| 1216 |
assert obj.store.get("#abc123:localhost")["id"] == response_obj["room_id"] |
| 1217 |
assert obj._room_join("abc123:localhost") == response_obj["room_id"] |
| 1218 |
|
| 1219 |
obj.store.clear() |
| 1220 |
assert obj._room_join("#abc123:localhost") == response_obj["room_id"] |
| 1221 |
# Use cache to get same results |
| 1222 |
assert obj.store.get("#abc123:localhost") is not None |
| 1223 |
assert obj.store.get("#abc123:localhost")["id"] == response_obj["room_id"] |
| 1224 |
assert obj._room_join("#abc123:localhost") == response_obj["room_id"] |
| 1225 |
|
| 1226 |
obj.store.clear() |
| 1227 |
assert obj._room_join("%") is None |
| 1228 |
assert obj._room_join(None) is None |
| 1229 |
|
| 1230 |
obj.store.clear() |
| 1231 |
obj.home_server = None |
| 1232 |
obj.user_id = "@apprise" |
| 1233 |
mock_post.reset_mock() |
| 1234 |
assert obj._room_join("abc123") is None |
| 1235 |
assert mock_post.call_count == 0 |
| 1236 |
|
| 1237 |
# 403 response; this will push for a room creation for alias based rooms |
| 1238 |
# and these will fail |
| 1239 |
request.status_code = 403 |
| 1240 |
obj.store.clear() |
| 1241 |
assert obj._room_join("!abc123") is None |
| 1242 |
obj.store.clear() |
| 1243 |
assert obj._room_join("!abc123:localhost") is None |
| 1244 |
obj.store.clear() |
| 1245 |
assert obj._room_join("abc123") is None |
| 1246 |
obj.store.clear() |
| 1247 |
assert obj._room_join("abc123:localhost") is None |
| 1248 |
obj.store.clear() |
| 1249 |
assert obj._room_join("#abc123:localhost") is None |
| 1250 |
del obj |
| 1251 |
|
| 1252 |
# Room creation |
| 1253 |
request.status_code = requests.codes.ok |
| 1254 |
obj = NotifyMatrix(host="host") |
| 1255 |
assert isinstance(obj, NotifyMatrix) is True |
| 1256 |
assert obj.access_token is None |
| 1257 |
|
| 1258 |
# Can't get room listing if we're not connnected |
| 1259 |
assert obj._room_create("#abc123") is None |
| 1260 |
|
| 1261 |
assert obj._register() is True |
| 1262 |
assert obj.access_token is not None |
| 1263 |
|
| 1264 |
# You can't add room_id's, they must be aliases |
| 1265 |
assert obj._room_create("!abc123") is None |
| 1266 |
assert obj._room_create("!abc123:localhost") is None |
| 1267 |
obj.store.clear() |
| 1268 |
assert obj._room_create("abc123") == response_obj["room_id"] |
| 1269 |
obj.store.clear() |
| 1270 |
assert obj._room_create("abc123:localhost") == response_obj["room_id"] |
| 1271 |
obj.store.clear() |
| 1272 |
assert obj._room_create("#abc123:localhost") == response_obj["room_id"] |
| 1273 |
obj.store.clear() |
| 1274 |
assert obj._room_create("%") is None |
| 1275 |
assert obj._room_create(None) is None |
| 1276 |
|
| 1277 |
# 403 response; this will push for a room creation for alias based rooms |
| 1278 |
# and these will fail |
| 1279 |
request.status_code = 403 |
| 1280 |
obj.store.clear() |
| 1281 |
assert obj._room_create("abc123") is None |
| 1282 |
obj.store.clear() |
| 1283 |
assert obj._room_create("abc123:localhost") is None |
| 1284 |
obj.store.clear() |
| 1285 |
assert obj._room_create("#abc123:localhost") is None |
| 1286 |
|
| 1287 |
request.status_code = 403 |
| 1288 |
request.content = dumps( |
| 1289 |
{ |
| 1290 |
"errcode": "M_ROOM_IN_USE", |
| 1291 |
"error": "Room alias already taken", |
| 1292 |
} |
| 1293 |
) |
| 1294 |
obj.store.clear() |
| 1295 |
# This causes us to look up a channel ID if we get a ROOM_IN_USE response |
| 1296 |
assert obj._room_create("#abc123:localhost") is None |
| 1297 |
del obj |
| 1298 |
|
| 1299 |
# Room detection |
| 1300 |
request.status_code = requests.codes.ok |
| 1301 |
request.content = dumps(response_obj) |
| 1302 |
obj = NotifyMatrix(host="localhost") |
| 1303 |
assert isinstance(obj, NotifyMatrix) is True |
| 1304 |
assert obj.access_token is None |
| 1305 |
|
| 1306 |
# No rooms if we're not connected |
| 1307 |
response = obj._joined_rooms() |
| 1308 |
assert isinstance(response, list) is True |
| 1309 |
assert len(response) == 0 |
| 1310 |
|
| 1311 |
# register our account |
| 1312 |
assert obj._register() is True |
| 1313 |
assert obj.access_token is not None |
| 1314 |
|
| 1315 |
response = obj._joined_rooms() |
| 1316 |
assert isinstance(response, list) is True |
| 1317 |
assert len(response) == len(response_obj["joined_rooms"]) |
| 1318 |
for r in response: |
| 1319 |
assert r in response_obj["joined_rooms"] |
| 1320 |
|
| 1321 |
request.status_code = 403 |
| 1322 |
response = obj._joined_rooms() |
| 1323 |
assert isinstance(response, list) is True |
| 1324 |
assert len(response) == 0 |
| 1325 |
del obj |
| 1326 |
|
| 1327 |
# Room id lookup |
| 1328 |
request.status_code = requests.codes.ok |
| 1329 |
obj = NotifyMatrix(host="localhost") |
| 1330 |
assert isinstance(obj, NotifyMatrix) is True |
| 1331 |
assert obj.access_token is None |
| 1332 |
|
| 1333 |
# Can't get room listing if we're not connnected |
| 1334 |
assert obj._room_id("#abc123") is None |
| 1335 |
|
| 1336 |
assert obj._register() is True |
| 1337 |
assert obj.access_token is not None |
| 1338 |
|
| 1339 |
# You can't add room_id's, they must be aliases |
| 1340 |
assert obj._room_id("!abc123") is None |
| 1341 |
assert obj._room_id("!abc123:localhost") is None |
| 1342 |
obj.store.clear() |
| 1343 |
assert obj._room_id("abc123") == response_obj["room_id"] |
| 1344 |
obj.store.clear() |
| 1345 |
assert obj._room_id("abc123:localhost") == response_obj["room_id"] |
| 1346 |
obj.store.clear() |
| 1347 |
assert obj._room_id("#abc123:localhost") == response_obj["room_id"] |
| 1348 |
obj.store.clear() |
| 1349 |
assert obj._room_id("%") is None |
| 1350 |
assert obj._room_id(None) is None |
| 1351 |
|
| 1352 |
# If we can't look the code up, we return None |
| 1353 |
request.status_code = 403 |
| 1354 |
obj.store.clear() |
| 1355 |
assert obj._room_id("#abc123:localhost") is None |
| 1356 |
|
| 1357 |
# Force a object removal (thus a logout call) |
| 1358 |
del obj |
| 1359 |
_force_del_cleanup() |
| 1360 |
|
| 1361 |
|
| 1362 |
def test_plugin_matrix_url_parsing(): |
| 1363 |
"""NotifyMatrix() URL Testing.""" |
| 1364 |
result = NotifyMatrix.parse_url("matrix://user:token@localhost?to=#room") |
| 1365 |
assert isinstance(result, dict) is True |
| 1366 |
assert len(result["targets"]) == 1 |
| 1367 |
assert "#room" in result["targets"] |
| 1368 |
|
| 1369 |
result = NotifyMatrix.parse_url( |
| 1370 |
"matrix://user:token@localhost?to=#room&hsreq=yes" |
| 1371 |
) |
| 1372 |
assert isinstance(result, dict) is True |
| 1373 |
assert result.get("hsreq") is True |
| 1374 |
|
| 1375 |
result = NotifyMatrix.parse_url( |
| 1376 |
"matrix://user:token@localhost?to=#room1,#room2,#room3" |
| 1377 |
) |
| 1378 |
assert isinstance(result, dict) is True |
| 1379 |
assert len(result["targets"]) == 3 |
| 1380 |
assert "#room1" in result["targets"] |
| 1381 |
assert "#room2" in result["targets"] |
| 1382 |
assert "#room3" in result["targets"] |
| 1383 |
|
| 1384 |
# Mixed-case alias with underscore should parse |
| 1385 |
result = NotifyMatrix.parse_url( |
| 1386 |
"matrix://user:token@localhost?to=#Dev_Room:localhost" |
| 1387 |
) |
| 1388 |
assert isinstance(result, dict) is True |
| 1389 |
assert len(result["targets"]) == 1 |
| 1390 |
assert "#Dev_Room:localhost" in result["targets"] |
| 1391 |
|
| 1392 |
# Mixed-case room id with underscore should be accepted by _room_join |
| 1393 |
from apprise.plugins.matrix import IS_ROOM_ID # local alias |
| 1394 |
|
| 1395 |
nm = NotifyMatrix(host="localhost") |
| 1396 |
nm.access_token = "abc" # simulate logged-in |
| 1397 |
nm.home_server = "localhost" |
| 1398 |
# this should NOT be rejected by the regex |
| 1399 |
assert IS_ROOM_ID.match("!Jm_LvU1nas_8KJPBmN9n:nginx.eu") |
| 1400 |
|
| 1401 |
|
| 1402 |
@mock.patch("requests.put") |
| 1403 |
@mock.patch("requests.get") |
| 1404 |
@mock.patch("requests.post") |
| 1405 |
def test_plugin_matrix_image_errors(mock_post, mock_get, mock_put): |
| 1406 |
"""NotifyMatrix() Image Error Handling.""" |
| 1407 |
|
| 1408 |
def mock_function_handing(url, data, **kwargs): |
| 1409 |
"""Dummy function for handling image posts (as a failure)""" |
| 1410 |
response_obj = { |
| 1411 |
"room_id": "!abc123:localhost", |
| 1412 |
"room_alias": "#abc123:localhost", |
| 1413 |
"joined_rooms": ["!abc123:localhost", "!def456:localhost"], |
| 1414 |
"access_token": "abcd1234", |
| 1415 |
"home_server": "localhost", |
| 1416 |
} |
| 1417 |
|
| 1418 |
request = _Response() |
| 1419 |
request.content = dumps(response_obj) |
| 1420 |
request.status_code = requests.codes.ok |
| 1421 |
|
| 1422 |
if "m.image" in data: |
| 1423 |
# Fail for images |
| 1424 |
request.status_code = 400 |
| 1425 |
|
| 1426 |
return request |
| 1427 |
|
| 1428 |
# Prepare Mock |
| 1429 |
mock_get.side_effect = mock_function_handing |
| 1430 |
mock_post.side_effect = mock_function_handing |
| 1431 |
mock_put.side_effect = mock_function_handing |
| 1432 |
|
| 1433 |
obj = NotifyMatrix(host="host", include_image=True, version="2") |
| 1434 |
assert isinstance(obj, NotifyMatrix) is True |
| 1435 |
assert obj.access_token is None |
| 1436 |
|
| 1437 |
# Notification was successful, however we could not post image and since |
| 1438 |
# we had post errors (of any kind) we still report a failure. |
| 1439 |
assert bool(obj.notify("test", "test")) is False |
| 1440 |
del obj |
| 1441 |
|
| 1442 |
obj = NotifyMatrix(host="host", include_image=False, version="2") |
| 1443 |
assert isinstance(obj, NotifyMatrix) is True |
| 1444 |
assert obj.access_token is None |
| 1445 |
|
| 1446 |
# We didn't post an image (which was set to fail) and therefore our |
| 1447 |
# post was okay |
| 1448 |
assert bool(obj.notify("test", "test")) is True |
| 1449 |
|
| 1450 |
# Force a object removal (thus a logout call) |
| 1451 |
del obj |
| 1452 |
_force_del_cleanup() |
| 1453 |
|
| 1454 |
def mock_function_handing(url, data, **kwargs): |
| 1455 |
"""Dummy function for handling image posts (successfully)""" |
| 1456 |
response_obj = { |
| 1457 |
"room_id": "!abc123:localhost", |
| 1458 |
"room_alias": "#abc123:localhost", |
| 1459 |
"joined_rooms": ["!abc123:localhost", "!def456:localhost"], |
| 1460 |
"access_token": "abcd1234", |
| 1461 |
"home_server": "localhost", |
| 1462 |
} |
| 1463 |
|
| 1464 |
request = _Response() |
| 1465 |
request.content = dumps(response_obj) |
| 1466 |
request.status_code = requests.codes.ok |
| 1467 |
|
| 1468 |
return request |
| 1469 |
|
| 1470 |
# Prepare Mock |
| 1471 |
mock_get.side_effect = mock_function_handing |
| 1472 |
mock_put.side_effect = mock_function_handing |
| 1473 |
mock_post.side_effect = mock_function_handing |
| 1474 |
obj = NotifyMatrix(host="host", include_image=True) |
| 1475 |
assert isinstance(obj, NotifyMatrix) is True |
| 1476 |
assert obj.access_token is None |
| 1477 |
|
| 1478 |
assert bool(obj.notify("test", "test")) is True |
| 1479 |
del obj |
| 1480 |
|
| 1481 |
obj = NotifyMatrix(host="host", include_image=False) |
| 1482 |
assert isinstance(obj, NotifyMatrix) is True |
| 1483 |
assert obj.access_token is None |
| 1484 |
|
| 1485 |
assert bool(obj.notify("test", "test")) is True |
| 1486 |
|
| 1487 |
# Force a object removal (thus a logout call) |
| 1488 |
del obj |
| 1489 |
_force_del_cleanup() |
| 1490 |
|
| 1491 |
|
| 1492 |
@mock.patch("requests.put") |
| 1493 |
@mock.patch("requests.post") |
| 1494 |
def test_plugin_matrix_attachments_api_v3(mock_post, mock_put): |
| 1495 |
"""NotifyMatrix() Attachment Checks (v3)""" |
| 1496 |
|
| 1497 |
# Prepare a good response |
| 1498 |
response = _Response() |
| 1499 |
response.status_code = requests.codes.ok |
| 1500 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 1501 |
|
| 1502 |
# Prepare a bad response |
| 1503 |
bad_response = _Response() |
| 1504 |
bad_response.status_code = requests.codes.internal_server_error |
| 1505 |
|
| 1506 |
# Prepare Mock return object |
| 1507 |
mock_post.return_value = response |
| 1508 |
mock_put.return_value = response |
| 1509 |
|
| 1510 |
# Instantiate our object |
| 1511 |
obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=3") |
| 1512 |
|
| 1513 |
# attach our content |
| 1514 |
attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")) |
| 1515 |
|
| 1516 |
assert ( |
| 1517 |
bool( |
| 1518 |
obj.notify( |
| 1519 |
body="body", |
| 1520 |
title="title", |
| 1521 |
notify_type=NotifyType.INFO, |
| 1522 |
attach=attach, |
| 1523 |
) |
| 1524 |
) |
| 1525 |
is True |
| 1526 |
) |
| 1527 |
|
| 1528 |
attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")) |
| 1529 |
|
| 1530 |
# Test our call count |
| 1531 |
assert mock_put.call_count == 2 |
| 1532 |
assert mock_post.call_count == 3 |
| 1533 |
assert ( |
| 1534 |
mock_post.call_args_list[0][0][0] |
| 1535 |
== "http://localhost/_matrix/client/v3/login" |
| 1536 |
) |
| 1537 |
assert ( |
| 1538 |
mock_post.call_args_list[1][0][0] |
| 1539 |
== "http://localhost/_matrix/client/v3/join/%23general%3Alocalhost" |
| 1540 |
) |
| 1541 |
assert ( |
| 1542 |
mock_post.call_args_list[2][0][0] |
| 1543 |
== "http://localhost/_matrix/media/v3/upload" |
| 1544 |
) |
| 1545 |
assert ( |
| 1546 |
mock_put.call_args_list[0][0][0] |
| 1547 |
== "http://localhost/_matrix/client/v3/rooms/%21abc123%3Alocalhost/" |
| 1548 |
"send/m.room.message/0" |
| 1549 |
) |
| 1550 |
assert ( |
| 1551 |
mock_put.call_args_list[1][0][0] |
| 1552 |
== "http://localhost/_matrix/client/v3/rooms/%21abc123%3Alocalhost/" |
| 1553 |
"send/m.room.message/1" |
| 1554 |
) |
| 1555 |
|
| 1556 |
# Attach a zip file type |
| 1557 |
attach = AppriseAttachment( |
| 1558 |
os.path.join(TEST_VAR_DIR, "apprise-archive.zip") |
| 1559 |
) |
| 1560 |
assert ( |
| 1561 |
bool( |
| 1562 |
obj.notify( |
| 1563 |
body="body", |
| 1564 |
title="title", |
| 1565 |
notify_type=NotifyType.INFO, |
| 1566 |
attach=attach, |
| 1567 |
) |
| 1568 |
) |
| 1569 |
is True |
| 1570 |
) |
| 1571 |
|
| 1572 |
# An invalid attachment will cause a failure |
| 1573 |
path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg") |
| 1574 |
attach = AppriseAttachment(path) |
| 1575 |
assert ( |
| 1576 |
bool( |
| 1577 |
obj.notify( |
| 1578 |
body="body", |
| 1579 |
title="title", |
| 1580 |
notify_type=NotifyType.INFO, |
| 1581 |
attach=path, |
| 1582 |
) |
| 1583 |
) |
| 1584 |
is False |
| 1585 |
) |
| 1586 |
|
| 1587 |
# update our attachment to be valid |
| 1588 |
attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")) |
| 1589 |
|
| 1590 |
mock_put.return_value = None |
| 1591 |
mock_post.return_value = None |
| 1592 |
|
| 1593 |
# Throw an exception on the first call to requests.post() |
| 1594 |
for side_effect in (requests.RequestException(), OSError(), bad_response): |
| 1595 |
# Reset our value |
| 1596 |
mock_put.reset_mock() |
| 1597 |
mock_post.reset_mock() |
| 1598 |
|
| 1599 |
mock_post.side_effect = [side_effect] |
| 1600 |
|
| 1601 |
assert obj.send(body="test", attach=attach) is False |
| 1602 |
|
| 1603 |
# Throw an exception on the second call to requests.post() |
| 1604 |
for side_effect in (requests.RequestException(), OSError(), bad_response): |
| 1605 |
# Reset our value |
| 1606 |
mock_put.reset_mock() |
| 1607 |
mock_post.reset_mock() |
| 1608 |
|
| 1609 |
mock_put.side_effect = [side_effect, response] |
| 1610 |
mock_post.side_effect = [response, side_effect, response] |
| 1611 |
|
| 1612 |
# We'll fail now because of our error handling |
| 1613 |
assert obj.send(body="test", attach=attach) is False |
| 1614 |
|
| 1615 |
# handle a bad response |
| 1616 |
mock_put.side_effect = [bad_response, response] |
| 1617 |
mock_post.side_effect = [response, bad_response, response] |
| 1618 |
|
| 1619 |
# We'll fail now because of an internal exception |
| 1620 |
assert obj.send(body="test", attach=attach) is False |
| 1621 |
|
| 1622 |
# Force a object removal (thus a logout call) |
| 1623 |
del obj |
| 1624 |
_force_del_cleanup() |
| 1625 |
|
| 1626 |
|
| 1627 |
@mock.patch("requests.put") |
| 1628 |
@mock.patch("requests.get") |
| 1629 |
@mock.patch("requests.post") |
| 1630 |
def test_plugin_matrix_discovery_service(mock_post, mock_get, mock_put): |
| 1631 |
"""NotifyMatrix() Discovery Service.""" |
| 1632 |
|
| 1633 |
# Prepare a good response |
| 1634 |
response = _Response() |
| 1635 |
response.status_code = requests.codes.ok |
| 1636 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 1637 |
|
| 1638 |
# Prepare a good response |
| 1639 |
bad_response = _Response() |
| 1640 |
bad_response.status_code = requests.codes.unauthorized |
| 1641 |
bad_response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 1642 |
|
| 1643 |
# Prepare Mock return object |
| 1644 |
mock_post.return_value = response |
| 1645 |
mock_get.return_value = response |
| 1646 |
mock_put.return_value = response |
| 1647 |
|
| 1648 |
# Instantiate our object |
| 1649 |
obj = Apprise.instantiate( |
| 1650 |
"matrixs://user:[email protected]/#general?v=2&discovery=yes" |
| 1651 |
) |
| 1652 |
assert bool(obj.notify("body")) is True |
| 1653 |
|
| 1654 |
response = _Response() |
| 1655 |
response.status_code = requests.codes.unavailable |
| 1656 |
resp = loads(MATRIX_GOOD_RESPONSE) |
| 1657 |
|
| 1658 |
mock_get.return_value = response |
| 1659 |
mock_post.return_value = response |
| 1660 |
obj = Apprise.instantiate( |
| 1661 |
"matrixs://user:[email protected]/#general?v=2&discovery=yes" |
| 1662 |
) |
| 1663 |
obj.store.clear( |
| 1664 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1665 |
) |
| 1666 |
|
| 1667 |
# Invalid host / fallback is to resolve our own host |
| 1668 |
with pytest.raises(MatrixDiscoveryException): |
| 1669 |
_ = obj.base_url |
| 1670 |
|
| 1671 |
# Verify cache is not saved |
| 1672 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1673 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1674 |
|
| 1675 |
response.status_code = requests.codes.ok |
| 1676 |
obj.store.clear( |
| 1677 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1678 |
) |
| 1679 |
|
| 1680 |
# bad data |
| 1681 |
resp["m.homeserver"] = "!garbage!:303" |
| 1682 |
response.content = dumps(resp).encode("utf-8") |
| 1683 |
obj.store.clear( |
| 1684 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1685 |
) |
| 1686 |
|
| 1687 |
with pytest.raises(MatrixDiscoveryException): |
| 1688 |
_ = obj.base_url |
| 1689 |
|
| 1690 |
# Verify cache is not saved |
| 1691 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1692 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1693 |
|
| 1694 |
# We fail our discovery and therefore can't send our notification |
| 1695 |
assert bool(obj.notify("hello world")) is False |
| 1696 |
|
| 1697 |
# bad key |
| 1698 |
resp["m.homeserver"] = {} |
| 1699 |
response.content = dumps(resp).encode("utf-8") |
| 1700 |
obj.store.clear( |
| 1701 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1702 |
) |
| 1703 |
with pytest.raises(MatrixDiscoveryException): |
| 1704 |
_ = obj.base_url |
| 1705 |
|
| 1706 |
# Verify cache is not saved |
| 1707 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1708 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1709 |
|
| 1710 |
resp["m.homeserver"] = {"base_url": "https://nuxref.com/base"} |
| 1711 |
response.content = dumps(resp).encode("utf-8") |
| 1712 |
obj.store.clear( |
| 1713 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1714 |
) |
| 1715 |
assert obj.base_url == "https://nuxref.com/base" |
| 1716 |
assert obj.identity_url == "https://vector.im" |
| 1717 |
|
| 1718 |
# Verify cache saved |
| 1719 |
assert NotifyMatrix.discovery_base_key in obj.store |
| 1720 |
assert NotifyMatrix.discovery_identity_key in obj.store |
| 1721 |
|
| 1722 |
# Discovery passes so notifications work too |
| 1723 |
assert bool(obj.notify("hello world")) is True |
| 1724 |
|
| 1725 |
# bad data |
| 1726 |
resp["m.identity_server"] = "!garbage!:303" |
| 1727 |
response.content = dumps(resp).encode("utf-8") |
| 1728 |
obj.store.clear( |
| 1729 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1730 |
) |
| 1731 |
|
| 1732 |
with pytest.raises(MatrixDiscoveryException): |
| 1733 |
_ = obj.base_url |
| 1734 |
|
| 1735 |
# Verify cache is not saved |
| 1736 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1737 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1738 |
|
| 1739 |
# no key |
| 1740 |
resp["m.identity_server"] = {} |
| 1741 |
response.content = dumps(resp).encode("utf-8") |
| 1742 |
obj.store.clear( |
| 1743 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1744 |
) |
| 1745 |
|
| 1746 |
with pytest.raises(MatrixDiscoveryException): |
| 1747 |
_ = obj.base_url |
| 1748 |
|
| 1749 |
# Verify cache is not saved |
| 1750 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1751 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1752 |
|
| 1753 |
# remove |
| 1754 |
del resp["m.identity_server"] |
| 1755 |
response.content = dumps(resp).encode("utf-8") |
| 1756 |
|
| 1757 |
obj.store.clear( |
| 1758 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1759 |
) |
| 1760 |
assert obj.base_url == "https://nuxref.com/base" |
| 1761 |
assert obj.identity_url == "https://nuxref.com/base" |
| 1762 |
|
| 1763 |
# restore |
| 1764 |
resp["m.identity_server"] = {"base_url": "https://vector.im"} |
| 1765 |
response.content = dumps(resp).encode("utf-8") |
| 1766 |
|
| 1767 |
# Not found is an acceptable response (no exceptions thrown) |
| 1768 |
response.status_code = requests.codes.not_found |
| 1769 |
obj.store.clear( |
| 1770 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1771 |
) |
| 1772 |
assert obj.base_url == "https://example.com" |
| 1773 |
assert obj.identity_url == "https://example.com" |
| 1774 |
|
| 1775 |
# Verify cache saved |
| 1776 |
assert NotifyMatrix.discovery_base_key in obj.store |
| 1777 |
assert NotifyMatrix.discovery_identity_key in obj.store |
| 1778 |
|
| 1779 |
# Discovery passes so notifications work too |
| 1780 |
response.status_code = requests.codes.ok |
| 1781 |
assert bool(obj.notify("hello world")) is True |
| 1782 |
|
| 1783 |
response.status_code = requests.codes.ok |
| 1784 |
mock_get.return_value = None |
| 1785 |
mock_get.side_effect = (response, bad_response) |
| 1786 |
obj.store.clear( |
| 1787 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1788 |
) |
| 1789 |
|
| 1790 |
with pytest.raises(MatrixDiscoveryException): |
| 1791 |
_ = obj.base_url |
| 1792 |
|
| 1793 |
# Verify cache is not saved |
| 1794 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1795 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1796 |
|
| 1797 |
# Test case where ourIdentity URI fails to do it's check |
| 1798 |
mock_get.side_effect = (response, response, bad_response) |
| 1799 |
obj.store.clear( |
| 1800 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1801 |
) |
| 1802 |
|
| 1803 |
with pytest.raises(MatrixDiscoveryException): |
| 1804 |
_ = obj.base_url |
| 1805 |
|
| 1806 |
# Verify cache is not saved |
| 1807 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1808 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1809 |
|
| 1810 |
# Test an empty block response |
| 1811 |
response.status_code = requests.codes.ok |
| 1812 |
response.content = "" |
| 1813 |
mock_get.return_value = response |
| 1814 |
mock_get.side_effect = None |
| 1815 |
mock_post.return_value = response |
| 1816 |
mock_post.side_effect = None |
| 1817 |
obj.store.clear( |
| 1818 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1819 |
) |
| 1820 |
|
| 1821 |
assert obj.base_url == "https://example.com" |
| 1822 |
assert obj.identity_url == "https://example.com" |
| 1823 |
|
| 1824 |
# Verify cache saved |
| 1825 |
assert NotifyMatrix.discovery_base_key in obj.store |
| 1826 |
assert NotifyMatrix.discovery_identity_key in obj.store |
| 1827 |
|
| 1828 |
del obj |
| 1829 |
|
| 1830 |
|
| 1831 |
@mock.patch("requests.put") |
| 1832 |
@mock.patch("requests.get") |
| 1833 |
@mock.patch("requests.post") |
| 1834 |
def test_plugin_matrix_rejects_unsafe_discovery(mock_post, mock_get, mock_put): |
| 1835 |
"""Reject unsafe addresses returned by Matrix discovery.""" |
| 1836 |
|
| 1837 |
# Prepare a good response |
| 1838 |
response = _Response() |
| 1839 |
response.status_code = requests.codes.ok |
| 1840 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 1841 |
|
| 1842 |
mock_post.return_value = response |
| 1843 |
mock_get.return_value = response |
| 1844 |
mock_put.return_value = response |
| 1845 |
|
| 1846 |
obj = Apprise.instantiate( |
| 1847 |
"matrixs://user:[email protected]/#general?v=2&discovery=yes" |
| 1848 |
) |
| 1849 |
|
| 1850 |
# Each of these is an address we refuse to send our token to |
| 1851 |
for base_url in ( |
| 1852 |
# An unencrypted address |
| 1853 |
"http://matrix.example.com", |
| 1854 |
# Embedded credentials |
| 1855 |
"https://attacker:[email protected]", |
| 1856 |
# Not a host we can make sense of |
| 1857 |
"https://-nope-.example.com", |
| 1858 |
): |
| 1859 |
resp = loads(MATRIX_GOOD_RESPONSE) |
| 1860 |
resp["m.homeserver"] = {"base_url": base_url} |
| 1861 |
response.content = dumps(resp).encode("utf-8") |
| 1862 |
obj.store.clear( |
| 1863 |
NotifyMatrix.discovery_base_key, |
| 1864 |
NotifyMatrix.discovery_identity_key, |
| 1865 |
) |
| 1866 |
|
| 1867 |
with pytest.raises(MatrixDiscoveryException): |
| 1868 |
_ = obj.base_url |
| 1869 |
|
| 1870 |
# Nothing is cached from a failed discovery |
| 1871 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1872 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1873 |
|
| 1874 |
# The identity server address is held to the same standard |
| 1875 |
resp = loads(MATRIX_GOOD_RESPONSE) |
| 1876 |
resp["m.identity_server"] = {"base_url": "http://identity.example.com"} |
| 1877 |
response.content = dumps(resp).encode("utf-8") |
| 1878 |
obj.store.clear( |
| 1879 |
NotifyMatrix.discovery_base_key, NotifyMatrix.discovery_identity_key |
| 1880 |
) |
| 1881 |
|
| 1882 |
with pytest.raises(MatrixDiscoveryException): |
| 1883 |
_ = obj.base_url |
| 1884 |
|
| 1885 |
assert NotifyMatrix.discovery_base_key not in obj.store |
| 1886 |
assert NotifyMatrix.discovery_identity_key not in obj.store |
| 1887 |
|
| 1888 |
del obj |
| 1889 |
_force_del_cleanup() |
| 1890 |
|
| 1891 |
|
| 1892 |
@mock.patch("requests.put") |
| 1893 |
@mock.patch("requests.get") |
| 1894 |
@mock.patch("requests.post") |
| 1895 |
def test_plugin_matrix_attachments_api_v2(mock_post, mock_get, mock_put): |
| 1896 |
"""NotifyMatrix() Attachment Checks (v2)""" |
| 1897 |
|
| 1898 |
# Prepare a good response |
| 1899 |
response = _Response() |
| 1900 |
response.status_code = requests.codes.ok |
| 1901 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 1902 |
|
| 1903 |
# Prepare a bad response |
| 1904 |
bad_response = _Response() |
| 1905 |
bad_response.status_code = requests.codes.internal_server_error |
| 1906 |
|
| 1907 |
# Prepare Mock return object |
| 1908 |
mock_post.return_value = response |
| 1909 |
mock_get.return_value = response |
| 1910 |
mock_put.return_value = response |
| 1911 |
|
| 1912 |
# Instantiate our object |
| 1913 |
obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=2") |
| 1914 |
|
| 1915 |
# attach our content |
| 1916 |
attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")) |
| 1917 |
|
| 1918 |
assert ( |
| 1919 |
bool( |
| 1920 |
obj.notify( |
| 1921 |
body="body", |
| 1922 |
title="title", |
| 1923 |
notify_type=NotifyType.INFO, |
| 1924 |
attach=attach, |
| 1925 |
) |
| 1926 |
) |
| 1927 |
is True |
| 1928 |
) |
| 1929 |
|
| 1930 |
attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")) |
| 1931 |
|
| 1932 |
# Attach an unsupported file |
| 1933 |
mock_post.return_value = response |
| 1934 |
mock_get.return_value = response |
| 1935 |
mock_post.side_effect = None |
| 1936 |
mock_get.side_effect = None |
| 1937 |
|
| 1938 |
# Force a object removal (thus a logout call) |
| 1939 |
del obj |
| 1940 |
_force_del_cleanup() |
| 1941 |
|
| 1942 |
# Instantiate our object |
| 1943 |
obj = Apprise.instantiate("matrixs://user:pass@localhost/#general?v=2") |
| 1944 |
|
| 1945 |
# Reset our object |
| 1946 |
mock_post.reset_mock() |
| 1947 |
mock_get.reset_mock() |
| 1948 |
mock_put.reset_mock() |
| 1949 |
|
| 1950 |
assert ( |
| 1951 |
bool( |
| 1952 |
obj.notify( |
| 1953 |
body="body", |
| 1954 |
title="title", |
| 1955 |
notify_type=NotifyType.INFO, |
| 1956 |
attach=attach, |
| 1957 |
) |
| 1958 |
) |
| 1959 |
is True |
| 1960 |
) |
| 1961 |
|
| 1962 |
# Test our call count -- login, join, upload use POST; sends use PUT |
| 1963 |
assert mock_post.call_count == 3 |
| 1964 |
assert ( |
| 1965 |
mock_post.call_args_list[0][0][0] |
| 1966 |
== "https://matrix.example.com/_matrix/client/r0/login" |
| 1967 |
) |
| 1968 |
assert ( |
| 1969 |
mock_post.call_args_list[1][0][0] |
| 1970 |
== "https://matrix.example.com/_matrix/client/r0/" |
| 1971 |
"join/%23general%3Alocalhost" |
| 1972 |
) |
| 1973 |
assert ( |
| 1974 |
mock_post.call_args_list[2][0][0] |
| 1975 |
== "https://matrix.example.com/_matrix/media/r0/upload" |
| 1976 |
) |
| 1977 |
assert mock_put.call_count == 2 |
| 1978 |
assert ( |
| 1979 |
mock_put.call_args_list[0][0][0] |
| 1980 |
== "https://matrix.example.com/_matrix/client/r0" |
| 1981 |
"/rooms/%21abc123%3Alocalhost/send/m.room.message/0" |
| 1982 |
) |
| 1983 |
assert ( |
| 1984 |
mock_put.call_args_list[1][0][0] |
| 1985 |
== "https://matrix.example.com/_matrix/client/r0/" |
| 1986 |
"rooms/%21abc123%3Alocalhost/send/m.room.message/1" |
| 1987 |
) |
| 1988 |
|
| 1989 |
# Attach an unsupported file type; these are skipped |
| 1990 |
attach = AppriseAttachment( |
| 1991 |
os.path.join(TEST_VAR_DIR, "apprise-archive.zip") |
| 1992 |
) |
| 1993 |
assert ( |
| 1994 |
bool( |
| 1995 |
obj.notify( |
| 1996 |
body="body", |
| 1997 |
title="title", |
| 1998 |
notify_type=NotifyType.INFO, |
| 1999 |
attach=attach, |
| 2000 |
) |
| 2001 |
) |
| 2002 |
is True |
| 2003 |
) |
| 2004 |
|
| 2005 |
# An invalid attachment will cause a failure |
| 2006 |
path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg") |
| 2007 |
attach = AppriseAttachment(path) |
| 2008 |
assert ( |
| 2009 |
bool( |
| 2010 |
obj.notify( |
| 2011 |
body="body", |
| 2012 |
title="title", |
| 2013 |
notify_type=NotifyType.INFO, |
| 2014 |
attach=path, |
| 2015 |
) |
| 2016 |
) |
| 2017 |
is False |
| 2018 |
) |
| 2019 |
|
| 2020 |
# update our attachment to be valid |
| 2021 |
attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")) |
| 2022 |
|
| 2023 |
mock_post.return_value = None |
| 2024 |
mock_get.return_value = None |
| 2025 |
|
| 2026 |
# Throw an exception on the first call to requests.post() |
| 2027 |
for side_effect in (requests.RequestException(), OSError(), bad_response): |
| 2028 |
# Reset our value |
| 2029 |
mock_post.reset_mock() |
| 2030 |
mock_get.reset_mock() |
| 2031 |
|
| 2032 |
mock_post.side_effect = [side_effect, response] |
| 2033 |
mock_get.side_effect = [side_effect, response] |
| 2034 |
|
| 2035 |
assert obj.send(body="test", attach=attach) is False |
| 2036 |
|
| 2037 |
# Throw an exception on the attachment send (now uses PUT) |
| 2038 |
for side_effect in (requests.RequestException(), OSError(), bad_response): |
| 2039 |
# Reset our value |
| 2040 |
mock_post.reset_mock() |
| 2041 |
mock_get.reset_mock() |
| 2042 |
mock_put.reset_mock() |
| 2043 |
|
| 2044 |
mock_post.side_effect = [response] # upload ok |
| 2045 |
mock_put.side_effect = [side_effect, side_effect] # sends fail |
| 2046 |
|
| 2047 |
# We'll fail now because of our error handling |
| 2048 |
assert obj.send(body="test", attach=attach) is False |
| 2049 |
|
| 2050 |
# handle a bad response on the attachment send (now PUT) |
| 2051 |
mock_post.side_effect = [response] # upload ok |
| 2052 |
mock_put.side_effect = [bad_response, response] # attachment fails |
| 2053 |
mock_get.side_effect = None |
| 2054 |
|
| 2055 |
# We'll fail now because of an internal exception |
| 2056 |
assert obj.send(body="test", attach=attach) is False |
| 2057 |
|
| 2058 |
# Force a object removal (thus a logout call) |
| 2059 |
del obj |
| 2060 |
_force_del_cleanup() |
| 2061 |
|
| 2062 |
# Instantiate our object (no discovery required) |
| 2063 |
obj = Apprise.instantiate( |
| 2064 |
"matrixs://user:pass@localhost/#general?v=2&discovery=no&image=y" |
| 2065 |
) |
| 2066 |
|
| 2067 |
# Reset our object |
| 2068 |
mock_post.reset_mock() |
| 2069 |
mock_get.reset_mock() |
| 2070 |
mock_put.reset_mock() |
| 2071 |
|
| 2072 |
# login + join succeed; image inline send (now PUT) fails |
| 2073 |
mock_post.side_effect = [response, response] |
| 2074 |
mock_get.side_effect = None |
| 2075 |
mock_put.side_effect = [bad_response] |
| 2076 |
|
| 2077 |
# image attachment didn't succeed |
| 2078 |
assert ( |
| 2079 |
bool( |
| 2080 |
obj.notify(body="body", title="title", notify_type=NotifyType.INFO) |
| 2081 |
) |
| 2082 |
is False |
| 2083 |
) |
| 2084 |
|
| 2085 |
# All calls now succeed |
| 2086 |
mock_post.return_value = response |
| 2087 |
mock_get.return_value = response |
| 2088 |
mock_put.return_value = response |
| 2089 |
mock_post.side_effect = None |
| 2090 |
mock_get.side_effect = None |
| 2091 |
mock_put.side_effect = None |
| 2092 |
|
| 2093 |
# We'll fail now because of an internal exception |
| 2094 |
assert obj.send(body="test", attach=attach) is True |
| 2095 |
|
| 2096 |
# Force __del__() call |
| 2097 |
del obj |
| 2098 |
|
| 2099 |
|
| 2100 |
@mock.patch("requests.put") |
| 2101 |
@mock.patch("requests.post") |
| 2102 |
def test_plugin_matrix_v2_compliance(mock_post, mock_put): |
| 2103 |
"""NotifyMatrix() Verify V2 uses PUT and TID for standard messages.""" |
| 2104 |
# Setup compliant response |
| 2105 |
response = _Response() |
| 2106 |
response.status_code = requests.codes.ok |
| 2107 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 2108 |
mock_post.return_value = response |
| 2109 |
mock_put.return_value = response |
| 2110 |
|
| 2111 |
# Instantiate as V2 |
| 2112 |
obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=2") |
| 2113 |
|
| 2114 |
# Send a standard notification |
| 2115 |
assert bool(obj.notify(body="test message")) is True |
| 2116 |
|
| 2117 |
# Confirm the fix: |
| 2118 |
# 1. Path contains the transaction ID '0' |
| 2119 |
# 2. Method is PUT |
| 2120 |
assert mock_put.call_count == 1 |
| 2121 |
assert "/_matrix/client/r0/rooms/" in mock_put.call_args_list[0][0][0] |
| 2122 |
assert "/send/m.room.message/0" in mock_put.call_args_list[0][0][0] |
| 2123 |
|
| 2124 |
|
| 2125 |
@mock.patch("requests.put") |
| 2126 |
@mock.patch("requests.get") |
| 2127 |
@mock.patch("requests.post") |
| 2128 |
def test_plugin_matrix_v2_token_mode_no_txn_increment( |
| 2129 |
mock_post, mock_get, mock_put |
| 2130 |
): |
| 2131 |
"""Token mode (access_token == password) skips transaction ID increment.""" |
| 2132 |
response = _Response() |
| 2133 |
response.status_code = requests.codes.ok |
| 2134 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 2135 |
mock_post.return_value = response |
| 2136 |
mock_get.return_value = response |
| 2137 |
mock_put.return_value = response |
| 2138 |
|
| 2139 |
# Token mode: user omitted, password treated as access token |
| 2140 |
# (parse_url swaps user->password when no password supplied) |
| 2141 |
obj = Apprise.instantiate( |
| 2142 |
"matrixs://my_access_token@localhost/#general?v=2&image=y" |
| 2143 |
) |
| 2144 |
assert obj is not None |
| 2145 |
|
| 2146 |
# Send with image inline enabled |
| 2147 |
assert bool(obj.notify(body="token mode image test")) is True |
| 2148 |
|
| 2149 |
# Send with an attachment |
| 2150 |
attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif")) |
| 2151 |
assert obj.send(body="token mode attach test", attach=attach) is True |
| 2152 |
|
| 2153 |
|
| 2154 |
def test_plugin_matrix_parse_native_url_no_match(): |
| 2155 |
"""parse_native_url returns None for non-t2bot URLs.""" |
| 2156 |
assert ( |
| 2157 |
NotifyMatrix.parse_native_url("https://not-a-t2bot-url.com/some/path") |
| 2158 |
is None |
| 2159 |
) |
| 2160 |
|
| 2161 |
|
| 2162 |
@mock.patch("requests.post") |
| 2163 |
def test_plugin_matrix_hookshot_webhook(mock_post): |
| 2164 |
"""matrix-hookshot webhook mode uses hookshot URL/payload conventions.""" |
| 2165 |
|
| 2166 |
response = _Response() |
| 2167 |
response.status_code = requests.codes.ok |
| 2168 |
response.content = b"{}" |
| 2169 |
mock_post.return_value = response |
| 2170 |
|
| 2171 |
obj = Apprise.instantiate( |
| 2172 |
"matrixs://apprise:[email protected]" |
| 2173 |
"?mode=hookshot&format=html&path=%2Fpublic-hooks" |
| 2174 |
) |
| 2175 |
assert obj is not None |
| 2176 |
|
| 2177 |
assert bool(obj.notify(title="Title", body="<b>Body</b>")) is True |
| 2178 |
|
| 2179 |
assert mock_post.call_args.args[0] == ( |
| 2180 |
"https://hookshot.example/public-hooks/supersecret" |
| 2181 |
) |
| 2182 |
|
| 2183 |
payload = loads(mock_post.call_args.kwargs["data"]) |
| 2184 |
assert payload["username"] == "apprise" |
| 2185 |
# Undeclared passthrough content remains untouched. |
| 2186 |
assert payload["text"] == "Title\r\n<b>Body</b>" |
| 2187 |
assert payload["html"] == "<h1>Title</h1><b>Body</b>" |
| 2188 |
|
| 2189 |
|
| 2190 |
@mock.patch("requests.post") |
| 2191 |
def test_plugin_matrix_hookshot_webhook_empty_title(mock_post): |
| 2192 |
"""Hookshot webhook mode avoids extra separators for empty titles.""" |
| 2193 |
from apprise.common import NotifyFormat |
| 2194 |
|
| 2195 |
response = _Response() |
| 2196 |
response.status_code = requests.codes.ok |
| 2197 |
response.content = b"{}" |
| 2198 |
mock_post.return_value = response |
| 2199 |
|
| 2200 |
obj = Apprise.instantiate( |
| 2201 |
"matrixs://apprise:[email protected]" |
| 2202 |
"?mode=hookshot&format=markdown&path=%2Fpublic-hooks" |
| 2203 |
) |
| 2204 |
assert obj is not None |
| 2205 |
|
| 2206 |
# Declaring Markdown enables HTML rendering. |
| 2207 |
assert ( |
| 2208 |
bool(obj.notify(body="**Body**", body_format=NotifyFormat.MARKDOWN)) |
| 2209 |
is True |
| 2210 |
) |
| 2211 |
|
| 2212 |
payload = loads(mock_post.call_args.kwargs["data"]) |
| 2213 |
assert payload["username"] == "apprise" |
| 2214 |
# The text fallback comes from the rendered HTML. |
| 2215 |
assert payload["text"] == "Body" |
| 2216 |
assert payload["html"] == "<p><strong>Body</strong></p>" |
| 2217 |
|
| 2218 |
|
| 2219 |
@mock.patch("requests.post") |
| 2220 |
def test_plugin_matrix_slack_webhook_markdown_untouched(mock_post): |
| 2221 |
"""Slack webhooks forward CommonMark for Slack to render.""" |
| 2222 |
from apprise.common import NotifyFormat |
| 2223 |
|
| 2224 |
response = _Response() |
| 2225 |
response.status_code = requests.codes.ok |
| 2226 |
response.content = b"{}" |
| 2227 |
mock_post.return_value = response |
| 2228 |
|
| 2229 |
obj = Apprise.instantiate( |
| 2230 |
"matrixs://apprise:[email protected]?mode=slack&format=markdown" |
| 2231 |
) |
| 2232 |
assert obj is not None |
| 2233 |
|
| 2234 |
assert ( |
| 2235 |
bool(obj.notify(body="**Body**", body_format=NotifyFormat.MARKDOWN)) |
| 2236 |
is True |
| 2237 |
) |
| 2238 |
|
| 2239 |
payload = loads(mock_post.call_args.kwargs["data"]) |
| 2240 |
assert payload["mrkdwn"] is True |
| 2241 |
# Slack receives the original CommonMark. |
| 2242 |
assert payload["attachments"][0]["text"] == "**Body**" |
| 2243 |
|
| 2244 |
|
| 2245 |
def test_plugin_matrix_hookshot_path_normalization(): |
| 2246 |
"""Hookshot webhook paths normalize missing leading slashes.""" |
| 2247 |
|
| 2248 |
obj = Apprise.instantiate( |
| 2249 |
"matrixs://apprise:[email protected]" |
| 2250 |
"?mode=hookshot&path=public-hooks" |
| 2251 |
) |
| 2252 |
assert obj is not None |
| 2253 |
assert obj.webhook_path == "/public-hooks" |
| 2254 |
|
| 2255 |
|
| 2256 |
@mock.patch("requests.post") |
| 2257 |
def test_plugin_matrix_hookshot_root_path_text(mock_post): |
| 2258 |
"""Hookshot root paths and text mode stay literal.""" |
| 2259 |
|
| 2260 |
response = _Response() |
| 2261 |
response.status_code = requests.codes.ok |
| 2262 |
response.content = b"{}" |
| 2263 |
mock_post.return_value = response |
| 2264 |
|
| 2265 |
obj = Apprise.instantiate( |
| 2266 |
"matrixs://apprise:[email protected]" |
| 2267 |
"?mode=hookshot&format=text&path=%2F" |
| 2268 |
) |
| 2269 |
assert obj is not None |
| 2270 |
assert bool(obj.notify(body="<b>Body</b>")) is True |
| 2271 |
|
| 2272 |
assert mock_post.call_args.args[0] == ( |
| 2273 |
"https://hookshot.example/supersecret" |
| 2274 |
) |
| 2275 |
assert loads(mock_post.call_args.kwargs["data"])["html"] == ( |
| 2276 |
"<b>Body</b>" |
| 2277 |
) |
| 2278 |
|
| 2279 |
|
| 2280 |
@mock.patch("requests.put") |
| 2281 |
@mock.patch("requests.get") |
| 2282 |
@mock.patch("requests.post") |
| 2283 |
def test_plugin_matrix_transaction_ids_api_v3_no_cache( |
| 2284 |
mock_post, mock_get, mock_put |
| 2285 |
): |
| 2286 |
"""NotifyMatrix() Transaction ID Checks (v3)""" |
| 2287 |
|
| 2288 |
# Prepare a good response |
| 2289 |
response = _Response() |
| 2290 |
response.status_code = requests.codes.ok |
| 2291 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 2292 |
|
| 2293 |
# Prepare a bad response |
| 2294 |
bad_response = _Response() |
| 2295 |
bad_response.status_code = requests.codes.internal_server_error |
| 2296 |
|
| 2297 |
# Prepare Mock return object |
| 2298 |
mock_post.return_value = response |
| 2299 |
mock_get.return_value = response |
| 2300 |
mock_put.return_value = response |
| 2301 |
|
| 2302 |
# For each element is 1 batch that is ran |
| 2303 |
# the number defined is the number of notifications to send |
| 2304 |
batch = [10, 1, 5] |
| 2305 |
|
| 2306 |
for notifications in batch: |
| 2307 |
# Instantiate our object |
| 2308 |
obj = Apprise.instantiate("matrix://user:pass@localhost/#general?v=3") |
| 2309 |
|
| 2310 |
# Ensure mode is memory |
| 2311 |
assert obj.store.mode == PersistentStoreMode.MEMORY |
| 2312 |
|
| 2313 |
# Performs a login |
| 2314 |
assert ( |
| 2315 |
bool( |
| 2316 |
obj.notify( |
| 2317 |
body="body", title="title", notify_type=NotifyType.INFO |
| 2318 |
) |
| 2319 |
) |
| 2320 |
is True |
| 2321 |
) |
| 2322 |
assert mock_get.call_count == 0 |
| 2323 |
assert mock_post.call_count == 2 |
| 2324 |
assert ( |
| 2325 |
mock_post.call_args_list[0][0][0] |
| 2326 |
== "http://localhost/_matrix/client/v3/login" |
| 2327 |
) |
| 2328 |
assert ( |
| 2329 |
mock_post.call_args_list[1][0][0] |
| 2330 |
== "http://localhost/_matrix/client/v3/join/%23general%3Alocalhost" |
| 2331 |
) |
| 2332 |
assert mock_put.call_count == 1 |
| 2333 |
assert ( |
| 2334 |
mock_put.call_args_list[0][0][0] |
| 2335 |
== "http://localhost/_matrix/client/v3/rooms/" |
| 2336 |
+ "%21abc123%3Alocalhost/send/m.room.message/0" |
| 2337 |
) |
| 2338 |
|
| 2339 |
for no, _ in enumerate(range(notifications), start=1): |
| 2340 |
# Clean our slate |
| 2341 |
mock_post.reset_mock() |
| 2342 |
mock_get.reset_mock() |
| 2343 |
mock_put.reset_mock() |
| 2344 |
|
| 2345 |
assert ( |
| 2346 |
bool( |
| 2347 |
obj.notify( |
| 2348 |
body="body", title="title", notify_type=NotifyType.INFO |
| 2349 |
) |
| 2350 |
) |
| 2351 |
is True |
| 2352 |
) |
| 2353 |
|
| 2354 |
assert mock_get.call_count == 0 |
| 2355 |
assert mock_post.call_count == 0 |
| 2356 |
assert mock_put.call_count == 1 |
| 2357 |
assert ( |
| 2358 |
mock_put.call_args_list[0][0][0] |
| 2359 |
== "http://localhost/_matrix/client/v3/rooms/" |
| 2360 |
+ f"%21abc123%3Alocalhost/send/m.room.message/{no}" |
| 2361 |
) |
| 2362 |
|
| 2363 |
mock_post.reset_mock() |
| 2364 |
mock_get.reset_mock() |
| 2365 |
mock_put.reset_mock() |
| 2366 |
|
| 2367 |
# Force a object removal (thus a logout call) |
| 2368 |
del obj |
| 2369 |
_force_del_cleanup() |
| 2370 |
|
| 2371 |
assert mock_get.call_count == 0 |
| 2372 |
assert mock_post.call_count == 1 |
| 2373 |
assert ( |
| 2374 |
mock_post.call_args_list[0][0][0] |
| 2375 |
== "http://localhost/_matrix/client/v3/logout" |
| 2376 |
) |
| 2377 |
mock_post.reset_mock() |
| 2378 |
assert mock_put.call_count == 0 |
| 2379 |
|
| 2380 |
|
| 2381 |
@mock.patch("requests.put") |
| 2382 |
@mock.patch("requests.get") |
| 2383 |
@mock.patch("requests.post") |
| 2384 |
def test_plugin_matrix_transaction_ids_api_v3_w_cache( |
| 2385 |
mock_post, mock_get, mock_put, tmpdir |
| 2386 |
): |
| 2387 |
"""NotifyMatrix() Transaction ID Checks (v3)""" |
| 2388 |
|
| 2389 |
# Prepare a good response |
| 2390 |
response = _Response() |
| 2391 |
response.status_code = requests.codes.ok |
| 2392 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 2393 |
|
| 2394 |
# Prepare a bad response |
| 2395 |
bad_response = _Response() |
| 2396 |
bad_response.status_code = requests.codes.internal_server_error |
| 2397 |
|
| 2398 |
# Prepare Mock return object |
| 2399 |
mock_post.return_value = response |
| 2400 |
mock_get.return_value = response |
| 2401 |
mock_put.return_value = response |
| 2402 |
|
| 2403 |
# For each element is 1 batch that is ran |
| 2404 |
# the number defined is the number of notifications to send |
| 2405 |
batch = [10, 1, 5] |
| 2406 |
|
| 2407 |
mock_post.reset_mock() |
| 2408 |
mock_get.reset_mock() |
| 2409 |
mock_put.reset_mock() |
| 2410 |
|
| 2411 |
asset = AppriseAsset( |
| 2412 |
storage_mode=PersistentStoreMode.FLUSH, |
| 2413 |
storage_path=str(tmpdir), |
| 2414 |
) |
| 2415 |
|
| 2416 |
# Message Counter |
| 2417 |
transaction_id = 1 |
| 2418 |
|
| 2419 |
for no, notifications in enumerate(batch): |
| 2420 |
# Instantiate our object |
| 2421 |
obj = Apprise.instantiate( |
| 2422 |
"matrix://user:pass@localhost/#general?v=3", asset=asset |
| 2423 |
) |
| 2424 |
|
| 2425 |
# Ensure mode is flush |
| 2426 |
assert obj.store.mode == PersistentStoreMode.FLUSH |
| 2427 |
|
| 2428 |
# Performs a login |
| 2429 |
assert ( |
| 2430 |
bool( |
| 2431 |
obj.notify( |
| 2432 |
body="body", title="title", notify_type=NotifyType.INFO |
| 2433 |
) |
| 2434 |
) |
| 2435 |
is True |
| 2436 |
) |
| 2437 |
assert mock_get.call_count == 0 |
| 2438 |
if no == 0: |
| 2439 |
# first entry |
| 2440 |
assert mock_post.call_count == 2 |
| 2441 |
assert ( |
| 2442 |
mock_post.call_args_list[0][0][0] |
| 2443 |
== "http://localhost/_matrix/client/v3/login" |
| 2444 |
) |
| 2445 |
assert ( |
| 2446 |
mock_post.call_args_list[1][0][0] |
| 2447 |
== "http://localhost/_matrix/client/v3/" |
| 2448 |
"join/%23general%3Alocalhost" |
| 2449 |
) |
| 2450 |
assert mock_put.call_count == 1 |
| 2451 |
assert ( |
| 2452 |
mock_put.call_args_list[0][0][0] |
| 2453 |
== "http://localhost/_matrix/client/v3/rooms/" |
| 2454 |
+ "%21abc123%3Alocalhost/send/m.room.message/0" |
| 2455 |
) |
| 2456 |
|
| 2457 |
for no, _ in enumerate(range(notifications), start=transaction_id): |
| 2458 |
# Clean our slate |
| 2459 |
mock_post.reset_mock() |
| 2460 |
mock_get.reset_mock() |
| 2461 |
mock_put.reset_mock() |
| 2462 |
|
| 2463 |
assert ( |
| 2464 |
bool( |
| 2465 |
obj.notify( |
| 2466 |
body="body", title="title", notify_type=NotifyType.INFO |
| 2467 |
) |
| 2468 |
) |
| 2469 |
is True |
| 2470 |
) |
| 2471 |
|
| 2472 |
# Increment transaction counter |
| 2473 |
transaction_id += 1 |
| 2474 |
|
| 2475 |
assert mock_get.call_count == 0 |
| 2476 |
assert mock_post.call_count == 0 |
| 2477 |
assert mock_put.call_count == 1 |
| 2478 |
assert ( |
| 2479 |
mock_put.call_args_list[0][0][0] |
| 2480 |
== "http://localhost/_matrix/client/v3/rooms/" |
| 2481 |
+ f"%21abc123%3Alocalhost/send/m.room.message/{no}" |
| 2482 |
) |
| 2483 |
|
| 2484 |
# Increment transaction counter |
| 2485 |
transaction_id += 1 |
| 2486 |
|
| 2487 |
mock_post.reset_mock() |
| 2488 |
mock_get.reset_mock() |
| 2489 |
mock_put.reset_mock() |
| 2490 |
|
| 2491 |
# Force a object removal |
| 2492 |
# Biggest takeaway is that a logout no longer happens |
| 2493 |
del obj |
| 2494 |
|
| 2495 |
assert mock_get.call_count == 0 |
| 2496 |
assert mock_post.call_count == 0 |
| 2497 |
assert mock_put.call_count == 0 |
| 2498 |
|
| 2499 |
|
| 2500 |
@mock.patch("requests.put") |
| 2501 |
@mock.patch("requests.get") |
| 2502 |
@mock.patch("requests.post") |
| 2503 |
def test_plugin_matrix_v3_url_with_port_assembly( |
| 2504 |
mock_post, mock_get, mock_put, tmpdir |
| 2505 |
): |
| 2506 |
"""NotifyMatrix() URL with Port Assembly Checks (v3)""" |
| 2507 |
|
| 2508 |
# Prepare a good response |
| 2509 |
response = _Response() |
| 2510 |
response.status_code = requests.codes.ok |
| 2511 |
response.content = MATRIX_GOOD_RESPONSE.encode("utf-8") |
| 2512 |
|
| 2513 |
# Prepare Mock return object |
| 2514 |
mock_post.return_value = response |
| 2515 |
mock_get.return_value = response |
| 2516 |
mock_put.return_value = response |
| 2517 |
|
| 2518 |
asset = AppriseAsset( |
| 2519 |
storage_mode=PersistentStoreMode.FLUSH, |
| 2520 |
storage_path=str(tmpdir), |
| 2521 |
) |
| 2522 |
|
| 2523 |
# Instantiate our object |
| 2524 |
obj = Apprise.instantiate( |
| 2525 |
"matrixs://user1:[email protected]:8080/#general?v=3", asset=asset |
| 2526 |
) |
| 2527 |
# Performs a login |
| 2528 |
assert ( |
| 2529 |
bool( |
| 2530 |
obj.notify(body="body", title="title", notify_type=NotifyType.INFO) |
| 2531 |
) |
| 2532 |
is True |
| 2533 |
) |
| 2534 |
|
| 2535 |
# Secure Connections have a bit of additional overhead to verify |
| 2536 |
# the authenticity of the server through discovery |
| 2537 |
assert mock_get.call_count == 3 |
| 2538 |
assert ( |
| 2539 |
mock_get.call_args_list[0][0][0] |
| 2540 |
== "https://example.ca:8080/.well-known/matrix/client" |
| 2541 |
) |
| 2542 |
assert ( |
| 2543 |
mock_get.call_args_list[1][0][0] |
| 2544 |
== "https://matrix.example.com/_matrix/client/versions" |
| 2545 |
) |
| 2546 |
assert ( |
| 2547 |
mock_get.call_args_list[2][0][0] |
| 2548 |
== "https://vector.im/_matrix/identity/v2" |
| 2549 |
) |
| 2550 |
|
| 2551 |
assert mock_post.call_count == 2 |
| 2552 |
# matrix.example.com comes from our MATRIX_GOOD_RESPONSE |
| 2553 |
# response which defines wht our .well-known returned to us |
| 2554 |
assert ( |
| 2555 |
mock_post.call_args_list[0][0][0] |
| 2556 |
== "https://matrix.example.com/_matrix/client/v3/login" |
| 2557 |
) |
| 2558 |
assert ( |
| 2559 |
mock_post.call_args_list[1][0][0] |
| 2560 |
== "https://matrix.example.com/_matrix/client/v3/" |
| 2561 |
"join/%23general%3Alocalhost" |
| 2562 |
) |
| 2563 |
assert mock_put.call_count == 1 |
| 2564 |
assert ( |
| 2565 |
mock_put.call_args_list[0][0][0] |
| 2566 |
== "https://matrix.example.com/_matrix/client/v3/rooms/" |
| 2567 |
+ "%21abc123%3Alocalhost/send/m.room.message/0" |
| 2568 |
) |
| 2569 |
|
| 2570 |
mock_post.reset_mock() |
| 2571 |
mock_get.reset_mock() |
| 2572 |
mock_put.reset_mock() |
| 2573 |
|
| 2574 |
assert obj.base_url == "https://matrix.example.com" |
| 2575 |
|
| 2576 |
# Cache is used under the hood; no second discover is performed |
| 2577 |
assert mock_put.call_count == 0 |
| 2578 |
assert mock_get.call_count == 0 |
| 2579 |
assert mock_post.call_count == 0 |
| 2580 |
|
| 2581 |
# Cleanup |
| 2582 |
del obj |
| 2583 |
|
| 2584 |
|
| 2585 |
@mock.patch("requests.put") |
| 2586 |
@mock.patch("requests.get") |
| 2587 |
@mock.patch("requests.post") |
| 2588 |
def test_plugin_matrix_no_room_create_on_non_not_found_join( |
| 2589 |
mock_post: mock.Mock, |
| 2590 |
mock_get: mock.Mock, |
| 2591 |
mock_put: mock.Mock, |
| 2592 |
) -> None: |
| 2593 |
"""No room creation when join fails with 400 (or other non-404). |
| 2594 |
|
| 2595 |
A join failure can occur for many reasons, such as auth failure or invite |
| 2596 |
required. In these cases, attempting to create the room is incorrect and |
| 2597 |
produces misleading follow-up errors like M_ROOM_IN_USE. |
| 2598 |
""" |
| 2599 |
|
| 2600 |
def _resp(status_code: int, content: Union[str, bytes]) -> mock.Mock: |
| 2601 |
r = _Response() |
| 2602 |
r.status_code = status_code |
| 2603 |
if isinstance(content, str): |
| 2604 |
r.content = content.encode("utf-8") |
| 2605 |
else: |
| 2606 |
r.content = content |
| 2607 |
return r |
| 2608 |
|
| 2609 |
login = dumps( |
| 2610 |
{ |
| 2611 |
"access_token": "t", |
| 2612 |
"home_server": "hs", |
| 2613 |
"user_id": "@u:hs", |
| 2614 |
} |
| 2615 |
) |
| 2616 |
|
| 2617 |
# POST sequence: |
| 2618 |
# 1. /login succeeds |
| 2619 |
# 2. /join/#backup fails with 400 and an empty body |
| 2620 |
# 3. /logout succeeds during object cleanup remembering token |
| 2621 |
mock_post.side_effect = [ |
| 2622 |
_resp(requests.codes.ok, login), |
| 2623 |
_resp(requests.codes.bad_request, b""), |
| 2624 |
_resp(requests.codes.ok, dumps({})), |
| 2625 |
] |
| 2626 |
|
| 2627 |
# No other requests should be needed (no createRoom, no directory lookup) |
| 2628 |
mock_get.return_value = _resp(requests.codes.internal_server_error, b"") |
| 2629 |
mock_put.return_value = _resp(requests.codes.ok, dumps({})) |
| 2630 |
|
| 2631 |
ap = Apprise() |
| 2632 |
ap.add("matrixs://user:[email protected]/#backup?discovery=no") |
| 2633 |
|
| 2634 |
assert bool(ap.notify(title="t", body="b")) is False |
| 2635 |
|
| 2636 |
# Cleanup explicitly to ensure __del__ executes while mocks are active. |
| 2637 |
import gc |
| 2638 |
|
| 2639 |
del ap |
| 2640 |
gc.collect() |
| 2641 |
|
| 2642 |
# login + join + logout |
| 2643 |
assert mock_post.call_count == 3 |
| 2644 |
assert mock_get.call_count == 0 |
| 2645 |
|
| 2646 |
|
| 2647 |
@mock.patch("requests.put") |
| 2648 |
@mock.patch("requests.get") |
| 2649 |
@mock.patch("requests.post") |
| 2650 |
def test_plugin_matrix_room_create_on_not_found_join( |
| 2651 |
mock_post: mock.Mock, |
| 2652 |
mock_get: mock.Mock, |
| 2653 |
mock_put: mock.Mock, |
| 2654 |
) -> None: |
| 2655 |
"""Attempt room creation only when join reports 404 / M_NOT_FOUND.""" |
| 2656 |
|
| 2657 |
def _resp(status_code: int, content: Union[str, bytes]) -> mock.Mock: |
| 2658 |
r = _Response() |
| 2659 |
r.status_code = status_code |
| 2660 |
if isinstance(content, str): |
| 2661 |
r.content = content.encode("utf-8") |
| 2662 |
else: |
| 2663 |
r.content = content |
| 2664 |
return r |
| 2665 |
|
| 2666 |
login = dumps( |
| 2667 |
{ |
| 2668 |
"access_token": "t", |
| 2669 |
"home_server": "hs", |
| 2670 |
"user_id": "@u:hs", |
| 2671 |
} |
| 2672 |
) |
| 2673 |
|
| 2674 |
# POST sequence: |
| 2675 |
# 1. /login succeeds |
| 2676 |
# 2. /join/#backup returns 404 not found |
| 2677 |
# 3. /createRoom returns alias in use, triggering alias resolution |
| 2678 |
# 4. /logout succeeds during object cleanup |
| 2679 |
mock_post.side_effect = [ |
| 2680 |
_resp(requests.codes.ok, login), |
| 2681 |
_resp( |
| 2682 |
requests.codes.not_found, |
| 2683 |
dumps({"errcode": "M_NOT_FOUND", "error": "Not found"}), |
| 2684 |
), |
| 2685 |
_resp( |
| 2686 |
requests.codes.bad_request, |
| 2687 |
dumps( |
| 2688 |
{ |
| 2689 |
"errcode": "M_ROOM_IN_USE", |
| 2690 |
"error": "Room alias already taken", |
| 2691 |
} |
| 2692 |
), |
| 2693 |
), |
| 2694 |
_resp(requests.codes.ok, dumps({})), |
| 2695 |
] |
| 2696 |
|
| 2697 |
# Directory lookup returns the room id |
| 2698 |
mock_get.return_value = _resp( |
| 2699 |
requests.codes.ok, |
| 2700 |
dumps({"room_id": "!abc123:matrix.vip"}), |
| 2701 |
) |
| 2702 |
|
| 2703 |
# Sending the message succeeds (v3 uses PUT) |
| 2704 |
mock_put.return_value = _resp(requests.codes.ok, dumps({})) |
| 2705 |
|
| 2706 |
ap = Apprise() |
| 2707 |
ap.add("matrixs://user:[email protected]/#backup?discovery=no") |
| 2708 |
|
| 2709 |
assert bool(ap.notify(title="t", body="b")) is True |
| 2710 |
|
| 2711 |
import gc |
| 2712 |
|
| 2713 |
del ap |
| 2714 |
gc.collect() |
| 2715 |
|
| 2716 |
# login + join + createRoom + logout |
| 2717 |
assert mock_post.call_count == 4 |
| 2718 |
assert mock_get.call_count == 1 |
| 2719 |
assert mock_put.call_count == 1 |
| 2720 |
|
| 2721 |
|
| 2722 |
# --------------------------------------------------------------------------- |
| 2723 |
# E2EE unit tests (require the cryptography package) |
| 2724 |
# --------------------------------------------------------------------------- |
| 2725 |
|
| 2726 |
try: |
| 2727 |
import cryptography # noqa: F401 |
| 2728 |
|
| 2729 |
CRYPTOGRAPHY_AVAILABLE = True |
| 2730 |
except ImportError: |
| 2731 |
CRYPTOGRAPHY_AVAILABLE = False |
| 2732 |
|
| 2733 |
|
| 2734 |
@mock.patch("requests.put") |
| 2735 |
@mock.patch("requests.get") |
| 2736 |
@mock.patch("requests.post") |
| 2737 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 2738 |
def test_plugin_matrix_room_create_e2ee_initial_state( |
| 2739 |
mock_post, mock_get, mock_put |
| 2740 |
): |
| 2741 |
"""_room_create with e2ee=True/secure=True embeds m.room.encryption in |
| 2742 |
initial_state and pre-seeds the room encryption cache.""" |
| 2743 |
response_obj = { |
| 2744 |
"access_token": "tok", |
| 2745 |
"user_id": "@u:localhost", |
| 2746 |
"home_server": "localhost", |
| 2747 |
"room_id": "!abc123", |
| 2748 |
} |
| 2749 |
r = _Response() |
| 2750 |
r.status_code = requests.codes.ok |
| 2751 |
r.content = dumps(response_obj).encode() |
| 2752 |
mock_post.return_value = r |
| 2753 |
mock_get.return_value = r |
| 2754 |
mock_put.return_value = r |
| 2755 |
|
| 2756 |
obj = NotifyMatrix( |
| 2757 |
host="localhost", |
| 2758 |
user="u", |
| 2759 |
password="p", |
| 2760 |
e2ee=True, |
| 2761 |
secure=True, |
| 2762 |
discovery=False, |
| 2763 |
) |
| 2764 |
obj.access_token = "tok" |
| 2765 |
obj.home_server = "localhost" |
| 2766 |
|
| 2767 |
captured_payloads = [] |
| 2768 |
_orig_fetch = obj._fetch |
| 2769 |
|
| 2770 |
def _capture_fetch(path, payload=None, **kw): |
| 2771 |
if path == "/createRoom": |
| 2772 |
captured_payloads.append(payload) |
| 2773 |
return _orig_fetch(path, payload=payload, **kw) |
| 2774 |
|
| 2775 |
obj._fetch = _capture_fetch |
| 2776 |
room_id = obj._room_create("e2ee_room") |
| 2777 |
assert room_id == response_obj["room_id"] |
| 2778 |
assert len(captured_payloads) == 1 |
| 2779 |
init_state = captured_payloads[0].get("initial_state", []) |
| 2780 |
assert any(s.get("type") == "m.room.encryption" for s in init_state) |
| 2781 |
assert obj.store.get("e2ee_room_enc_{}".format(room_id)) is True |
| 2782 |
|
| 2783 |
|
| 2784 |
def _rand_b64_32(): |
| 2785 |
"""32 bytes of random data encoded as unpadded base64.""" |
| 2786 |
import base64 |
| 2787 |
|
| 2788 |
return base64.b64encode(os.urandom(32)).decode() |
| 2789 |
|
| 2790 |
|
| 2791 |
def _make_signed_otk(account, user_id, device_id, key_b64=None): |
| 2792 |
"""Return a signed_curve25519 OTK dict signed by *account*. |
| 2793 |
|
| 2794 |
Produces {"key": ..., "signatures": {user_id: {"ed25519:DEV": ...}}} |
| 2795 |
suitable for inclusion in a /keys/claim mock response. |
| 2796 |
""" |
| 2797 |
from apprise.plugins.matrix.e2ee import _canonical_json |
| 2798 |
|
| 2799 |
if key_b64 is None: |
| 2800 |
key_b64 = _rand_b64_32() |
| 2801 |
payload = {"key": key_b64} |
| 2802 |
sig = account.sign(_canonical_json(payload)) |
| 2803 |
payload["signatures"] = {user_id: {"ed25519:{}".format(device_id): sig}} |
| 2804 |
return payload |
| 2805 |
|
| 2806 |
|
| 2807 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 2808 |
def test_plugin_matrix_e2ee_helpers(): |
| 2809 |
"""e2ee helper functions.""" |
| 2810 |
from apprise.plugins.matrix.e2ee import ( |
| 2811 |
_b64dec, |
| 2812 |
_b64enc, |
| 2813 |
_canonical_json, |
| 2814 |
_hmac_sha256, |
| 2815 |
_pb_bytes, |
| 2816 |
_pb_varint_field, |
| 2817 |
_varint, |
| 2818 |
) |
| 2819 |
|
| 2820 |
# _b64enc / _b64dec round-trip |
| 2821 |
raw = b"\x00\x01\x02\x03" |
| 2822 |
assert _b64dec(_b64enc(raw)) == raw |
| 2823 |
|
| 2824 |
# _b64dec tolerates missing padding and URL-safe chars |
| 2825 |
# "AA==" -> decode "AA" (2 chars, pad=2) |
| 2826 |
assert _b64dec("AA") == b"\x00" |
| 2827 |
# URL-safe chars are normalised |
| 2828 |
assert _b64dec("AA--") == _b64dec("AA++") |
| 2829 |
|
| 2830 |
# _hmac_sha256 returns 32 bytes |
| 2831 |
mac = _hmac_sha256(b"\x00" * 32, b"data") |
| 2832 |
assert isinstance(mac, bytes) and len(mac) == 32 |
| 2833 |
|
| 2834 |
# _varint: n==0 -> single zero byte |
| 2835 |
assert _varint(0) == b"\x00" |
| 2836 |
# n>0 is encoded as multi-byte varint |
| 2837 |
assert _varint(128) == b"\x80\x01" |
| 2838 |
|
| 2839 |
# _pb_bytes / _pb_varint_field produce bytes |
| 2840 |
pb = _pb_bytes(1, b"hello") |
| 2841 |
assert isinstance(pb, bytes) and len(pb) > 5 |
| 2842 |
pv = _pb_varint_field(2, 42) |
| 2843 |
assert isinstance(pv, bytes) |
| 2844 |
|
| 2845 |
# _canonical_json produces sorted-key JSON bytes |
| 2846 |
data = {"z": 1, "a": 2} |
| 2847 |
out = _canonical_json(data) |
| 2848 |
assert out.startswith(b'{"a"') |
| 2849 |
|
| 2850 |
|
| 2851 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 2852 |
def test_plugin_matrix_sas_responder_roundtrip(): |
| 2853 |
"""The custom SAS responder interoperates without libolm.""" |
| 2854 |
import hashlib |
| 2855 |
|
| 2856 |
from cryptography.hazmat.primitives.asymmetric.x25519 import ( |
| 2857 |
X25519PrivateKey, |
| 2858 |
X25519PublicKey, |
| 2859 |
) |
| 2860 |
from cryptography.hazmat.primitives.serialization import ( |
| 2861 |
Encoding, |
| 2862 |
PublicFormat, |
| 2863 |
) |
| 2864 |
|
| 2865 |
from apprise.plugins.matrix.e2ee import ( |
| 2866 |
MatrixOlmAccount, |
| 2867 |
MatrixSASVerification, |
| 2868 |
_b64dec, |
| 2869 |
_b64enc, |
| 2870 |
_canonical_json, |
| 2871 |
_hkdf_sha256, |
| 2872 |
_hmac_sha256, |
| 2873 |
) |
| 2874 |
|
| 2875 |
own_user = peer_user = "@u:h" |
| 2876 |
own_device = "APPRISE" |
| 2877 |
peer_device = "ELEMENT" |
| 2878 |
transaction_id = "sas-transaction" |
| 2879 |
start = { |
| 2880 |
"from_device": peer_device, |
| 2881 |
"transaction_id": transaction_id, |
| 2882 |
"method": "m.sas.v1", |
| 2883 |
"key_agreement_protocols": ["curve25519-hkdf-sha256"], |
| 2884 |
"hashes": ["sha256"], |
| 2885 |
"message_authentication_codes": ["hkdf-hmac-sha256.v2"], |
| 2886 |
"short_authentication_string": ["decimal", "emoji"], |
| 2887 |
} |
| 2888 |
sas = MatrixSASVerification( |
| 2889 |
own_user, |
| 2890 |
own_device, |
| 2891 |
peer_user, |
| 2892 |
peer_device, |
| 2893 |
start, |
| 2894 |
) |
| 2895 |
accept = sas.accept_content() |
| 2896 |
commitment = hashlib.sha256( |
| 2897 |
sas.public_key.encode("ascii") + _canonical_json(start) |
| 2898 |
).digest() |
| 2899 |
assert accept["commitment"] == _b64enc(commitment) |
| 2900 |
assert accept["message_authentication_code"] == ("hkdf-hmac-sha256.v2") |
| 2901 |
|
| 2902 |
peer_private = X25519PrivateKey.generate() |
| 2903 |
peer_public = _b64enc( |
| 2904 |
peer_private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) |
| 2905 |
) |
| 2906 |
sas.receive_key(peer_public) |
| 2907 |
assert sas.key_content()["key"] == sas.public_key |
| 2908 |
shared_secret = peer_private.exchange( |
| 2909 |
X25519PublicKey.from_public_bytes(_b64dec(sas.public_key)) |
| 2910 |
) |
| 2911 |
|
| 2912 |
def peer_mac(value, key_id): |
| 2913 |
info = ( |
| 2914 |
"MATRIX_KEY_VERIFICATION_MAC" |
| 2915 |
+ peer_user |
| 2916 |
+ peer_device |
| 2917 |
+ own_user |
| 2918 |
+ own_device |
| 2919 |
+ transaction_id |
| 2920 |
+ key_id |
| 2921 |
).encode("utf-8") |
| 2922 |
key = _hkdf_sha256(shared_secret, 32, salt=None, info=info) |
| 2923 |
return _b64enc(_hmac_sha256(key, value.encode("utf-8"))) |
| 2924 |
|
| 2925 |
own_account = MatrixOlmAccount() |
| 2926 |
own_mac = sas.mac_content(own_account.signing_key) |
| 2927 |
assert "ed25519:APPRISE" in own_mac["mac"] |
| 2928 |
|
| 2929 |
peer_account = MatrixOlmAccount() |
| 2930 |
peer_key_id = "ed25519:{}".format(peer_device) |
| 2931 |
peer_content = { |
| 2932 |
"transaction_id": transaction_id, |
| 2933 |
"mac": {peer_key_id: peer_mac(peer_account.signing_key, peer_key_id)}, |
| 2934 |
"keys": peer_mac(peer_key_id, "KEY_IDS"), |
| 2935 |
} |
| 2936 |
tampered = dict(peer_content) |
| 2937 |
tampered["keys"] = "invalid" |
| 2938 |
with pytest.raises(ValueError, match="key list MAC"): |
| 2939 |
sas.verify_peer_mac(tampered, {peer_key_id: peer_account.signing_key}) |
| 2940 |
assert sas.verify_peer_mac( |
| 2941 |
peer_content, {peer_key_id: peer_account.signing_key} |
| 2942 |
) |
| 2943 |
assert sas.state == "verified" |
| 2944 |
|
| 2945 |
|
| 2946 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 2947 |
def test_plugin_matrix_sas_init_validation(): |
| 2948 |
"""MatrixSASVerification rejects malformed SAS start content.""" |
| 2949 |
from apprise.plugins.matrix.e2ee import MatrixSASVerification |
| 2950 |
|
| 2951 |
own_user = peer_user = "@u:h" |
| 2952 |
own_device, peer_device = "APPRISE", "ELEMENT" |
| 2953 |
base_start = { |
| 2954 |
"from_device": peer_device, |
| 2955 |
"transaction_id": "tx", |
| 2956 |
"method": "m.sas.v1", |
| 2957 |
"key_agreement_protocols": ["curve25519-hkdf-sha256"], |
| 2958 |
"hashes": ["sha256"], |
| 2959 |
"message_authentication_codes": ["hkdf-hmac-sha256.v2"], |
| 2960 |
"short_authentication_string": ["decimal", "emoji"], |
| 2961 |
} |
| 2962 |
|
| 2963 |
def build(**overrides): |
| 2964 |
content = dict(base_start) |
| 2965 |
content.update(overrides) |
| 2966 |
return content |
| 2967 |
|
| 2968 |
cases = ( |
| 2969 |
({"transaction_id": ""}, "Missing SAS transaction"), |
| 2970 |
({"from_device": "OTHER"}, "does not match request device"), |
| 2971 |
({"method": "m.other.v1"}, "Unsupported SAS verification method"), |
| 2972 |
( |
| 2973 |
{"key_agreement_protocols": ["other"]}, |
| 2974 |
"Unsupported SAS key agreement", |
| 2975 |
), |
| 2976 |
({"hashes": ["sha1"]}, "Unsupported SAS hash"), |
| 2977 |
( |
| 2978 |
{"message_authentication_codes": ["other"]}, |
| 2979 |
"Unsupported SAS MAC", |
| 2980 |
), |
| 2981 |
( |
| 2982 |
{"short_authentication_string": ["emoji"]}, |
| 2983 |
"does not offer decimal", |
| 2984 |
), |
| 2985 |
) |
| 2986 |
for overrides, match in cases: |
| 2987 |
with pytest.raises(ValueError, match=match): |
| 2988 |
MatrixSASVerification( |
| 2989 |
own_user, |
| 2990 |
own_device, |
| 2991 |
peer_user, |
| 2992 |
peer_device, |
| 2993 |
build(**overrides), |
| 2994 |
) |
| 2995 |
|
| 2996 |
# A peer device ID is required with the transaction ID. |
| 2997 |
with pytest.raises(ValueError, match="Missing SAS transaction"): |
| 2998 |
MatrixSASVerification(own_user, own_device, peer_user, "", base_start) |
| 2999 |
|
| 3000 |
|
| 3001 |
def _make_sas(own_user, own_device, peer_user, peer_device, transaction_id): |
| 3002 |
"""Build a fresh MatrixSASVerification responder for *transaction_id*.""" |
| 3003 |
from apprise.plugins.matrix.e2ee import MatrixSASVerification |
| 3004 |
|
| 3005 |
start = { |
| 3006 |
"from_device": peer_device, |
| 3007 |
"transaction_id": transaction_id, |
| 3008 |
"method": "m.sas.v1", |
| 3009 |
"key_agreement_protocols": ["curve25519-hkdf-sha256"], |
| 3010 |
"hashes": ["sha256"], |
| 3011 |
"message_authentication_codes": ["hkdf-hmac-sha256.v2"], |
| 3012 |
"short_authentication_string": ["decimal", "emoji"], |
| 3013 |
} |
| 3014 |
return MatrixSASVerification( |
| 3015 |
own_user, own_device, peer_user, peer_device, start |
| 3016 |
) |
| 3017 |
|
| 3018 |
|
| 3019 |
def _completed_sas_pair( |
| 3020 |
own_user, |
| 3021 |
own_device, |
| 3022 |
peer_user, |
| 3023 |
peer_device, |
| 3024 |
transaction_id, |
| 3025 |
own_account, |
| 3026 |
peer_account, |
| 3027 |
): |
| 3028 |
"""Build a responder and matching peer at the MAC stage. |
| 3029 |
|
| 3030 |
The returned helper creates additional valid MAC values for edge cases. |
| 3031 |
""" |
| 3032 |
from cryptography.hazmat.primitives.asymmetric.x25519 import ( |
| 3033 |
X25519PrivateKey, |
| 3034 |
X25519PublicKey, |
| 3035 |
) |
| 3036 |
from cryptography.hazmat.primitives.serialization import ( |
| 3037 |
Encoding, |
| 3038 |
PublicFormat, |
| 3039 |
) |
| 3040 |
|
| 3041 |
from apprise.plugins.matrix.e2ee import ( |
| 3042 |
_b64dec, |
| 3043 |
_b64enc, |
| 3044 |
_hkdf_sha256, |
| 3045 |
_hmac_sha256, |
| 3046 |
) |
| 3047 |
|
| 3048 |
sas = _make_sas( |
| 3049 |
own_user, own_device, peer_user, peer_device, transaction_id |
| 3050 |
) |
| 3051 |
sas.accept_content() |
| 3052 |
|
| 3053 |
peer_private = X25519PrivateKey.generate() |
| 3054 |
peer_public = _b64enc( |
| 3055 |
peer_private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) |
| 3056 |
) |
| 3057 |
sas.receive_key(peer_public) |
| 3058 |
sas.mac_content(own_account.signing_key) |
| 3059 |
|
| 3060 |
shared_secret = peer_private.exchange( |
| 3061 |
X25519PublicKey.from_public_bytes(_b64dec(sas.public_key)) |
| 3062 |
) |
| 3063 |
|
| 3064 |
def peer_mac(value, key_id): |
| 3065 |
info = ( |
| 3066 |
"MATRIX_KEY_VERIFICATION_MAC" |
| 3067 |
+ peer_user |
| 3068 |
+ peer_device |
| 3069 |
+ own_user |
| 3070 |
+ own_device |
| 3071 |
+ transaction_id |
| 3072 |
+ key_id |
| 3073 |
).encode("utf-8") |
| 3074 |
key = _hkdf_sha256(shared_secret, 32, salt=None, info=info) |
| 3075 |
return _b64enc(_hmac_sha256(key, value.encode("utf-8"))) |
| 3076 |
|
| 3077 |
key_id = "ed25519:{}".format(peer_device) |
| 3078 |
content = { |
| 3079 |
"transaction_id": transaction_id, |
| 3080 |
"mac": {key_id: peer_mac(peer_account.signing_key, key_id)}, |
| 3081 |
"keys": peer_mac(key_id, "KEY_IDS"), |
| 3082 |
} |
| 3083 |
peer_keys = {key_id: peer_account.signing_key} |
| 3084 |
return sas, content, peer_keys, peer_mac |
| 3085 |
|
| 3086 |
|
| 3087 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3088 |
def test_plugin_matrix_sas_verification_state_guards(): |
| 3089 |
"""Out-of-order calls against MatrixSASVerification are rejected.""" |
| 3090 |
own_user = peer_user = "@u:h" |
| 3091 |
own_device, peer_device = "APPRISE", "ELEMENT" |
| 3092 |
|
| 3093 |
sas = _make_sas(own_user, own_device, peer_user, peer_device, "tx") |
| 3094 |
with pytest.raises(ValueError, match="peer key has not been received"): |
| 3095 |
sas.key_content() |
| 3096 |
with pytest.raises(ValueError, match="peer key has not been received"): |
| 3097 |
sas.mac_content("sig") |
| 3098 |
with pytest.raises(ValueError, match="Unexpected SAS key event"): |
| 3099 |
sas.receive_key("AAAA") |
| 3100 |
|
| 3101 |
sas.accept_content() |
| 3102 |
with pytest.raises(ValueError, match="already accepted"): |
| 3103 |
sas.accept_content() |
| 3104 |
with pytest.raises(ValueError, match="Unexpected SAS MAC event"): |
| 3105 |
sas.verify_peer_mac({}, {}) |
| 3106 |
|
| 3107 |
with pytest.raises( |
| 3108 |
ValueError, match="shared secret has not been established" |
| 3109 |
): |
| 3110 |
sas.decimal_sas() |
| 3111 |
|
| 3112 |
|
| 3113 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3114 |
def test_plugin_matrix_sas_invalid_peer_key(): |
| 3115 |
"""Reject malformed peer keys before decoding them.""" |
| 3116 |
own_user = peer_user = "@u:h" |
| 3117 |
own_device, peer_device = "APPRISE", "ELEMENT" |
| 3118 |
|
| 3119 |
for bad_key in ("", "A" * 513, None, 12345): |
| 3120 |
sas = _make_sas(own_user, own_device, peer_user, peer_device, "tx") |
| 3121 |
sas.accept_content() |
| 3122 |
with pytest.raises(ValueError, match="missing or malformed"): |
| 3123 |
sas.receive_key(bad_key) |
| 3124 |
|
| 3125 |
|
| 3126 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3127 |
def test_plugin_matrix_sas_mac_requires_secret(): |
| 3128 |
"""_calculate_mac refuses to run before the SAS key exchange.""" |
| 3129 |
sas = _make_sas("@u:h", "APPRISE", "@u:h", "ELEMENT", "tx") |
| 3130 |
# Reach the MAC guard without creating a shared secret. |
| 3131 |
sas.state = "key_received" |
| 3132 |
with pytest.raises( |
| 3133 |
ValueError, match="shared secret has not been established" |
| 3134 |
): |
| 3135 |
sas._calculate_mac("v", "kid", "@u:h", "APPRISE", "@u:h", "ELEMENT") |
| 3136 |
|
| 3137 |
|
| 3138 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3139 |
def test_plugin_matrix_sas_decimal_sas(): |
| 3140 |
"""decimal_sas derives the 3-number code the Matrix spec defines.""" |
| 3141 |
from cryptography.hazmat.primitives.asymmetric.x25519 import ( |
| 3142 |
X25519PrivateKey, |
| 3143 |
) |
| 3144 |
from cryptography.hazmat.primitives.serialization import ( |
| 3145 |
Encoding, |
| 3146 |
PublicFormat, |
| 3147 |
) |
| 3148 |
|
| 3149 |
from apprise.plugins.matrix.e2ee import _b64enc |
| 3150 |
|
| 3151 |
sas = _make_sas("@u:h", "APPRISE", "@u:h", "ELEMENT", "tx") |
| 3152 |
sas.accept_content() |
| 3153 |
peer_private = X25519PrivateKey.generate() |
| 3154 |
peer_public = _b64enc( |
| 3155 |
peer_private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) |
| 3156 |
) |
| 3157 |
sas.receive_key(peer_public) |
| 3158 |
|
| 3159 |
# Check the decimal bit splitting independently with five known bytes. |
| 3160 |
with mock.patch( |
| 3161 |
"apprise.plugins.matrix.e2ee._hkdf_sha256", |
| 3162 |
return_value=bytes([0xFF] * 5), |
| 3163 |
) as hkdf: |
| 3164 |
# All 40 bits set -> each 13-bit group is 8191 -> +1000 = 9191. |
| 3165 |
assert sas.decimal_sas() == (9191, 9191, 9191) |
| 3166 |
assert hkdf.call_args.args[1] == 5 |
| 3167 |
|
| 3168 |
with mock.patch( |
| 3169 |
"apprise.plugins.matrix.e2ee._hkdf_sha256", |
| 3170 |
return_value=bytes(5), |
| 3171 |
): |
| 3172 |
# All bits clear -> each 13-bit group is 0 -> +1000 = 1000. |
| 3173 |
assert sas.decimal_sas() == (1000, 1000, 1000) |
| 3174 |
|
| 3175 |
with mock.patch( |
| 3176 |
"apprise.plugins.matrix.e2ee._hkdf_sha256", |
| 3177 |
return_value=b"\x00\x01\x00\x00\x00", |
| 3178 |
) as hkdf: |
| 3179 |
# Cross-check against the spec's byte-by-byte formula. |
| 3180 |
b0, b1, b2, b3, b4 = b"\x00\x01\x00\x00\x00" |
| 3181 |
expected = ( |
| 3182 |
((b0 << 5) | (b1 >> 3)) + 1000, |
| 3183 |
(((b1 & 0x7) << 10) | (b2 << 2) | (b3 >> 6)) + 1000, |
| 3184 |
(((b3 & 0x3F) << 7) | (b4 >> 1)) + 1000, |
| 3185 |
) |
| 3186 |
assert sas.decimal_sas() == expected |
| 3187 |
|
| 3188 |
# Require the spec's exact separators and initiator-first field order. |
| 3189 |
info = hkdf.call_args.kwargs["info"] |
| 3190 |
assert info == ( |
| 3191 |
"MATRIX_KEY_VERIFICATION_SAS|" |
| 3192 |
"@u:h|ELEMENT|" + peer_public + "|" |
| 3193 |
"@u:h|APPRISE|" + sas.public_key + "|" |
| 3194 |
"tx" |
| 3195 |
).encode("utf-8") |
| 3196 |
|
| 3197 |
|
| 3198 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3199 |
def test_plugin_matrix_sas_verify_peer_mac_errors(): |
| 3200 |
"""verify_peer_mac rejects tampered or incomplete MAC content.""" |
| 3201 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 3202 |
|
| 3203 |
own_user = peer_user = "@u:h" |
| 3204 |
own_device, peer_device = "APPRISE", "ELEMENT" |
| 3205 |
own_account = MatrixOlmAccount() |
| 3206 |
peer_account = MatrixOlmAccount() |
| 3207 |
|
| 3208 |
def build(): |
| 3209 |
return _completed_sas_pair( |
| 3210 |
own_user, |
| 3211 |
own_device, |
| 3212 |
peer_user, |
| 3213 |
peer_device, |
| 3214 |
"tx", |
| 3215 |
own_account, |
| 3216 |
peer_account, |
| 3217 |
) |
| 3218 |
|
| 3219 |
# Wrong transaction id |
| 3220 |
sas, content, peer_keys, _mac = build() |
| 3221 |
content["transaction_id"] = "other" |
| 3222 |
with pytest.raises(ValueError, match="transaction does not match"): |
| 3223 |
sas.verify_peer_mac(content, peer_keys) |
| 3224 |
|
| 3225 |
# Missing/empty mac dict |
| 3226 |
sas, content, peer_keys, _mac = build() |
| 3227 |
content["mac"] = {} |
| 3228 |
with pytest.raises(ValueError, match="contains no keys"): |
| 3229 |
sas.verify_peer_mac(content, peer_keys) |
| 3230 |
|
| 3231 |
# mac dict present but missing the peer's own device key id |
| 3232 |
sas, content, peer_keys, _mac = build() |
| 3233 |
content["mac"] = {"ed25519:someone-else": "AAAA"} |
| 3234 |
with pytest.raises(ValueError, match="omits the peer device key"): |
| 3235 |
sas.verify_peer_mac(content, peer_keys) |
| 3236 |
|
| 3237 |
# An oversized key list is rejected before it is ever sorted/hashed. |
| 3238 |
sas, content, peer_keys, _mac = build() |
| 3239 |
device_key_id = next(iter(content["mac"])) |
| 3240 |
content["mac"] = { |
| 3241 |
device_key_id: content["mac"][device_key_id], |
| 3242 |
**{ |
| 3243 |
f"ed25519:junk-{i}": "AAAA" |
| 3244 |
for i in range(matrix_sas.MatrixSASVerification.MAX_MAC_KEYS) |
| 3245 |
}, |
| 3246 |
} |
| 3247 |
with pytest.raises(ValueError, match="too many keys"): |
| 3248 |
sas.verify_peer_mac(content, peer_keys) |
| 3249 |
|
| 3250 |
# peer_keys is not a mapping at all (TypeError branch) |
| 3251 |
sas, content, peer_keys, _mac = build() |
| 3252 |
with pytest.raises(ValueError, match="unknown key"): |
| 3253 |
sas.verify_peer_mac(content, None) |
| 3254 |
|
| 3255 |
# Reference an unknown key while keeping the key-list MAC valid. |
| 3256 |
sas, content, peer_keys, peer_mac = build() |
| 3257 |
device_key_id = next(iter(content["mac"])) |
| 3258 |
unknown_key_id = "ed25519:unknown-device" |
| 3259 |
macs = { |
| 3260 |
device_key_id: content["mac"][device_key_id], |
| 3261 |
unknown_key_id: peer_mac("garbage", unknown_key_id), |
| 3262 |
} |
| 3263 |
tampered = { |
| 3264 |
"transaction_id": "tx", |
| 3265 |
"mac": macs, |
| 3266 |
"keys": peer_mac(",".join(sorted(macs)), "KEY_IDS"), |
| 3267 |
} |
| 3268 |
with pytest.raises(ValueError, match="unknown key"): |
| 3269 |
sas.verify_peer_mac(tampered, peer_keys) |
| 3270 |
|
| 3271 |
# Tampered per-device MAC value |
| 3272 |
sas, content, peer_keys, _mac = build() |
| 3273 |
content["mac"][device_key_id] = "tampered-value" |
| 3274 |
with pytest.raises(ValueError, match="device key MAC does not match"): |
| 3275 |
sas.verify_peer_mac(content, peer_keys) |
| 3276 |
|
| 3277 |
|
| 3278 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3279 |
def test_plugin_matrix_sas_mac_field_limits(): |
| 3280 |
"""Reject oversized MAC fields before processing them.""" |
| 3281 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 3282 |
|
| 3283 |
own_user = peer_user = "@u:h" |
| 3284 |
own_device, peer_device = "APPRISE", "ELEMENT" |
| 3285 |
own_account = MatrixOlmAccount() |
| 3286 |
peer_account = MatrixOlmAccount() |
| 3287 |
|
| 3288 |
def build(): |
| 3289 |
return _completed_sas_pair( |
| 3290 |
own_user, |
| 3291 |
own_device, |
| 3292 |
peer_user, |
| 3293 |
peer_device, |
| 3294 |
"tx", |
| 3295 |
own_account, |
| 3296 |
peer_account, |
| 3297 |
) |
| 3298 |
|
| 3299 |
# Oversized MAC value for an otherwise-valid key ID. |
| 3300 |
sas, content, peer_keys, _mac = build() |
| 3301 |
device_key_id = next(iter(content["mac"])) |
| 3302 |
content["mac"][device_key_id] = "A" * 513 |
| 3303 |
with pytest.raises(ValueError, match="malformed entry"): |
| 3304 |
sas.verify_peer_mac(content, peer_keys) |
| 3305 |
|
| 3306 |
# Oversized key ID replacing the real one. |
| 3307 |
sas, content, peer_keys, _mac = build() |
| 3308 |
device_key_id = next(iter(content["mac"])) |
| 3309 |
content["mac"] = {"ed25519:" + "A" * 513: content["mac"][device_key_id]} |
| 3310 |
with pytest.raises(ValueError, match="malformed entry"): |
| 3311 |
sas.verify_peer_mac(content, peer_keys) |
| 3312 |
|
| 3313 |
# Oversized aggregate key-list MAC. |
| 3314 |
sas, content, peer_keys, _mac = build() |
| 3315 |
content["keys"] = "A" * 513 |
| 3316 |
with pytest.raises(ValueError, match="malformed key list MAC"): |
| 3317 |
sas.verify_peer_mac(content, peer_keys) |
| 3318 |
|
| 3319 |
# Missing key-list MAC. |
| 3320 |
sas, content, peer_keys, _mac = build() |
| 3321 |
del content["keys"] |
| 3322 |
with pytest.raises(ValueError, match="malformed key list MAC"): |
| 3323 |
sas.verify_peer_mac(content, peer_keys) |
| 3324 |
|
| 3325 |
# An oversized public key returned for the peer's device. |
| 3326 |
sas, content, peer_keys, _mac = build() |
| 3327 |
device_key_id = next(iter(content["mac"])) |
| 3328 |
peer_keys = dict(peer_keys, **{device_key_id: "A" * 513}) |
| 3329 |
with pytest.raises(ValueError, match="malformed key"): |
| 3330 |
sas.verify_peer_mac(content, peer_keys) |
| 3331 |
|
| 3332 |
|
| 3333 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3334 |
def test_plugin_matrix_e2ee_binding_key(): |
| 3335 |
"""_e2ee_binding_key reflects the current device/account identity.""" |
| 3336 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 3337 |
|
| 3338 |
obj = NotifyMatrix( |
| 3339 |
host="h", user="u", password="pass", targets=["#r"], secure=True |
| 3340 |
) |
| 3341 |
assert obj._e2ee_binding_key() == "" |
| 3342 |
|
| 3343 |
obj._e2ee_account = MatrixOlmAccount() |
| 3344 |
obj.user_id = "@u:h" |
| 3345 |
obj.device_id = "APPRISE" |
| 3346 |
assert obj._e2ee_binding_key() == "{}|{}|{}|{}".format( |
| 3347 |
"@u:h", |
| 3348 |
"APPRISE", |
| 3349 |
obj._e2ee_account.identity_key, |
| 3350 |
obj._e2ee_account.signing_key, |
| 3351 |
) |
| 3352 |
|
| 3353 |
|
| 3354 |
def test_plugin_matrix_autoverify_implies_e2ee(): |
| 3355 |
"""autoverify=yes implies e2ee=yes unless e2ee is set explicitly.""" |
| 3356 |
|
| 3357 |
# autoverify alone turns e2ee on without spelling it out. |
| 3358 |
obj = NotifyMatrix( |
| 3359 |
host="h", |
| 3360 |
user="u", |
| 3361 |
password="pass", |
| 3362 |
targets=["#r"], |
| 3363 |
secure=True, |
| 3364 |
autoverify=True, |
| 3365 |
) |
| 3366 |
assert obj.autoverify is True |
| 3367 |
assert obj.e2ee is True |
| 3368 |
|
| 3369 |
# An explicit e2ee=no is still honored even with autoverify=yes. |
| 3370 |
obj = NotifyMatrix( |
| 3371 |
host="h", |
| 3372 |
user="u", |
| 3373 |
password="pass", |
| 3374 |
targets=["#r"], |
| 3375 |
secure=True, |
| 3376 |
autoverify=True, |
| 3377 |
e2ee=False, |
| 3378 |
) |
| 3379 |
assert obj.autoverify is True |
| 3380 |
assert obj.e2ee is False |
| 3381 |
|
| 3382 |
# An explicit e2ee=yes alongside autoverify=yes is unaffected. |
| 3383 |
obj = NotifyMatrix( |
| 3384 |
host="h", |
| 3385 |
user="u", |
| 3386 |
password="pass", |
| 3387 |
targets=["#r"], |
| 3388 |
secure=True, |
| 3389 |
autoverify=True, |
| 3390 |
e2ee=True, |
| 3391 |
) |
| 3392 |
assert obj.autoverify is True |
| 3393 |
assert obj.e2ee is True |
| 3394 |
|
| 3395 |
# Without autoverify, e2ee keeps its own (already-True) default. |
| 3396 |
obj = NotifyMatrix( |
| 3397 |
host="h", user="u", password="pass", targets=["#r"], secure=True |
| 3398 |
) |
| 3399 |
assert obj.autoverify is False |
| 3400 |
assert obj.e2ee is True |
| 3401 |
|
| 3402 |
# The implied e2ee=yes survives a URL round trip: autoverify=yes is |
| 3403 |
# emitted, e2ee=no is not, and re-parsing yields the same identity. |
| 3404 |
obj = NotifyMatrix( |
| 3405 |
host="h", |
| 3406 |
user="u", |
| 3407 |
password="pass", |
| 3408 |
targets=["#r"], |
| 3409 |
secure=True, |
| 3410 |
autoverify=True, |
| 3411 |
) |
| 3412 |
url = obj.url() |
| 3413 |
assert "autoverify=yes" in url |
| 3414 |
assert "e2ee=no" not in url |
| 3415 |
|
| 3416 |
results = NotifyMatrix.parse_url(url) |
| 3417 |
obj2 = NotifyMatrix(**results) |
| 3418 |
assert obj2.autoverify is True |
| 3419 |
assert obj2.e2ee is True |
| 3420 |
assert obj.url_identifier == obj2.url_identifier |
| 3421 |
|
| 3422 |
|
| 3423 |
def _matrix_sas_plugin(user_id="@u:h", device_id="APPRISE"): |
| 3424 |
"""A NotifyMatrix instance with a ready-to-use E2EE identity.""" |
| 3425 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 3426 |
|
| 3427 |
obj = NotifyMatrix( |
| 3428 |
host="h", |
| 3429 |
user="u", |
| 3430 |
password="pass", |
| 3431 |
targets=["#r"], |
| 3432 |
e2ee=True, |
| 3433 |
autoverify=True, |
| 3434 |
secure=True, |
| 3435 |
) |
| 3436 |
obj.user_id = user_id |
| 3437 |
obj.device_id = device_id |
| 3438 |
obj._e2ee_account = MatrixOlmAccount() |
| 3439 |
return obj |
| 3440 |
|
| 3441 |
|
| 3442 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3443 |
def test_plugin_matrix_sas_send_event_and_cancel(): |
| 3444 |
"""_send_event builds the /sendToDevice request; _cancel/_fail no-op |
| 3445 |
without an active transaction.""" |
| 3446 |
import re |
| 3447 |
|
| 3448 |
obj = _matrix_sas_plugin() |
| 3449 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 3450 |
|
| 3451 |
assert verifier._cancel("m.timeout", "x") is False |
| 3452 |
assert verifier._fail("m.timeout", "x") is False |
| 3453 |
|
| 3454 |
with mock.patch.object( |
| 3455 |
obj, "_fetch", return_value=(True, {}, requests.codes.ok) |
| 3456 |
) as fetch: |
| 3457 |
assert ( |
| 3458 |
verifier._send_event( |
| 3459 |
"m.key.verification.ready", "@peer:h", "DEV", {"a": 1} |
| 3460 |
) |
| 3461 |
is True |
| 3462 |
) |
| 3463 |
args, kwargs = fetch.call_args |
| 3464 |
assert re.match(r"^/sendToDevice/[^/]+/[0-9a-f]{32}$", args[0]) |
| 3465 |
assert kwargs["method"] == "PUT" |
| 3466 |
assert kwargs["payload"] == {"messages": {"@peer:h": {"DEV": {"a": 1}}}} |
| 3467 |
# To-device sends use the same bounded verification budget as sync. |
| 3468 |
assert kwargs["timeout"][0] > 0 |
| 3469 |
assert kwargs["timeout"][1] > 0 |
| 3470 |
assert 0 < kwargs["max_retry_wait"] <= obj.default_autoverify_timeout_sec |
| 3471 |
|
| 3472 |
with mock.patch.object(obj, "_fetch", return_value=(False, {}, 500)): |
| 3473 |
assert ( |
| 3474 |
verifier._send_event("m.key.verification.ready", "u", "d", {}) |
| 3475 |
is False |
| 3476 |
) |
| 3477 |
|
| 3478 |
verifier.active = { |
| 3479 |
"transaction_id": "tx", |
| 3480 |
"user_id": "@peer:h", |
| 3481 |
"device_id": "DEV", |
| 3482 |
} |
| 3483 |
with mock.patch.object( |
| 3484 |
obj, "_fetch", return_value=(True, {}, requests.codes.ok) |
| 3485 |
) as fetch: |
| 3486 |
assert verifier._cancel("m.timeout", "reason") is True |
| 3487 |
_, kwargs = fetch.call_args |
| 3488 |
assert kwargs["payload"] == { |
| 3489 |
"messages": { |
| 3490 |
"@peer:h": { |
| 3491 |
"DEV": { |
| 3492 |
"transaction_id": "tx", |
| 3493 |
"code": "m.timeout", |
| 3494 |
"reason": "reason", |
| 3495 |
} |
| 3496 |
} |
| 3497 |
} |
| 3498 |
} |
| 3499 |
assert verifier._fail("m.timeout", "reason") is False |
| 3500 |
|
| 3501 |
|
| 3502 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3503 |
def test_plugin_matrix_sas_peer_keys_branches(): |
| 3504 |
"""_peer_keys covers every failure and success path.""" |
| 3505 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 3506 |
|
| 3507 |
obj = _matrix_sas_plugin() |
| 3508 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 3509 |
|
| 3510 |
with mock.patch.object( |
| 3511 |
obj, "_fetch", return_value=(False, {}, 500) |
| 3512 |
) as fetch: |
| 3513 |
assert verifier._peer_keys("@peer:h", "DEV") is None |
| 3514 |
# Key queries use the same bounded verification budget. |
| 3515 |
kwargs = fetch.call_args.kwargs |
| 3516 |
assert kwargs["timeout"][0] > 0 |
| 3517 |
assert kwargs["timeout"][1] > 0 |
| 3518 |
assert 0 < kwargs["max_retry_wait"] <= obj.default_autoverify_timeout_sec |
| 3519 |
|
| 3520 |
with mock.patch.object( |
| 3521 |
obj, "_fetch", return_value=(True, [], requests.codes.ok) |
| 3522 |
): |
| 3523 |
assert verifier._peer_keys("@peer:h", "DEV") is None |
| 3524 |
|
| 3525 |
with mock.patch.object( |
| 3526 |
obj, |
| 3527 |
"_fetch", |
| 3528 |
return_value=(True, {"device_keys": {}}, requests.codes.ok), |
| 3529 |
): |
| 3530 |
assert verifier._peer_keys("@peer:h", "DEV") is None |
| 3531 |
|
| 3532 |
# Null server fields are malformed but must not crash verification. |
| 3533 |
for malformed_response in ( |
| 3534 |
{"device_keys": None}, |
| 3535 |
{"device_keys": {"@peer:h": None}}, |
| 3536 |
{"device_keys": "not-a-dict"}, |
| 3537 |
): |
| 3538 |
with mock.patch.object( |
| 3539 |
obj, |
| 3540 |
"_fetch", |
| 3541 |
return_value=(True, malformed_response, requests.codes.ok), |
| 3542 |
): |
| 3543 |
assert verifier._peer_keys("@peer:h", "DEV") is None |
| 3544 |
|
| 3545 |
bad_device = { |
| 3546 |
"user_id": "@peer:h", |
| 3547 |
"device_id": "DEV", |
| 3548 |
"keys": {}, |
| 3549 |
"signatures": {}, |
| 3550 |
} |
| 3551 |
with mock.patch.object( |
| 3552 |
obj, |
| 3553 |
"_fetch", |
| 3554 |
return_value=( |
| 3555 |
True, |
| 3556 |
{"device_keys": {"@peer:h": {"DEV": bad_device}}}, |
| 3557 |
requests.codes.ok, |
| 3558 |
), |
| 3559 |
): |
| 3560 |
assert verifier._peer_keys("@peer:h", "DEV") is None |
| 3561 |
|
| 3562 |
peer_account = MatrixOlmAccount() |
| 3563 |
device = peer_account.device_keys_payload("@peer:h", "DEV") |
| 3564 |
response = { |
| 3565 |
"device_keys": {"@peer:h": {"DEV": device}}, |
| 3566 |
"master_keys": {"@peer:h": {"keys": {"ed25519:master": "abc"}}}, |
| 3567 |
} |
| 3568 |
with mock.patch.object( |
| 3569 |
obj, "_fetch", return_value=(True, response, requests.codes.ok) |
| 3570 |
): |
| 3571 |
keys = verifier._peer_keys("@peer:h", "DEV") |
| 3572 |
assert keys["ed25519:master"] == "abc" |
| 3573 |
assert "ed25519:DEV" in keys |
| 3574 |
|
| 3575 |
# An implausibly large keys map is rejected rather than copied; a real |
| 3576 |
# device or master-key object only ever advertises a couple of keys. |
| 3577 |
oversized_keys = { |
| 3578 |
f"curve25519:{i}": "k" for i in range(matrix_sas.MAX_DEVICE_KEYS + 1) |
| 3579 |
} |
| 3580 |
oversized_device = dict(device, keys=oversized_keys) |
| 3581 |
with ( |
| 3582 |
mock.patch.object(matrix_sas, "verify_device_keys", return_value=True), |
| 3583 |
mock.patch.object( |
| 3584 |
obj, |
| 3585 |
"_fetch", |
| 3586 |
return_value=( |
| 3587 |
True, |
| 3588 |
{"device_keys": {"@peer:h": {"DEV": oversized_device}}}, |
| 3589 |
requests.codes.ok, |
| 3590 |
), |
| 3591 |
), |
| 3592 |
): |
| 3593 |
keys = verifier._peer_keys("@peer:h", "DEV") |
| 3594 |
assert keys == {} |
| 3595 |
|
| 3596 |
oversized_master = dict( |
| 3597 |
response, |
| 3598 |
master_keys={"@peer:h": {"keys": oversized_keys}}, |
| 3599 |
) |
| 3600 |
with mock.patch.object( |
| 3601 |
obj, "_fetch", return_value=(True, oversized_master, requests.codes.ok) |
| 3602 |
): |
| 3603 |
keys = verifier._peer_keys("@peer:h", "DEV") |
| 3604 |
assert "curve25519:0" not in keys |
| 3605 |
assert "ed25519:DEV" in keys |
| 3606 |
|
| 3607 |
malformed = dict(response, master_keys={"@peer:h": "not-a-dict"}) |
| 3608 |
with mock.patch.object( |
| 3609 |
obj, "_fetch", return_value=(True, malformed, requests.codes.ok) |
| 3610 |
): |
| 3611 |
keys = verifier._peer_keys("@peer:h", "DEV") |
| 3612 |
assert "ed25519:master" not in keys |
| 3613 |
|
| 3614 |
# Treat null or malformed optional master keys as absent. |
| 3615 |
for master_keys_value in (None, {"@peer:h": {"keys": None}}): |
| 3616 |
with mock.patch.object( |
| 3617 |
obj, |
| 3618 |
"_fetch", |
| 3619 |
return_value=( |
| 3620 |
True, |
| 3621 |
dict(response, master_keys=master_keys_value), |
| 3622 |
requests.codes.ok, |
| 3623 |
), |
| 3624 |
): |
| 3625 |
keys = verifier._peer_keys("@peer:h", "DEV") |
| 3626 |
assert "ed25519:master" not in keys |
| 3627 |
assert "ed25519:DEV" in keys |
| 3628 |
|
| 3629 |
|
| 3630 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3631 |
def test_plugin_matrix_sas_handle_request_branches(): |
| 3632 |
"""_handle_request covers ignore/fail/success outcomes.""" |
| 3633 |
from time import time |
| 3634 |
|
| 3635 |
obj = _matrix_sas_plugin() |
| 3636 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 3637 |
now_ms = int(time() * 1000) |
| 3638 |
|
| 3639 |
assert verifier._handle_request("@u:h", {"timestamp": "nope"}) is None |
| 3640 |
|
| 3641 |
stale = { |
| 3642 |
"timestamp": now_ms - 20 * 60 * 1000, |
| 3643 |
"transaction_id": "tx", |
| 3644 |
"from_device": "DEV", |
| 3645 |
"methods": ["m.sas.v1"], |
| 3646 |
} |
| 3647 |
assert verifier._handle_request("@u:h", stale) is None |
| 3648 |
|
| 3649 |
future = dict(stale, timestamp=now_ms + 20 * 60 * 1000) |
| 3650 |
assert verifier._handle_request("@u:h", future) is None |
| 3651 |
|
| 3652 |
missing_tx = { |
| 3653 |
"timestamp": now_ms, |
| 3654 |
"from_device": "DEV", |
| 3655 |
"methods": ["m.sas.v1"], |
| 3656 |
} |
| 3657 |
assert verifier._handle_request("@u:h", missing_tx) is None |
| 3658 |
|
| 3659 |
missing_device = { |
| 3660 |
"timestamp": now_ms, |
| 3661 |
"transaction_id": "tx", |
| 3662 |
"methods": ["m.sas.v1"], |
| 3663 |
} |
| 3664 |
assert verifier._handle_request("@u:h", missing_device) is None |
| 3665 |
|
| 3666 |
wrong_method = { |
| 3667 |
"timestamp": now_ms, |
| 3668 |
"transaction_id": "tx", |
| 3669 |
"from_device": "DEV", |
| 3670 |
"methods": ["other"], |
| 3671 |
} |
| 3672 |
assert verifier._handle_request("@u:h", wrong_method) is None |
| 3673 |
|
| 3674 |
# A present-but-null "methods" field must not crash the "in" check. |
| 3675 |
null_methods = { |
| 3676 |
"timestamp": now_ms, |
| 3677 |
"transaction_id": "tx", |
| 3678 |
"from_device": "DEV", |
| 3679 |
"methods": None, |
| 3680 |
} |
| 3681 |
assert verifier._handle_request("@u:h", null_methods) is None |
| 3682 |
|
| 3683 |
# Identifiers are validated by type and length, not just truthiness. |
| 3684 |
for bad_transaction_id, bad_from_device in ( |
| 3685 |
(["tx"], "DEV"), |
| 3686 |
("x" * (matrix_sas.MAX_ID_LEN + 1), "DEV"), |
| 3687 |
("tx", 12345), |
| 3688 |
("tx", "x" * (matrix_sas.MAX_ID_LEN + 1)), |
| 3689 |
): |
| 3690 |
bad_ids = { |
| 3691 |
"timestamp": now_ms, |
| 3692 |
"transaction_id": bad_transaction_id, |
| 3693 |
"from_device": bad_from_device, |
| 3694 |
"methods": ["m.sas.v1"], |
| 3695 |
} |
| 3696 |
assert verifier._handle_request("@u:h", bad_ids) is None |
| 3697 |
assert verifier.active is None |
| 3698 |
|
| 3699 |
valid = { |
| 3700 |
"timestamp": now_ms, |
| 3701 |
"transaction_id": "tx", |
| 3702 |
"from_device": "DEV", |
| 3703 |
"methods": ["m.sas.v1"], |
| 3704 |
} |
| 3705 |
|
| 3706 |
with mock.patch.object(verifier, "_peer_keys", return_value=None): |
| 3707 |
assert verifier._handle_request("@u:h", valid) is False |
| 3708 |
assert verifier.active is None |
| 3709 |
|
| 3710 |
# Reject a new request without changing the active transaction. |
| 3711 |
active = { |
| 3712 |
"transaction_id": "other", |
| 3713 |
"user_id": "@u:h", |
| 3714 |
"device_id": "OLD", |
| 3715 |
} |
| 3716 |
verifier.active = active |
| 3717 |
with mock.patch.object(verifier, "_send_event", return_value=True) as se: |
| 3718 |
assert verifier._handle_request("@u:h", valid) is None |
| 3719 |
se.assert_called_once_with( |
| 3720 |
matrix_sas.EVENT_CANCEL, |
| 3721 |
"@u:h", |
| 3722 |
"DEV", |
| 3723 |
{ |
| 3724 |
"transaction_id": "tx", |
| 3725 |
"code": "m.unexpected_message", |
| 3726 |
"reason": "Another verification is already active", |
| 3727 |
}, |
| 3728 |
) |
| 3729 |
assert verifier.active is active |
| 3730 |
verifier.active = None |
| 3731 |
|
| 3732 |
# An exact replay of the request that started the active transaction |
| 3733 |
# is ignored silently -- it must not cancel our own exchange. |
| 3734 |
active = { |
| 3735 |
"transaction_id": "tx", |
| 3736 |
"user_id": "@u:h", |
| 3737 |
"device_id": "DEV", |
| 3738 |
} |
| 3739 |
verifier.active = active |
| 3740 |
with mock.patch.object(verifier, "_send_event") as se: |
| 3741 |
assert verifier._handle_request("@u:h", valid) is None |
| 3742 |
se.assert_not_called() |
| 3743 |
assert verifier.active is active |
| 3744 |
verifier.active = None |
| 3745 |
|
| 3746 |
# A second transaction from the same device cancels both attempts. |
| 3747 |
active = { |
| 3748 |
"transaction_id": "other", |
| 3749 |
"user_id": "@u:h", |
| 3750 |
"device_id": "DEV", |
| 3751 |
} |
| 3752 |
verifier.active = active |
| 3753 |
with ( |
| 3754 |
mock.patch.object(verifier, "_cancel", return_value=True) as cancel, |
| 3755 |
mock.patch.object(verifier, "_send_event", return_value=True) as se, |
| 3756 |
): |
| 3757 |
assert verifier._handle_request("@u:h", valid) is None |
| 3758 |
cancel.assert_called_once_with( |
| 3759 |
"m.unexpected_message", |
| 3760 |
"A newer verification request superseded this one", |
| 3761 |
) |
| 3762 |
se.assert_called_once_with( |
| 3763 |
matrix_sas.EVENT_CANCEL, |
| 3764 |
"@u:h", |
| 3765 |
"DEV", |
| 3766 |
{ |
| 3767 |
"transaction_id": "tx", |
| 3768 |
"code": "m.unexpected_message", |
| 3769 |
"reason": "Another verification is already active", |
| 3770 |
}, |
| 3771 |
) |
| 3772 |
assert verifier.active is None |
| 3773 |
|
| 3774 |
with ( |
| 3775 |
mock.patch.object( |
| 3776 |
verifier, "_peer_keys", return_value={"ed25519:DEV": "k"} |
| 3777 |
), |
| 3778 |
mock.patch.object(verifier, "_send_event", return_value=False) as se, |
| 3779 |
): |
| 3780 |
assert verifier._handle_request("@u:h", valid) is False |
| 3781 |
se.assert_called_once() |
| 3782 |
verifier.active = None |
| 3783 |
|
| 3784 |
with ( |
| 3785 |
mock.patch.object( |
| 3786 |
verifier, "_peer_keys", return_value={"ed25519:DEV": "k"} |
| 3787 |
), |
| 3788 |
mock.patch.object(verifier, "_send_event", return_value=True), |
| 3789 |
): |
| 3790 |
assert verifier._handle_request("@u:h", valid) is None |
| 3791 |
assert verifier.active["transaction_id"] == "tx" |
| 3792 |
|
| 3793 |
|
| 3794 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3795 |
def test_plugin_matrix_sas_handle_cancel(): |
| 3796 |
"""_handle_cancel always reports failure.""" |
| 3797 |
obj = _matrix_sas_plugin() |
| 3798 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 3799 |
assert verifier._handle_cancel({"reason": "user declined"}) is False |
| 3800 |
assert verifier._handle_cancel({}) is False |
| 3801 |
|
| 3802 |
|
| 3803 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3804 |
def test_plugin_matrix_sas_handle_start_branches(): |
| 3805 |
"""_handle_start covers the invalid-params, send-failure, and success |
| 3806 |
outcomes.""" |
| 3807 |
obj = _matrix_sas_plugin() |
| 3808 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 3809 |
verifier.active = { |
| 3810 |
"transaction_id": "tx", |
| 3811 |
"user_id": "@peer:h", |
| 3812 |
"device_id": "DEV", |
| 3813 |
} |
| 3814 |
|
| 3815 |
with mock.patch.object(verifier, "_cancel", return_value=True) as cancel: |
| 3816 |
assert ( |
| 3817 |
verifier._handle_start("@peer:h", {"transaction_id": "tx"}) |
| 3818 |
is False |
| 3819 |
) |
| 3820 |
cancel.assert_called_once_with( |
| 3821 |
"m.unknown_method", "Unsupported SAS verification parameters" |
| 3822 |
) |
| 3823 |
|
| 3824 |
valid_start = { |
| 3825 |
"from_device": "DEV", |
| 3826 |
"transaction_id": "tx", |
| 3827 |
"method": "m.sas.v1", |
| 3828 |
"key_agreement_protocols": ["curve25519-hkdf-sha256"], |
| 3829 |
"hashes": ["sha256"], |
| 3830 |
"message_authentication_codes": ["hkdf-hmac-sha256.v2"], |
| 3831 |
"short_authentication_string": ["decimal", "emoji"], |
| 3832 |
} |
| 3833 |
|
| 3834 |
with mock.patch.object(verifier, "_send_event", return_value=False): |
| 3835 |
assert verifier._handle_start("@peer:h", valid_start) is False |
| 3836 |
assert verifier.active["sas"] is not None |
| 3837 |
|
| 3838 |
verifier.active["sas"] = None |
| 3839 |
with mock.patch.object(verifier, "_send_event", return_value=True): |
| 3840 |
assert verifier._handle_start("@peer:h", valid_start) is None |
| 3841 |
assert verifier.active["sas"] is not None |
| 3842 |
first_sas = verifier.active["sas"] |
| 3843 |
|
| 3844 |
# A second start must not replace an already committed temporary key. |
| 3845 |
with mock.patch.object(verifier, "_cancel", return_value=True) as cancel: |
| 3846 |
assert verifier._handle_start("@peer:h", valid_start) is False |
| 3847 |
cancel.assert_called_once_with( |
| 3848 |
"m.unexpected_message", "SAS verification was already started" |
| 3849 |
) |
| 3850 |
assert verifier.active["sas"] is first_sas |
| 3851 |
|
| 3852 |
|
| 3853 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3854 |
def test_plugin_matrix_sas_handle_key_branches(): |
| 3855 |
"""_handle_key covers the invalid-key and send-failure/success paths.""" |
| 3856 |
from cryptography.hazmat.primitives.asymmetric.x25519 import ( |
| 3857 |
X25519PrivateKey, |
| 3858 |
) |
| 3859 |
from cryptography.hazmat.primitives.serialization import ( |
| 3860 |
Encoding, |
| 3861 |
PublicFormat, |
| 3862 |
) |
| 3863 |
|
| 3864 |
from apprise.plugins.matrix.e2ee import _b64enc |
| 3865 |
|
| 3866 |
obj = _matrix_sas_plugin() |
| 3867 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 3868 |
verifier.active = { |
| 3869 |
"transaction_id": "tx", |
| 3870 |
"user_id": "@peer:h", |
| 3871 |
"device_id": "DEV", |
| 3872 |
} |
| 3873 |
|
| 3874 |
invalid_sas = _make_sas(obj.user_id, obj.device_id, "@peer:h", "DEV", "tx") |
| 3875 |
invalid_sas.accept_content() |
| 3876 |
with mock.patch.object(verifier, "_cancel", return_value=True) as cancel: |
| 3877 |
assert ( |
| 3878 |
verifier._handle_key( |
| 3879 |
invalid_sas, "@peer:h", {"key": "not-valid-base64!!"} |
| 3880 |
) |
| 3881 |
is False |
| 3882 |
) |
| 3883 |
cancel.assert_called_once_with( |
| 3884 |
"m.invalid_message", "Invalid SAS public key" |
| 3885 |
) |
| 3886 |
|
| 3887 |
# A present-but-null "key" field must not crash before it is rejected |
| 3888 |
# as an invalid public key. |
| 3889 |
null_key_sas = _make_sas( |
| 3890 |
obj.user_id, obj.device_id, "@peer:h", "DEV", "tx" |
| 3891 |
) |
| 3892 |
null_key_sas.accept_content() |
| 3893 |
with mock.patch.object(verifier, "_cancel", return_value=True): |
| 3894 |
assert ( |
| 3895 |
verifier._handle_key(null_key_sas, "@peer:h", {"key": None}) |
| 3896 |
is False |
| 3897 |
) |
| 3898 |
|
| 3899 |
peer_private = X25519PrivateKey.generate() |
| 3900 |
peer_public = _b64enc( |
| 3901 |
peer_private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) |
| 3902 |
) |
| 3903 |
|
| 3904 |
key_fail_sas = _make_sas( |
| 3905 |
obj.user_id, obj.device_id, "@peer:h", "DEV", "tx" |
| 3906 |
) |
| 3907 |
key_fail_sas.accept_content() |
| 3908 |
with mock.patch.object(verifier, "_send_event", return_value=False): |
| 3909 |
assert ( |
| 3910 |
verifier._handle_key(key_fail_sas, "@peer:h", {"key": peer_public}) |
| 3911 |
is False |
| 3912 |
) |
| 3913 |
|
| 3914 |
mac_fail_sas = _make_sas( |
| 3915 |
obj.user_id, obj.device_id, "@peer:h", "DEV", "tx" |
| 3916 |
) |
| 3917 |
mac_fail_sas.accept_content() |
| 3918 |
with mock.patch.object(verifier, "_send_event", side_effect=[True, False]): |
| 3919 |
assert ( |
| 3920 |
verifier._handle_key(mac_fail_sas, "@peer:h", {"key": peer_public}) |
| 3921 |
is False |
| 3922 |
) |
| 3923 |
|
| 3924 |
ok_sas = _make_sas(obj.user_id, obj.device_id, "@peer:h", "DEV", "tx") |
| 3925 |
ok_sas.accept_content() |
| 3926 |
with ( |
| 3927 |
mock.patch.object(verifier, "_send_event", return_value=True), |
| 3928 |
mock.patch.object(obj.logger, "info") as log_info, |
| 3929 |
): |
| 3930 |
assert ( |
| 3931 |
verifier._handle_key(ok_sas, "@peer:h", {"key": peer_public}) |
| 3932 |
is None |
| 3933 |
) |
| 3934 |
assert any( |
| 3935 |
"SAS code" in str(call.args[0]) for call in log_info.call_args_list |
| 3936 |
) |
| 3937 |
|
| 3938 |
|
| 3939 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 3940 |
def test_plugin_matrix_sas_handle_mac_branches(): |
| 3941 |
"""_handle_mac covers the mismatch, send-failure, and completion |
| 3942 |
outcomes.""" |
| 3943 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 3944 |
|
| 3945 |
obj = _matrix_sas_plugin() |
| 3946 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 3947 |
own_account = obj._e2ee_account |
| 3948 |
peer_account = MatrixOlmAccount() |
| 3949 |
|
| 3950 |
def build_active(peer_done): |
| 3951 |
sas, content, peer_keys, _mac = _completed_sas_pair( |
| 3952 |
obj.user_id, |
| 3953 |
obj.device_id, |
| 3954 |
"@peer:h", |
| 3955 |
"DEV", |
| 3956 |
"tx", |
| 3957 |
own_account, |
| 3958 |
peer_account, |
| 3959 |
) |
| 3960 |
verifier.active = { |
| 3961 |
"transaction_id": "tx", |
| 3962 |
"user_id": "@peer:h", |
| 3963 |
"device_id": "DEV", |
| 3964 |
"peer_keys": peer_keys, |
| 3965 |
"peer_done": peer_done, |
| 3966 |
} |
| 3967 |
return sas, content |
| 3968 |
|
| 3969 |
sas, _content = build_active(False) |
| 3970 |
with mock.patch.object(verifier, "_cancel", return_value=True) as cancel: |
| 3971 |
assert ( |
| 3972 |
verifier._handle_mac(sas, {"transaction_id": "tx", "mac": {}}) |
| 3973 |
is False |
| 3974 |
) |
| 3975 |
cancel.assert_called_once_with( |
| 3976 |
"m.key_mismatch", "SAS device key MAC did not match" |
| 3977 |
) |
| 3978 |
|
| 3979 |
sas, content = build_active(False) |
| 3980 |
with mock.patch.object(verifier, "_send_event", return_value=False): |
| 3981 |
assert verifier._handle_mac(sas, content) is False |
| 3982 |
|
| 3983 |
sas, content = build_active(True) |
| 3984 |
with ( |
| 3985 |
mock.patch.object(verifier, "_send_event", return_value=True), |
| 3986 |
mock.patch.object( |
| 3987 |
matrix_sas, "store_verified_binding", return_value=True |
| 3988 |
) as store, |
| 3989 |
): |
| 3990 |
assert verifier._handle_mac(sas, content) is True |
| 3991 |
store.assert_called_once_with(obj) |
| 3992 |
|
| 3993 |
# A failed persistence write must not be reported as success. |
| 3994 |
sas, content = build_active(True) |
| 3995 |
with ( |
| 3996 |
mock.patch.object(verifier, "_send_event", return_value=True), |
| 3997 |
mock.patch.object( |
| 3998 |
matrix_sas, "store_verified_binding", return_value=False |
| 3999 |
), |
| 4000 |
): |
| 4001 |
assert verifier._handle_mac(sas, content) is False |
| 4002 |
|
| 4003 |
sas, content = build_active(False) |
| 4004 |
with mock.patch.object(verifier, "_send_event", return_value=True): |
| 4005 |
assert verifier._handle_mac(sas, content) is None |
| 4006 |
|
| 4007 |
|
| 4008 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4009 |
def test_plugin_matrix_sas_handle_done_branches(): |
| 4010 |
"""_handle_done only reports success once the local SAS is verified.""" |
| 4011 |
obj = _matrix_sas_plugin() |
| 4012 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4013 |
verifier.active = {"peer_done": False} |
| 4014 |
|
| 4015 |
class _FakeSAS: |
| 4016 |
state = "mac_sent" |
| 4017 |
|
| 4018 |
fake = _FakeSAS() |
| 4019 |
assert verifier._handle_done(fake) is None |
| 4020 |
assert verifier.active["peer_done"] is True |
| 4021 |
|
| 4022 |
fake.state = "verified" |
| 4023 |
verifier.active["peer_done"] = False |
| 4024 |
with mock.patch.object( |
| 4025 |
matrix_sas, "store_verified_binding", return_value=True |
| 4026 |
) as store: |
| 4027 |
assert verifier._handle_done(fake) is True |
| 4028 |
store.assert_called_once_with(obj) |
| 4029 |
|
| 4030 |
# A failed persistence write must not be reported as success. |
| 4031 |
verifier.active["peer_done"] = False |
| 4032 |
with mock.patch.object( |
| 4033 |
matrix_sas, "store_verified_binding", return_value=False |
| 4034 |
): |
| 4035 |
assert verifier._handle_done(fake) is False |
| 4036 |
|
| 4037 |
|
| 4038 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4039 |
def test_plugin_matrix_sas_handle_event_dispatch(): |
| 4040 |
"""_handle_event routes every to-device event type correctly.""" |
| 4041 |
obj = _matrix_sas_plugin() |
| 4042 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4043 |
|
| 4044 |
assert verifier._handle_event("not-a-dict") is None |
| 4045 |
assert verifier._handle_event({"type": "x", "sender": "@other:h"}) is None |
| 4046 |
assert ( |
| 4047 |
verifier._handle_event( |
| 4048 |
{"type": "x", "sender": obj.user_id, "content": "nope"} |
| 4049 |
) |
| 4050 |
is None |
| 4051 |
) |
| 4052 |
|
| 4053 |
with mock.patch.object(verifier, "_handle_request", return_value="R") as h: |
| 4054 |
result = verifier._handle_event( |
| 4055 |
{ |
| 4056 |
"type": matrix_sas.EVENT_REQUEST, |
| 4057 |
"sender": obj.user_id, |
| 4058 |
"content": {"a": 1}, |
| 4059 |
} |
| 4060 |
) |
| 4061 |
assert result == "R" |
| 4062 |
h.assert_called_once_with(obj.user_id, {"a": 1}) |
| 4063 |
|
| 4064 |
# No active transaction yet -- every non-request event is ignored. |
| 4065 |
assert ( |
| 4066 |
verifier._handle_event( |
| 4067 |
{ |
| 4068 |
"type": matrix_sas.EVENT_START, |
| 4069 |
"sender": obj.user_id, |
| 4070 |
"content": {"transaction_id": "tx"}, |
| 4071 |
} |
| 4072 |
) |
| 4073 |
is None |
| 4074 |
) |
| 4075 |
|
| 4076 |
verifier.active = { |
| 4077 |
"transaction_id": "tx", |
| 4078 |
"user_id": obj.user_id, |
| 4079 |
"sas": None, |
| 4080 |
} |
| 4081 |
|
| 4082 |
assert ( |
| 4083 |
verifier._handle_event( |
| 4084 |
{ |
| 4085 |
"type": matrix_sas.EVENT_START, |
| 4086 |
"sender": obj.user_id, |
| 4087 |
"content": {"transaction_id": "other"}, |
| 4088 |
} |
| 4089 |
) |
| 4090 |
is None |
| 4091 |
) |
| 4092 |
|
| 4093 |
# Defensive same-transaction-owner check. |
| 4094 |
verifier.active["user_id"] = "@different:h" |
| 4095 |
assert ( |
| 4096 |
verifier._handle_event( |
| 4097 |
{ |
| 4098 |
"type": matrix_sas.EVENT_START, |
| 4099 |
"sender": obj.user_id, |
| 4100 |
"content": {"transaction_id": "tx"}, |
| 4101 |
} |
| 4102 |
) |
| 4103 |
is None |
| 4104 |
) |
| 4105 |
verifier.active["user_id"] = obj.user_id |
| 4106 |
|
| 4107 |
with mock.patch.object( |
| 4108 |
verifier, "_handle_cancel", return_value=False |
| 4109 |
) as h: |
| 4110 |
result = verifier._handle_event( |
| 4111 |
{ |
| 4112 |
"type": matrix_sas.EVENT_CANCEL, |
| 4113 |
"sender": obj.user_id, |
| 4114 |
"content": {"transaction_id": "tx"}, |
| 4115 |
} |
| 4116 |
) |
| 4117 |
assert result is False |
| 4118 |
h.assert_called_once() |
| 4119 |
|
| 4120 |
with mock.patch.object(verifier, "_handle_start", return_value=None) as h: |
| 4121 |
result = verifier._handle_event( |
| 4122 |
{ |
| 4123 |
"type": matrix_sas.EVENT_START, |
| 4124 |
"sender": obj.user_id, |
| 4125 |
"content": {"transaction_id": "tx"}, |
| 4126 |
} |
| 4127 |
) |
| 4128 |
assert result is None |
| 4129 |
h.assert_called_once() |
| 4130 |
|
| 4131 |
with mock.patch.object(verifier, "_cancel", return_value=True) as cancel: |
| 4132 |
result = verifier._handle_event( |
| 4133 |
{ |
| 4134 |
"type": matrix_sas.EVENT_KEY, |
| 4135 |
"sender": obj.user_id, |
| 4136 |
"content": {"transaction_id": "tx"}, |
| 4137 |
} |
| 4138 |
) |
| 4139 |
assert result is False |
| 4140 |
cancel.assert_called_once_with( |
| 4141 |
"m.unexpected_message", "SAS verification has not started" |
| 4142 |
) |
| 4143 |
|
| 4144 |
verifier.active["sas"] = mock.Mock() |
| 4145 |
for event_type, method in ( |
| 4146 |
(matrix_sas.EVENT_KEY, "_handle_key"), |
| 4147 |
(matrix_sas.EVENT_MAC, "_handle_mac"), |
| 4148 |
(matrix_sas.EVENT_DONE, "_handle_done"), |
| 4149 |
): |
| 4150 |
with mock.patch.object(verifier, method, return_value=None) as h: |
| 4151 |
result = verifier._handle_event( |
| 4152 |
{ |
| 4153 |
"type": event_type, |
| 4154 |
"sender": obj.user_id, |
| 4155 |
"content": {"transaction_id": "tx"}, |
| 4156 |
} |
| 4157 |
) |
| 4158 |
assert result is None |
| 4159 |
h.assert_called_once() |
| 4160 |
|
| 4161 |
assert ( |
| 4162 |
verifier._handle_event( |
| 4163 |
{ |
| 4164 |
"type": "m.some.other.event", |
| 4165 |
"sender": obj.user_id, |
| 4166 |
"content": {"transaction_id": "tx"}, |
| 4167 |
} |
| 4168 |
) |
| 4169 |
is None |
| 4170 |
) |
| 4171 |
|
| 4172 |
|
| 4173 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4174 |
def test_plugin_matrix_sas_run_loop_mechanics(): |
| 4175 |
"""run() covers sync failure, malformed responses, the since token, |
| 4176 |
early termination, and timeout handling.""" |
| 4177 |
obj = _matrix_sas_plugin() |
| 4178 |
|
| 4179 |
# Sync itself fails outright. |
| 4180 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4181 |
with mock.patch.object(obj, "_fetch", return_value=(False, {}, 500)): |
| 4182 |
assert verifier.run() is False |
| 4183 |
|
| 4184 |
# Sync succeeds but returns a non-dict body. |
| 4185 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4186 |
with mock.patch.object( |
| 4187 |
obj, "_fetch", return_value=(True, [], requests.codes.ok) |
| 4188 |
): |
| 4189 |
assert verifier.run() is False |
| 4190 |
|
| 4191 |
# Reject missing or invalid sync tokens instead of polling repeatedly. |
| 4192 |
for bad_batch_response in ( |
| 4193 |
{"to_device": {"events": []}}, |
| 4194 |
{"next_batch": None, "to_device": {"events": []}}, |
| 4195 |
{"next_batch": "", "to_device": {"events": []}}, |
| 4196 |
{"next_batch": 123, "to_device": {"events": []}}, |
| 4197 |
): |
| 4198 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4199 |
with mock.patch.object( |
| 4200 |
obj, |
| 4201 |
"_fetch", |
| 4202 |
return_value=(True, bad_batch_response, requests.codes.ok), |
| 4203 |
): |
| 4204 |
assert verifier.run() is False |
| 4205 |
|
| 4206 |
# A non-list "events" value is treated as empty rather than crashing. |
| 4207 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4208 |
responses = iter( |
| 4209 |
[ |
| 4210 |
( |
| 4211 |
True, |
| 4212 |
{ |
| 4213 |
"next_batch": "1", |
| 4214 |
"to_device": {"events": "not-a-list"}, |
| 4215 |
}, |
| 4216 |
requests.codes.ok, |
| 4217 |
), |
| 4218 |
(False, {}, 500), |
| 4219 |
] |
| 4220 |
) |
| 4221 |
with mock.patch.object( |
| 4222 |
obj, "_fetch", side_effect=lambda *a, **k: next(responses) |
| 4223 |
): |
| 4224 |
assert verifier.run() is False |
| 4225 |
|
| 4226 |
# A present-but-null "to_device" field is treated the same way. |
| 4227 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4228 |
responses = iter( |
| 4229 |
[ |
| 4230 |
(True, {"next_batch": "1", "to_device": None}, requests.codes.ok), |
| 4231 |
(False, {}, 500), |
| 4232 |
] |
| 4233 |
) |
| 4234 |
with mock.patch.object( |
| 4235 |
obj, "_fetch", side_effect=lambda *a, **k: next(responses) |
| 4236 |
): |
| 4237 |
assert verifier.run() is False |
| 4238 |
|
| 4239 |
# Skip malformed events and continue polling. |
| 4240 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4241 |
responses = iter( |
| 4242 |
[ |
| 4243 |
( |
| 4244 |
True, |
| 4245 |
{ |
| 4246 |
"next_batch": "1", |
| 4247 |
"to_device": {"events": [{"type": "x"}]}, |
| 4248 |
}, |
| 4249 |
requests.codes.ok, |
| 4250 |
), |
| 4251 |
(False, {}, 500), |
| 4252 |
] |
| 4253 |
) |
| 4254 |
with ( |
| 4255 |
mock.patch.object( |
| 4256 |
obj, "_fetch", side_effect=lambda *a, **k: next(responses) |
| 4257 |
), |
| 4258 |
mock.patch.object( |
| 4259 |
verifier, "_handle_event", side_effect=AttributeError("boom") |
| 4260 |
), |
| 4261 |
): |
| 4262 |
assert verifier.run() is False |
| 4263 |
|
| 4264 |
# Stop processing an oversized event batch at the deadline. |
| 4265 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4266 |
# Set the construction-time deadline directly for this mocked clock. |
| 4267 |
verifier.deadline = 100 |
| 4268 |
with ( |
| 4269 |
mock.patch.object( |
| 4270 |
obj, |
| 4271 |
"_fetch", |
| 4272 |
return_value=( |
| 4273 |
True, |
| 4274 |
{ |
| 4275 |
"next_batch": "1", |
| 4276 |
"to_device": {"events": [{"type": "a"}, {"type": "b"}]}, |
| 4277 |
}, |
| 4278 |
requests.codes.ok, |
| 4279 |
), |
| 4280 |
), |
| 4281 |
mock.patch.object(verifier, "_handle_event", return_value=None) as h, |
| 4282 |
mock.patch( |
| 4283 |
"apprise.plugins.matrix.sas.monotonic", |
| 4284 |
# while-check, remaining_ms, _bounded_fetch's own check, |
| 4285 |
# post-event-1 check, post-event-2 check (breaks), while |
| 4286 |
# re-check (exits). |
| 4287 |
side_effect=[1, 1, 1, 50, 150, 200], |
| 4288 |
), |
| 4289 |
): |
| 4290 |
assert verifier.run() is False |
| 4291 |
# The expired batch must not trigger another sync. |
| 4292 |
assert h.call_count == 2 |
| 4293 |
|
| 4294 |
# A terminal per-event result short-circuits the loop. |
| 4295 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4296 |
with ( |
| 4297 |
mock.patch.object( |
| 4298 |
obj, |
| 4299 |
"_fetch", |
| 4300 |
return_value=( |
| 4301 |
True, |
| 4302 |
{ |
| 4303 |
"next_batch": "1", |
| 4304 |
"to_device": {"events": [{"type": "x"}]}, |
| 4305 |
}, |
| 4306 |
requests.codes.ok, |
| 4307 |
), |
| 4308 |
), |
| 4309 |
mock.patch.object(verifier, "_handle_event", return_value=True), |
| 4310 |
): |
| 4311 |
assert verifier.run() is True |
| 4312 |
|
| 4313 |
# The since token from one iteration is threaded into the next, and |
| 4314 |
# the reduced long-poll timeout is what actually gets sent. |
| 4315 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4316 |
calls = [] |
| 4317 |
|
| 4318 |
def fake_fetch(path, params=None, method="GET", **kwargs): |
| 4319 |
calls.append(params) |
| 4320 |
if len(calls) == 1: |
| 4321 |
return ( |
| 4322 |
True, |
| 4323 |
{"next_batch": "abc", "to_device": {"events": []}}, |
| 4324 |
requests.codes.ok, |
| 4325 |
) |
| 4326 |
return (False, {}, 500) |
| 4327 |
|
| 4328 |
with mock.patch.object(obj, "_fetch", side_effect=fake_fetch): |
| 4329 |
assert verifier.run() is False |
| 4330 |
assert "since" not in calls[0] |
| 4331 |
assert calls[0]["timeout"] == int(obj.socket_read_timeout * 1000 / 2) |
| 4332 |
assert calls[1]["since"] == "abc" |
| 4333 |
|
| 4334 |
# Deadline reached with no active transaction -- fails closed with no |
| 4335 |
# network call for the no-op cancellation. Configure it before creation. |
| 4336 |
obj.default_autoverify_timeout_sec = 0 |
| 4337 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4338 |
with mock.patch.object(obj, "_fetch") as fetch: |
| 4339 |
assert verifier.run() is False |
| 4340 |
fetch.assert_not_called() |
| 4341 |
|
| 4342 |
# Deadline reached with an active transaction -- the peer is told. |
| 4343 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4344 |
verifier.active = { |
| 4345 |
"transaction_id": "tx", |
| 4346 |
"user_id": "@peer:h", |
| 4347 |
"device_id": "DEV", |
| 4348 |
} |
| 4349 |
with mock.patch.object( |
| 4350 |
obj, "_fetch", return_value=(True, {}, requests.codes.ok) |
| 4351 |
) as fetch: |
| 4352 |
assert verifier.run() is False |
| 4353 |
assert fetch.call_args[0][0].startswith( |
| 4354 |
"/sendToDevice/m.key.verification.cancel/" |
| 4355 |
) |
| 4356 |
obj.default_autoverify_timeout_sec = ( |
| 4357 |
NotifyMatrix.default_autoverify_timeout_sec |
| 4358 |
) |
| 4359 |
|
| 4360 |
|
| 4361 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4362 |
def test_plugin_matrix_sas_poll_timeout_margin(): |
| 4363 |
"""Sync uses bounded timeouts and does not mark the account online.""" |
| 4364 |
import json |
| 4365 |
|
| 4366 |
obj = _matrix_sas_plugin() |
| 4367 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4368 |
|
| 4369 |
with mock.patch.object( |
| 4370 |
obj, "_fetch", return_value=(False, {}, 500) |
| 4371 |
) as fetch: |
| 4372 |
assert verifier.run() is False |
| 4373 |
sent_params = fetch.call_args.kwargs["params"] |
| 4374 |
assert sent_params["timeout"] == int(obj.socket_read_timeout * 1000 / 2) |
| 4375 |
assert sent_params["timeout"] < obj.socket_read_timeout * 1000 |
| 4376 |
assert sent_params["set_presence"] == "offline" |
| 4377 |
|
| 4378 |
# Both HTTP timeouts use the sanitized polling budget. |
| 4379 |
fetch_timeout = fetch.call_args.kwargs["timeout"] |
| 4380 |
expected = pytest.approx(sent_params["timeout"] / 1000 + 2) |
| 4381 |
assert fetch_timeout[0] == expected |
| 4382 |
assert fetch_timeout[1] == expected |
| 4383 |
assert fetch_timeout[1] < obj.socket_read_timeout * 10 # sane, not huge |
| 4384 |
|
| 4385 |
# A 429 mid-poll must not be allowed to wait out the server's own |
| 4386 |
# arbitrary requested delay past what remains of this attempt. |
| 4387 |
assert fetch.call_args.kwargs["max_retry_wait"] == pytest.approx( |
| 4388 |
obj.default_autoverify_timeout_sec, abs=1 |
| 4389 |
) |
| 4390 |
|
| 4391 |
# Check filter behavior, including that any limits are positive. |
| 4392 |
parsed_filter = json.loads(sent_params["filter"]) |
| 4393 |
assert parsed_filter["room"]["rooms"] == [] |
| 4394 |
assert parsed_filter["presence"]["types"] == [] |
| 4395 |
assert parsed_filter["account_data"]["types"] == [] |
| 4396 |
|
| 4397 |
def _walk_limits(node): |
| 4398 |
if isinstance(node, dict): |
| 4399 |
if "limit" in node: |
| 4400 |
yield node["limit"] |
| 4401 |
for value in node.values(): |
| 4402 |
yield from _walk_limits(value) |
| 4403 |
elif isinstance(node, list): |
| 4404 |
for value in node: |
| 4405 |
yield from _walk_limits(value) |
| 4406 |
|
| 4407 |
assert all(limit > 0 for limit in _walk_limits(parsed_filter)) |
| 4408 |
|
| 4409 |
# A custom ?rto= override scales the poll with it. |
| 4410 |
custom = NotifyMatrix( |
| 4411 |
host="h", user="u", password="pass", targets=["#r"], rto=10.0 |
| 4412 |
) |
| 4413 |
custom.user_id = obj.user_id |
| 4414 |
custom.device_id = obj.device_id |
| 4415 |
custom._e2ee_account = obj._e2ee_account |
| 4416 |
custom_verifier = matrix_sas.MatrixSASAutoVerifier(custom) |
| 4417 |
with mock.patch.object( |
| 4418 |
custom, "_fetch", return_value=(False, {}, 500) |
| 4419 |
) as fetch: |
| 4420 |
assert custom_verifier.run() is False |
| 4421 |
assert fetch.call_args.kwargs["params"]["timeout"] == 5000 |
| 4422 |
|
| 4423 |
|
| 4424 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4425 |
def test_plugin_matrix_sas_expired_fetch(): |
| 4426 |
"""Do not start helper requests after the attempt deadline.""" |
| 4427 |
obj = _matrix_sas_plugin() |
| 4428 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4429 |
verifier.deadline = 0 # already expired relative to real monotonic time |
| 4430 |
|
| 4431 |
with mock.patch.object(obj, "_fetch") as fetch: |
| 4432 |
result = verifier._bounded_fetch("/keys/query", payload={}) |
| 4433 |
|
| 4434 |
fetch.assert_not_called() |
| 4435 |
assert result == (False, {}, None) |
| 4436 |
|
| 4437 |
|
| 4438 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4439 |
def test_plugin_matrix_sas_expired_best_effort_fetch(): |
| 4440 |
"""A best-effort call still fires once the deadline has passed. |
| 4441 |
|
| 4442 |
The terminal cancellation notice is deliberately sent past the |
| 4443 |
deadline -- that is exactly why the attempt is ending. |
| 4444 |
""" |
| 4445 |
obj = _matrix_sas_plugin() |
| 4446 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4447 |
verifier.deadline = 0 # already expired relative to real monotonic time |
| 4448 |
|
| 4449 |
with mock.patch.object( |
| 4450 |
obj, "_fetch", return_value=(True, {}, requests.codes.ok) |
| 4451 |
) as fetch: |
| 4452 |
result = verifier._bounded_fetch( |
| 4453 |
"/keys/query", payload={}, best_effort=True |
| 4454 |
) |
| 4455 |
|
| 4456 |
fetch.assert_called_once() |
| 4457 |
assert result == (True, {}, requests.codes.ok) |
| 4458 |
|
| 4459 |
|
| 4460 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4461 |
def test_plugin_matrix_sas_fetch_response_limit(): |
| 4462 |
"""Every SAS request bounds how large a response it will accept.""" |
| 4463 |
obj = _matrix_sas_plugin() |
| 4464 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4465 |
|
| 4466 |
with mock.patch.object( |
| 4467 |
obj, "_fetch", return_value=(True, {}, requests.codes.ok) |
| 4468 |
) as fetch: |
| 4469 |
verifier._bounded_fetch("/keys/query", payload={}) |
| 4470 |
|
| 4471 |
assert ( |
| 4472 |
fetch.call_args.kwargs["max_response_bytes"] |
| 4473 |
== matrix_sas.MAX_RESPONSE_BYTES |
| 4474 |
) |
| 4475 |
|
| 4476 |
|
| 4477 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4478 |
def test_plugin_matrix_sas_invalid_read_timeout(): |
| 4479 |
"""Invalid read timeouts use the safe polling fallback.""" |
| 4480 |
obj = _matrix_sas_plugin() |
| 4481 |
|
| 4482 |
for bad_value in ( |
| 4483 |
float("nan"), |
| 4484 |
float("inf"), |
| 4485 |
float("-inf"), |
| 4486 |
0.0, |
| 4487 |
-5.0, |
| 4488 |
# Finite on its own, but 1e306 * 1000 overflows to inf -- this |
| 4489 |
# must be caught too, not just outright non-finite input. |
| 4490 |
1e306, |
| 4491 |
): |
| 4492 |
obj.socket_read_timeout = bad_value |
| 4493 |
assert ( |
| 4494 |
matrix_sas._sync_poll_ms(obj) == matrix_sas.FALLBACK_SYNC_POLL_MS |
| 4495 |
) |
| 4496 |
|
| 4497 |
obj.socket_read_timeout = 8.0 |
| 4498 |
assert matrix_sas._sync_poll_ms(obj) == 4000 |
| 4499 |
|
| 4500 |
# A tiny-but-valid timeout floors to a usable minimum poll rather |
| 4501 |
# than truncating toward a near-zero, busy-looping value. |
| 4502 |
obj.socket_read_timeout = 0.0001 |
| 4503 |
assert matrix_sas._sync_poll_ms(obj) == matrix_sas.MIN_SYNC_POLL_MS |
| 4504 |
|
| 4505 |
# The full run() loop must not raise either. |
| 4506 |
obj.socket_read_timeout = float("nan") |
| 4507 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4508 |
with mock.patch.object( |
| 4509 |
obj, "_fetch", return_value=(False, {}, 500) |
| 4510 |
) as fetch: |
| 4511 |
assert verifier.run() is False |
| 4512 |
assert ( |
| 4513 |
fetch.call_args.kwargs["params"]["timeout"] |
| 4514 |
== matrix_sas.FALLBACK_SYNC_POLL_MS |
| 4515 |
) |
| 4516 |
|
| 4517 |
|
| 4518 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4519 |
def test_plugin_matrix_sas_poll_capped_by_deadline(): |
| 4520 |
"""The verification deadline also caps each poll request.""" |
| 4521 |
obj = _matrix_sas_plugin() |
| 4522 |
obj.socket_read_timeout = 600.0 # would otherwise poll for 300s |
| 4523 |
obj.default_autoverify_timeout_sec = 5 |
| 4524 |
|
| 4525 |
verifier = matrix_sas.MatrixSASAutoVerifier(obj) |
| 4526 |
with mock.patch.object( |
| 4527 |
obj, "_fetch", return_value=(False, {}, 500) |
| 4528 |
) as fetch: |
| 4529 |
assert verifier.run() is False |
| 4530 |
sent_timeout = fetch.call_args.kwargs["params"]["timeout"] |
| 4531 |
assert sent_timeout <= 5000 |
| 4532 |
assert sent_timeout < int(obj.socket_read_timeout * 1000 / 2) |
| 4533 |
obj.default_autoverify_timeout_sec = ( |
| 4534 |
NotifyMatrix.default_autoverify_timeout_sec |
| 4535 |
) |
| 4536 |
|
| 4537 |
|
| 4538 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4539 |
def test_plugin_matrix_sas_auto_verify_fast_paths(): |
| 4540 |
"""auto_verify() short-circuits when already verified or when the |
| 4541 |
plugin identity is not ready yet.""" |
| 4542 |
obj = _matrix_sas_plugin() |
| 4543 |
binding = obj._e2ee_binding_key() |
| 4544 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 4545 |
obj.store.set("e2ee_verified_binding", binding, expires=60) |
| 4546 |
with mock.patch.object(obj, "_fetch") as fetch: |
| 4547 |
assert matrix_sas.auto_verify(obj) is True |
| 4548 |
fetch.assert_not_called() |
| 4549 |
|
| 4550 |
obj2 = NotifyMatrix( |
| 4551 |
host="h", |
| 4552 |
user="u", |
| 4553 |
password="pass", |
| 4554 |
targets=["#r"], |
| 4555 |
e2ee=True, |
| 4556 |
autoverify=True, |
| 4557 |
) |
| 4558 |
assert matrix_sas.auto_verify(obj2) is False |
| 4559 |
|
| 4560 |
obj3 = _matrix_sas_plugin() |
| 4561 |
obj3.store.set("e2ee_device_binding", "unverified", expires=60) |
| 4562 |
with mock.patch.object( |
| 4563 |
matrix_sas.MatrixSASAutoVerifier, "run", return_value=True |
| 4564 |
) as run: |
| 4565 |
assert matrix_sas.auto_verify(obj3) is True |
| 4566 |
run.assert_called_once() |
| 4567 |
|
| 4568 |
|
| 4569 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4570 |
def test_plugin_matrix_sas_auto_verify_cooldown(): |
| 4571 |
"""A failed attempt sets a cooldown so every later send is not |
| 4572 |
blocked for the full timeout until it expires.""" |
| 4573 |
obj = _matrix_sas_plugin() |
| 4574 |
binding = obj._e2ee_binding_key() |
| 4575 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 4576 |
|
| 4577 |
with mock.patch.object( |
| 4578 |
matrix_sas.MatrixSASAutoVerifier, "run", return_value=False |
| 4579 |
) as run: |
| 4580 |
assert matrix_sas.auto_verify(obj) is False |
| 4581 |
run.assert_called_once() |
| 4582 |
|
| 4583 |
# The next call in the cooldown window returns immediately -- no new |
| 4584 |
# attempt, no network call. |
| 4585 |
with mock.patch.object(matrix_sas.MatrixSASAutoVerifier, "run") as run: |
| 4586 |
assert matrix_sas.auto_verify(obj) is False |
| 4587 |
run.assert_not_called() |
| 4588 |
|
| 4589 |
# A changed identity is not blocked by another identity's cooldown. |
| 4590 |
obj.store.set("e2ee_device_binding", "a-different-binding", expires=60) |
| 4591 |
with mock.patch.object( |
| 4592 |
matrix_sas.MatrixSASAutoVerifier, "run", return_value=True |
| 4593 |
) as run: |
| 4594 |
assert matrix_sas.auto_verify(obj) is True |
| 4595 |
run.assert_called_once() |
| 4596 |
|
| 4597 |
|
| 4598 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4599 |
def test_plugin_matrix_sas_auto_verify_concurrency(): |
| 4600 |
"""Let concurrent callers deliver while one caller verifies.""" |
| 4601 |
import threading as _threading |
| 4602 |
import time as _time |
| 4603 |
|
| 4604 |
obj = _matrix_sas_plugin() |
| 4605 |
obj.store.set("e2ee_device_binding", obj._e2ee_binding_key(), expires=60) |
| 4606 |
|
| 4607 |
state_lock = _threading.Lock() |
| 4608 |
active = 0 |
| 4609 |
max_concurrent = 0 |
| 4610 |
calls = 0 |
| 4611 |
|
| 4612 |
def fake_run(_self): |
| 4613 |
nonlocal active, max_concurrent, calls |
| 4614 |
with state_lock: |
| 4615 |
active += 1 |
| 4616 |
max_concurrent = max(max_concurrent, active) |
| 4617 |
calls += 1 |
| 4618 |
# Long enough that a blocking wait for this call would make the |
| 4619 |
# elapsed-time assertion below fail. |
| 4620 |
_time.sleep(1.0) |
| 4621 |
with state_lock: |
| 4622 |
active -= 1 |
| 4623 |
return True |
| 4624 |
|
| 4625 |
results = [] |
| 4626 |
|
| 4627 |
def call_auto_verify(): |
| 4628 |
results.append(matrix_sas.auto_verify(obj)) |
| 4629 |
|
| 4630 |
with mock.patch.object(matrix_sas.MatrixSASAutoVerifier, "run", fake_run): |
| 4631 |
threads = [ |
| 4632 |
_threading.Thread(target=call_auto_verify) for _ in range(4) |
| 4633 |
] |
| 4634 |
start = _time.monotonic() |
| 4635 |
for thread in threads: |
| 4636 |
thread.start() |
| 4637 |
for thread in threads: |
| 4638 |
thread.join(timeout=15) |
| 4639 |
elapsed = _time.monotonic() - start |
| 4640 |
|
| 4641 |
# The group finishes near the single verifier's running time. |
| 4642 |
assert elapsed < 2.5 |
| 4643 |
assert calls == 1 |
| 4644 |
assert max_concurrent == 1 |
| 4645 |
assert results.count(True) == 1 |
| 4646 |
assert results.count(False) == 3 |
| 4647 |
|
| 4648 |
|
| 4649 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4650 |
def test_plugin_matrix_sas_refresh_concurrency(): |
| 4651 |
"""A concurrent refresh does not wait on an in-progress verification. |
| 4652 |
|
| 4653 |
The verification lock can be held by a live SAS exchange for up to the |
| 4654 |
full attempt timeout; refreshing trust must not block behind it. |
| 4655 |
""" |
| 4656 |
import time as _time |
| 4657 |
|
| 4658 |
obj = _matrix_sas_plugin() |
| 4659 |
|
| 4660 |
# Simulate a verification attempt already holding the lock. |
| 4661 |
obj._autoverify_lock.acquire() |
| 4662 |
try: |
| 4663 |
start = _time.monotonic() |
| 4664 |
result = matrix_sas.refresh_verified_state(obj) |
| 4665 |
elapsed = _time.monotonic() - start |
| 4666 |
finally: |
| 4667 |
obj._autoverify_lock.release() |
| 4668 |
|
| 4669 |
assert result is False |
| 4670 |
# Non-blocking lock acquisition never waits on the held lock; this is |
| 4671 |
# only guarding against an accidental blocking wait being introduced, |
| 4672 |
# so leave generous headroom for slow/loaded CI machines. |
| 4673 |
assert elapsed < 2.0 |
| 4674 |
|
| 4675 |
|
| 4676 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4677 |
def test_plugin_matrix_sas_store_verified_binding(): |
| 4678 |
"""store_verified_binding no-ops without a device binding to trust.""" |
| 4679 |
obj = _matrix_sas_plugin() |
| 4680 |
assert matrix_sas.store_verified_binding(obj) is False |
| 4681 |
|
| 4682 |
obj.store.set("e2ee_device_binding", "B", expires=60) |
| 4683 |
assert matrix_sas.store_verified_binding(obj) is True |
| 4684 |
assert obj.store.get("e2ee_verified_binding") == "B" |
| 4685 |
|
| 4686 |
|
| 4687 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4688 |
def test_plugin_matrix_sas_refresh_state(): |
| 4689 |
"""Trust refresh requires matching identities and successful writes.""" |
| 4690 |
obj = _matrix_sas_plugin() |
| 4691 |
assert matrix_sas.refresh_verified_state(obj) is False |
| 4692 |
|
| 4693 |
binding = obj._e2ee_binding_key() |
| 4694 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 4695 |
assert matrix_sas.refresh_verified_state(obj) is False |
| 4696 |
|
| 4697 |
obj.store.set("e2ee_verified_binding", binding, expires=60) |
| 4698 |
|
| 4699 |
obj.device_id = "OTHERDEV" |
| 4700 |
assert matrix_sas.refresh_verified_state(obj) is False |
| 4701 |
obj.device_id = "APPRISE" |
| 4702 |
|
| 4703 |
with mock.patch.object( |
| 4704 |
obj.store, "set", side_effect=[True, False, True, True] |
| 4705 |
): |
| 4706 |
assert matrix_sas.refresh_verified_state(obj) is False |
| 4707 |
|
| 4708 |
assert matrix_sas.refresh_verified_state(obj) is True |
| 4709 |
|
| 4710 |
|
| 4711 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4712 |
def test_plugin_matrix_sas_auto_verify_flow(): |
| 4713 |
"""Exercise the full same-user SAS event flow.""" |
| 4714 |
import re |
| 4715 |
from time import time |
| 4716 |
|
| 4717 |
from cryptography.hazmat.primitives.asymmetric.x25519 import ( |
| 4718 |
X25519PrivateKey, |
| 4719 |
X25519PublicKey, |
| 4720 |
) |
| 4721 |
from cryptography.hazmat.primitives.serialization import ( |
| 4722 |
Encoding, |
| 4723 |
PublicFormat, |
| 4724 |
) |
| 4725 |
|
| 4726 |
from apprise.plugins.matrix.e2ee import ( |
| 4727 |
MatrixOlmAccount, |
| 4728 |
_b64dec, |
| 4729 |
_b64enc, |
| 4730 |
_hkdf_sha256, |
| 4731 |
_hmac_sha256, |
| 4732 |
) |
| 4733 |
|
| 4734 |
user_id = "@u:h" |
| 4735 |
own_device = "APPRISE" |
| 4736 |
peer_device = "ELEMENT" |
| 4737 |
transaction_id = "sas-flow" |
| 4738 |
own_account = MatrixOlmAccount() |
| 4739 |
peer_account = MatrixOlmAccount() |
| 4740 |
peer_private = X25519PrivateKey.generate() |
| 4741 |
peer_public = _b64enc( |
| 4742 |
peer_private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) |
| 4743 |
) |
| 4744 |
peer_device_keys = peer_account.device_keys_payload(user_id, peer_device) |
| 4745 |
|
| 4746 |
obj = NotifyMatrix( |
| 4747 |
host="h", |
| 4748 |
user="u", |
| 4749 |
password="pass", |
| 4750 |
targets=["#r"], |
| 4751 |
e2ee=True, |
| 4752 |
autoverify=True, |
| 4753 |
) |
| 4754 |
obj.user_id = user_id |
| 4755 |
obj.device_id = own_device |
| 4756 |
obj._e2ee_account = own_account |
| 4757 |
binding = obj._e2ee_binding_key() |
| 4758 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 4759 |
|
| 4760 |
sent = [] |
| 4761 |
sync_index = 0 |
| 4762 |
|
| 4763 |
def fake_fetch(path, payload=None, params=None, method="POST", **kwargs): |
| 4764 |
nonlocal sync_index |
| 4765 |
if path == "/keys/query": |
| 4766 |
return ( |
| 4767 |
True, |
| 4768 |
{"device_keys": {user_id: {peer_device: peer_device_keys}}}, |
| 4769 |
requests.codes.ok, |
| 4770 |
) |
| 4771 |
if path.startswith("/sendToDevice/"): |
| 4772 |
assert re.match(r"^/sendToDevice/[^/]+/[0-9a-f]{32}$", path) |
| 4773 |
event_type = path.split("/")[2] |
| 4774 |
target_user, devices = next(iter(payload["messages"].items())) |
| 4775 |
_target_device, content = next(iter(devices.items())) |
| 4776 |
sent.append((event_type, target_user, content)) |
| 4777 |
return (True, {}, requests.codes.ok) |
| 4778 |
|
| 4779 |
assert path == "/sync" |
| 4780 |
if sync_index == 0: |
| 4781 |
event_type = "m.key.verification.request" |
| 4782 |
content = { |
| 4783 |
"from_device": peer_device, |
| 4784 |
"transaction_id": transaction_id, |
| 4785 |
"methods": ["m.sas.v1"], |
| 4786 |
"timestamp": int(time() * 1000), |
| 4787 |
} |
| 4788 |
elif sync_index == 1: |
| 4789 |
event_type = "m.key.verification.start" |
| 4790 |
content = { |
| 4791 |
"from_device": peer_device, |
| 4792 |
"transaction_id": transaction_id, |
| 4793 |
"method": "m.sas.v1", |
| 4794 |
"key_agreement_protocols": ["curve25519-hkdf-sha256"], |
| 4795 |
"hashes": ["sha256"], |
| 4796 |
"message_authentication_codes": ["hkdf-hmac-sha256.v2"], |
| 4797 |
"short_authentication_string": ["decimal", "emoji"], |
| 4798 |
} |
| 4799 |
elif sync_index == 2: |
| 4800 |
event_type = "m.key.verification.key" |
| 4801 |
content = { |
| 4802 |
"transaction_id": transaction_id, |
| 4803 |
"key": peer_public, |
| 4804 |
} |
| 4805 |
elif sync_index == 3: |
| 4806 |
event_type = "m.key.verification.mac" |
| 4807 |
own_key_event = next( |
| 4808 |
item for item in sent if item[0] == "m.key.verification.key" |
| 4809 |
) |
| 4810 |
own_public = own_key_event[2]["key"] |
| 4811 |
shared_secret = peer_private.exchange( |
| 4812 |
X25519PublicKey.from_public_bytes(_b64dec(own_public)) |
| 4813 |
) |
| 4814 |
key_id = "ed25519:{}".format(peer_device) |
| 4815 |
|
| 4816 |
def calculate_mac(value, info_key_id): |
| 4817 |
info = ( |
| 4818 |
"MATRIX_KEY_VERIFICATION_MAC" |
| 4819 |
+ user_id |
| 4820 |
+ peer_device |
| 4821 |
+ user_id |
| 4822 |
+ own_device |
| 4823 |
+ transaction_id |
| 4824 |
+ info_key_id |
| 4825 |
).encode("utf-8") |
| 4826 |
key = _hkdf_sha256(shared_secret, 32, salt=None, info=info) |
| 4827 |
return _b64enc(_hmac_sha256(key, value.encode("utf-8"))) |
| 4828 |
|
| 4829 |
content = { |
| 4830 |
"transaction_id": transaction_id, |
| 4831 |
"mac": { |
| 4832 |
key_id: calculate_mac(peer_account.signing_key, key_id) |
| 4833 |
}, |
| 4834 |
"keys": calculate_mac(key_id, "KEY_IDS"), |
| 4835 |
} |
| 4836 |
else: |
| 4837 |
event_type = "m.key.verification.done" |
| 4838 |
content = {"transaction_id": transaction_id} |
| 4839 |
|
| 4840 |
sync_index += 1 |
| 4841 |
return ( |
| 4842 |
True, |
| 4843 |
{ |
| 4844 |
"next_batch": "sync-{}".format(sync_index), |
| 4845 |
"to_device": { |
| 4846 |
"events": [ |
| 4847 |
{ |
| 4848 |
"type": event_type, |
| 4849 |
"sender": user_id, |
| 4850 |
"content": content, |
| 4851 |
} |
| 4852 |
] |
| 4853 |
}, |
| 4854 |
}, |
| 4855 |
requests.codes.ok, |
| 4856 |
) |
| 4857 |
|
| 4858 |
with mock.patch.object(obj, "_fetch", side_effect=fake_fetch): |
| 4859 |
assert obj._e2ee_auto_verify() is True |
| 4860 |
|
| 4861 |
assert [item[0] for item in sent] == [ |
| 4862 |
"m.key.verification.ready", |
| 4863 |
"m.key.verification.accept", |
| 4864 |
"m.key.verification.key", |
| 4865 |
"m.key.verification.mac", |
| 4866 |
"m.key.verification.done", |
| 4867 |
] |
| 4868 |
assert obj.store.get("e2ee_verified_binding") == binding |
| 4869 |
|
| 4870 |
|
| 4871 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4872 |
def test_plugin_matrix_sas_failure_allows_send(): |
| 4873 |
"""A failed SAS bootstrap does not prevent message delivery.""" |
| 4874 |
obj = NotifyMatrix( |
| 4875 |
host="h", |
| 4876 |
user="u", |
| 4877 |
password="pass", |
| 4878 |
targets=["#r"], |
| 4879 |
e2ee=True, |
| 4880 |
autoverify=True, |
| 4881 |
secure=True, |
| 4882 |
) |
| 4883 |
obj.access_token = "token" |
| 4884 |
obj.user_id = "@u:h" |
| 4885 |
obj.device_id = "APPRISE" |
| 4886 |
|
| 4887 |
with ( |
| 4888 |
mock.patch.object(obj, "_e2ee_setup", return_value=True), |
| 4889 |
mock.patch.object( |
| 4890 |
obj, "_e2ee_auto_verify", return_value=False |
| 4891 |
) as verify, |
| 4892 |
mock.patch.object(obj, "_room_join", return_value="!r:h") as join, |
| 4893 |
mock.patch.object(obj, "_e2ee_room_encrypted", return_value=True), |
| 4894 |
mock.patch.object( |
| 4895 |
obj, "_e2ee_send_to_room", return_value=True |
| 4896 |
) as send, |
| 4897 |
mock.patch.object( |
| 4898 |
obj, "_e2ee_refresh_verified_state", return_value=False |
| 4899 |
), |
| 4900 |
): |
| 4901 |
assert obj._send_server_notification(body="test") is True |
| 4902 |
|
| 4903 |
verify.assert_called_once() |
| 4904 |
join.assert_called_once() |
| 4905 |
send.assert_called_once() |
| 4906 |
|
| 4907 |
|
| 4908 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4909 |
def test_plugin_matrix_sas_refresh_is_minimal(): |
| 4910 |
"""Only identity state required to retain SAS trust is refreshed.""" |
| 4911 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 4912 |
|
| 4913 |
obj = NotifyMatrix( |
| 4914 |
host="h", |
| 4915 |
user="u", |
| 4916 |
password="pass", |
| 4917 |
targets=["#r"], |
| 4918 |
e2ee=True, |
| 4919 |
autoverify=True, |
| 4920 |
secure=True, |
| 4921 |
) |
| 4922 |
obj.user_id = "@u:h" |
| 4923 |
obj.device_id = "APPRISE" |
| 4924 |
obj._e2ee_account = MatrixOlmAccount() |
| 4925 |
binding = "{}|{}|{}|{}".format( |
| 4926 |
obj.user_id, |
| 4927 |
obj.device_id, |
| 4928 |
obj._e2ee_account.identity_key, |
| 4929 |
obj._e2ee_account.signing_key, |
| 4930 |
) |
| 4931 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 4932 |
obj.store.set("e2ee_verified_binding", binding, expires=60) |
| 4933 |
|
| 4934 |
with mock.patch.object(obj.store, "set", wraps=obj.store.set) as store_set: |
| 4935 |
assert obj._e2ee_refresh_verified_state() is True |
| 4936 |
|
| 4937 |
assert [call.args[0] for call in store_set.call_args_list] == [ |
| 4938 |
"device_id", |
| 4939 |
"e2ee_account", |
| 4940 |
"e2ee_device_binding", |
| 4941 |
"e2ee_verified_binding", |
| 4942 |
"e2ee_autoverify_refreshed_at", |
| 4943 |
] |
| 4944 |
assert all( |
| 4945 |
call.kwargs["expires"] == obj.default_cache_expiry_sec |
| 4946 |
for call in store_set.call_args_list |
| 4947 |
) |
| 4948 |
|
| 4949 |
|
| 4950 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4951 |
def test_plugin_matrix_sas_refresh_throttled(): |
| 4952 |
"""A recent refresh is skipped entirely -- no rewrite of the |
| 4953 |
serialized E2EE account (or anything else) on every single send.""" |
| 4954 |
from time import time as _time |
| 4955 |
|
| 4956 |
obj = _matrix_sas_plugin() |
| 4957 |
binding = obj._e2ee_binding_key() |
| 4958 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 4959 |
obj.store.set("e2ee_verified_binding", binding, expires=60) |
| 4960 |
obj.store.set("e2ee_autoverify_refreshed_at", _time(), expires=60) |
| 4961 |
|
| 4962 |
with mock.patch.object(obj.store, "set") as store_set: |
| 4963 |
assert matrix_sas.refresh_verified_state(obj) is True |
| 4964 |
store_set.assert_not_called() |
| 4965 |
|
| 4966 |
# Once the interval has genuinely elapsed, it refreshes normally. |
| 4967 |
obj.store.set( |
| 4968 |
"e2ee_autoverify_refreshed_at", |
| 4969 |
_time() - obj.default_autoverify_refresh_interval_sec - 1, |
| 4970 |
expires=60, |
| 4971 |
) |
| 4972 |
with mock.patch.object(obj.store, "set", wraps=obj.store.set) as store_set: |
| 4973 |
assert matrix_sas.refresh_verified_state(obj) is True |
| 4974 |
assert store_set.call_count == 5 |
| 4975 |
|
| 4976 |
|
| 4977 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 4978 |
def test_plugin_matrix_sas_refresh_trust_write_failure(): |
| 4979 |
"""A failed write of the trust marker itself must not be reported as |
| 4980 |
success, and must not go on to touch the refresh bookkeeping key.""" |
| 4981 |
obj = _matrix_sas_plugin() |
| 4982 |
binding = obj._e2ee_binding_key() |
| 4983 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 4984 |
obj.store.set("e2ee_verified_binding", binding, expires=60) |
| 4985 |
|
| 4986 |
real_set = obj.store.set |
| 4987 |
|
| 4988 |
def flaky_set(key, *args, **kwargs): |
| 4989 |
if key == "e2ee_verified_binding": |
| 4990 |
return False |
| 4991 |
return real_set(key, *args, **kwargs) |
| 4992 |
|
| 4993 |
with mock.patch.object( |
| 4994 |
obj.store, "set", side_effect=flaky_set |
| 4995 |
) as store_set: |
| 4996 |
assert matrix_sas.refresh_verified_state(obj) is False |
| 4997 |
assert "e2ee_autoverify_refreshed_at" not in [ |
| 4998 |
call.args[0] for call in store_set.call_args_list |
| 4999 |
] |
| 5000 |
|
| 5001 |
|
| 5002 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5003 |
def test_plugin_matrix_sas_refresh_invalid_timestamp(): |
| 5004 |
"""A malformed refresh timestamp is treated as missing.""" |
| 5005 |
obj = _matrix_sas_plugin() |
| 5006 |
binding = obj._e2ee_binding_key() |
| 5007 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 5008 |
obj.store.set("e2ee_verified_binding", binding, expires=60) |
| 5009 |
obj.store.set("e2ee_autoverify_refreshed_at", "not-a-number", expires=60) |
| 5010 |
|
| 5011 |
assert matrix_sas.refresh_verified_state(obj) is True |
| 5012 |
|
| 5013 |
|
| 5014 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5015 |
def test_plugin_matrix_sas_refresh_writes_short_circuit(): |
| 5016 |
"""A failure partway through the identity refresh stops immediately |
| 5017 |
instead of continuing to write (and serialize) the rest regardless.""" |
| 5018 |
obj = _matrix_sas_plugin() |
| 5019 |
binding = obj._e2ee_binding_key() |
| 5020 |
|
| 5021 |
write_order = [ |
| 5022 |
"device_id", |
| 5023 |
"e2ee_account", |
| 5024 |
"e2ee_device_binding", |
| 5025 |
"e2ee_verified_binding", |
| 5026 |
] |
| 5027 |
for fail_at in write_order: |
| 5028 |
obj.store.set("e2ee_device_binding", binding, expires=60) |
| 5029 |
obj.store.set("e2ee_verified_binding", binding, expires=60) |
| 5030 |
|
| 5031 |
def flaky_set( |
| 5032 |
key, *args, _fail_at=fail_at, _real_set=obj.store.set, **kwargs |
| 5033 |
): |
| 5034 |
if key == _fail_at: |
| 5035 |
return False |
| 5036 |
return _real_set(key, *args, **kwargs) |
| 5037 |
|
| 5038 |
with mock.patch.object( |
| 5039 |
obj.store, "set", side_effect=flaky_set |
| 5040 |
) as store_set: |
| 5041 |
assert matrix_sas.refresh_verified_state(obj) is False |
| 5042 |
|
| 5043 |
called_keys = [call.args[0] for call in store_set.call_args_list] |
| 5044 |
# Every key up to and including the failed one was attempted, in |
| 5045 |
# order, and nothing after it was. |
| 5046 |
assert called_keys == write_order[: write_order.index(fail_at) + 1] |
| 5047 |
|
| 5048 |
|
| 5049 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5050 |
@pytest.mark.parametrize("delivery_ok", [True, False]) |
| 5051 |
def test_plugin_matrix_sas_refresh_after_success(delivery_ok): |
| 5052 |
"""A failed Matrix delivery must not extend SAS trust.""" |
| 5053 |
obj = NotifyMatrix( |
| 5054 |
host="h", |
| 5055 |
user="u", |
| 5056 |
password="pass", |
| 5057 |
targets=["#r"], |
| 5058 |
e2ee=True, |
| 5059 |
autoverify=True, |
| 5060 |
secure=True, |
| 5061 |
) |
| 5062 |
obj.access_token = "token" |
| 5063 |
obj.user_id = "@u:h" |
| 5064 |
obj.device_id = "APPRISE" |
| 5065 |
|
| 5066 |
with ( |
| 5067 |
mock.patch.object(obj, "_e2ee_setup", return_value=True), |
| 5068 |
mock.patch.object(obj, "_e2ee_auto_verify", return_value=True), |
| 5069 |
mock.patch.object(obj, "_room_join", return_value="!r:h"), |
| 5070 |
mock.patch.object(obj, "_e2ee_room_encrypted", return_value=True), |
| 5071 |
mock.patch.object(obj, "_e2ee_send_to_room", return_value=delivery_ok), |
| 5072 |
mock.patch.object( |
| 5073 |
obj, "_e2ee_refresh_verified_state", return_value=True |
| 5074 |
) as refresh, |
| 5075 |
): |
| 5076 |
assert obj._send_server_notification(body="test") is delivery_ok |
| 5077 |
|
| 5078 |
assert refresh.call_count == (1 if delivery_ok else 0) |
| 5079 |
|
| 5080 |
|
| 5081 |
def test_plugin_matrix_e2ee_no_cryptography(): |
| 5082 |
"""MATRIX_E2EE_SUPPORT is False when cryptography is unavailable.""" |
| 5083 |
import importlib |
| 5084 |
import sys |
| 5085 |
|
| 5086 |
# Block 'cryptography' so the ImportError branch is taken on reload |
| 5087 |
saved = { |
| 5088 |
k: v for k, v in sys.modules.items() if k.startswith("cryptography") |
| 5089 |
} |
| 5090 |
for key in list(saved): |
| 5091 |
sys.modules[key] = None # type: ignore[assignment] |
| 5092 |
|
| 5093 |
try: |
| 5094 |
import apprise.plugins.matrix.e2ee as e2ee_mod |
| 5095 |
|
| 5096 |
importlib.reload(e2ee_mod) |
| 5097 |
assert e2ee_mod.MATRIX_E2EE_SUPPORT is False |
| 5098 |
finally: |
| 5099 |
# Restore everything so subsequent tests are not broken |
| 5100 |
for key in list(saved): |
| 5101 |
if saved[key] is None: |
| 5102 |
del sys.modules[key] |
| 5103 |
else: |
| 5104 |
sys.modules[key] = saved[key] |
| 5105 |
# Force a clean reload so MATRIX_E2EE_SUPPORT is True again |
| 5106 |
importlib.reload(e2ee_mod) |
| 5107 |
|
| 5108 |
|
| 5109 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5110 |
def test_plugin_matrix_e2ee_olm_account(): |
| 5111 |
"""MatrixOlmAccount creation, signing, serialisation.""" |
| 5112 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 5113 |
|
| 5114 |
# Fresh account |
| 5115 |
acct = MatrixOlmAccount() |
| 5116 |
assert isinstance(acct.identity_key, str) |
| 5117 |
assert isinstance(acct.signing_key, str) |
| 5118 |
|
| 5119 |
# sign() accepts str and bytes |
| 5120 |
sig = acct.sign("hello") |
| 5121 |
assert isinstance(sig, str) |
| 5122 |
sig2 = acct.sign(b"hello") |
| 5123 |
assert isinstance(sig2, str) |
| 5124 |
|
| 5125 |
# to_dict / from_dict round-trip |
| 5126 |
d = acct.to_dict() |
| 5127 |
assert "ik" in d and "sk" in d |
| 5128 |
restored = MatrixOlmAccount.from_dict(d) |
| 5129 |
assert restored.identity_key == acct.identity_key |
| 5130 |
assert restored.signing_key == acct.signing_key |
| 5131 |
|
| 5132 |
# Explicit key construction from stored keys |
| 5133 |
acct2 = MatrixOlmAccount( |
| 5134 |
ik_priv_b64=d["ik"], |
| 5135 |
sk_priv_b64=d["sk"], |
| 5136 |
) |
| 5137 |
assert acct2.identity_key == acct.identity_key |
| 5138 |
|
| 5139 |
# device_keys_payload produces a signed dict |
| 5140 |
payload = acct.device_keys_payload("@u:h", "DEVID") |
| 5141 |
assert "signatures" in payload |
| 5142 |
assert "algorithms" in payload |
| 5143 |
|
| 5144 |
# fallback_keys_payload |
| 5145 |
fb1 = acct.fallback_keys_payload("@u:h", "DEVID") |
| 5146 |
assert len(fb1) == 1 |
| 5147 |
fb_key_id1 = next(iter(fb1.keys())) |
| 5148 |
assert fb_key_id1.startswith("signed_curve25519:") |
| 5149 |
fb2 = acct.fallback_keys_payload("@u:h", "DEVID") |
| 5150 |
# second call returns the same key id (key not regenerated) |
| 5151 |
assert next(iter(fb2.keys())) == fb_key_id1 |
| 5152 |
|
| 5153 |
|
| 5154 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5155 |
def test_plugin_matrix_e2ee_olm_session(): |
| 5156 |
"""MatrixOlmSession encrypts and produces correct wire format.""" |
| 5157 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount, _b64dec |
| 5158 |
|
| 5159 |
acct = MatrixOlmAccount() |
| 5160 |
# Create a second account to act as recipient |
| 5161 |
recipient = MatrixOlmAccount() |
| 5162 |
|
| 5163 |
session = acct.create_outbound_session( |
| 5164 |
recipient.identity_key, |
| 5165 |
recipient.identity_key, # reuse IK as a stand-in OTK |
| 5166 |
) |
| 5167 |
|
| 5168 |
assert session.their_identity_key == recipient.identity_key |
| 5169 |
|
| 5170 |
# str plaintext |
| 5171 |
result = session.encrypt("test plaintext") |
| 5172 |
assert result["type"] == 0 |
| 5173 |
assert isinstance(result["body"], str) |
| 5174 |
|
| 5175 |
# Decode and check the outer pre-key wire format. |
| 5176 |
# Outer: version(0x03) | field1(OTK) | field2(EK) | field3(IK) | |
| 5177 |
# field4(inner+mac) |
| 5178 |
# Inner (in field 4): version(0x03) | field1(ratchet_key) | |
| 5179 |
# field2(chain_index) | field4(ciphertext,tag=0x22) | inner_mac(8) |
| 5180 |
raw = _b64dec(result["body"]) |
| 5181 |
assert raw[0:1] == b"\x03", "outer version must be 0x03" |
| 5182 |
# field 4, wire-type 2 -> tag = (4<<3)|2 = 0x22 -- ciphertext in inner msg |
| 5183 |
assert b"\x22" in raw, "ciphertext field tag 0x22 must be present" |
| 5184 |
# Outer field 1 (OTK, tag 0x0A), field 2 (EK, tag 0x12) must appear |
| 5185 |
assert b"\x0a" in raw, "outer OTK field (tag 0x0A) must be present" |
| 5186 |
assert b"\x12" in raw, "outer EK field (tag 0x12) must be present" |
| 5187 |
|
| 5188 |
# bytes plaintext also accepted |
| 5189 |
result2 = session.encrypt(b"bytes input") |
| 5190 |
assert result2["type"] == 0 |
| 5191 |
|
| 5192 |
|
| 5193 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5194 |
def test_plugin_matrix_e2ee_olm_roundtrip(): |
| 5195 |
"""Confirm that Bob can decrypt an Olm message from Alice. |
| 5196 |
|
| 5197 |
The receiver-side reconstruction verifies compatible X3DH output. |
| 5198 |
It also confirms the outer base key matches the inner ratchet key, |
| 5199 |
which receivers need to reconstruct the session. |
| 5200 |
""" |
| 5201 |
import hmac as _hmac_stdlib |
| 5202 |
|
| 5203 |
from cryptography.hazmat.backends import default_backend |
| 5204 |
from cryptography.hazmat.primitives import hashes, hmac as _hmac_mod |
| 5205 |
from cryptography.hazmat.primitives.asymmetric.x25519 import ( |
| 5206 |
X25519PrivateKey, |
| 5207 |
) |
| 5208 |
from cryptography.hazmat.primitives.ciphers import ( |
| 5209 |
Cipher, |
| 5210 |
algorithms, |
| 5211 |
modes, |
| 5212 |
) |
| 5213 |
from cryptography.hazmat.primitives.kdf.hkdf import HKDF |
| 5214 |
from cryptography.hazmat.primitives.padding import PKCS7 |
| 5215 |
from cryptography.hazmat.primitives.serialization import ( |
| 5216 |
Encoding, |
| 5217 |
PublicFormat, |
| 5218 |
) |
| 5219 |
|
| 5220 |
from apprise.plugins.matrix.e2ee import ( |
| 5221 |
MatrixOlmAccount, |
| 5222 |
_b64dec, |
| 5223 |
_b64enc, |
| 5224 |
) |
| 5225 |
|
| 5226 |
# -- helpers (Bob-side) ------------------------------------------- |
| 5227 |
|
| 5228 |
def _hmac(key, data): |
| 5229 |
h = _hmac_mod.HMAC(key, hashes.SHA256(), backend=default_backend()) |
| 5230 |
h.update(data) |
| 5231 |
return h.finalize() |
| 5232 |
|
| 5233 |
def _hkdf(ikm, length, salt, info): |
| 5234 |
return HKDF( |
| 5235 |
algorithm=hashes.SHA256(), |
| 5236 |
length=length, |
| 5237 |
salt=salt, |
| 5238 |
info=info, |
| 5239 |
backend=default_backend(), |
| 5240 |
).derive(ikm) |
| 5241 |
|
| 5242 |
def _aes_cbc_decrypt(key, iv, ciphertext): |
| 5243 |
cipher = Cipher( |
| 5244 |
algorithms.AES(key), modes.CBC(iv), backend=default_backend() |
| 5245 |
) |
| 5246 |
dec = cipher.decryptor() |
| 5247 |
padded = dec.update(ciphertext) + dec.finalize() |
| 5248 |
unpadder = PKCS7(128).unpadder() |
| 5249 |
return unpadder.update(padded) + unpadder.finalize() |
| 5250 |
|
| 5251 |
def _read_varint(data, pos): |
| 5252 |
val, shift = 0, 0 |
| 5253 |
while True: |
| 5254 |
b = data[pos] |
| 5255 |
pos += 1 |
| 5256 |
val |= (b & 0x7F) << shift |
| 5257 |
shift += 7 |
| 5258 |
if not (b & 0x80): |
| 5259 |
return val, pos |
| 5260 |
|
| 5261 |
def _parse_pb_fields(data): |
| 5262 |
"""Parse length-delimited protobuf body; return {field_num: bytes}.""" |
| 5263 |
fields = {} |
| 5264 |
pos = 0 |
| 5265 |
while pos < len(data): |
| 5266 |
tag, pos = _read_varint(data, pos) |
| 5267 |
field_num = tag >> 3 |
| 5268 |
wire_type = tag & 0x07 |
| 5269 |
if wire_type == 2: |
| 5270 |
length, pos = _read_varint(data, pos) |
| 5271 |
fields[field_num] = data[pos : pos + length] |
| 5272 |
pos += length |
| 5273 |
elif wire_type == 0: |
| 5274 |
val, pos = _read_varint(data, pos) |
| 5275 |
fields[field_num] = val |
| 5276 |
else: |
| 5277 |
raise ValueError("Unexpected wire type {}".format(wire_type)) |
| 5278 |
return fields |
| 5279 |
|
| 5280 |
# -- test setup --------------------------------------------------- |
| 5281 |
|
| 5282 |
# Alice's account (sender) |
| 5283 |
alice = MatrixOlmAccount() |
| 5284 |
|
| 5285 |
# Bob's account: identity key + a separate one-time key |
| 5286 |
bob = MatrixOlmAccount() |
| 5287 |
bob_otk_priv = X25519PrivateKey.generate() |
| 5288 |
bob_otk_pub = bob_otk_priv.public_key().public_bytes( |
| 5289 |
Encoding.Raw, PublicFormat.Raw |
| 5290 |
) |
| 5291 |
bob_otk_pub_b64 = _b64enc(bob_otk_pub) |
| 5292 |
|
| 5293 |
# Bob's identity-key private (for DH computation) |
| 5294 |
bob_ik_priv = bob._ik |
| 5295 |
|
| 5296 |
# Alice creates an outbound session to Bob using his real OTK |
| 5297 |
session = alice.create_outbound_session( |
| 5298 |
bob.identity_key, # Bob's Curve25519 identity key |
| 5299 |
bob_otk_pub_b64, # Bob's one-time key |
| 5300 |
) |
| 5301 |
|
| 5302 |
plaintext = "hello from Alice" |
| 5303 |
result = session.encrypt(plaintext) |
| 5304 |
assert result["type"] == 0 |
| 5305 |
|
| 5306 |
# -- Bob-side decryption ------------------------------------------ |
| 5307 |
|
| 5308 |
raw = _b64dec(result["body"]) |
| 5309 |
|
| 5310 |
# The outer message contains the one-time, base, identity, and inner |
| 5311 |
# message fields. Only the inner message has a MAC. |
| 5312 |
assert raw[0:1] == b"\x03", "outer version must be 0x03" |
| 5313 |
|
| 5314 |
# Parse the full outer protobuf body (all bytes after the version byte) |
| 5315 |
outer_fields = _parse_pb_fields(raw[1:]) |
| 5316 |
otk_pub_in_msg = outer_fields[1] # field 1: Bob's OTK public bytes |
| 5317 |
base_key = outer_fields[2] # field 2: Alice's ephemeral E_A |
| 5318 |
alice_ik_pub = outer_fields[3] # field 3: Alice's identity key |
| 5319 |
|
| 5320 |
# The OTK bytes in the message must equal Bob's OTK public key |
| 5321 |
assert otk_pub_in_msg == bob_otk_pub, ( |
| 5322 |
"OTK in pre-key message must match the OTK that was claimed" |
| 5323 |
) |
| 5324 |
|
| 5325 |
# Bob computes X3DH (mirroring Alice's DH operations) |
| 5326 |
# DH1 = X25519(OTK_B_priv, IK_A_pub) |
| 5327 |
# DH2 = X25519(IK_B_priv, E_A_pub) |
| 5328 |
# DH3 = X25519(OTK_B_priv, E_A_pub) |
| 5329 |
from cryptography.hazmat.primitives.asymmetric.x25519 import ( |
| 5330 |
X25519PublicKey, |
| 5331 |
) |
| 5332 |
|
| 5333 |
alice_ik = X25519PublicKey.from_public_bytes(alice_ik_pub) |
| 5334 |
e_a = X25519PublicKey.from_public_bytes(base_key) |
| 5335 |
|
| 5336 |
dh1 = bob_otk_priv.exchange(alice_ik) |
| 5337 |
dh2 = bob_ik_priv.exchange(e_a) |
| 5338 |
dh3 = bob_otk_priv.exchange(e_a) |
| 5339 |
|
| 5340 |
ikm = dh1 + dh2 + dh3 |
| 5341 |
keys64 = _hkdf(ikm, 64, salt=None, info=b"OLM_ROOT") |
| 5342 |
root_key = keys64[:32] |
| 5343 |
chain_key = keys64[32:] |
| 5344 |
del root_key # not needed for first-message decryption |
| 5345 |
|
| 5346 |
# Derive message keys from the initial chain key |
| 5347 |
msg_key = _hmac(chain_key, b"\x01") |
| 5348 |
keys80 = _hkdf(msg_key, 80, salt=b"\x00" * 32, info=b"OLM_KEYS") |
| 5349 |
aes_key = keys80[:32] |
| 5350 |
mac_key = keys80[32:64] |
| 5351 |
iv = keys80[64:80] |
| 5352 |
|
| 5353 |
# Field 4 = inner_normal_message || 8-byte MAC. |
| 5354 |
# The inner normal message itself starts with version byte 0x03 followed |
| 5355 |
# by the protobuf body; the MAC covers the version + protobuf body. |
| 5356 |
inner_with_mac = outer_fields[4] |
| 5357 |
inner_body = inner_with_mac[:-8] # version(1) + pb_fields |
| 5358 |
inner_mac_received = inner_with_mac[-8:] |
| 5359 |
|
| 5360 |
# Verify the inner MAC (HMAC-SHA-256 of inner_body, truncated to 8 bytes) |
| 5361 |
inner_mac_expected = _hmac(mac_key, inner_body)[:8] |
| 5362 |
assert _hmac_stdlib.compare_digest( |
| 5363 |
inner_mac_expected, inner_mac_received |
| 5364 |
), "inner MAC verification failed" |
| 5365 |
|
| 5366 |
# Parse inner fields |
| 5367 |
# inner_body = version(0x03) | pb_fields |
| 5368 |
assert inner_body[0:1] == b"\x03", "inner version must be 0x03" |
| 5369 |
inner_fields = _parse_pb_fields(inner_body[1:]) |
| 5370 |
|
| 5371 |
# CRITICAL invariant: |
| 5372 |
# ratchet_key (inner field 1) == base_key (outer field 2) |
| 5373 |
ratchet_key = inner_fields[1] |
| 5374 |
assert ratchet_key == base_key, ( |
| 5375 |
"Olm invariant violated: inner ratchet_key must equal outer base_key " |
| 5376 |
"(E_A must be used in BOTH positions per Olm spec Section 5.1). " |
| 5377 |
"Got ratchet_key={} base_key={}".format( |
| 5378 |
_b64enc(ratchet_key), _b64enc(base_key) |
| 5379 |
) |
| 5380 |
) |
| 5381 |
|
| 5382 |
# Decrypt the AES-256-CBC ciphertext (inner field 4) |
| 5383 |
ciphertext = inner_fields[4] |
| 5384 |
decrypted = _aes_cbc_decrypt(aes_key, iv, ciphertext) |
| 5385 |
|
| 5386 |
assert decrypted.decode("utf-8") == plaintext, ( |
| 5387 |
"round-trip decryption failed: got {!r}".format(decrypted) |
| 5388 |
) |
| 5389 |
|
| 5390 |
|
| 5391 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5392 |
def test_plugin_matrix_e2ee_verify_keys(): |
| 5393 |
"""verify_device_keys and verify_signed_otk accept/reject signatures.""" |
| 5394 |
from apprise.plugins.matrix.e2ee import ( |
| 5395 |
MatrixOlmAccount, |
| 5396 |
_canonical_json, |
| 5397 |
verify_device_keys, |
| 5398 |
verify_signed_otk, |
| 5399 |
) |
| 5400 |
|
| 5401 |
acct = MatrixOlmAccount() |
| 5402 |
uid = "@alice:h" |
| 5403 |
dev = "DEVID" |
| 5404 |
|
| 5405 |
# --- verify_device_keys --- |
| 5406 |
|
| 5407 |
# Valid self-signed device keys -> True |
| 5408 |
dk = acct.device_keys_payload(uid, dev) |
| 5409 |
assert verify_device_keys(dk, uid, dev) is True |
| 5410 |
|
| 5411 |
# Payload user_id doesn't match -> False (identity binding check) |
| 5412 |
mismatched_uid = {**dk, "user_id": "@other:h"} |
| 5413 |
assert verify_device_keys(mismatched_uid, uid, dev) is False |
| 5414 |
|
| 5415 |
# Payload device_id doesn't match -> False (identity binding check) |
| 5416 |
mismatched_dev = {**dk, "device_id": "WRONGDEV"} |
| 5417 |
assert verify_device_keys(mismatched_dev, uid, dev) is False |
| 5418 |
|
| 5419 |
# Missing user_id in payload -> False |
| 5420 |
no_user_id = {k: v for k, v in dk.items() if k != "user_id"} |
| 5421 |
assert verify_device_keys(no_user_id, uid, dev) is False |
| 5422 |
|
| 5423 |
# Missing signatures field -> False |
| 5424 |
no_sig = {k: v for k, v in dk.items() if k != "signatures"} |
| 5425 |
assert verify_device_keys(no_sig, uid, dev) is False |
| 5426 |
|
| 5427 |
# Wrong user_id in signatures -> False |
| 5428 |
wrong_uid = { |
| 5429 |
**dk, |
| 5430 |
"signatures": {"@wrong:h": dk["signatures"][uid]}, |
| 5431 |
} |
| 5432 |
assert verify_device_keys(wrong_uid, uid, dev) is False |
| 5433 |
|
| 5434 |
# Tampered key value -> False |
| 5435 |
tampered = {**dk, "keys": {**dk["keys"], f"ed25519:{dev}": "bad"}} |
| 5436 |
assert verify_device_keys(tampered, uid, dev) is False |
| 5437 |
|
| 5438 |
# Missing ed25519 key entry -> False |
| 5439 |
no_keys = {**dk, "keys": {f"curve25519:{dev}": acct.identity_key}} |
| 5440 |
assert verify_device_keys(no_keys, uid, dev) is False |
| 5441 |
|
| 5442 |
# Malformed homeserver keys must fail closed. |
| 5443 |
assert verify_device_keys(None, uid, dev) is False |
| 5444 |
assert verify_device_keys("not-a-dict", uid, dev) is False |
| 5445 |
assert verify_device_keys({**dk, "keys": None}, uid, dev) is False |
| 5446 |
assert verify_device_keys({**dk, "keys": "not-a-dict"}, uid, dev) is False |
| 5447 |
assert verify_device_keys({**dk, "signatures": None}, uid, dev) is False |
| 5448 |
assert verify_device_keys({**dk, "signatures": [1, 2]}, uid, dev) is False |
| 5449 |
assert ( |
| 5450 |
verify_device_keys({**dk, "signatures": {uid: None}}, uid, dev) |
| 5451 |
is False |
| 5452 |
) |
| 5453 |
|
| 5454 |
# --- verify_signed_otk --- |
| 5455 |
|
| 5456 |
key_b64 = _rand_b64_32() |
| 5457 |
otk_obj = {"key": key_b64} |
| 5458 |
sig = acct.sign(_canonical_json(otk_obj)) |
| 5459 |
signed_otk = { |
| 5460 |
**otk_obj, |
| 5461 |
"signatures": {uid: {f"ed25519:{dev}": sig}}, |
| 5462 |
} |
| 5463 |
|
| 5464 |
# Valid OTK -> True |
| 5465 |
assert verify_signed_otk(signed_otk, uid, dev, acct.signing_key) is True |
| 5466 |
|
| 5467 |
# Missing signatures -> False |
| 5468 |
assert verify_signed_otk(otk_obj, uid, dev, acct.signing_key) is False |
| 5469 |
|
| 5470 |
# Wrong signing key -> False |
| 5471 |
other = MatrixOlmAccount() |
| 5472 |
assert verify_signed_otk(signed_otk, uid, dev, other.signing_key) is False |
| 5473 |
|
| 5474 |
# Tampered key value -> False |
| 5475 |
tampered_otk = {**signed_otk, "key": _rand_b64_32()} |
| 5476 |
assert verify_signed_otk(tampered_otk, uid, dev, acct.signing_key) is False |
| 5477 |
|
| 5478 |
|
| 5479 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5480 |
def test_plugin_matrix_e2ee_megolm_session(): |
| 5481 |
"""MatrixMegOlmSession encrypt, session_key, rotation, serialisation.""" |
| 5482 |
from apprise.plugins.matrix.e2ee import ( |
| 5483 |
MATRIX_MEGOLM_STORE_VERSION, |
| 5484 |
MEGOLM_ROTATION_MSGS, |
| 5485 |
MatrixMegOlmSession, |
| 5486 |
) |
| 5487 |
|
| 5488 |
s = MatrixMegOlmSession() |
| 5489 |
assert isinstance(s.session_id, str) |
| 5490 |
|
| 5491 |
# encrypt returns base64 ciphertext |
| 5492 |
ct = s.encrypt({"type": "m.room.message", "content": {}}) |
| 5493 |
assert isinstance(ct, str) |
| 5494 |
|
| 5495 |
# Verify MegOLM wire format (libolm message.cpp): |
| 5496 |
# version(0x03) | field1_varint(msg_index,tag=0x08) | |
| 5497 |
# field2_bytes(ciphertext,tag=0x12) | mac(8) | sig(64) |
| 5498 |
from apprise.plugins.matrix.e2ee import _b64dec |
| 5499 |
|
| 5500 |
raw = _b64dec(ct) |
| 5501 |
assert raw[0:1] == b"\x03", "MegOLM version must be 0x03" |
| 5502 |
assert raw[1:2] == b"\x08", "MegOLM field 1 tag must be 0x08 (varint)" |
| 5503 |
# After tag 0x08: the varint counter value (0 -> single byte 0x00), |
| 5504 |
# then the ciphertext tag 0x12. |
| 5505 |
assert b"\x12" in raw, "MegOLM ciphertext field tag 0x12 must be present" |
| 5506 |
|
| 5507 |
# session_key returns base64 -- verify wire format per libolm |
| 5508 |
# outbound_group_session.c: version(1) + counter(4) + ratchet(128) |
| 5509 |
# + ed25519_pub(32) + ed25519_sig(64) = 229 bytes raw = 308 base64 chars |
| 5510 |
sk = s.session_key() |
| 5511 |
assert isinstance(sk, str) |
| 5512 |
sk_raw = _b64dec(sk) |
| 5513 |
assert len(sk_raw) == 229, "session_key must be 229 bytes (sig included)" |
| 5514 |
assert sk_raw[0:1] == b"\x02", "session_key version must be 0x02" |
| 5515 |
|
| 5516 |
# to_dict / from_dict round-trip |
| 5517 |
d = s.to_dict() |
| 5518 |
assert d["version"] == MATRIX_MEGOLM_STORE_VERSION |
| 5519 |
s2 = MatrixMegOlmSession.from_dict(d) |
| 5520 |
assert s2.session_id == s.session_id |
| 5521 |
assert s2._counter == s._counter |
| 5522 |
|
| 5523 |
# Cache data from an unsupported version is invalid, not a setting error. |
| 5524 |
with pytest.raises( |
| 5525 |
AppriseInvalidData, match="Incompatible MegOLM session cache format" |
| 5526 |
) as exc_info: |
| 5527 |
MatrixMegOlmSession.from_dict({"version": -1}) |
| 5528 |
assert exc_info.value.error_code == errno.EINVAL |
| 5529 |
|
| 5530 |
# should_rotate: explicit count threshold |
| 5531 |
assert not s.should_rotate(msg_count=MEGOLM_ROTATION_MSGS - 1) |
| 5532 |
assert s.should_rotate(msg_count=MEGOLM_ROTATION_MSGS) |
| 5533 |
|
| 5534 |
# should_rotate: time threshold (old created_at) |
| 5535 |
old = MatrixMegOlmSession(created_at=0.0) |
| 5536 |
assert old.should_rotate() |
| 5537 |
|
| 5538 |
# _advance branches -- cascade fires when (n+1) % threshold == 0, |
| 5539 |
# i.e. when the counter is one less than a threshold multiple. |
| 5540 |
|
| 5541 |
# -- normal step (else branch) |
| 5542 |
s3 = MatrixMegOlmSession() |
| 5543 |
s3._advance() # counter 0 -> 1 (1 % 256 != 0, else: R[3] only) |
| 5544 |
|
| 5545 |
# -- %256 branch: next counter will be 256 |
| 5546 |
s4 = MatrixMegOlmSession() |
| 5547 |
s4._counter = 255 |
| 5548 |
s4._advance() |
| 5549 |
|
| 5550 |
# -- %65536 branch: next counter will be 65536 |
| 5551 |
s5 = MatrixMegOlmSession() |
| 5552 |
s5._counter = 65535 |
| 5553 |
s5._advance() |
| 5554 |
|
| 5555 |
# -- %2^24 branch: next counter will be 2^24 |
| 5556 |
s6 = MatrixMegOlmSession() |
| 5557 |
s6._counter = (1 << 24) - 1 |
| 5558 |
s6._advance() |
| 5559 |
|
| 5560 |
|
| 5561 |
# --------------------------------------------------------------------------- |
| 5562 |
# E2EE integration tests -- URL parsing and send flow |
| 5563 |
# --------------------------------------------------------------------------- |
| 5564 |
|
| 5565 |
|
| 5566 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5567 |
def test_plugin_matrix_e2ee_url_roundtrip(): |
| 5568 |
"""e2ee default is True; disabled state survives url() / parse_url().""" |
| 5569 |
# Default (no e2ee param) is now True |
| 5570 |
obj = NotifyMatrix( |
| 5571 |
host="matrix.example.com", |
| 5572 |
user="user", |
| 5573 |
password="pass", |
| 5574 |
targets=["#room"], |
| 5575 |
) |
| 5576 |
assert obj.e2ee is True |
| 5577 |
# Enabled is the default -- not written to URL |
| 5578 |
assert "e2ee" not in obj.url() |
| 5579 |
|
| 5580 |
# Disabled survives round-trip |
| 5581 |
obj2 = NotifyMatrix( |
| 5582 |
host="matrix.example.com", |
| 5583 |
user="user", |
| 5584 |
password="pass", |
| 5585 |
targets=["#room"], |
| 5586 |
e2ee=False, |
| 5587 |
) |
| 5588 |
assert obj2.e2ee is False |
| 5589 |
u2 = obj2.url() |
| 5590 |
assert "e2ee=no" in u2 |
| 5591 |
|
| 5592 |
result = NotifyMatrix.parse_url(u2) |
| 5593 |
assert result is not None |
| 5594 |
assert result.get("e2ee") is False or str(result.get("e2ee")).lower() in ( |
| 5595 |
"false", |
| 5596 |
"no", |
| 5597 |
"0", |
| 5598 |
) |
| 5599 |
|
| 5600 |
# Automatic verification is opt-in and survives URL round-trip. |
| 5601 |
obj3 = NotifyMatrix( |
| 5602 |
host="matrix.example.com", |
| 5603 |
user="user", |
| 5604 |
password="pass", |
| 5605 |
targets=["#room"], |
| 5606 |
autoverify=True, |
| 5607 |
) |
| 5608 |
assert obj3.autoverify is True |
| 5609 |
u3 = obj3.url() |
| 5610 |
assert "autoverify=yes" in u3 |
| 5611 |
result = NotifyMatrix.parse_url(u3) |
| 5612 |
assert result is not None |
| 5613 |
assert result.get("autoverify") is True |
| 5614 |
|
| 5615 |
|
| 5616 |
@mock.patch("requests.put") |
| 5617 |
@mock.patch("requests.get") |
| 5618 |
@mock.patch("requests.post") |
| 5619 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5620 |
def test_plugin_matrix_e2ee_insecure_connection(mock_post, mock_get, mock_put): |
| 5621 |
"""e2ee=yes over insecure (matrix://) falls back to unencrypted.""" |
| 5622 |
resp = _Response() |
| 5623 |
resp.status_code = requests.codes.ok |
| 5624 |
resp.content = dumps( |
| 5625 |
{ |
| 5626 |
"access_token": "tok", |
| 5627 |
"user_id": "@u:h", |
| 5628 |
"home_server": "h", |
| 5629 |
"device_id": "DEV", |
| 5630 |
"room_id": "!r:h", |
| 5631 |
} |
| 5632 |
).encode() |
| 5633 |
mock_post.return_value = resp |
| 5634 |
mock_get.return_value = resp |
| 5635 |
mock_put.return_value = resp |
| 5636 |
|
| 5637 |
# matrix:// (not matrixs://) -- E2EE silently skipped, plain delivery |
| 5638 |
obj = NotifyMatrix( |
| 5639 |
host="h", |
| 5640 |
user="u", |
| 5641 |
password="pass", |
| 5642 |
targets=["#room"], |
| 5643 |
e2ee=True, |
| 5644 |
# secure=False is the default for matrix:// URLs |
| 5645 |
) |
| 5646 |
assert not obj.secure |
| 5647 |
assert obj.send(body="test") is True |
| 5648 |
|
| 5649 |
|
| 5650 |
@mock.patch("requests.put") |
| 5651 |
@mock.patch("requests.get") |
| 5652 |
@mock.patch("requests.post") |
| 5653 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5654 |
def test_plugin_matrix_e2ee_no_support(mock_post, mock_get, mock_put): |
| 5655 |
"""e2ee=yes with MATRIX_E2EE_SUPPORT=False sends unencrypted.""" |
| 5656 |
resp = _Response() |
| 5657 |
resp.status_code = requests.codes.ok |
| 5658 |
resp.content = dumps( |
| 5659 |
{ |
| 5660 |
"access_token": "tok", |
| 5661 |
"user_id": "@u:h", |
| 5662 |
"home_server": "h", |
| 5663 |
"device_id": "DEV", |
| 5664 |
"room_id": "!r:h", |
| 5665 |
} |
| 5666 |
).encode() |
| 5667 |
mock_post.return_value = resp |
| 5668 |
mock_get.return_value = resp |
| 5669 |
mock_put.return_value = resp |
| 5670 |
|
| 5671 |
with mock.patch( |
| 5672 |
"apprise.plugins.matrix.base.MATRIX_E2EE_SUPPORT", |
| 5673 |
False, |
| 5674 |
): |
| 5675 |
obj = NotifyMatrix( |
| 5676 |
host="h", |
| 5677 |
user="u", |
| 5678 |
password="pass", |
| 5679 |
targets=["#room"], |
| 5680 |
e2ee=True, |
| 5681 |
) |
| 5682 |
# Should succeed (falls back to unencrypted) |
| 5683 |
assert obj.send(body="test") is True |
| 5684 |
|
| 5685 |
|
| 5686 |
@mock.patch("requests.put") |
| 5687 |
@mock.patch("requests.get") |
| 5688 |
@mock.patch("requests.post") |
| 5689 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5690 |
def test_plugin_matrix_e2ee_send(mock_post, mock_get, mock_put): |
| 5691 |
"""Full E2EE send path via _send_server_notification.""" |
| 5692 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 5693 |
|
| 5694 |
# Recipient device (acts as a room member) |
| 5695 |
recipient = MatrixOlmAccount() |
| 5696 |
|
| 5697 |
login_resp = { |
| 5698 |
"access_token": "tok123", |
| 5699 |
"user_id": "@sender:localhost", |
| 5700 |
"home_server": "localhost", |
| 5701 |
"device_id": "SENDERDEV", |
| 5702 |
} |
| 5703 |
|
| 5704 |
members_resp = { |
| 5705 |
"joined": {"@other:localhost": {}}, |
| 5706 |
} |
| 5707 |
|
| 5708 |
# Properly signed device keys (required by verify_device_keys) |
| 5709 |
signed_dev = recipient.device_keys_payload("@other:localhost", "OTHERDEV") |
| 5710 |
query_resp = { |
| 5711 |
"device_keys": {"@other:localhost": {"OTHERDEV": signed_dev}} |
| 5712 |
} |
| 5713 |
|
| 5714 |
# Properly signed OTK (required by verify_signed_otk) |
| 5715 |
signed_otk = _make_signed_otk(recipient, "@other:localhost", "OTHERDEV") |
| 5716 |
claim_resp = { |
| 5717 |
"one_time_keys": { |
| 5718 |
"@other:localhost": { |
| 5719 |
"OTHERDEV": {"signed_curve25519:KEYID": signed_otk} |
| 5720 |
} |
| 5721 |
} |
| 5722 |
} |
| 5723 |
|
| 5724 |
def _mk_resp(d): |
| 5725 |
r = _Response() |
| 5726 |
r.status_code = requests.codes.ok |
| 5727 |
r.content = dumps(d).encode() |
| 5728 |
return r |
| 5729 |
|
| 5730 |
# POST sequence: |
| 5731 |
# login, keys/upload (with OTK count), join, keys/query, keys/claim, |
| 5732 |
# keys/upload (OTK replenishment), logout |
| 5733 |
mock_post.side_effect = [ |
| 5734 |
_mk_resp(login_resp), |
| 5735 |
_mk_resp({"one_time_key_counts": {"signed_curve25519": 1}}), |
| 5736 |
_mk_resp({"room_id": "!room:localhost"}), # join |
| 5737 |
_mk_resp(query_resp), # keys/query |
| 5738 |
_mk_resp(claim_resp), # keys/claim |
| 5739 |
# Replenishment: remaining = 1 - 1 (built_count) = 0 < threshold |
| 5740 |
_mk_resp( |
| 5741 |
{ |
| 5742 |
"one_time_key_counts": { |
| 5743 |
"signed_curve25519": NotifyMatrix.default_e2ee_otk_count, |
| 5744 |
} |
| 5745 |
} |
| 5746 |
), |
| 5747 |
_mk_resp({}), # logout |
| 5748 |
] |
| 5749 |
mock_get.return_value = _mk_resp(members_resp) |
| 5750 |
mock_put.return_value = _mk_resp({}) |
| 5751 |
|
| 5752 |
obj = NotifyMatrix( |
| 5753 |
host="localhost", |
| 5754 |
user="sender", |
| 5755 |
password="pass", |
| 5756 |
targets=["#room"], |
| 5757 |
e2ee=True, |
| 5758 |
secure=True, |
| 5759 |
discovery=False, |
| 5760 |
) |
| 5761 |
assert obj.send(body="hello", title="hi") is True |
| 5762 |
|
| 5763 |
# PUT was called: sendToDevice + rooms/send/encrypted |
| 5764 |
assert mock_put.call_count >= 2 |
| 5765 |
|
| 5766 |
|
| 5767 |
@mock.patch("requests.put") |
| 5768 |
@mock.patch("requests.get") |
| 5769 |
@mock.patch("requests.post") |
| 5770 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5771 |
def test_plugin_matrix_e2ee_send_cached_session(mock_post, mock_get, mock_put): |
| 5772 |
"""E2EE send skips key-share when session key already shared.""" |
| 5773 |
login_resp = { |
| 5774 |
"access_token": "tok", |
| 5775 |
"user_id": "@u:h", |
| 5776 |
"home_server": "h", |
| 5777 |
"device_id": "DEV", |
| 5778 |
} |
| 5779 |
|
| 5780 |
def _mk_resp(d): |
| 5781 |
r = _Response() |
| 5782 |
r.status_code = requests.codes.ok |
| 5783 |
r.content = dumps(d).encode() |
| 5784 |
return r |
| 5785 |
|
| 5786 |
# POST: login, keys/upload, join, logout |
| 5787 |
mock_post.side_effect = [ |
| 5788 |
_mk_resp(login_resp), |
| 5789 |
_mk_resp({}), # keys/upload |
| 5790 |
_mk_resp({"room_id": "!r:h"}), # join |
| 5791 |
_mk_resp({}), # logout |
| 5792 |
] |
| 5793 |
mock_put.return_value = _mk_resp({}) |
| 5794 |
|
| 5795 |
from apprise.plugins.matrix.e2ee import MatrixMegOlmSession |
| 5796 |
|
| 5797 |
obj = NotifyMatrix( |
| 5798 |
host="h", |
| 5799 |
user="u", |
| 5800 |
password="pass", |
| 5801 |
targets=["!r:h"], |
| 5802 |
e2ee=True, |
| 5803 |
secure=True, |
| 5804 |
discovery=False, |
| 5805 |
) |
| 5806 |
# Pre-seed room encryption state, MegOLM session, and key-shared flag |
| 5807 |
# so that no additional GETs or key-exchange PUTs are issued. |
| 5808 |
_sess = MatrixMegOlmSession() |
| 5809 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 5810 |
obj.store.set("e2ee_megolm_!r:h", _sess.to_dict()) |
| 5811 |
obj.store.set("e2ee_key_shared_!r:h", _sess.session_id) |
| 5812 |
assert obj.send(body="silent") is True |
| 5813 |
# Only one PUT for the encrypted message itself |
| 5814 |
assert mock_put.call_count == 1 |
| 5815 |
|
| 5816 |
|
| 5817 |
@mock.patch("requests.put") |
| 5818 |
@mock.patch("requests.get") |
| 5819 |
@mock.patch("requests.post") |
| 5820 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5821 |
def test_plugin_matrix_e2ee_send_legacy_shared_flag_rekeys( |
| 5822 |
mock_post, mock_get, mock_put |
| 5823 |
): |
| 5824 |
"""Legacy boolean key-share cache forces a fresh room-key share.""" |
| 5825 |
from apprise.plugins.matrix.e2ee import ( |
| 5826 |
MatrixMegOlmSession, |
| 5827 |
MatrixOlmAccount, |
| 5828 |
) |
| 5829 |
|
| 5830 |
obj = NotifyMatrix( |
| 5831 |
host="h", |
| 5832 |
user="u", |
| 5833 |
password="pass", |
| 5834 |
targets=["#r"], |
| 5835 |
e2ee=True, |
| 5836 |
) |
| 5837 |
obj.access_token = "tok" |
| 5838 |
obj.home_server = "h" |
| 5839 |
obj.user_id = "@u:h" |
| 5840 |
obj.device_id = "DEV" |
| 5841 |
obj._e2ee_account = MatrixOlmAccount() |
| 5842 |
session = MatrixMegOlmSession() |
| 5843 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 5844 |
obj.store.set("e2ee_key_shared_!r:h", True) |
| 5845 |
|
| 5846 |
with ( |
| 5847 |
mock.patch.object( |
| 5848 |
obj, "_e2ee_share_room_key", return_value=True |
| 5849 |
) as share, |
| 5850 |
mock.patch.object(obj, "_fetch", return_value=(True, {}, 200)), |
| 5851 |
): |
| 5852 |
assert ( |
| 5853 |
obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO) is True |
| 5854 |
) |
| 5855 |
|
| 5856 |
assert share.call_count == 1 |
| 5857 |
assert obj.store.get("e2ee_key_shared_!r:h") == session.session_id |
| 5858 |
|
| 5859 |
|
| 5860 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5861 |
def test_plugin_matrix_e2ee_setup_restored(): |
| 5862 |
"""E2EE account restores from store via _e2ee_setup and __init__.""" |
| 5863 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 5864 |
|
| 5865 |
acct = MatrixOlmAccount() |
| 5866 |
|
| 5867 |
obj = NotifyMatrix( |
| 5868 |
host="h", |
| 5869 |
user="u", |
| 5870 |
password="pass", |
| 5871 |
targets=["#r"], |
| 5872 |
e2ee=True, |
| 5873 |
) |
| 5874 |
# Seed account + mark keys already uploaded |
| 5875 |
obj.store.set("e2ee_account", acct.to_dict()) |
| 5876 |
obj.store.set("e2ee_keys_uploaded", True) |
| 5877 |
obj.store.set( |
| 5878 |
"e2ee_device_binding", |
| 5879 |
"{}|{}|{}|{}".format( |
| 5880 |
obj.user_id or "", |
| 5881 |
obj.device_id or "", |
| 5882 |
acct.identity_key, |
| 5883 |
acct.signing_key, |
| 5884 |
), |
| 5885 |
) |
| 5886 |
|
| 5887 |
# Simulate state where account is not yet loaded in memory |
| 5888 |
obj._e2ee_account = None |
| 5889 |
|
| 5890 |
# _e2ee_setup should restore the account from the store |
| 5891 |
assert obj._e2ee_setup() is True |
| 5892 |
assert obj._e2ee_account is not None |
| 5893 |
assert obj._e2ee_account.identity_key == acct.identity_key |
| 5894 |
|
| 5895 |
# Bad account data in store -> _e2ee_setup creates a fresh account; |
| 5896 |
# the try/except in _e2ee_setup is exercised when from_dict raises. |
| 5897 |
obj._e2ee_account = None |
| 5898 |
obj.store.set("e2ee_account", {"bad": "data"}) |
| 5899 |
obj.store.clear("e2ee_keys_uploaded") |
| 5900 |
with mock.patch.object(obj, "_e2ee_upload_keys", return_value=True): |
| 5901 |
result = obj._e2ee_setup() |
| 5902 |
assert result is True |
| 5903 |
assert obj._e2ee_account is not None |
| 5904 |
|
| 5905 |
# Patch the store so __init__ sees a valid pre-existing account, |
| 5906 |
# exercising the success path of the contextlib.suppress block. |
| 5907 |
valid_data = obj._e2ee_account.to_dict() |
| 5908 |
with mock.patch( |
| 5909 |
"apprise.persistent_store.PersistentStore.get", |
| 5910 |
return_value=valid_data, |
| 5911 |
): |
| 5912 |
obj2 = NotifyMatrix( |
| 5913 |
host="h", |
| 5914 |
user="u", |
| 5915 |
password="pass", |
| 5916 |
targets=["#r"], |
| 5917 |
e2ee=True, |
| 5918 |
) |
| 5919 |
assert obj2._e2ee_account is not None |
| 5920 |
|
| 5921 |
|
| 5922 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5923 |
def test_plugin_matrix_e2ee_setup_reuploads_on_binding_change(): |
| 5924 |
"""Changed device/account identity forces a fresh key upload.""" |
| 5925 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 5926 |
|
| 5927 |
acct = MatrixOlmAccount() |
| 5928 |
obj = NotifyMatrix( |
| 5929 |
host="h", |
| 5930 |
user="u", |
| 5931 |
password="pass", |
| 5932 |
targets=["#r"], |
| 5933 |
e2ee=True, |
| 5934 |
) |
| 5935 |
obj.user_id = "@u:h" |
| 5936 |
obj.device_id = "DEV_NEW" |
| 5937 |
obj._e2ee_account = acct |
| 5938 |
obj.store.set("e2ee_account", acct.to_dict()) |
| 5939 |
obj.store.set("e2ee_keys_uploaded", True) |
| 5940 |
obj.store.set("e2ee_device_binding", "@u:h|DEV_OLD|oldik|oldsk") |
| 5941 |
|
| 5942 |
with mock.patch.object( |
| 5943 |
obj, "_e2ee_upload_keys", return_value=True |
| 5944 |
) as upload: |
| 5945 |
assert obj._e2ee_setup() is True |
| 5946 |
|
| 5947 |
assert upload.call_count == 1 |
| 5948 |
|
| 5949 |
|
| 5950 |
@mock.patch("requests.put") |
| 5951 |
@mock.patch("requests.get") |
| 5952 |
@mock.patch("requests.post") |
| 5953 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5954 |
def test_plugin_matrix_e2ee_upload_keys_no_ids(mock_post, mock_get, mock_put): |
| 5955 |
"""_e2ee_upload_keys returns False when user_id/device_id missing.""" |
| 5956 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 5957 |
|
| 5958 |
obj = NotifyMatrix( |
| 5959 |
host="h", |
| 5960 |
user="u", |
| 5961 |
password="pass", |
| 5962 |
targets=["#r"], |
| 5963 |
e2ee=True, |
| 5964 |
) |
| 5965 |
obj._e2ee_account = MatrixOlmAccount() |
| 5966 |
# No user_id / device_id set |
| 5967 |
assert obj._e2ee_upload_keys() is False |
| 5968 |
|
| 5969 |
|
| 5970 |
@mock.patch("requests.put") |
| 5971 |
@mock.patch("requests.get") |
| 5972 |
@mock.patch("requests.post") |
| 5973 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 5974 |
def test_plugin_matrix_e2ee_upload_keys_http_fail( |
| 5975 |
mock_post, mock_get, mock_put |
| 5976 |
): |
| 5977 |
"""_e2ee_upload_keys returns False on HTTP error.""" |
| 5978 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 5979 |
|
| 5980 |
resp = _Response() |
| 5981 |
resp.status_code = 500 |
| 5982 |
resp.content = dumps({}).encode() |
| 5983 |
mock_post.return_value = resp |
| 5984 |
|
| 5985 |
obj = NotifyMatrix( |
| 5986 |
host="h", |
| 5987 |
user="u", |
| 5988 |
password="pass", |
| 5989 |
targets=["#r"], |
| 5990 |
e2ee=True, |
| 5991 |
) |
| 5992 |
obj._e2ee_account = MatrixOlmAccount() |
| 5993 |
obj.access_token = "tok" |
| 5994 |
obj.user_id = "@u:h" |
| 5995 |
obj.device_id = "DEV" |
| 5996 |
obj.home_server = "h" |
| 5997 |
assert obj._e2ee_upload_keys() is False |
| 5998 |
|
| 5999 |
|
| 6000 |
@mock.patch("requests.put") |
| 6001 |
@mock.patch("requests.get") |
| 6002 |
@mock.patch("requests.post") |
| 6003 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6004 |
def test_plugin_matrix_e2ee_upload_keys_success_marks_published( |
| 6005 |
mock_post, mock_get, mock_put |
| 6006 |
): |
| 6007 |
"""Successful upload clears the current unpublished OTK batch.""" |
| 6008 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 6009 |
|
| 6010 |
resp = _Response() |
| 6011 |
resp.status_code = requests.codes.ok |
| 6012 |
resp.content = dumps( |
| 6013 |
{ |
| 6014 |
"one_time_key_counts": { |
| 6015 |
"signed_curve25519": NotifyMatrix.default_e2ee_otk_count, |
| 6016 |
} |
| 6017 |
} |
| 6018 |
).encode() |
| 6019 |
mock_post.return_value = resp |
| 6020 |
|
| 6021 |
obj = NotifyMatrix( |
| 6022 |
host="h", |
| 6023 |
user="u", |
| 6024 |
password="pass", |
| 6025 |
targets=["#r"], |
| 6026 |
e2ee=True, |
| 6027 |
) |
| 6028 |
obj._e2ee_account = MatrixOlmAccount() |
| 6029 |
obj.access_token = "tok" |
| 6030 |
obj.user_id = "@u:h" |
| 6031 |
obj.device_id = "DEV" |
| 6032 |
obj.home_server = "h" |
| 6033 |
|
| 6034 |
# Pre-generate one-time keys so we can verify they are marked published. |
| 6035 |
obj._e2ee_account.one_time_keys_payload( |
| 6036 |
obj.user_id, obj.device_id, count=3 |
| 6037 |
) |
| 6038 |
assert obj._e2ee_account._otks |
| 6039 |
assert obj._e2ee_upload_keys() is True |
| 6040 |
assert obj._e2ee_account._otks == {} |
| 6041 |
# Server OTK count from the response is persisted for threshold checks. |
| 6042 |
assert obj.store.get("e2ee_otk_server_count") == ( |
| 6043 |
NotifyMatrix.default_e2ee_otk_count |
| 6044 |
) |
| 6045 |
|
| 6046 |
|
| 6047 |
@mock.patch("requests.put") |
| 6048 |
@mock.patch("requests.get") |
| 6049 |
@mock.patch("requests.post") |
| 6050 |
def test_plugin_matrix_whoami(mock_post, mock_get, mock_put): |
| 6051 |
"""_whoami() resolves user_id and device_id from GET /account/whoami.""" |
| 6052 |
|
| 6053 |
def _mk_resp(d, code=requests.codes.ok): |
| 6054 |
r = _Response() |
| 6055 |
r.status_code = code |
| 6056 |
r.content = dumps(d).encode() |
| 6057 |
return r |
| 6058 |
|
| 6059 |
obj = NotifyMatrix( |
| 6060 |
host="h", |
| 6061 |
password="rawtoken", |
| 6062 |
targets=["#r"], |
| 6063 |
e2ee=True, |
| 6064 |
) |
| 6065 |
obj.access_token = "rawtoken" |
| 6066 |
obj.home_server = "h" |
| 6067 |
|
| 6068 |
# Success: server returns user_id and device_id; home_server is |
| 6069 |
# extracted from user_id so DM targets resolve correctly. |
| 6070 |
mock_get.return_value = _mk_resp( |
| 6071 |
{"user_id": "@tok:h", "device_id": "TOKDEV"} |
| 6072 |
) |
| 6073 |
assert obj._whoami() is True |
| 6074 |
assert obj.user_id == "@tok:h" |
| 6075 |
assert obj.device_id == "TOKDEV" |
| 6076 |
assert obj.home_server == "h" |
| 6077 |
assert obj.store.get("user_id") == "@tok:h" |
| 6078 |
assert obj.store.get("device_id") == "TOKDEV" |
| 6079 |
assert obj.store.get("home_server") == "h" |
| 6080 |
|
| 6081 |
# user_id without homeserver component (@alice, no colon) -> home_server |
| 6082 |
# is not extracted (branch where len(parts) != 2 is not taken). |
| 6083 |
obj.user_id = None |
| 6084 |
obj.home_server = None |
| 6085 |
mock_get.return_value = _mk_resp( |
| 6086 |
{"user_id": "@noserver", "device_id": "DEV2"} |
| 6087 |
) |
| 6088 |
assert obj._whoami() is True |
| 6089 |
assert obj.user_id == "@noserver" |
| 6090 |
assert obj.home_server is None # no colon -> not extracted |
| 6091 |
|
| 6092 |
# home_server already known -> not overwritten |
| 6093 |
obj.home_server = "existing.h" |
| 6094 |
mock_get.return_value = _mk_resp( |
| 6095 |
{"user_id": "@tok:other.h", "device_id": "DEV3"} |
| 6096 |
) |
| 6097 |
assert obj._whoami() is True |
| 6098 |
assert obj.home_server == "existing.h" |
| 6099 |
|
| 6100 |
# Failure: server returns non-200 |
| 6101 |
obj.user_id = None |
| 6102 |
obj.device_id = None |
| 6103 |
mock_get.return_value = _mk_resp({}, code=401) |
| 6104 |
assert obj._whoami() is False |
| 6105 |
|
| 6106 |
|
| 6107 |
@mock.patch("requests.put") |
| 6108 |
@mock.patch("requests.get") |
| 6109 |
@mock.patch("requests.post") |
| 6110 |
def test_plugin_matrix_send_cached_token_recovers_home_server( |
| 6111 |
mock_post, mock_get, mock_put |
| 6112 |
): |
| 6113 |
"""Cached auth without home_server should be repaired via _whoami().""" |
| 6114 |
|
| 6115 |
obj = NotifyMatrix( |
| 6116 |
host="matrix.org", |
| 6117 |
user="apprise", |
| 6118 |
password="pass", |
| 6119 |
targets=["#general"], |
| 6120 |
) |
| 6121 |
obj.access_token = "cached-token" |
| 6122 |
obj.user_id = None |
| 6123 |
obj.device_id = None |
| 6124 |
obj.home_server = None |
| 6125 |
|
| 6126 |
whoami_called = {"count": 0} |
| 6127 |
|
| 6128 |
def _fake_whoami(): |
| 6129 |
whoami_called["count"] += 1 |
| 6130 |
obj.user_id = "@apprise:matrix.org" |
| 6131 |
obj.device_id = "DEV42" |
| 6132 |
obj.home_server = "matrix.org" |
| 6133 |
return True |
| 6134 |
|
| 6135 |
with ( |
| 6136 |
mock.patch.object(obj, "_room_join", return_value="!room:matrix.org"), |
| 6137 |
mock.patch.object(obj, "_whoami", side_effect=_fake_whoami), |
| 6138 |
mock.patch.object( |
| 6139 |
obj, "_fetch", return_value=(True, {"event_id": "$1"}, 200) |
| 6140 |
), |
| 6141 |
): |
| 6142 |
assert obj.send("body", title="test") is True |
| 6143 |
|
| 6144 |
assert whoami_called["count"] == 1 |
| 6145 |
assert obj.home_server == "matrix.org" |
| 6146 |
assert obj.user_id == "@apprise:matrix.org" |
| 6147 |
|
| 6148 |
|
| 6149 |
@mock.patch("requests.put") |
| 6150 |
@mock.patch("requests.get") |
| 6151 |
@mock.patch("requests.post") |
| 6152 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6153 |
def test_plugin_matrix_e2ee_get_megolm_rotation(mock_post, mock_get, mock_put): |
| 6154 |
"""_e2ee_get_megolm rotates session after threshold.""" |
| 6155 |
from apprise.plugins.matrix.e2ee import ( |
| 6156 |
MEGOLM_ROTATION_MSGS, |
| 6157 |
MatrixMegOlmSession, |
| 6158 |
) |
| 6159 |
|
| 6160 |
obj = NotifyMatrix( |
| 6161 |
host="h", |
| 6162 |
user="u", |
| 6163 |
password="pass", |
| 6164 |
targets=["#r"], |
| 6165 |
e2ee=True, |
| 6166 |
) |
| 6167 |
|
| 6168 |
# Seed a session that is already past the rotation threshold |
| 6169 |
stale = MatrixMegOlmSession() |
| 6170 |
stale._counter = MEGOLM_ROTATION_MSGS |
| 6171 |
obj.store.set("e2ee_megolm_!r:h", stale.to_dict()) |
| 6172 |
obj.store.set("e2ee_key_shared_!r:h", True) |
| 6173 |
|
| 6174 |
new_session = obj._e2ee_get_megolm("!r:h") |
| 6175 |
assert new_session.session_id != stale.session_id |
| 6176 |
|
| 6177 |
# The shared flag should be cleared on rotation |
| 6178 |
assert obj.store.get("e2ee_key_shared_!r:h") is None |
| 6179 |
|
| 6180 |
# Legacy cached sessions without the current version marker are |
| 6181 |
# invalidated and replaced with a fresh session. |
| 6182 |
legacy = stale.to_dict() |
| 6183 |
del legacy["version"] |
| 6184 |
obj.store.set("e2ee_megolm_!r:h", legacy) |
| 6185 |
obj.store.set("e2ee_key_shared_!r:h", stale.session_id) |
| 6186 |
replaced = obj._e2ee_get_megolm("!r:h") |
| 6187 |
assert replaced.session_id != stale.session_id |
| 6188 |
assert obj.store.get("e2ee_key_shared_!r:h") is None |
| 6189 |
|
| 6190 |
|
| 6191 |
@mock.patch("requests.put") |
| 6192 |
@mock.patch("requests.get") |
| 6193 |
@mock.patch("requests.post") |
| 6194 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6195 |
def test_plugin_matrix_e2ee_room_encrypted(mock_post, mock_get, mock_put): |
| 6196 |
"""_e2ee_room_encrypted: cached, GET success, GET failure paths.""" |
| 6197 |
|
| 6198 |
def _mk_resp(d, code=requests.codes.ok): |
| 6199 |
r = _Response() |
| 6200 |
r.status_code = code |
| 6201 |
r.content = dumps(d).encode() |
| 6202 |
return r |
| 6203 |
|
| 6204 |
obj = NotifyMatrix( |
| 6205 |
host="h", |
| 6206 |
user="u", |
| 6207 |
password="pass", |
| 6208 |
targets=["#r"], |
| 6209 |
e2ee=True, |
| 6210 |
) |
| 6211 |
obj.access_token = "tok" |
| 6212 |
obj.home_server = "h" |
| 6213 |
|
| 6214 |
# Cache hit -- no GET fired |
| 6215 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 6216 |
assert obj._e2ee_room_encrypted("!r:h") is True |
| 6217 |
assert mock_get.call_count == 0 |
| 6218 |
|
| 6219 |
# Cache miss, GET returns 200 with content -> True |
| 6220 |
obj.store.clear("e2ee_room_enc_!r:h") |
| 6221 |
mock_get.return_value = _mk_resp({"algorithm": "m.megolm.v1.aes-sha2"}) |
| 6222 |
assert obj._e2ee_room_encrypted("!r:h") is True |
| 6223 |
assert mock_get.call_count == 1 |
| 6224 |
|
| 6225 |
# Cache is now populated |
| 6226 |
assert obj.store.get("e2ee_room_enc_!r:h") is True |
| 6227 |
|
| 6228 |
# Cache miss, GET returns 404 -> False |
| 6229 |
obj.store.clear("e2ee_room_enc_!r:h") |
| 6230 |
mock_get.return_value = _mk_resp({}, code=404) |
| 6231 |
assert obj._e2ee_room_encrypted("!r:h") is False |
| 6232 |
assert obj.store.get("e2ee_room_enc_!r:h") is False |
| 6233 |
|
| 6234 |
|
| 6235 |
@mock.patch("requests.put") |
| 6236 |
@mock.patch("requests.get") |
| 6237 |
@mock.patch("requests.post") |
| 6238 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6239 |
def test_plugin_matrix_e2ee_room_members(mock_post, mock_get, mock_put): |
| 6240 |
"""_e2ee_room_members handles HTTP failures and empty rooms.""" |
| 6241 |
|
| 6242 |
def _mk_resp(d, code=requests.codes.ok): |
| 6243 |
r = _Response() |
| 6244 |
r.status_code = code |
| 6245 |
r.content = dumps(d).encode() |
| 6246 |
return r |
| 6247 |
|
| 6248 |
obj = NotifyMatrix( |
| 6249 |
host="h", |
| 6250 |
user="u", |
| 6251 |
password="pass", |
| 6252 |
targets=["#r"], |
| 6253 |
e2ee=True, |
| 6254 |
) |
| 6255 |
obj.access_token = "tok" |
| 6256 |
obj.home_server = "h" |
| 6257 |
|
| 6258 |
# joined_members HTTP failure -> None |
| 6259 |
mock_get.return_value = _mk_resp({}, code=500) |
| 6260 |
assert obj._e2ee_room_members("!r:h") is None |
| 6261 |
|
| 6262 |
# No joined members -> empty dict |
| 6263 |
mock_get.return_value = _mk_resp({"joined": {}}) |
| 6264 |
assert obj._e2ee_room_members("!r:h") == {} |
| 6265 |
|
| 6266 |
# keys/query failure -> None |
| 6267 |
mock_get.return_value = _mk_resp({"joined": {"@u:h": {}}}) |
| 6268 |
mock_post.return_value = _mk_resp({}, code=500) |
| 6269 |
assert obj._e2ee_room_members("!r:h") is None |
| 6270 |
|
| 6271 |
# Unsigned device key -> device is rejected (empty result for that uid) |
| 6272 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 6273 |
|
| 6274 |
unsigned_resp = { |
| 6275 |
"device_keys": { |
| 6276 |
"@u:h": { |
| 6277 |
"DEV": { |
| 6278 |
"keys": { |
| 6279 |
"curve25519:DEV": "IK", |
| 6280 |
"ed25519:DEV": "SK", |
| 6281 |
} |
| 6282 |
# no "signatures" field |
| 6283 |
} |
| 6284 |
} |
| 6285 |
} |
| 6286 |
} |
| 6287 |
mock_get.return_value = _mk_resp({"joined": {"@u:h": {}}}) |
| 6288 |
mock_post.return_value = _mk_resp(unsigned_resp) |
| 6289 |
result = obj._e2ee_room_members("!r:h") |
| 6290 |
assert result["@u:h"] == {} |
| 6291 |
|
| 6292 |
# Properly signed device key -> device included |
| 6293 |
acct = MatrixOlmAccount() |
| 6294 |
signed_dev = acct.device_keys_payload("@u:h", "DEV") |
| 6295 |
query_resp = {"device_keys": {"@u:h": {"DEV": signed_dev}}} |
| 6296 |
mock_get.return_value = _mk_resp({"joined": {"@u:h": {}}}) |
| 6297 |
mock_post.return_value = _mk_resp(query_resp) |
| 6298 |
result = obj._e2ee_room_members("!r:h") |
| 6299 |
assert "@u:h" in result |
| 6300 |
assert result["@u:h"]["DEV"]["curve25519"] == acct.identity_key |
| 6301 |
|
| 6302 |
|
| 6303 |
@mock.patch("requests.put") |
| 6304 |
@mock.patch("requests.get") |
| 6305 |
@mock.patch("requests.post") |
| 6306 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6307 |
def test_plugin_matrix_e2ee_share_room_key_branches( |
| 6308 |
mock_post, mock_get, mock_put |
| 6309 |
): |
| 6310 |
"""_e2ee_share_room_key edge cases.""" |
| 6311 |
from apprise.plugins.matrix.e2ee import ( |
| 6312 |
MatrixMegOlmSession, |
| 6313 |
MatrixOlmAccount, |
| 6314 |
) |
| 6315 |
|
| 6316 |
def _mk_resp(d, code=requests.codes.ok): |
| 6317 |
r = _Response() |
| 6318 |
r.status_code = code |
| 6319 |
r.content = dumps(d).encode() |
| 6320 |
return r |
| 6321 |
|
| 6322 |
obj = NotifyMatrix( |
| 6323 |
host="h", |
| 6324 |
user="u", |
| 6325 |
password="pass", |
| 6326 |
targets=["#r"], |
| 6327 |
e2ee=True, |
| 6328 |
) |
| 6329 |
obj.access_token = "tok" |
| 6330 |
obj.home_server = "h" |
| 6331 |
obj.user_id = "@sender:h" |
| 6332 |
obj.device_id = "SDEV" |
| 6333 |
obj._e2ee_account = MatrixOlmAccount() |
| 6334 |
session = MatrixMegOlmSession() |
| 6335 |
|
| 6336 |
# members failure -> False |
| 6337 |
with mock.patch.object(obj, "_e2ee_room_members", return_value=None): |
| 6338 |
assert obj._e2ee_share_room_key("!r:h", session) is False |
| 6339 |
|
| 6340 |
# empty members -> True (nothing to send) |
| 6341 |
with mock.patch.object(obj, "_e2ee_room_members", return_value={}): |
| 6342 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6343 |
|
| 6344 |
# keys/claim failure -> False |
| 6345 |
members = {"@other:h": {"DEV": {"curve25519": "IK", "ed25519": "SK"}}} |
| 6346 |
mock_post.return_value = _mk_resp({}, code=500) |
| 6347 |
with mock.patch.object(obj, "_e2ee_room_members", return_value=members): |
| 6348 |
assert obj._e2ee_share_room_key("!r:h", session) is False |
| 6349 |
|
| 6350 |
# keys/claim succeeds but server reports failures{} for remote servers |
| 6351 |
failures_resp = { |
| 6352 |
"one_time_keys": {}, |
| 6353 |
"failures": {"remote.example": {"errcode": "M_UNREACHABLE"}}, |
| 6354 |
} |
| 6355 |
mock_post.return_value = _mk_resp(failures_resp) |
| 6356 |
with mock.patch.object(obj, "_e2ee_room_members", return_value=members): |
| 6357 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6358 |
|
| 6359 |
# own device is skipped (sender uid + device match) |
| 6360 |
own_members = { |
| 6361 |
"@sender:h": {"SDEV": {"curve25519": "IK", "ed25519": "SK"}} |
| 6362 |
} |
| 6363 |
otk_resp = { |
| 6364 |
"one_time_keys": { |
| 6365 |
"@sender:h": {"SDEV": {"signed_curve25519:KID": _rand_b64_32()}} |
| 6366 |
} |
| 6367 |
} |
| 6368 |
mock_post.return_value = _mk_resp(otk_resp) |
| 6369 |
mock_put.return_value = _mk_resp({}) |
| 6370 |
with mock.patch.object( |
| 6371 |
obj, "_e2ee_room_members", return_value=own_members |
| 6372 |
): |
| 6373 |
# All devices skipped -> no PUT; still returns True |
| 6374 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6375 |
|
| 6376 |
# missing curve25519 key -> device skipped |
| 6377 |
no_ik = {"@other:h": {"DEV": {"curve25519": "", "ed25519": "SK"}}} |
| 6378 |
with mock.patch.object(obj, "_e2ee_room_members", return_value=no_ik): |
| 6379 |
mock_post.return_value = _mk_resp( |
| 6380 |
{"one_time_keys": {"@other:h": {"DEV": {}}}} |
| 6381 |
) |
| 6382 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6383 |
|
| 6384 |
# dict-valued OTK with valid signature succeeds end-to-end |
| 6385 |
recipient = MatrixOlmAccount() |
| 6386 |
their_ik = recipient.identity_key |
| 6387 |
their_otk_b64 = _rand_b64_32() |
| 6388 |
signed_otk_dict = _make_signed_otk( |
| 6389 |
recipient, "@other:h", "DEV", their_otk_b64 |
| 6390 |
) |
| 6391 |
dict_members = { |
| 6392 |
"@other:h": { |
| 6393 |
"DEV": { |
| 6394 |
"curve25519": their_ik, |
| 6395 |
"ed25519": recipient.signing_key, |
| 6396 |
} |
| 6397 |
} |
| 6398 |
} |
| 6399 |
dict_otk = { |
| 6400 |
"one_time_keys": { |
| 6401 |
"@other:h": {"DEV": {"signed_curve25519:KID": signed_otk_dict}} |
| 6402 |
} |
| 6403 |
} |
| 6404 |
mock_post.return_value = _mk_resp(dict_otk) |
| 6405 |
mock_put.return_value = _mk_resp({}) |
| 6406 |
with mock.patch.object( |
| 6407 |
obj, "_e2ee_room_members", return_value=dict_members |
| 6408 |
): |
| 6409 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6410 |
payload = loads(mock_put.call_args.kwargs["data"]) |
| 6411 |
dev_payload = payload["messages"]["@other:h"]["DEV"] |
| 6412 |
assert dev_payload["sender_key"] == obj._e2ee_account.identity_key |
| 6413 |
# recipient_key and org.matrix.msgid are non-standard fields |
| 6414 |
# that were removed; verify they are absent |
| 6415 |
assert "recipient_key" not in dev_payload |
| 6416 |
assert "org.matrix.msgid" not in dev_payload |
| 6417 |
|
| 6418 |
# dict-valued OTK with no signatures -> OTK rejected, device skipped |
| 6419 |
unsigned_otk_dict = {"key": their_otk_b64} # no "signatures" field |
| 6420 |
unsigned_otk_resp = { |
| 6421 |
"one_time_keys": { |
| 6422 |
"@other:h": {"DEV": {"signed_curve25519:KID": unsigned_otk_dict}} |
| 6423 |
} |
| 6424 |
} |
| 6425 |
mock_post.return_value = _mk_resp(unsigned_otk_resp) |
| 6426 |
with mock.patch.object( |
| 6427 |
obj, "_e2ee_room_members", return_value=dict_members |
| 6428 |
): |
| 6429 |
# No valid OTK -> no messages built -> True (nothing to send) |
| 6430 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6431 |
|
| 6432 |
# Plain-string OTK for signed_curve25519 -> rejected (not a KeyObject) |
| 6433 |
str_members = { |
| 6434 |
"@other:h": { |
| 6435 |
"DEV": { |
| 6436 |
"curve25519": their_ik, |
| 6437 |
"ed25519": recipient.signing_key, |
| 6438 |
} |
| 6439 |
} |
| 6440 |
} |
| 6441 |
str_otk = { |
| 6442 |
"one_time_keys": { |
| 6443 |
"@other:h": {"DEV": {"signed_curve25519:KID": their_otk_b64}} |
| 6444 |
} |
| 6445 |
} |
| 6446 |
mock_post.return_value = _mk_resp(str_otk) |
| 6447 |
with mock.patch.object( |
| 6448 |
obj, "_e2ee_room_members", return_value=str_members |
| 6449 |
): |
| 6450 |
# No valid KeyObject OTK -> no messages built -> True (nothing sent) |
| 6451 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6452 |
|
| 6453 |
# OTK key not prefixed with "signed_curve25519:" -> skipped, no OTK found |
| 6454 |
bad_key_otk = { |
| 6455 |
"one_time_keys": {"@other:h": {"DEV": {"ed25519:KID": their_otk_b64}}} |
| 6456 |
} |
| 6457 |
mock_post.return_value = _mk_resp(bad_key_otk) |
| 6458 |
with mock.patch.object( |
| 6459 |
obj, "_e2ee_room_members", return_value=str_members |
| 6460 |
): |
| 6461 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6462 |
|
| 6463 |
# OTK entry is not a dict (unexpected server response format) |
| 6464 |
non_dict_otk = {"one_time_keys": {"@other:h": {"DEV": "invalid_format"}}} |
| 6465 |
mock_post.return_value = _mk_resp(non_dict_otk) |
| 6466 |
with mock.patch.object( |
| 6467 |
obj, "_e2ee_room_members", return_value=str_members |
| 6468 |
): |
| 6469 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6470 |
|
| 6471 |
# OTK value is an integer (unknown format) -> skipped |
| 6472 |
non_str_otk = { |
| 6473 |
"one_time_keys": {"@other:h": {"DEV": {"signed_curve25519:KID": 42}}} |
| 6474 |
} |
| 6475 |
mock_post.return_value = _mk_resp(non_str_otk) |
| 6476 |
with mock.patch.object( |
| 6477 |
obj, "_e2ee_room_members", return_value=str_members |
| 6478 |
): |
| 6479 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6480 |
|
| 6481 |
# create_outbound_session raises -> device is skipped gracefully |
| 6482 |
# Use a properly signed OTK so verification passes and the Olm call |
| 6483 |
# is actually reached. |
| 6484 |
create_fail_signed = _make_signed_otk( |
| 6485 |
recipient, "@other:h", "DEV", their_otk_b64 |
| 6486 |
) |
| 6487 |
create_fail_otk = { |
| 6488 |
"one_time_keys": { |
| 6489 |
"@other:h": {"DEV": {"signed_curve25519:KID": create_fail_signed}} |
| 6490 |
} |
| 6491 |
} |
| 6492 |
mock_post.return_value = _mk_resp(create_fail_otk) |
| 6493 |
with ( |
| 6494 |
mock.patch.object( |
| 6495 |
obj, "_e2ee_room_members", return_value=dict_members |
| 6496 |
), |
| 6497 |
mock.patch.object( |
| 6498 |
obj._e2ee_account, |
| 6499 |
"create_outbound_session", |
| 6500 |
side_effect=Exception("olm error"), |
| 6501 |
), |
| 6502 |
): |
| 6503 |
assert obj._e2ee_share_room_key("!r:h", session) is True |
| 6504 |
|
| 6505 |
# sendToDevice PUT fails -> returns False (key-shared flag not set) |
| 6506 |
# Uses a signed OTK so the full Olm path is exercised before the PUT |
| 6507 |
full_signed_otk = _make_signed_otk( |
| 6508 |
recipient, "@other:h", "DEV", their_otk_b64 |
| 6509 |
) |
| 6510 |
full_otk_resp = { |
| 6511 |
"one_time_keys": { |
| 6512 |
"@other:h": {"DEV": {"signed_curve25519:KID": full_signed_otk}} |
| 6513 |
} |
| 6514 |
} |
| 6515 |
mock_post.return_value = _mk_resp(full_otk_resp) |
| 6516 |
mock_put.return_value = _mk_resp({}, code=500) |
| 6517 |
with mock.patch.object( |
| 6518 |
obj, "_e2ee_room_members", return_value=dict_members |
| 6519 |
): |
| 6520 |
assert obj._e2ee_share_room_key("!r:h", session) is False |
| 6521 |
|
| 6522 |
# token-as-password mode: transaction_id is a UUID, not an int. |
| 6523 |
# Previously, the unconditional `+= 1` raised TypeError (UUID + int). |
| 6524 |
# With the guard in place the UUID is used as-is and the send succeeds. |
| 6525 |
import uuid as _uuid_mod |
| 6526 |
|
| 6527 |
uuid_obj = NotifyMatrix( |
| 6528 |
host="h", password="rawtoken", targets=["#r"], e2ee=True |
| 6529 |
) |
| 6530 |
uuid_obj.access_token = "rawtoken" |
| 6531 |
uuid_obj.password = "rawtoken" |
| 6532 |
uuid_obj.transaction_id = _uuid_mod.uuid4() # UUID, not int |
| 6533 |
uuid_obj.home_server = "h" |
| 6534 |
uuid_obj.user_id = "@tok:h" |
| 6535 |
uuid_obj.device_id = "TOKDEV" |
| 6536 |
uuid_obj._e2ee_account = MatrixOlmAccount() |
| 6537 |
|
| 6538 |
uuid_session = MatrixMegOlmSession() |
| 6539 |
uuid_otk = _make_signed_otk(recipient, "@other:h", "DEV", their_otk_b64) |
| 6540 |
uuid_claim = { |
| 6541 |
"one_time_keys": { |
| 6542 |
"@other:h": {"DEV": {"signed_curve25519:KID": uuid_otk}} |
| 6543 |
} |
| 6544 |
} |
| 6545 |
mock_post.return_value = _mk_resp(uuid_claim) |
| 6546 |
mock_put.return_value = _mk_resp({}) |
| 6547 |
with mock.patch.object( |
| 6548 |
uuid_obj, "_e2ee_room_members", return_value=dict_members |
| 6549 |
): |
| 6550 |
# Must not raise TypeError; transaction_id stays as UUID |
| 6551 |
assert uuid_obj._e2ee_share_room_key("!r:h", uuid_session) is True |
| 6552 |
assert isinstance(uuid_obj.transaction_id, _uuid_mod.UUID) |
| 6553 |
|
| 6554 |
|
| 6555 |
@mock.patch("requests.post") |
| 6556 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6557 |
def test_plugin_matrix_e2ee_replenish_otks(mock_post): |
| 6558 |
"""_e2ee_replenish_otks: threshold logic, diagnostics, and error paths.""" |
| 6559 |
from apprise.plugins.matrix.e2ee import MatrixOlmAccount |
| 6560 |
|
| 6561 |
otk_count = NotifyMatrix.default_e2ee_otk_count |
| 6562 |
otk_threshold = NotifyMatrix.default_e2ee_otk_replenish_threshold |
| 6563 |
|
| 6564 |
def _mk_resp(d, code=requests.codes.ok): |
| 6565 |
r = _Response() |
| 6566 |
r.status_code = code |
| 6567 |
r.content = dumps(d).encode() |
| 6568 |
return r |
| 6569 |
|
| 6570 |
def _make_obj(): |
| 6571 |
obj = NotifyMatrix( |
| 6572 |
host="h", user="u", password="pass", targets=["#r"], e2ee=True |
| 6573 |
) |
| 6574 |
obj.user_id = "@u:h" |
| 6575 |
obj.device_id = "DEV" |
| 6576 |
obj._e2ee_account = MatrixOlmAccount() |
| 6577 |
return obj |
| 6578 |
|
| 6579 |
# --- missing credentials: no network call, returns False --- |
| 6580 |
obj = _make_obj() |
| 6581 |
obj.user_id = None |
| 6582 |
assert obj._e2ee_replenish_otks() is False |
| 6583 |
assert mock_post.call_count == 0 |
| 6584 |
|
| 6585 |
obj = _make_obj() |
| 6586 |
obj.device_id = None |
| 6587 |
assert obj._e2ee_replenish_otks() is False |
| 6588 |
assert mock_post.call_count == 0 |
| 6589 |
|
| 6590 |
# --- pool sufficient: skip upload --- |
| 6591 |
# Store a count well above threshold; claimed_count=1 -> remaining is |
| 6592 |
# above default_e2ee_otk_replenish_threshold so no upload should happen. |
| 6593 |
obj = _make_obj() |
| 6594 |
obj.store.set("e2ee_otk_server_count", otk_threshold + otk_count) |
| 6595 |
result = obj._e2ee_replenish_otks(claimed_count=1, skipped_no_otk=0) |
| 6596 |
assert result is True |
| 6597 |
assert mock_post.call_count == 0 |
| 6598 |
|
| 6599 |
# --- pool low: remaining < threshold triggers upload --- |
| 6600 |
obj = _make_obj() |
| 6601 |
obj.store.set("e2ee_otk_server_count", otk_threshold - 1) |
| 6602 |
mock_post.return_value = _mk_resp( |
| 6603 |
{"one_time_key_counts": {"signed_curve25519": otk_count}} |
| 6604 |
) |
| 6605 |
assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is True |
| 6606 |
assert mock_post.call_count == 1 |
| 6607 |
assert obj.store.get("e2ee_otk_server_count") == otk_count |
| 6608 |
assert obj.store.get("e2ee_account") is not None |
| 6609 |
mock_post.reset_mock() |
| 6610 |
|
| 6611 |
# --- unknown server count (no store entry): replenish as precaution --- |
| 6612 |
obj = _make_obj() |
| 6613 |
# e2ee_otk_server_count not set -> unknown |
| 6614 |
mock_post.return_value = _mk_resp( |
| 6615 |
{"one_time_key_counts": {"signed_curve25519": otk_count}} |
| 6616 |
) |
| 6617 |
assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is True |
| 6618 |
assert mock_post.call_count == 1 |
| 6619 |
mock_post.reset_mock() |
| 6620 |
|
| 6621 |
# --- skipped_no_otk > 0: always replenishes regardless of count --- |
| 6622 |
obj = _make_obj() |
| 6623 |
obj.store.set("e2ee_otk_server_count", otk_threshold + otk_count) |
| 6624 |
mock_post.return_value = _mk_resp( |
| 6625 |
{"one_time_key_counts": {"signed_curve25519": otk_count}} |
| 6626 |
) |
| 6627 |
assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=2) is True |
| 6628 |
assert mock_post.call_count == 1 |
| 6629 |
mock_post.reset_mock() |
| 6630 |
|
| 6631 |
# --- upload failure: returns False, logs warning --- |
| 6632 |
obj = _make_obj() |
| 6633 |
obj.store.set("e2ee_otk_server_count", 0) |
| 6634 |
mock_post.return_value = _mk_resp({}, code=500) |
| 6635 |
assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is False |
| 6636 |
mock_post.reset_mock() |
| 6637 |
|
| 6638 |
# --- response missing one_time_key_counts: new count defaults to 0 --- |
| 6639 |
obj = _make_obj() |
| 6640 |
obj.store.set("e2ee_otk_server_count", 0) |
| 6641 |
mock_post.return_value = _mk_resp({}) # no one_time_key_counts key |
| 6642 |
assert obj._e2ee_replenish_otks(claimed_count=0, skipped_no_otk=0) is True |
| 6643 |
assert obj.store.get("e2ee_otk_server_count") == 0 |
| 6644 |
mock_post.reset_mock() |
| 6645 |
|
| 6646 |
|
| 6647 |
@mock.patch("requests.put") |
| 6648 |
@mock.patch("requests.get") |
| 6649 |
@mock.patch("requests.post") |
| 6650 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6651 |
def test_plugin_matrix_e2ee_send_to_room_formats( |
| 6652 |
mock_post, mock_get, mock_put |
| 6653 |
): |
| 6654 |
"""_e2ee_send_to_room: HTML/Markdown format paths and key-share fail.""" |
| 6655 |
from apprise.common import NotifyFormat |
| 6656 |
from apprise.plugins.matrix.e2ee import ( |
| 6657 |
MatrixMegOlmSession, |
| 6658 |
MatrixOlmAccount, |
| 6659 |
) |
| 6660 |
|
| 6661 |
def _mk_resp(d): |
| 6662 |
r = _Response() |
| 6663 |
r.status_code = requests.codes.ok |
| 6664 |
r.content = dumps(d).encode() |
| 6665 |
return r |
| 6666 |
|
| 6667 |
mock_put.return_value = _mk_resp({}) |
| 6668 |
|
| 6669 |
def _make_obj(fmt): |
| 6670 |
obj = NotifyMatrix( |
| 6671 |
host="h", |
| 6672 |
user="u", |
| 6673 |
password="pass", |
| 6674 |
targets=["#r"], |
| 6675 |
e2ee=True, |
| 6676 |
) |
| 6677 |
obj.notify_format = fmt |
| 6678 |
obj.access_token = "tok" |
| 6679 |
obj.home_server = "h" |
| 6680 |
obj.user_id = "@u:h" |
| 6681 |
obj.device_id = "DEV" |
| 6682 |
obj._e2ee_account = MatrixOlmAccount() |
| 6683 |
return obj |
| 6684 |
|
| 6685 |
# HTML format |
| 6686 |
obj = _make_obj(NotifyFormat.HTML) |
| 6687 |
session = MatrixMegOlmSession() |
| 6688 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 6689 |
obj.store.set("e2ee_key_shared_!r:h", session.session_id) |
| 6690 |
assert ( |
| 6691 |
obj._e2ee_send_to_room( |
| 6692 |
"!r:h", "<b>body</b>", "<h1>title</h1>", NotifyType.INFO |
| 6693 |
) |
| 6694 |
is True |
| 6695 |
) |
| 6696 |
|
| 6697 |
# Markdown format |
| 6698 |
obj = _make_obj(NotifyFormat.MARKDOWN) |
| 6699 |
session = MatrixMegOlmSession() |
| 6700 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 6701 |
obj.store.set("e2ee_key_shared_!r:h", session.session_id) |
| 6702 |
assert ( |
| 6703 |
obj._e2ee_send_to_room("!r:h", "**bold**", "title", NotifyType.INFO) |
| 6704 |
is True |
| 6705 |
) |
| 6706 |
|
| 6707 |
# key-share flags set after successful share (no pre-seeded flag) |
| 6708 |
obj = _make_obj(NotifyFormat.TEXT) |
| 6709 |
session = MatrixMegOlmSession() |
| 6710 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 6711 |
with mock.patch.object(obj, "_e2ee_share_room_key", return_value=True): |
| 6712 |
assert ( |
| 6713 |
obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO) is True |
| 6714 |
) |
| 6715 |
|
| 6716 |
# token-as-password mode: access_token == password skips txn increment |
| 6717 |
obj = _make_obj(NotifyFormat.TEXT) |
| 6718 |
obj.access_token = "same" |
| 6719 |
obj.password = "same" |
| 6720 |
session2 = MatrixMegOlmSession() |
| 6721 |
obj.store.set("e2ee_megolm_!r:h", session2.to_dict()) |
| 6722 |
obj.store.set("e2ee_key_shared_!r:h", session2.session_id) |
| 6723 |
assert obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO) is True |
| 6724 |
|
| 6725 |
# key-share failure aborts send |
| 6726 |
obj = _make_obj(NotifyFormat.TEXT) |
| 6727 |
obj.store.clear("e2ee_key_shared_!r:h") |
| 6728 |
with mock.patch.object(obj, "_e2ee_share_room_key", return_value=False): |
| 6729 |
assert ( |
| 6730 |
obj._e2ee_send_to_room("!r:h", "body", "", NotifyType.INFO) |
| 6731 |
is False |
| 6732 |
) |
| 6733 |
|
| 6734 |
|
| 6735 |
@mock.patch("requests.put") |
| 6736 |
@mock.patch("requests.get") |
| 6737 |
@mock.patch("requests.post") |
| 6738 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6739 |
def test_plugin_matrix_e2ee_setup_failure(mock_post, mock_get, mock_put): |
| 6740 |
"""When E2EE setup fails, send falls back to unencrypted.""" |
| 6741 |
resp = _Response() |
| 6742 |
resp.status_code = requests.codes.ok |
| 6743 |
resp.content = dumps( |
| 6744 |
{ |
| 6745 |
"access_token": "tok", |
| 6746 |
"user_id": "@u:h", |
| 6747 |
"home_server": "h", |
| 6748 |
"device_id": "DEV", |
| 6749 |
"room_id": "!r:h", |
| 6750 |
} |
| 6751 |
).encode() |
| 6752 |
# upload keys call fails |
| 6753 |
fail_resp = _Response() |
| 6754 |
fail_resp.status_code = 500 |
| 6755 |
fail_resp.content = dumps({}).encode() |
| 6756 |
mock_put.return_value = resp |
| 6757 |
|
| 6758 |
mock_post.side_effect = [ |
| 6759 |
resp, # login |
| 6760 |
fail_resp, # keys/upload -> failure |
| 6761 |
resp, # join |
| 6762 |
resp, # logout |
| 6763 |
] |
| 6764 |
mock_get.return_value = resp |
| 6765 |
|
| 6766 |
obj = NotifyMatrix( |
| 6767 |
host="h", |
| 6768 |
user="u", |
| 6769 |
password="pass", |
| 6770 |
targets=["!r:h"], |
| 6771 |
e2ee=True, |
| 6772 |
secure=True, |
| 6773 |
discovery=False, |
| 6774 |
) |
| 6775 |
# Falls back to unencrypted -> send succeeds |
| 6776 |
assert obj.send(body="fallback") is True |
| 6777 |
|
| 6778 |
|
| 6779 |
@mock.patch("requests.put") |
| 6780 |
@mock.patch("requests.get") |
| 6781 |
@mock.patch("requests.post") |
| 6782 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6783 |
def test_plugin_matrix_e2ee_attachment_encrypted( |
| 6784 |
mock_post, mock_get, mock_put |
| 6785 |
): |
| 6786 |
"""E2EE mode encrypts and delivers attachments.""" |
| 6787 |
import tempfile |
| 6788 |
|
| 6789 |
login_resp = { |
| 6790 |
"access_token": "tok", |
| 6791 |
"user_id": "@u:h", |
| 6792 |
"home_server": "h", |
| 6793 |
"device_id": "DEV", |
| 6794 |
} |
| 6795 |
upload_resp = {"content_uri": "mxc://h/enc123"} |
| 6796 |
|
| 6797 |
def _mk_resp(d): |
| 6798 |
r = _Response() |
| 6799 |
r.status_code = requests.codes.ok |
| 6800 |
r.content = dumps(d).encode() |
| 6801 |
return r |
| 6802 |
|
| 6803 |
mock_post.side_effect = [ |
| 6804 |
_mk_resp(login_resp), |
| 6805 |
_mk_resp({}), # keys/upload |
| 6806 |
_mk_resp({"room_id": "!r:h"}), # join |
| 6807 |
_mk_resp(upload_resp), # encrypted attachment upload |
| 6808 |
_mk_resp({}), # logout |
| 6809 |
] |
| 6810 |
mock_get.return_value = _mk_resp({"joined": {}}) |
| 6811 |
mock_put.return_value = _mk_resp({}) |
| 6812 |
|
| 6813 |
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f: |
| 6814 |
f.write(b"test attachment") |
| 6815 |
attach_path = f.name |
| 6816 |
|
| 6817 |
try: |
| 6818 |
attach = AppriseAttachment() |
| 6819 |
attach.add(attach_path) |
| 6820 |
|
| 6821 |
obj = NotifyMatrix( |
| 6822 |
host="h", |
| 6823 |
user="u", |
| 6824 |
password="pass", |
| 6825 |
targets=["!r:h"], |
| 6826 |
e2ee=True, |
| 6827 |
secure=True, |
| 6828 |
discovery=False, |
| 6829 |
) |
| 6830 |
from apprise.plugins.matrix.e2ee import MatrixMegOlmSession |
| 6831 |
|
| 6832 |
_s = MatrixMegOlmSession() |
| 6833 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 6834 |
obj.store.set("e2ee_megolm_!r:h", _s.to_dict()) |
| 6835 |
obj.store.set("e2ee_key_shared_!r:h", _s.session_id) |
| 6836 |
assert obj.send(body="body", attach=attach) is True |
| 6837 |
|
| 6838 |
# Two PUTs: encrypted message + encrypted attachment event |
| 6839 |
assert mock_put.call_count == 2 |
| 6840 |
|
| 6841 |
finally: |
| 6842 |
os.unlink(attach_path) |
| 6843 |
|
| 6844 |
|
| 6845 |
@mock.patch("requests.put") |
| 6846 |
@mock.patch("requests.get") |
| 6847 |
@mock.patch("requests.post") |
| 6848 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 6849 |
def test_plugin_matrix_e2ee_send_attachment_errors( |
| 6850 |
mock_post, mock_get, mock_put |
| 6851 |
): |
| 6852 |
"""_e2ee_send_attachment error branches: OSError, network, HTTP fail.""" |
| 6853 |
import tempfile |
| 6854 |
|
| 6855 |
from apprise.plugins.matrix.e2ee import ( |
| 6856 |
MatrixMegOlmSession, |
| 6857 |
MatrixOlmAccount, |
| 6858 |
) |
| 6859 |
|
| 6860 |
def _mk_resp(d, code=requests.codes.ok): |
| 6861 |
r = _Response() |
| 6862 |
r.status_code = code |
| 6863 |
r.content = dumps(d).encode() |
| 6864 |
return r |
| 6865 |
|
| 6866 |
obj = NotifyMatrix( |
| 6867 |
host="h", |
| 6868 |
user="u", |
| 6869 |
password="pass", |
| 6870 |
targets=["!r:h"], |
| 6871 |
e2ee=True, |
| 6872 |
secure=True, |
| 6873 |
discovery=False, |
| 6874 |
) |
| 6875 |
obj.access_token = "tok" |
| 6876 |
obj.home_server = "h" |
| 6877 |
obj.user_id = "@u:h" |
| 6878 |
obj.device_id = "DEV" |
| 6879 |
obj._e2ee_account = MatrixOlmAccount() |
| 6880 |
session = MatrixMegOlmSession() |
| 6881 |
|
| 6882 |
# OSError reading file -> False |
| 6883 |
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f: |
| 6884 |
f.write(b"data") |
| 6885 |
tmp_path = f.name |
| 6886 |
|
| 6887 |
try: |
| 6888 |
|
| 6889 |
class _BadAttach: |
| 6890 |
path = tmp_path |
| 6891 |
name = "f.txt" |
| 6892 |
mimetype = "text/plain" |
| 6893 |
|
| 6894 |
def __len__(self): |
| 6895 |
return 0 |
| 6896 |
|
| 6897 |
with mock.patch("builtins.open", side_effect=OSError("no read")): |
| 6898 |
assert ( |
| 6899 |
obj._e2ee_send_attachment(_BadAttach(), "!r:h", session) |
| 6900 |
is False |
| 6901 |
) |
| 6902 |
|
| 6903 |
# Network error during upload -> False |
| 6904 |
with mock.patch( |
| 6905 |
"requests.post", |
| 6906 |
side_effect=requests.RequestException("boom"), |
| 6907 |
): |
| 6908 |
assert ( |
| 6909 |
obj._e2ee_send_attachment(_BadAttach(), "!r:h", session) |
| 6910 |
is False |
| 6911 |
) |
| 6912 |
|
| 6913 |
# HTTP error from media server -> False |
| 6914 |
with mock.patch("requests.post", return_value=_mk_resp({}, code=500)): |
| 6915 |
assert ( |
| 6916 |
obj._e2ee_send_attachment(_BadAttach(), "!r:h", session) |
| 6917 |
is False |
| 6918 |
) |
| 6919 |
|
| 6920 |
# Upload succeeds but response body is not valid JSON -> treated as |
| 6921 |
# missing content_uri -> False |
| 6922 |
bad_json_resp = _Response() |
| 6923 |
bad_json_resp.status_code = requests.codes.ok |
| 6924 |
bad_json_resp.content = b"not-json" |
| 6925 |
with mock.patch("requests.post", return_value=bad_json_resp): |
| 6926 |
assert ( |
| 6927 |
obj._e2ee_send_attachment(_BadAttach(), "!r:h", session) |
| 6928 |
is False |
| 6929 |
) |
| 6930 |
|
| 6931 |
# base_url raises -> False |
| 6932 |
with mock.patch( |
| 6933 |
"apprise.plugins.matrix.base.NotifyMatrix.base_url", |
| 6934 |
new_callable=mock.PropertyMock, |
| 6935 |
side_effect=Exception("discovery fail"), |
| 6936 |
): |
| 6937 |
assert ( |
| 6938 |
obj._e2ee_send_attachment(_BadAttach(), "!r:h", session) |
| 6939 |
is False |
| 6940 |
) |
| 6941 |
|
| 6942 |
# No access_token -> Authorization header omitted, upload still works |
| 6943 |
obj_noauth = NotifyMatrix( |
| 6944 |
host="h", |
| 6945 |
user="u", |
| 6946 |
password="pass", |
| 6947 |
targets=["!r:h"], |
| 6948 |
e2ee=True, |
| 6949 |
secure=True, |
| 6950 |
discovery=False, |
| 6951 |
) |
| 6952 |
obj_noauth.access_token = None |
| 6953 |
obj_noauth.home_server = "h" |
| 6954 |
obj_noauth.user_id = "@u:h" |
| 6955 |
obj_noauth.device_id = "DEV" |
| 6956 |
obj_noauth._e2ee_account = MatrixOlmAccount() |
| 6957 |
sess_noauth = MatrixMegOlmSession() |
| 6958 |
with mock.patch( |
| 6959 |
"requests.post", |
| 6960 |
return_value=_mk_resp({"content_uri": "mxc://h/y"}), |
| 6961 |
): |
| 6962 |
mock_put.return_value = _mk_resp({}) |
| 6963 |
assert ( |
| 6964 |
obj_noauth._e2ee_send_attachment( |
| 6965 |
_BadAttach(), "!r:h", sess_noauth |
| 6966 |
) |
| 6967 |
is True |
| 6968 |
) |
| 6969 |
|
| 6970 |
# access_token == password -> transaction ID not incremented |
| 6971 |
obj2 = NotifyMatrix( |
| 6972 |
host="h", |
| 6973 |
user="u", |
| 6974 |
password="tok", |
| 6975 |
targets=["!r:h"], |
| 6976 |
e2ee=True, |
| 6977 |
secure=True, |
| 6978 |
discovery=False, |
| 6979 |
) |
| 6980 |
obj2.access_token = "tok" |
| 6981 |
obj2.password = "tok" |
| 6982 |
obj2.home_server = "h" |
| 6983 |
obj2.user_id = "@u:h" |
| 6984 |
obj2.device_id = "DEV" |
| 6985 |
obj2._e2ee_account = MatrixOlmAccount() |
| 6986 |
sess2 = MatrixMegOlmSession() |
| 6987 |
txn_before = obj2.transaction_id |
| 6988 |
upload_r = _mk_resp({"content_uri": "mxc://h/x"}) |
| 6989 |
put_r = _mk_resp({}) |
| 6990 |
with mock.patch("requests.post", return_value=upload_r): |
| 6991 |
mock_put.return_value = put_r |
| 6992 |
result = obj2._e2ee_send_attachment(_BadAttach(), "!r:h", sess2) |
| 6993 |
assert result is True |
| 6994 |
assert obj2.transaction_id == txn_before |
| 6995 |
|
| 6996 |
# Image mimetype -> is_image branch (no 'filename' field added) |
| 6997 |
class _ImageAttach: |
| 6998 |
path = tmp_path |
| 6999 |
name = "photo.png" |
| 7000 |
mimetype = "image/png" |
| 7001 |
|
| 7002 |
def __len__(self): |
| 7003 |
return 4 |
| 7004 |
|
| 7005 |
with mock.patch("requests.post", return_value=upload_r): |
| 7006 |
mock_put.return_value = put_r |
| 7007 |
result = obj2._e2ee_send_attachment(_ImageAttach(), "!r:h", sess2) |
| 7008 |
assert result is True |
| 7009 |
|
| 7010 |
finally: |
| 7011 |
os.unlink(tmp_path) |
| 7012 |
|
| 7013 |
|
| 7014 |
@mock.patch("requests.put") |
| 7015 |
@mock.patch("requests.get") |
| 7016 |
@mock.patch("requests.post") |
| 7017 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 7018 |
def test_plugin_matrix_e2ee_send_attachment_invalid( |
| 7019 |
mock_post, mock_get, mock_put |
| 7020 |
): |
| 7021 |
"""Invalid attachment and _e2ee_send_attachment failure mark has_error.""" |
| 7022 |
import tempfile |
| 7023 |
|
| 7024 |
login_resp = { |
| 7025 |
"access_token": "tok", |
| 7026 |
"user_id": "@u:h", |
| 7027 |
"home_server": "h", |
| 7028 |
"device_id": "DEV", |
| 7029 |
} |
| 7030 |
|
| 7031 |
def _mk_resp(d): |
| 7032 |
r = _Response() |
| 7033 |
r.status_code = requests.codes.ok |
| 7034 |
r.content = dumps(d).encode() |
| 7035 |
return r |
| 7036 |
|
| 7037 |
mock_post.side_effect = [ |
| 7038 |
_mk_resp(login_resp), |
| 7039 |
_mk_resp({}), # keys/upload |
| 7040 |
_mk_resp({"room_id": "!r:h"}), # join |
| 7041 |
_mk_resp({}), # logout |
| 7042 |
] |
| 7043 |
mock_get.return_value = _mk_resp({}) |
| 7044 |
mock_put.return_value = _mk_resp({}) |
| 7045 |
|
| 7046 |
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f: |
| 7047 |
f.write(b"data") |
| 7048 |
attach_path = f.name |
| 7049 |
|
| 7050 |
try: |
| 7051 |
from apprise.plugins.matrix.e2ee import MatrixMegOlmSession |
| 7052 |
|
| 7053 |
obj = NotifyMatrix( |
| 7054 |
host="h", |
| 7055 |
user="u", |
| 7056 |
password="pass", |
| 7057 |
targets=["!r:h"], |
| 7058 |
e2ee=True, |
| 7059 |
secure=True, |
| 7060 |
discovery=False, |
| 7061 |
) |
| 7062 |
_s = MatrixMegOlmSession() |
| 7063 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 7064 |
obj.store.set("e2ee_megolm_!r:h", _s.to_dict()) |
| 7065 |
obj.store.set("e2ee_key_shared_!r:h", _s.session_id) |
| 7066 |
|
| 7067 |
attach = AppriseAttachment() |
| 7068 |
attach.add(attach_path) |
| 7069 |
|
| 7070 |
# _e2ee_send_attachment fails -> send returns False |
| 7071 |
with mock.patch.object( |
| 7072 |
obj, "_e2ee_send_attachment", return_value=False |
| 7073 |
): |
| 7074 |
assert obj.send(body="body", attach=attach) is False |
| 7075 |
|
| 7076 |
# Invalid attachment (falsy) in list -> has_error set and loop breaks |
| 7077 |
mock_post.reset_mock() |
| 7078 |
mock_post.side_effect = [ |
| 7079 |
_mk_resp(login_resp), |
| 7080 |
_mk_resp({}), # keys/upload |
| 7081 |
_mk_resp({"room_id": "!r:h"}), # join |
| 7082 |
_mk_resp({}), # logout |
| 7083 |
] |
| 7084 |
obj2 = NotifyMatrix( |
| 7085 |
host="h", |
| 7086 |
user="u", |
| 7087 |
password="pass", |
| 7088 |
targets=["!r:h"], |
| 7089 |
e2ee=True, |
| 7090 |
secure=True, |
| 7091 |
discovery=False, |
| 7092 |
) |
| 7093 |
_s2 = MatrixMegOlmSession() |
| 7094 |
obj2.store.set("e2ee_room_enc_!r:h", True) |
| 7095 |
obj2.store.set("e2ee_megolm_!r:h", _s2.to_dict()) |
| 7096 |
obj2.store.set("e2ee_key_shared_!r:h", _s2.session_id) |
| 7097 |
# Add a non-existent file to get a falsy attachment |
| 7098 |
bad_attach = AppriseAttachment() |
| 7099 |
bad_attach.add("/nonexistent/path/file.txt") |
| 7100 |
with mock.patch.object(obj2, "_e2ee_send_to_room", return_value=True): |
| 7101 |
assert obj2.send(body="body", attach=bad_attach) is False |
| 7102 |
|
| 7103 |
finally: |
| 7104 |
os.unlink(attach_path) |
| 7105 |
|
| 7106 |
|
| 7107 |
@mock.patch("requests.put") |
| 7108 |
@mock.patch("requests.get") |
| 7109 |
@mock.patch("requests.post") |
| 7110 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 7111 |
def test_plugin_matrix_e2ee_send_room_failure(mock_post, mock_get, mock_put): |
| 7112 |
"""E2EE path returns False when _e2ee_send_to_room fails.""" |
| 7113 |
login_resp = { |
| 7114 |
"access_token": "tok", |
| 7115 |
"user_id": "@u:h", |
| 7116 |
"home_server": "h", |
| 7117 |
"device_id": "DEV", |
| 7118 |
} |
| 7119 |
|
| 7120 |
def _mk_resp(d): |
| 7121 |
r = _Response() |
| 7122 |
r.status_code = requests.codes.ok |
| 7123 |
r.content = dumps(d).encode() |
| 7124 |
return r |
| 7125 |
|
| 7126 |
mock_post.side_effect = [ |
| 7127 |
_mk_resp(login_resp), |
| 7128 |
_mk_resp({}), # keys/upload |
| 7129 |
_mk_resp({"room_id": "!r:h"}), # join |
| 7130 |
_mk_resp({}), # logout |
| 7131 |
] |
| 7132 |
mock_get.return_value = _mk_resp({}) |
| 7133 |
mock_put.return_value = _mk_resp({}) |
| 7134 |
|
| 7135 |
from apprise.plugins.matrix.e2ee import MatrixMegOlmSession |
| 7136 |
|
| 7137 |
obj = NotifyMatrix( |
| 7138 |
host="h", |
| 7139 |
user="u", |
| 7140 |
password="pass", |
| 7141 |
targets=["!r:h"], |
| 7142 |
e2ee=True, |
| 7143 |
secure=True, |
| 7144 |
discovery=False, |
| 7145 |
) |
| 7146 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 7147 |
_s = MatrixMegOlmSession() |
| 7148 |
obj.store.set("e2ee_megolm_!r:h", _s.to_dict()) |
| 7149 |
obj.store.set("e2ee_key_shared_!r:h", _s.session_id) |
| 7150 |
|
| 7151 |
with mock.patch.object(obj, "_e2ee_send_to_room", return_value=False): |
| 7152 |
assert obj.send(body="fail") is False |
| 7153 |
|
| 7154 |
|
| 7155 |
@mock.patch("requests.put") |
| 7156 |
@mock.patch("requests.get") |
| 7157 |
@mock.patch("requests.post") |
| 7158 |
def test_plugin_matrix_register_with_device_id(mock_post, mock_get, mock_put): |
| 7159 |
"""Registration response that includes device_id persists it.""" |
| 7160 |
r = _Response() |
| 7161 |
r.status_code = requests.codes.ok |
| 7162 |
r.content = dumps( |
| 7163 |
{ |
| 7164 |
"access_token": "tok", |
| 7165 |
"user_id": "@u:h", |
| 7166 |
"home_server": "h", |
| 7167 |
"device_id": "REG_DEV", |
| 7168 |
} |
| 7169 |
).encode() |
| 7170 |
mock_post.return_value = r |
| 7171 |
|
| 7172 |
obj = NotifyMatrix(host="h", discovery=False) |
| 7173 |
assert obj._register() is True |
| 7174 |
assert obj.device_id == "REG_DEV" |
| 7175 |
assert obj.store.get("device_id") == "REG_DEV" |
| 7176 |
|
| 7177 |
|
| 7178 |
@mock.patch("requests.put") |
| 7179 |
@mock.patch("requests.get") |
| 7180 |
@mock.patch("requests.post") |
| 7181 |
def test_plugin_matrix_login_reuses_device_id(mock_post, mock_get, mock_put): |
| 7182 |
"""Login payload reuses the stored device ID when present.""" |
| 7183 |
r = _Response() |
| 7184 |
r.status_code = requests.codes.ok |
| 7185 |
r.content = dumps( |
| 7186 |
{ |
| 7187 |
"access_token": "tok", |
| 7188 |
"user_id": "@u:h", |
| 7189 |
"home_server": "h", |
| 7190 |
"device_id": "DEV_REUSED", |
| 7191 |
} |
| 7192 |
).encode() |
| 7193 |
mock_post.return_value = r |
| 7194 |
|
| 7195 |
obj = NotifyMatrix(host="h", user="u", password="pass", discovery=False) |
| 7196 |
obj.device_id = "DEV_REUSED" |
| 7197 |
assert obj._login() is True |
| 7198 |
|
| 7199 |
payload = mock_post.call_args.kwargs["data"] |
| 7200 |
assert '"device_id": "DEV_REUSED"' in payload |
| 7201 |
|
| 7202 |
|
| 7203 |
@mock.patch("requests.put") |
| 7204 |
@mock.patch("requests.get") |
| 7205 |
@mock.patch("requests.post") |
| 7206 |
def test_plugin_matrix_register_reuses_device_id( |
| 7207 |
mock_post, mock_get, mock_put |
| 7208 |
): |
| 7209 |
"""Register payload reuses the stored device ID when present.""" |
| 7210 |
r = _Response() |
| 7211 |
r.status_code = requests.codes.ok |
| 7212 |
r.content = dumps( |
| 7213 |
{ |
| 7214 |
"access_token": "tok", |
| 7215 |
"user_id": "@u:h", |
| 7216 |
"home_server": "h", |
| 7217 |
"device_id": "DEV_REUSED", |
| 7218 |
} |
| 7219 |
).encode() |
| 7220 |
mock_post.return_value = r |
| 7221 |
|
| 7222 |
obj = NotifyMatrix(host="h", user="u", password="pass", discovery=False) |
| 7223 |
obj.device_id = "DEV_REUSED" |
| 7224 |
assert obj._register() is True |
| 7225 |
|
| 7226 |
payload = mock_post.call_args.kwargs["data"] |
| 7227 |
assert '"device_id": "DEV_REUSED"' in payload |
| 7228 |
|
| 7229 |
|
| 7230 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 7231 |
def test_plugin_matrix_e2ee_account_bad_store_data(): |
| 7232 |
"""Corrupt e2ee_account in store is silently ignored.""" |
| 7233 |
obj = NotifyMatrix( |
| 7234 |
host="h", |
| 7235 |
user="u", |
| 7236 |
password="pass", |
| 7237 |
targets=["#r"], |
| 7238 |
e2ee=True, |
| 7239 |
) |
| 7240 |
obj.store.set("e2ee_account", {"ik": "NOTVALID", "sk": "NOTVALID"}) |
| 7241 |
|
| 7242 |
# Re-instantiate with the same store to trigger the restore path |
| 7243 |
obj2 = NotifyMatrix( |
| 7244 |
host="h", |
| 7245 |
user="u", |
| 7246 |
password="pass", |
| 7247 |
targets=["#r"], |
| 7248 |
e2ee=True, |
| 7249 |
store=obj.store, |
| 7250 |
) |
| 7251 |
# Bad data is suppressed; account is None until setup is called |
| 7252 |
assert obj2._e2ee_account is None |
| 7253 |
|
| 7254 |
|
| 7255 |
def test_plugin_matrix_del_suppresses_logout_exceptions(): |
| 7256 |
"""__del__ should never raise if logout fails during GC cleanup.""" |
| 7257 |
obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"]) |
| 7258 |
obj.access_token = "tok" |
| 7259 |
|
| 7260 |
with mock.patch.object(obj, "_logout", side_effect=RuntimeError("boom")): |
| 7261 |
obj.__del__() |
| 7262 |
|
| 7263 |
|
| 7264 |
# --------------------------------------------------------------------------- |
| 7265 |
# DM / direct-message tests |
| 7266 |
# --------------------------------------------------------------------------- |
| 7267 |
|
| 7268 |
|
| 7269 |
def test_plugin_matrix_dm_target_separation(): |
| 7270 |
"""@user targets are separated from room targets at init time.""" |
| 7271 |
obj = NotifyMatrix( |
| 7272 |
host="h", |
| 7273 |
user="u", |
| 7274 |
password="pass", |
| 7275 |
targets=["#general", "@alice", "@bob:other.com", "!room:h"], |
| 7276 |
discovery=False, |
| 7277 |
) |
| 7278 |
assert "#general" in obj.rooms |
| 7279 |
assert "!room:h" in obj.rooms |
| 7280 |
assert "@alice" in obj.users |
| 7281 |
assert "@bob:other.com" in obj.users |
| 7282 |
assert len(obj.rooms) == 2 |
| 7283 |
assert len(obj.users) == 2 |
| 7284 |
|
| 7285 |
# __len__ accounts for both rooms and users |
| 7286 |
assert len(obj) == 4 |
| 7287 |
|
| 7288 |
|
| 7289 |
def test_plugin_matrix_dm_url_roundtrip(): |
| 7290 |
"""@user targets survive a url() -> parse_url() -> NotifyMatrix cycle.""" |
| 7291 |
obj = NotifyMatrix( |
| 7292 |
host="h", |
| 7293 |
user="u", |
| 7294 |
password="pass", |
| 7295 |
targets=["#room", "@alice"], |
| 7296 |
discovery=False, |
| 7297 |
secure=True, |
| 7298 |
) |
| 7299 |
url = obj.url() |
| 7300 |
# @ is URL-encoded to %40 inside the path segment |
| 7301 |
assert "%40alice" in url |
| 7302 |
|
| 7303 |
result = NotifyMatrix.parse_url(url) |
| 7304 |
assert result is not None |
| 7305 |
obj2 = NotifyMatrix(**result) |
| 7306 |
assert "@alice" in obj2.users |
| 7307 |
assert any("room" in r for r in obj2.rooms) |
| 7308 |
|
| 7309 |
|
| 7310 |
@mock.patch("requests.put") |
| 7311 |
@mock.patch("requests.get") |
| 7312 |
@mock.patch("requests.post") |
| 7313 |
def test_plugin_matrix_dm_room_find_cached(mock_post, mock_get, mock_put): |
| 7314 |
"""_dm_room_find_or_create returns cached room ID without HTTP calls.""" |
| 7315 |
|
| 7316 |
def _mk_resp(d, code=requests.codes.ok): |
| 7317 |
r = _Response() |
| 7318 |
r.status_code = code |
| 7319 |
r.content = dumps(d).encode() |
| 7320 |
return r |
| 7321 |
|
| 7322 |
mock_post.return_value = _mk_resp({}) |
| 7323 |
mock_get.return_value = _mk_resp({}) |
| 7324 |
mock_put.return_value = _mk_resp({}) |
| 7325 |
|
| 7326 |
obj = NotifyMatrix( |
| 7327 |
host="h", |
| 7328 |
user="u", |
| 7329 |
password="pass", |
| 7330 |
targets=["@alice"], |
| 7331 |
discovery=False, |
| 7332 |
) |
| 7333 |
obj.access_token = "tok" |
| 7334 |
obj.user_id = "@u:h" |
| 7335 |
obj.home_server = "h" |
| 7336 |
|
| 7337 |
# Seed the cache |
| 7338 |
obj.store.set("dm_room_@alice:h", "!dm123:h") |
| 7339 |
|
| 7340 |
room_id = obj._dm_room_find_or_create("@alice") |
| 7341 |
assert room_id == "!dm123:h" |
| 7342 |
# No HTTP calls should have been made |
| 7343 |
assert mock_get.call_count == 0 |
| 7344 |
assert mock_post.call_count == 0 |
| 7345 |
|
| 7346 |
|
| 7347 |
@mock.patch("requests.put") |
| 7348 |
@mock.patch("requests.get") |
| 7349 |
@mock.patch("requests.post") |
| 7350 |
def test_plugin_matrix_dm_room_find_via_mdirect(mock_post, mock_get, mock_put): |
| 7351 |
"""_dm_room_find_or_create finds existing room from m.direct data.""" |
| 7352 |
|
| 7353 |
def _mk_resp(d, code=requests.codes.ok): |
| 7354 |
r = _Response() |
| 7355 |
r.status_code = code |
| 7356 |
r.content = dumps(d).encode() |
| 7357 |
return r |
| 7358 |
|
| 7359 |
mdirect = {"@alice:h": ["!existing_dm:h"]} |
| 7360 |
mock_get.return_value = _mk_resp(mdirect) |
| 7361 |
mock_post.return_value = _mk_resp({}) |
| 7362 |
mock_put.return_value = _mk_resp({}) |
| 7363 |
|
| 7364 |
obj = NotifyMatrix( |
| 7365 |
host="h", |
| 7366 |
user="u", |
| 7367 |
password="pass", |
| 7368 |
targets=["@alice"], |
| 7369 |
discovery=False, |
| 7370 |
) |
| 7371 |
obj.access_token = "tok" |
| 7372 |
obj.user_id = "@u:h" |
| 7373 |
obj.home_server = "h" |
| 7374 |
|
| 7375 |
room_id = obj._dm_room_find_or_create("@alice") |
| 7376 |
assert room_id == "!existing_dm:h" |
| 7377 |
|
| 7378 |
# Result is now cached |
| 7379 |
assert obj.store.get("dm_room_@alice:h") == "!existing_dm:h" |
| 7380 |
|
| 7381 |
# No createRoom POST should have been made |
| 7382 |
assert mock_post.call_count == 0 |
| 7383 |
|
| 7384 |
|
| 7385 |
@mock.patch("requests.put") |
| 7386 |
@mock.patch("requests.get") |
| 7387 |
@mock.patch("requests.post") |
| 7388 |
def test_plugin_matrix_dm_room_create_new(mock_post, mock_get, mock_put): |
| 7389 |
"""_dm_room_find_or_create creates a new room when none exists.""" |
| 7390 |
|
| 7391 |
def _mk_resp(d, code=requests.codes.ok): |
| 7392 |
r = _Response() |
| 7393 |
r.status_code = code |
| 7394 |
r.content = dumps(d).encode() |
| 7395 |
return r |
| 7396 |
|
| 7397 |
# GET m.direct returns empty (no existing DM for alice) |
| 7398 |
mock_get.return_value = _mk_resp({}) |
| 7399 |
# First POST = createRoom, second = (not called) |
| 7400 |
mock_post.return_value = _mk_resp({"room_id": "!new_dm:h"}) |
| 7401 |
mock_put.return_value = _mk_resp({}) |
| 7402 |
|
| 7403 |
obj = NotifyMatrix( |
| 7404 |
host="h", |
| 7405 |
user="u", |
| 7406 |
password="pass", |
| 7407 |
targets=["@alice"], |
| 7408 |
discovery=False, |
| 7409 |
) |
| 7410 |
obj.access_token = "tok" |
| 7411 |
obj.user_id = "@u:h" |
| 7412 |
obj.home_server = "h" |
| 7413 |
|
| 7414 |
room_id = obj._dm_room_find_or_create("@alice") |
| 7415 |
assert room_id == "!new_dm:h" |
| 7416 |
|
| 7417 |
# Should be cached |
| 7418 |
assert obj.store.get("dm_room_@alice:h") == "!new_dm:h" |
| 7419 |
|
| 7420 |
# m.direct PUT should have been called to update the mapping |
| 7421 |
assert mock_put.call_count >= 1 |
| 7422 |
|
| 7423 |
|
| 7424 |
@mock.patch("requests.put") |
| 7425 |
@mock.patch("requests.get") |
| 7426 |
@mock.patch("requests.post") |
| 7427 |
def test_plugin_matrix_dm_room_create_failure(mock_post, mock_get, mock_put): |
| 7428 |
"""_dm_room_find_or_create returns None when createRoom fails.""" |
| 7429 |
|
| 7430 |
def _mk_resp(d, code=requests.codes.ok): |
| 7431 |
r = _Response() |
| 7432 |
r.status_code = code |
| 7433 |
r.content = dumps(d).encode() |
| 7434 |
return r |
| 7435 |
|
| 7436 |
mock_get.return_value = _mk_resp({}) |
| 7437 |
mock_post.return_value = _mk_resp( |
| 7438 |
{"errcode": "M_FORBIDDEN"}, code=requests.codes.forbidden |
| 7439 |
) |
| 7440 |
mock_put.return_value = _mk_resp({}) |
| 7441 |
|
| 7442 |
obj = NotifyMatrix( |
| 7443 |
host="h", |
| 7444 |
user="u", |
| 7445 |
password="pass", |
| 7446 |
targets=["@alice"], |
| 7447 |
discovery=False, |
| 7448 |
) |
| 7449 |
obj.access_token = "tok" |
| 7450 |
obj.user_id = "@u:h" |
| 7451 |
obj.home_server = "h" |
| 7452 |
|
| 7453 |
assert obj._dm_room_find_or_create("@alice") is None |
| 7454 |
|
| 7455 |
|
| 7456 |
@mock.patch("requests.put") |
| 7457 |
@mock.patch("requests.get") |
| 7458 |
@mock.patch("requests.post") |
| 7459 |
def test_plugin_matrix_dm_room_create_no_room_id( |
| 7460 |
mock_post, mock_get, mock_put |
| 7461 |
): |
| 7462 |
"""_dm_room_find_or_create returns None when createRoom omits room_id.""" |
| 7463 |
|
| 7464 |
def _mk_resp(d, code=requests.codes.ok): |
| 7465 |
r = _Response() |
| 7466 |
r.status_code = code |
| 7467 |
r.content = dumps(d).encode() |
| 7468 |
return r |
| 7469 |
|
| 7470 |
mock_get.return_value = _mk_resp({}) |
| 7471 |
# createRoom returns 200 but no room_id key |
| 7472 |
mock_post.return_value = _mk_resp({}) |
| 7473 |
mock_put.return_value = _mk_resp({}) |
| 7474 |
|
| 7475 |
obj = NotifyMatrix( |
| 7476 |
host="h", |
| 7477 |
user="u", |
| 7478 |
password="pass", |
| 7479 |
targets=["@alice"], |
| 7480 |
discovery=False, |
| 7481 |
) |
| 7482 |
obj.access_token = "tok" |
| 7483 |
obj.user_id = "@u:h" |
| 7484 |
obj.home_server = "h" |
| 7485 |
|
| 7486 |
assert obj._dm_room_find_or_create("@alice") is None |
| 7487 |
|
| 7488 |
|
| 7489 |
def test_plugin_matrix_dm_invalid_user(): |
| 7490 |
"""_dm_room_find_or_create returns None for a malformed user target.""" |
| 7491 |
obj = NotifyMatrix( |
| 7492 |
host="h", |
| 7493 |
user="u", |
| 7494 |
password="pass", |
| 7495 |
targets=["#r"], |
| 7496 |
discovery=False, |
| 7497 |
) |
| 7498 |
obj.access_token = "tok" |
| 7499 |
obj.user_id = "@u:h" |
| 7500 |
obj.home_server = "h" |
| 7501 |
|
| 7502 |
# No @ prefix -- not a valid user target |
| 7503 |
assert obj._dm_room_find_or_create("notauser") is None |
| 7504 |
|
| 7505 |
|
| 7506 |
@mock.patch("requests.put") |
| 7507 |
@mock.patch("requests.get") |
| 7508 |
@mock.patch("requests.post") |
| 7509 |
def test_plugin_matrix_dm_send_notification(mock_post, mock_get, mock_put): |
| 7510 |
"""Sending to @user target resolves DM room and delivers message.""" |
| 7511 |
|
| 7512 |
def _mk_resp(d, code=requests.codes.ok): |
| 7513 |
r = _Response() |
| 7514 |
r.status_code = code |
| 7515 |
r.content = dumps(d).encode() |
| 7516 |
return r |
| 7517 |
|
| 7518 |
mock_get.return_value = _mk_resp({}) |
| 7519 |
mock_put.return_value = _mk_resp({}) |
| 7520 |
mock_post.side_effect = [ |
| 7521 |
_mk_resp( |
| 7522 |
{"access_token": "tok", "user_id": "@u:h", "home_server": "h"} |
| 7523 |
), # login |
| 7524 |
_mk_resp({"room_id": "!new_dm:h"}), # createRoom |
| 7525 |
_mk_resp({}), # logout |
| 7526 |
] |
| 7527 |
|
| 7528 |
obj = NotifyMatrix( |
| 7529 |
host="h", |
| 7530 |
user="u", |
| 7531 |
password="pass", |
| 7532 |
targets=["@alice"], |
| 7533 |
discovery=False, |
| 7534 |
e2ee=False, |
| 7535 |
) |
| 7536 |
|
| 7537 |
# Pre-seed DM room so _room_join succeeds |
| 7538 |
def _join_side(*a, **kw): |
| 7539 |
return "!new_dm:h" |
| 7540 |
|
| 7541 |
with ( |
| 7542 |
mock.patch.object(obj, "_room_join", side_effect=_join_side), |
| 7543 |
mock.patch.object( |
| 7544 |
obj, "_dm_room_find_or_create", return_value="!new_dm:h" |
| 7545 |
), |
| 7546 |
): |
| 7547 |
assert obj.send(body="hello DM") is True |
| 7548 |
|
| 7549 |
|
| 7550 |
def test_plugin_matrix_failed_dm_is_retried(): |
| 7551 |
"""A resolved DM is recorded only after its message succeeds.""" |
| 7552 |
|
| 7553 |
obj = NotifyMatrix( |
| 7554 |
host="h", |
| 7555 |
user="u", |
| 7556 |
password="pass", |
| 7557 |
targets=["@alice"], |
| 7558 |
discovery=False, |
| 7559 |
e2ee=False, |
| 7560 |
) |
| 7561 |
obj.access_token = "tok" |
| 7562 |
obj.user_id = "@u:h" |
| 7563 |
obj.home_server = "h" |
| 7564 |
|
| 7565 |
tracker_token = _delivery_tracker.set(set()) |
| 7566 |
try: |
| 7567 |
with ( |
| 7568 |
mock.patch.object( |
| 7569 |
obj, |
| 7570 |
"_dm_room_find_or_create", |
| 7571 |
return_value="!dm:h", |
| 7572 |
) as resolve, |
| 7573 |
mock.patch.object(obj, "_room_join", return_value="!dm:h"), |
| 7574 |
mock.patch.object( |
| 7575 |
obj, |
| 7576 |
"_fetch", |
| 7577 |
side_effect=[ |
| 7578 |
(False, {}, requests.codes.bad_request), |
| 7579 |
(True, {}, requests.codes.ok), |
| 7580 |
], |
| 7581 |
), |
| 7582 |
): |
| 7583 |
assert obj.send(body="hello") is False |
| 7584 |
assert obj.is_delivered(("user", "@alice")) is False |
| 7585 |
|
| 7586 |
assert obj.send(body="hello") is True |
| 7587 |
assert resolve.call_count == 2 |
| 7588 |
assert obj.is_delivered(("user", "@alice")) is True |
| 7589 |
finally: |
| 7590 |
_delivery_tracker.reset(tracker_token) |
| 7591 |
|
| 7592 |
|
| 7593 |
def test_plugin_matrix_retry_does_not_repeat_attachment_message(): |
| 7594 |
"""Retry the failed body without repeating a visible attachment.""" |
| 7595 |
|
| 7596 |
obj = NotifyMatrix( |
| 7597 |
host="h", |
| 7598 |
user="u", |
| 7599 |
password="pass", |
| 7600 |
targets=["#general"], |
| 7601 |
discovery=False, |
| 7602 |
e2ee=False, |
| 7603 |
) |
| 7604 |
obj.access_token = "tok" |
| 7605 |
obj.user_id = "@u:h" |
| 7606 |
obj.home_server = "h" |
| 7607 |
|
| 7608 |
attachment_payload = { |
| 7609 |
"msgtype": "m.file", |
| 7610 |
"body": "report.pdf", |
| 7611 |
"url": "mxc://h/file", |
| 7612 |
} |
| 7613 |
tracker_token = _delivery_tracker.set(set()) |
| 7614 |
try: |
| 7615 |
with ( |
| 7616 |
mock.patch.object(obj, "_room_join", return_value="!room:h"), |
| 7617 |
mock.patch.object( |
| 7618 |
obj, |
| 7619 |
"_send_attachments", |
| 7620 |
return_value=[attachment_payload.copy()], |
| 7621 |
), |
| 7622 |
mock.patch.object( |
| 7623 |
obj, |
| 7624 |
"_fetch", |
| 7625 |
side_effect=[ |
| 7626 |
(True, {}, requests.codes.ok), |
| 7627 |
(False, {}, requests.codes.bad_request), |
| 7628 |
(True, {}, requests.codes.ok), |
| 7629 |
], |
| 7630 |
) as fetch, |
| 7631 |
): |
| 7632 |
assert obj.send(body="hello", attach=[mock.Mock()]) is False |
| 7633 |
assert obj.send(body="hello", attach=[mock.Mock()]) is True |
| 7634 |
|
| 7635 |
finally: |
| 7636 |
_delivery_tracker.reset(tracker_token) |
| 7637 |
|
| 7638 |
attachment_calls = [ |
| 7639 |
call |
| 7640 |
for call in fetch.call_args_list |
| 7641 |
if call.kwargs.get("payload", {}).get("msgtype") == "m.file" |
| 7642 |
] |
| 7643 |
assert len(attachment_calls) == 1 |
| 7644 |
|
| 7645 |
|
| 7646 |
@mock.patch("requests.put") |
| 7647 |
@mock.patch("requests.get") |
| 7648 |
@mock.patch("requests.post") |
| 7649 |
def test_plugin_matrix_dm_only_users_no_rooms_skips_joined( |
| 7650 |
mock_post, mock_get, mock_put |
| 7651 |
): |
| 7652 |
"""When only @user targets are present, _joined_rooms is not queried.""" |
| 7653 |
|
| 7654 |
def _mk_resp(d, code=requests.codes.ok): |
| 7655 |
r = _Response() |
| 7656 |
r.status_code = code |
| 7657 |
r.content = dumps(d).encode() |
| 7658 |
return r |
| 7659 |
|
| 7660 |
mock_get.return_value = _mk_resp({}) |
| 7661 |
mock_put.return_value = _mk_resp({}) |
| 7662 |
mock_post.side_effect = [ |
| 7663 |
_mk_resp( |
| 7664 |
{"access_token": "tok", "user_id": "@u:h", "home_server": "h"} |
| 7665 |
), # login |
| 7666 |
_mk_resp({}), # logout |
| 7667 |
] |
| 7668 |
|
| 7669 |
obj = NotifyMatrix( |
| 7670 |
host="h", |
| 7671 |
user="u", |
| 7672 |
password="pass", |
| 7673 |
targets=["@alice"], |
| 7674 |
discovery=False, |
| 7675 |
e2ee=False, |
| 7676 |
) |
| 7677 |
|
| 7678 |
with ( |
| 7679 |
mock.patch.object(obj, "_joined_rooms", return_value=[]) as mock_jr, |
| 7680 |
mock.patch.object(obj, "_dm_room_find_or_create", return_value=None), |
| 7681 |
): |
| 7682 |
obj.send(body="hi") |
| 7683 |
# _joined_rooms must NOT have been called |
| 7684 |
assert mock_jr.call_count == 0 |
| 7685 |
|
| 7686 |
|
| 7687 |
@mock.patch("requests.put") |
| 7688 |
@mock.patch("requests.get") |
| 7689 |
@mock.patch("requests.post") |
| 7690 |
def test_plugin_matrix_dm_room_create_mdirect_get_fails( |
| 7691 |
mock_post, mock_get, mock_put |
| 7692 |
): |
| 7693 |
"""_dm_room_find_or_create still creates room if m.direct GET fails.""" |
| 7694 |
|
| 7695 |
def _mk_resp(d, code=requests.codes.ok): |
| 7696 |
r = _Response() |
| 7697 |
r.status_code = code |
| 7698 |
r.content = dumps(d).encode() |
| 7699 |
return r |
| 7700 |
|
| 7701 |
# GET fails (404) |
| 7702 |
mock_get.return_value = _mk_resp({}, code=404) |
| 7703 |
mock_post.return_value = _mk_resp({"room_id": "!fallback:h"}) |
| 7704 |
mock_put.return_value = _mk_resp({}) |
| 7705 |
|
| 7706 |
obj = NotifyMatrix( |
| 7707 |
host="h", |
| 7708 |
user="u", |
| 7709 |
password="pass", |
| 7710 |
targets=["@alice"], |
| 7711 |
discovery=False, |
| 7712 |
) |
| 7713 |
obj.access_token = "tok" |
| 7714 |
obj.user_id = "@u:h" |
| 7715 |
obj.home_server = "h" |
| 7716 |
|
| 7717 |
room_id = obj._dm_room_find_or_create("@alice") |
| 7718 |
assert room_id == "!fallback:h" |
| 7719 |
|
| 7720 |
|
| 7721 |
@mock.patch("requests.put") |
| 7722 |
@mock.patch("requests.get") |
| 7723 |
@mock.patch("requests.post") |
| 7724 |
def test_plugin_matrix_dm_room_create_no_user_id( |
| 7725 |
mock_post, mock_get, mock_put |
| 7726 |
): |
| 7727 |
"""_dm_room_find_or_create creates room when user_id is None (skips |
| 7728 |
the m.direct GET and PUT).""" |
| 7729 |
|
| 7730 |
def _mk_resp(d, code=requests.codes.ok): |
| 7731 |
r = _Response() |
| 7732 |
r.status_code = code |
| 7733 |
r.content = dumps(d).encode() |
| 7734 |
return r |
| 7735 |
|
| 7736 |
mock_get.return_value = _mk_resp({}) |
| 7737 |
mock_post.return_value = _mk_resp({"room_id": "!nodm:h"}) |
| 7738 |
mock_put.return_value = _mk_resp({}) |
| 7739 |
|
| 7740 |
obj = NotifyMatrix( |
| 7741 |
host="h", |
| 7742 |
user="u", |
| 7743 |
password="pass", |
| 7744 |
targets=["@alice"], |
| 7745 |
discovery=False, |
| 7746 |
) |
| 7747 |
obj.access_token = "tok" |
| 7748 |
# user_id intentionally left as None so the m.direct branch is skipped |
| 7749 |
obj.home_server = "h" |
| 7750 |
|
| 7751 |
room_id = obj._dm_room_find_or_create("@alice") |
| 7752 |
assert room_id == "!nodm:h" |
| 7753 |
# No GET and no PUT for m.direct since user_id is None |
| 7754 |
assert mock_get.call_count == 0 |
| 7755 |
|
| 7756 |
|
| 7757 |
@mock.patch("requests.put") |
| 7758 |
@mock.patch("requests.get") |
| 7759 |
@mock.patch("requests.post") |
| 7760 |
def test_plugin_matrix_dm_room_create_e2ee(mock_post, mock_get, mock_put): |
| 7761 |
"""_dm_room_find_or_create with e2ee=True/secure=True embeds |
| 7762 |
initial_state and pre-seeds the room encryption cache.""" |
| 7763 |
from apprise.plugins.matrix.base import MATRIX_E2EE_SUPPORT |
| 7764 |
|
| 7765 |
if not MATRIX_E2EE_SUPPORT: |
| 7766 |
pytest.skip("cryptography package not installed") |
| 7767 |
|
| 7768 |
def _mk_resp(d, code=requests.codes.ok): |
| 7769 |
r = _Response() |
| 7770 |
r.status_code = code |
| 7771 |
r.content = dumps(d).encode() |
| 7772 |
return r |
| 7773 |
|
| 7774 |
mock_get.return_value = _mk_resp({}) |
| 7775 |
mock_post.return_value = _mk_resp({"room_id": "!dm_e2ee:h"}) |
| 7776 |
mock_put.return_value = _mk_resp({}) |
| 7777 |
|
| 7778 |
obj = NotifyMatrix( |
| 7779 |
host="h", |
| 7780 |
user="u", |
| 7781 |
password="pass", |
| 7782 |
targets=["@alice"], |
| 7783 |
e2ee=True, |
| 7784 |
secure=True, |
| 7785 |
discovery=False, |
| 7786 |
) |
| 7787 |
obj.access_token = "tok" |
| 7788 |
obj.user_id = "@u:h" |
| 7789 |
obj.home_server = "h" |
| 7790 |
|
| 7791 |
captured_payloads = [] |
| 7792 |
_orig_fetch = obj._fetch |
| 7793 |
|
| 7794 |
def _capture_fetch(path, payload=None, **kw): |
| 7795 |
if path == "/createRoom": |
| 7796 |
captured_payloads.append(payload or {}) |
| 7797 |
return _orig_fetch(path, payload=payload, **kw) |
| 7798 |
|
| 7799 |
obj._fetch = _capture_fetch |
| 7800 |
|
| 7801 |
room_id = obj._dm_room_find_or_create("@alice") |
| 7802 |
assert room_id == "!dm_e2ee:h" |
| 7803 |
|
| 7804 |
# Verify initial_state was sent with m.room.encryption |
| 7805 |
assert len(captured_payloads) == 1 |
| 7806 |
init_state = captured_payloads[0].get("initial_state", []) |
| 7807 |
assert any(s.get("type") == "m.room.encryption" for s in init_state) |
| 7808 |
|
| 7809 |
# Room encryption cache must be pre-seeded |
| 7810 |
assert obj.store.get("e2ee_room_enc_!dm_e2ee:h") is True |
| 7811 |
|
| 7812 |
|
| 7813 |
# --------------------------------------------------------------------------- |
| 7814 |
# home_server recovery-from-user_id coverage tests |
| 7815 |
# --------------------------------------------------------------------------- |
| 7816 |
|
| 7817 |
|
| 7818 |
def test_plugin_matrix_init_recovers_home_server_from_user_id(tmpdir): |
| 7819 |
"""__init__ extracts home_server from a cached user_id when home_server |
| 7820 |
was not stored (older cache entries that predate the home_server field).""" |
| 7821 |
# A disk-backed asset ensures two separate NotifyMatrix instances that |
| 7822 |
# share the same url_id() also share the same persistent store file. |
| 7823 |
asset = AppriseAsset( |
| 7824 |
storage_mode=PersistentStoreMode.FLUSH, |
| 7825 |
storage_path=str(tmpdir), |
| 7826 |
) |
| 7827 |
|
| 7828 |
# First instance: simulate a login that wrote user_id/access_token but |
| 7829 |
# did NOT write home_server (older Apprise behaviour). |
| 7830 |
obj = NotifyMatrix( |
| 7831 |
host="h", user="u", password="pass", targets=["#r"], asset=asset |
| 7832 |
) |
| 7833 |
obj.store.set("user_id", "@u:recovered.com") |
| 7834 |
obj.store.set("access_token", "tok") |
| 7835 |
# Flush to disk before the second instance reads it. |
| 7836 |
obj.store.flush() |
| 7837 |
|
| 7838 |
# Second instance with the same credentials (same url_id) reads the store. |
| 7839 |
# The recovery path should derive home_server from the stored user_id. |
| 7840 |
obj2 = NotifyMatrix( |
| 7841 |
host="h", user="u", password="pass", targets=["#r"], asset=asset |
| 7842 |
) |
| 7843 |
assert obj2.home_server == "recovered.com" |
| 7844 |
|
| 7845 |
|
| 7846 |
def test_plugin_matrix_init_no_home_server_recovery_without_colon(tmpdir): |
| 7847 |
"""__init__ leaves home_server as None when the cached user_id has no |
| 7848 |
colon -- the recovery split yields a single part and the assignment is |
| 7849 |
skipped.""" |
| 7850 |
asset = AppriseAsset( |
| 7851 |
storage_mode=PersistentStoreMode.FLUSH, |
| 7852 |
storage_path=str(tmpdir), |
| 7853 |
) |
| 7854 |
|
| 7855 |
obj = NotifyMatrix( |
| 7856 |
host="h", user="u", password="pass", targets=["#r"], asset=asset |
| 7857 |
) |
| 7858 |
# user_id with no colon -- split(":", 1) produces only one element. |
| 7859 |
obj.store.set("user_id", "nocolon") |
| 7860 |
obj.store.set("access_token", "tok") |
| 7861 |
obj.store.flush() |
| 7862 |
|
| 7863 |
obj2 = NotifyMatrix( |
| 7864 |
host="h", user="u", password="pass", targets=["#r"], asset=asset |
| 7865 |
) |
| 7866 |
# No colon in user_id means home_server cannot be extracted. |
| 7867 |
assert obj2.home_server is None |
| 7868 |
|
| 7869 |
|
| 7870 |
@mock.patch("requests.put") |
| 7871 |
@mock.patch("requests.get") |
| 7872 |
@mock.patch("requests.post") |
| 7873 |
def test_plugin_matrix_whoami_recovers_home_server_from_user_id( |
| 7874 |
mock_post, mock_get, mock_put |
| 7875 |
): |
| 7876 |
"""_whoami() extracts home_server from user_id when the server does not |
| 7877 |
return a home_server field and self.home_server is unset.""" |
| 7878 |
r = _Response() |
| 7879 |
r.status_code = requests.codes.ok |
| 7880 |
r.content = dumps( |
| 7881 |
{"user_id": "@u:whoami.example.com", "device_id": "DEVX"} |
| 7882 |
).encode() |
| 7883 |
mock_get.return_value = r |
| 7884 |
|
| 7885 |
obj = NotifyMatrix(host="h", user="u", password="pass", discovery=False) |
| 7886 |
obj.access_token = "tok" |
| 7887 |
obj.home_server = None |
| 7888 |
|
| 7889 |
assert obj._whoami() is True |
| 7890 |
assert obj.home_server == "whoami.example.com" |
| 7891 |
|
| 7892 |
|
| 7893 |
def test_plugin_matrix_room_create_recovers_home_server_from_user_id(): |
| 7894 |
"""_room_create() falls back to extracting home_server from user_id when |
| 7895 |
both the room alias and self.home_server carry no homeserver part.""" |
| 7896 |
obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"]) |
| 7897 |
obj.access_token = "tok" |
| 7898 |
obj.home_server = None |
| 7899 |
obj.user_id = "@u:create.example.com" |
| 7900 |
|
| 7901 |
# Capture the /createRoom POST so we can verify the room name used. |
| 7902 |
captured = {} |
| 7903 |
|
| 7904 |
def _fake_fetch(path, payload=None, **kw): |
| 7905 |
if path == "/createRoom": |
| 7906 |
captured["payload"] = payload |
| 7907 |
return True, {"room_id": "!newroom:create.example.com"}, 200 |
| 7908 |
return False, {}, 404 |
| 7909 |
|
| 7910 |
with mock.patch.object(obj, "_fetch", side_effect=_fake_fetch): |
| 7911 |
room_id = obj._room_create("#bare_alias") |
| 7912 |
|
| 7913 |
assert room_id == "!newroom:create.example.com" |
| 7914 |
# The room name in the request must use the homeserver from user_id. |
| 7915 |
assert captured["payload"]["room_alias_name"] == "bare_alias" |
| 7916 |
|
| 7917 |
|
| 7918 |
def test_plugin_matrix_room_create_returns_none_without_home_server(): |
| 7919 |
"""_room_create() returns None when neither the alias, self.home_server, |
| 7920 |
nor self.user_id can supply a homeserver component.""" |
| 7921 |
obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"]) |
| 7922 |
obj.access_token = "tok" |
| 7923 |
obj.home_server = None |
| 7924 |
# user_id with no colon -> extraction yields nothing. |
| 7925 |
obj.user_id = "nocolon" |
| 7926 |
|
| 7927 |
result = obj._room_create("#bare_alias") |
| 7928 |
assert result is None |
| 7929 |
|
| 7930 |
|
| 7931 |
def test_plugin_matrix_room_id_recovers_home_server_from_user_id(): |
| 7932 |
"""_room_id() falls back to extracting home_server from user_id when both |
| 7933 |
the alias and self.home_server carry no homeserver part.""" |
| 7934 |
obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"]) |
| 7935 |
obj.access_token = "tok" |
| 7936 |
obj.home_server = None |
| 7937 |
obj.user_id = "@u:lookup.example.com" |
| 7938 |
|
| 7939 |
def _fake_fetch(path, payload=None, **kw): |
| 7940 |
return True, {"room_id": "!found:lookup.example.com"}, 200 |
| 7941 |
|
| 7942 |
with mock.patch.object(obj, "_fetch", side_effect=_fake_fetch): |
| 7943 |
room_id = obj._room_id("#bare_alias") |
| 7944 |
|
| 7945 |
assert room_id == "!found:lookup.example.com" |
| 7946 |
|
| 7947 |
|
| 7948 |
def test_plugin_matrix_room_id_returns_none_without_home_server(): |
| 7949 |
"""_room_id() returns None when neither the alias, self.home_server, |
| 7950 |
nor self.user_id can supply a homeserver component.""" |
| 7951 |
obj = NotifyMatrix(host="h", user="u", password="pass", targets=["#r"]) |
| 7952 |
obj.access_token = "tok" |
| 7953 |
obj.home_server = None |
| 7954 |
obj.user_id = "nocolon" |
| 7955 |
|
| 7956 |
result = obj._room_id("#bare_alias") |
| 7957 |
assert result is None |
| 7958 |
|
| 7959 |
|
| 7960 |
@mock.patch("requests.put") |
| 7961 |
@mock.patch("requests.get") |
| 7962 |
@mock.patch("requests.post") |
| 7963 |
def test_plugin_matrix_html_plain_fallback(mock_post, mock_get, mock_put): |
| 7964 |
"""Declared HTML receives a plain-text fallback.""" |
| 7965 |
from apprise.common import NotifyFormat |
| 7966 |
|
| 7967 |
response_obj = { |
| 7968 |
"room_id": "!abc123:localhost", |
| 7969 |
"room_alias": "#abc123:localhost", |
| 7970 |
"joined_rooms": ["!abc123:localhost"], |
| 7971 |
"access_token": "abcd1234", |
| 7972 |
"home_server": "localhost", |
| 7973 |
} |
| 7974 |
request = _Response() |
| 7975 |
request.content = dumps(response_obj) |
| 7976 |
request.status_code = requests.codes.ok |
| 7977 |
|
| 7978 |
mock_get.return_value = request |
| 7979 |
mock_post.return_value = request |
| 7980 |
mock_put.return_value = request |
| 7981 |
|
| 7982 |
kwargs = NotifyMatrix.parse_url( |
| 7983 |
"matrix://user:passwd@hostname/#abcd?format=html" |
| 7984 |
) |
| 7985 |
obj = NotifyMatrix(**kwargs) |
| 7986 |
|
| 7987 |
# Declaring the source confirms that the content is HTML. |
| 7988 |
assert ( |
| 7989 |
bool( |
| 7990 |
obj.notify( |
| 7991 |
title="Title", |
| 7992 |
body="<b>Bold</b> text", |
| 7993 |
body_format=NotifyFormat.HTML, |
| 7994 |
) |
| 7995 |
) |
| 7996 |
is True |
| 7997 |
) |
| 7998 |
|
| 7999 |
payload = loads(mock_put.call_args.kwargs["data"]) |
| 8000 |
assert payload["formatted_body"] == "<h1>Title</h1><b>Bold</b> text" |
| 8001 |
# The plain-text fallback must not carry the raw markup a second time. |
| 8002 |
assert "<b>" not in payload["body"] |
| 8003 |
assert "Bold text" in payload["body"] |
| 8004 |
|
| 8005 |
|
| 8006 |
@mock.patch("requests.put") |
| 8007 |
@mock.patch("requests.get") |
| 8008 |
@mock.patch("requests.post") |
| 8009 |
def test_plugin_matrix_html_passthrough_untouched( |
| 8010 |
mock_post, mock_get, mock_put |
| 8011 |
): |
| 8012 |
"""Undeclared content remains unchanged when routed as rich text.""" |
| 8013 |
|
| 8014 |
response_obj = { |
| 8015 |
"room_id": "!abc123:localhost", |
| 8016 |
"room_alias": "#abc123:localhost", |
| 8017 |
"joined_rooms": ["!abc123:localhost"], |
| 8018 |
"access_token": "abcd1234", |
| 8019 |
"home_server": "localhost", |
| 8020 |
} |
| 8021 |
request = _Response() |
| 8022 |
request.content = dumps(response_obj) |
| 8023 |
request.status_code = requests.codes.ok |
| 8024 |
|
| 8025 |
mock_get.return_value = request |
| 8026 |
mock_post.return_value = request |
| 8027 |
mock_put.return_value = request |
| 8028 |
|
| 8029 |
kwargs = NotifyMatrix.parse_url( |
| 8030 |
"matrix://user:passwd@hostname/#abcd?format=html" |
| 8031 |
) |
| 8032 |
obj = NotifyMatrix(**kwargs) |
| 8033 |
|
| 8034 |
# No body_format declared: a passthrough source. |
| 8035 |
assert bool(obj.notify(title="Title", body="<b>Bold</b> text")) is True |
| 8036 |
|
| 8037 |
payload = loads(mock_put.call_args.kwargs["data"]) |
| 8038 |
assert payload["formatted_body"] == "<h1>Title</h1><b>Bold</b> text" |
| 8039 |
# Preserve the source when its format is unknown. |
| 8040 |
assert payload["body"] == "# Title\r\n<b>Bold</b> text" |
| 8041 |
|
| 8042 |
|
| 8043 |
@mock.patch("requests.put") |
| 8044 |
@mock.patch("requests.get") |
| 8045 |
@mock.patch("requests.post") |
| 8046 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 8047 |
def test_plugin_matrix_e2ee_html_plain_fallback(mock_post, mock_get, mock_put): |
| 8048 |
"""Encrypted HTML also receives a plain-text fallback.""" |
| 8049 |
from apprise.common import NotifyFormat |
| 8050 |
from apprise.plugins.matrix.e2ee import ( |
| 8051 |
MatrixMegOlmSession, |
| 8052 |
MatrixOlmAccount, |
| 8053 |
) |
| 8054 |
|
| 8055 |
def _mk_resp(d): |
| 8056 |
r = _Response() |
| 8057 |
r.status_code = requests.codes.ok |
| 8058 |
r.content = dumps(d).encode() |
| 8059 |
return r |
| 8060 |
|
| 8061 |
mock_put.return_value = _mk_resp({}) |
| 8062 |
|
| 8063 |
obj = NotifyMatrix( |
| 8064 |
host="h", user="u", password="pass", targets=["#r"], e2ee=True |
| 8065 |
) |
| 8066 |
obj.access_token = "tok" |
| 8067 |
obj.home_server = "h" |
| 8068 |
obj.user_id = "@u:h" |
| 8069 |
obj.device_id = "DEV" |
| 8070 |
obj._e2ee_account = MatrixOlmAccount() |
| 8071 |
|
| 8072 |
session = MatrixMegOlmSession() |
| 8073 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 8074 |
obj.store.set("e2ee_key_shared_!r:h", session.session_id) |
| 8075 |
|
| 8076 |
# Capture the event before encryption. |
| 8077 |
captured = {} |
| 8078 |
original_encrypt = MatrixMegOlmSession.encrypt |
| 8079 |
|
| 8080 |
def _spy_encrypt(self, event): |
| 8081 |
captured["event"] = event |
| 8082 |
return original_encrypt(self, event) |
| 8083 |
|
| 8084 |
with mock.patch.object(MatrixMegOlmSession, "encrypt", _spy_encrypt): |
| 8085 |
assert ( |
| 8086 |
obj._e2ee_send_to_room( |
| 8087 |
"!r:h", |
| 8088 |
"<b>Bold</b> text", |
| 8089 |
"Title", |
| 8090 |
NotifyType.INFO, |
| 8091 |
body_format=NotifyFormat.HTML, |
| 8092 |
body_passthrough=False, |
| 8093 |
) |
| 8094 |
is True |
| 8095 |
) |
| 8096 |
|
| 8097 |
msg_content = captured["event"]["content"] |
| 8098 |
assert msg_content["formatted_body"] == "<h1>Title</h1><b>Bold</b> text" |
| 8099 |
assert "<b>" not in msg_content["body"] |
| 8100 |
assert "Bold text" in msg_content["body"] |
| 8101 |
|
| 8102 |
|
| 8103 |
def test_plugin_matrix_e2ee_body_limit(): |
| 8104 |
"""Encrypted messages use a smaller limit when E2EE is available.""" |
| 8105 |
obj = NotifyMatrix( |
| 8106 |
host="h", |
| 8107 |
user="u", |
| 8108 |
password="pass", |
| 8109 |
targets=["#r"], |
| 8110 |
e2ee=False, |
| 8111 |
secure=True, |
| 8112 |
) |
| 8113 |
assert obj.e2ee is False |
| 8114 |
assert obj.body_maxlen == obj.body_maxlen_default |
| 8115 |
|
| 8116 |
# Non-TLS connections cannot use encryption. |
| 8117 |
obj = NotifyMatrix( |
| 8118 |
host="h", |
| 8119 |
user="u", |
| 8120 |
password="pass", |
| 8121 |
targets=["#r"], |
| 8122 |
e2ee=True, |
| 8123 |
secure=False, |
| 8124 |
) |
| 8125 |
assert obj.e2ee is True |
| 8126 |
assert obj.body_maxlen == obj.body_maxlen_default |
| 8127 |
|
| 8128 |
obj = NotifyMatrix( |
| 8129 |
host="h", |
| 8130 |
user="u", |
| 8131 |
password="pass", |
| 8132 |
targets=["#r"], |
| 8133 |
e2ee=True, |
| 8134 |
secure=True, |
| 8135 |
) |
| 8136 |
assert obj.e2ee is True |
| 8137 |
|
| 8138 |
if CRYPTOGRAPHY_AVAILABLE: |
| 8139 |
assert obj.body_maxlen == obj.body_maxlen_e2ee |
| 8140 |
assert obj.body_maxlen < obj.body_maxlen_default |
| 8141 |
else: |
| 8142 |
# Encryption also requires the optional cryptography package. |
| 8143 |
assert obj.body_maxlen == obj.body_maxlen_default |
| 8144 |
|
| 8145 |
|
| 8146 |
def test_plugin_matrix_webhook_mode_body_maxlen_unaffected(): |
| 8147 |
"""Webhook modes keep their flat limit for their distinct payloads.""" |
| 8148 |
from apprise.common import NotifyFormat, OverflowMode |
| 8149 |
from apprise.plugins.matrix import base as matrix_base |
| 8150 |
from apprise.plugins.matrix.base import MatrixWebhookMode |
| 8151 |
|
| 8152 |
for mode in ( |
| 8153 |
MatrixWebhookMode.SLACK, |
| 8154 |
MatrixWebhookMode.MATRIX, |
| 8155 |
MatrixWebhookMode.HOOKSHOT, |
| 8156 |
): |
| 8157 |
obj = NotifyMatrix( |
| 8158 |
host="h", user="u", token="tok", mode=mode, secure=True |
| 8159 |
) |
| 8160 |
# Webhooks ignore the default E2EE setting. |
| 8161 |
assert obj.e2ee is True |
| 8162 |
assert obj.body_maxlen == obj.body_maxlen_default |
| 8163 |
|
| 8164 |
list( |
| 8165 |
obj._build_send_calls( |
| 8166 |
body="hello world " * 20, |
| 8167 |
title="", |
| 8168 |
body_format=NotifyFormat.HTML, |
| 8169 |
overflow=OverflowMode.SPLIT, |
| 8170 |
) |
| 8171 |
) |
| 8172 |
# Webhook preparation does not activate content-aware sizing. |
| 8173 |
assert matrix_base._matrix_effective_body_maxlen_var.get() is None |
| 8174 |
assert obj.body_maxlen == obj.body_maxlen_default |
| 8175 |
|
| 8176 |
|
| 8177 |
def test_plugin_matrix_body_maxlen_content_aware(): |
| 8178 |
"""Direct sends choose a content-aware limit while preparing chunks.""" |
| 8179 |
from apprise.common import OverflowMode |
| 8180 |
from apprise.plugins.matrix import base as matrix_base |
| 8181 |
|
| 8182 |
obj = NotifyMatrix( |
| 8183 |
host="h", |
| 8184 |
user="u", |
| 8185 |
password="pass", |
| 8186 |
targets=["#r"], |
| 8187 |
secure=True, |
| 8188 |
e2ee=False, |
| 8189 |
) |
| 8190 |
|
| 8191 |
# No send in progress: fall back to the flat default. |
| 8192 |
assert matrix_base._matrix_effective_body_maxlen_var.get() is None |
| 8193 |
assert obj.body_maxlen == obj.body_maxlen_default |
| 8194 |
|
| 8195 |
observed = {} |
| 8196 |
|
| 8197 |
# Capture the computed limit while the generator is active. |
| 8198 |
original_property = NotifyMatrix.body_maxlen.fget |
| 8199 |
|
| 8200 |
def _spy_body_maxlen(self): |
| 8201 |
observed["body_maxlen"] = ( |
| 8202 |
matrix_base._matrix_effective_body_maxlen_var.get() |
| 8203 |
) |
| 8204 |
return original_property(self) |
| 8205 |
|
| 8206 |
with mock.patch.object( |
| 8207 |
NotifyMatrix, "body_maxlen", property(_spy_body_maxlen) |
| 8208 |
): |
| 8209 |
list( |
| 8210 |
obj._build_send_calls( |
| 8211 |
# This length makes UTF-8 density determine the limit. |
| 8212 |
body="\U0001f600" * 20000, |
| 8213 |
title="", |
| 8214 |
overflow=OverflowMode.SPLIT, |
| 8215 |
) |
| 8216 |
) |
| 8217 |
|
| 8218 |
# Emoji require four UTF-8 bytes and therefore a smaller limit. |
| 8219 |
emoji_limit = observed["body_maxlen"] |
| 8220 |
assert emoji_limit < obj.body_maxlen_default |
| 8221 |
|
| 8222 |
# Restored after the call completes. |
| 8223 |
assert matrix_base._matrix_effective_body_maxlen_var.get() is None |
| 8224 |
|
| 8225 |
with mock.patch.object( |
| 8226 |
NotifyMatrix, "body_maxlen", property(_spy_body_maxlen) |
| 8227 |
): |
| 8228 |
list( |
| 8229 |
obj._build_send_calls( |
| 8230 |
body="hello world " * 10000, |
| 8231 |
title="", |
| 8232 |
overflow=OverflowMode.SPLIT, |
| 8233 |
) |
| 8234 |
) |
| 8235 |
|
| 8236 |
# Plain ASCII content allows a much larger character limit. |
| 8237 |
assert observed["body_maxlen"] > emoji_limit |
| 8238 |
assert matrix_base._matrix_effective_body_maxlen_var.get() is None |
| 8239 |
|
| 8240 |
|
| 8241 |
@mock.patch("requests.put") |
| 8242 |
@mock.patch("requests.get") |
| 8243 |
@mock.patch("requests.post") |
| 8244 |
def test_plugin_matrix_concentrated_density_split( |
| 8245 |
mock_post, mock_get, mock_put |
| 8246 |
): |
| 8247 |
"""Dense Unicode regions must fit even when ASCII lowers the average.""" |
| 8248 |
from apprise.common import OverflowMode |
| 8249 |
|
| 8250 |
response_obj = { |
| 8251 |
"room_id": "!abc123:localhost", |
| 8252 |
"room_alias": "#abc123:localhost", |
| 8253 |
"joined_rooms": ["!abc123:localhost"], |
| 8254 |
"access_token": "abcd1234", |
| 8255 |
"home_server": "localhost", |
| 8256 |
} |
| 8257 |
request = _Response() |
| 8258 |
request.content = dumps(response_obj) |
| 8259 |
request.status_code = requests.codes.ok |
| 8260 |
|
| 8261 |
mock_get.return_value = request |
| 8262 |
mock_post.return_value = request |
| 8263 |
mock_put.return_value = request |
| 8264 |
|
| 8265 |
obj = NotifyMatrix(host="hostname", user="user", password="passwd") |
| 8266 |
|
| 8267 |
original_body = ("\U0001f600" * 20000) + ("a" * 80000) |
| 8268 |
assert ( |
| 8269 |
bool(obj.notify(body=original_body, overflow=OverflowMode.SPLIT)) |
| 8270 |
is True |
| 8271 |
) |
| 8272 |
|
| 8273 |
assert mock_put.call_count > 1 |
| 8274 |
reconstructed = "" |
| 8275 |
for call in mock_put.call_args_list: |
| 8276 |
payload = loads(call.kwargs["data"]) |
| 8277 |
encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 8278 |
assert encoded_len <= 65536 |
| 8279 |
reconstructed += payload["body"] |
| 8280 |
|
| 8281 |
# No content was dropped or duplicated across the split events. |
| 8282 |
assert reconstructed == original_body |
| 8283 |
|
| 8284 |
|
| 8285 |
@mock.patch("requests.put") |
| 8286 |
@mock.patch("requests.get") |
| 8287 |
@mock.patch("requests.post") |
| 8288 |
def test_plugin_matrix_json_escape_heavy_split(mock_post, mock_get, mock_put): |
| 8289 |
"""Backslash-heavy bodies must fit after JSON escape expansion.""" |
| 8290 |
from apprise.common import OverflowMode |
| 8291 |
|
| 8292 |
response_obj = { |
| 8293 |
"room_id": "!abc123:localhost", |
| 8294 |
"room_alias": "#abc123:localhost", |
| 8295 |
"joined_rooms": ["!abc123:localhost"], |
| 8296 |
"access_token": "abcd1234", |
| 8297 |
"home_server": "localhost", |
| 8298 |
} |
| 8299 |
request = _Response() |
| 8300 |
request.content = dumps(response_obj) |
| 8301 |
request.status_code = requests.codes.ok |
| 8302 |
|
| 8303 |
mock_get.return_value = request |
| 8304 |
mock_post.return_value = request |
| 8305 |
mock_put.return_value = request |
| 8306 |
|
| 8307 |
obj = NotifyMatrix(host="hostname", user="user", password="passwd") |
| 8308 |
|
| 8309 |
original_body = "\\" * 70000 |
| 8310 |
assert ( |
| 8311 |
bool(obj.notify(body=original_body, overflow=OverflowMode.SPLIT)) |
| 8312 |
is True |
| 8313 |
) |
| 8314 |
|
| 8315 |
assert mock_put.call_count > 1 |
| 8316 |
reconstructed = "" |
| 8317 |
for call in mock_put.call_args_list: |
| 8318 |
payload = loads(call.kwargs["data"]) |
| 8319 |
encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 8320 |
assert encoded_len <= 65536 |
| 8321 |
reconstructed += payload["body"] |
| 8322 |
|
| 8323 |
assert reconstructed == original_body |
| 8324 |
|
| 8325 |
|
| 8326 |
@mock.patch("requests.put") |
| 8327 |
@mock.patch("requests.get") |
| 8328 |
@mock.patch("requests.post") |
| 8329 |
def test_plugin_matrix_mixed_escape_and_unicode_split( |
| 8330 |
mock_post, mock_get, mock_put |
| 8331 |
): |
| 8332 |
"""Mixed JSON escapes and Unicode must remain within the byte limit.""" |
| 8333 |
from apprise.common import OverflowMode |
| 8334 |
|
| 8335 |
response_obj = { |
| 8336 |
"room_id": "!abc123:localhost", |
| 8337 |
"room_alias": "#abc123:localhost", |
| 8338 |
"joined_rooms": ["!abc123:localhost"], |
| 8339 |
"access_token": "abcd1234", |
| 8340 |
"home_server": "localhost", |
| 8341 |
} |
| 8342 |
request = _Response() |
| 8343 |
request.content = dumps(response_obj) |
| 8344 |
request.status_code = requests.codes.ok |
| 8345 |
|
| 8346 |
mock_get.return_value = request |
| 8347 |
mock_post.return_value = request |
| 8348 |
mock_put.return_value = request |
| 8349 |
|
| 8350 |
obj = NotifyMatrix(host="hostname", user="user", password="passwd") |
| 8351 |
|
| 8352 |
# Include escapes, a non-whitespace control, CJK, and emoji characters. |
| 8353 |
# Whitespace controls are avoided because chunk splitting may trim them. |
| 8354 |
cluster = '"\\\x01ä¸\U0001f600' |
| 8355 |
original_body = cluster * 15000 |
| 8356 |
assert ( |
| 8357 |
bool(obj.notify(body=original_body, overflow=OverflowMode.SPLIT)) |
| 8358 |
is True |
| 8359 |
) |
| 8360 |
|
| 8361 |
assert mock_put.call_count > 1 |
| 8362 |
reconstructed = "" |
| 8363 |
for call in mock_put.call_args_list: |
| 8364 |
payload = loads(call.kwargs["data"]) |
| 8365 |
encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 8366 |
assert encoded_len <= 65536 |
| 8367 |
reconstructed += payload["body"] |
| 8368 |
|
| 8369 |
assert reconstructed == original_body |
| 8370 |
|
| 8371 |
|
| 8372 |
@mock.patch("requests.put") |
| 8373 |
@mock.patch("requests.get") |
| 8374 |
@mock.patch("requests.post") |
| 8375 |
def test_plugin_matrix_html_dual_representation_split( |
| 8376 |
mock_post, mock_get, mock_put |
| 8377 |
): |
| 8378 |
"""HTML events fit with both plain and formatted representations.""" |
| 8379 |
from apprise.common import NotifyFormat, OverflowMode |
| 8380 |
|
| 8381 |
response_obj = { |
| 8382 |
"room_id": "!abc123:localhost", |
| 8383 |
"room_alias": "#abc123:localhost", |
| 8384 |
"joined_rooms": ["!abc123:localhost"], |
| 8385 |
"access_token": "abcd1234", |
| 8386 |
"home_server": "localhost", |
| 8387 |
} |
| 8388 |
request = _Response() |
| 8389 |
request.content = dumps(response_obj) |
| 8390 |
request.status_code = requests.codes.ok |
| 8391 |
|
| 8392 |
mock_get.return_value = request |
| 8393 |
mock_post.return_value = request |
| 8394 |
mock_put.return_value = request |
| 8395 |
|
| 8396 |
obj = NotifyMatrix(host="hostname", user="user", password="passwd") |
| 8397 |
|
| 8398 |
body = ("word " * 12999) + "end" |
| 8399 |
assert ( |
| 8400 |
bool( |
| 8401 |
obj.notify( |
| 8402 |
body=body, |
| 8403 |
body_format=NotifyFormat.HTML, |
| 8404 |
overflow=OverflowMode.SPLIT, |
| 8405 |
) |
| 8406 |
) |
| 8407 |
is True |
| 8408 |
) |
| 8409 |
|
| 8410 |
assert mock_put.call_count > 1 |
| 8411 |
for call in mock_put.call_args_list: |
| 8412 |
payload = loads(call.kwargs["data"]) |
| 8413 |
assert "formatted_body" in payload |
| 8414 |
encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 8415 |
assert encoded_len <= 65536 |
| 8416 |
|
| 8417 |
|
| 8418 |
@mock.patch("requests.put") |
| 8419 |
@mock.patch("requests.get") |
| 8420 |
@mock.patch("requests.post") |
| 8421 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 8422 |
def test_plugin_matrix_e2ee_html_split(mock_post, mock_get, mock_put): |
| 8423 |
"""Encrypted HTML chunks fit after formatting and MegOLM expansion.""" |
| 8424 |
from apprise.common import NotifyFormat, OverflowMode |
| 8425 |
from apprise.plugins.matrix.e2ee import MatrixMegOlmSession |
| 8426 |
|
| 8427 |
def _mk_resp(d): |
| 8428 |
r = _Response() |
| 8429 |
r.status_code = requests.codes.ok |
| 8430 |
r.content = dumps(d).encode() |
| 8431 |
return r |
| 8432 |
|
| 8433 |
login_resp = { |
| 8434 |
"access_token": "tok", |
| 8435 |
"user_id": "@u:h", |
| 8436 |
"home_server": "h", |
| 8437 |
"device_id": "DEV", |
| 8438 |
} |
| 8439 |
mock_post.side_effect = [ |
| 8440 |
_mk_resp(login_resp), |
| 8441 |
_mk_resp({}), # keys/upload |
| 8442 |
_mk_resp({"room_id": "!r:h"}), # join |
| 8443 |
_mk_resp({}), # logout |
| 8444 |
] |
| 8445 |
mock_get.return_value = _mk_resp({}) |
| 8446 |
mock_put.return_value = _mk_resp({}) |
| 8447 |
|
| 8448 |
obj = NotifyMatrix( |
| 8449 |
host="h", |
| 8450 |
user="u", |
| 8451 |
password="pass", |
| 8452 |
targets=["!r:h"], |
| 8453 |
e2ee=True, |
| 8454 |
secure=True, |
| 8455 |
discovery=False, |
| 8456 |
) |
| 8457 |
# Pre-seed encryption state so the test only sends message events. |
| 8458 |
session = MatrixMegOlmSession() |
| 8459 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 8460 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 8461 |
obj.store.set("e2ee_key_shared_!r:h", session.session_id) |
| 8462 |
|
| 8463 |
body = ("<b>hello world this is a test</b> " * 2000).strip() |
| 8464 |
assert ( |
| 8465 |
bool( |
| 8466 |
obj.notify( |
| 8467 |
body=body, |
| 8468 |
body_format=NotifyFormat.HTML, |
| 8469 |
overflow=OverflowMode.SPLIT, |
| 8470 |
) |
| 8471 |
) |
| 8472 |
is True |
| 8473 |
) |
| 8474 |
|
| 8475 |
assert mock_put.call_count > 1 |
| 8476 |
for call in mock_put.call_args_list: |
| 8477 |
payload = loads(call.kwargs["data"]) |
| 8478 |
assert payload["algorithm"] == "m.megolm.v1.aes-sha2" |
| 8479 |
encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 8480 |
assert encoded_len <= 65536 |
| 8481 |
|
| 8482 |
|
| 8483 |
@mock.patch("requests.put") |
| 8484 |
@mock.patch("requests.get") |
| 8485 |
@mock.patch("requests.post") |
| 8486 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 8487 |
@pytest.mark.parametrize("device_id_len", [3, 128, 255, 1000]) |
| 8488 |
def test_plugin_matrix_e2ee_long_device_id_and_title( |
| 8489 |
mock_post, mock_get, mock_put, device_id_len |
| 8490 |
): |
| 8491 |
"""Long device IDs and escaped titles must fit encrypted events. |
| 8492 |
|
| 8493 |
Both values are measured because neither raw character counts nor a |
| 8494 |
fixed envelope estimate represent their final JSON byte cost. |
| 8495 |
""" |
| 8496 |
from apprise.common import NotifyFormat, OverflowMode |
| 8497 |
from apprise.plugins.matrix.e2ee import MatrixMegOlmSession |
| 8498 |
|
| 8499 |
def _mk_resp(d): |
| 8500 |
r = _Response() |
| 8501 |
r.status_code = requests.codes.ok |
| 8502 |
r.content = dumps(d).encode() |
| 8503 |
return r |
| 8504 |
|
| 8505 |
mock_get.return_value = _mk_resp({}) |
| 8506 |
mock_put.return_value = _mk_resp({}) |
| 8507 |
mock_post.return_value = _mk_resp({}) |
| 8508 |
|
| 8509 |
obj = NotifyMatrix( |
| 8510 |
host="h", |
| 8511 |
user="u", |
| 8512 |
password="pass", |
| 8513 |
targets=["!r:h"], |
| 8514 |
e2ee=True, |
| 8515 |
secure=True, |
| 8516 |
discovery=False, |
| 8517 |
) |
| 8518 |
session = MatrixMegOlmSession() |
| 8519 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 8520 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 8521 |
obj.store.set("e2ee_key_shared_!r:h", session.session_id) |
| 8522 |
obj.access_token = "tok" |
| 8523 |
obj.home_server = "h" |
| 8524 |
obj.user_id = "@u:h" |
| 8525 |
# A known device_id (as if cached from a prior login) is measured |
| 8526 |
# exactly rather than falling back to the generous default. |
| 8527 |
obj.device_id = "D" * device_id_len |
| 8528 |
|
| 8529 |
title = "\x01" * 250 # near title_maxlen, maximal 6-byte JSON escape |
| 8530 |
body = "\x01" * 200000 |
| 8531 |
|
| 8532 |
assert ( |
| 8533 |
bool( |
| 8534 |
obj.notify( |
| 8535 |
body=body, |
| 8536 |
title=title, |
| 8537 |
body_format=NotifyFormat.HTML, |
| 8538 |
overflow=OverflowMode.SPLIT, |
| 8539 |
) |
| 8540 |
) |
| 8541 |
is True |
| 8542 |
) |
| 8543 |
|
| 8544 |
assert mock_put.call_count > 1 |
| 8545 |
for call in mock_put.call_args_list: |
| 8546 |
payload = loads(call.kwargs["data"]) |
| 8547 |
assert payload["algorithm"] == "m.megolm.v1.aes-sha2" |
| 8548 |
encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 8549 |
assert encoded_len <= 65536 |
| 8550 |
|
| 8551 |
|
| 8552 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 8553 |
def test_plugin_matrix_e2ee_rejects_late_oversize(): |
| 8554 |
"""Refuse a first-login event that becomes too large after sizing. |
| 8555 |
|
| 8556 |
The final device ID must not consume the safety margin reserved for |
| 8557 |
homeserver-added metadata. |
| 8558 |
""" |
| 8559 |
from apprise.common import NotifyFormat, OverflowMode |
| 8560 |
from apprise.plugins.matrix.base import ( |
| 8561 |
MATRIX_EVENT_BYTE_LIMIT, |
| 8562 |
MATRIX_EVENT_SAFETY_MARGIN, |
| 8563 |
) |
| 8564 |
from apprise.plugins.matrix.e2ee import ( |
| 8565 |
MatrixMegOlmSession, |
| 8566 |
MatrixOlmAccount, |
| 8567 |
) |
| 8568 |
|
| 8569 |
safe_byte_budget = MATRIX_EVENT_BYTE_LIMIT - MATRIX_EVENT_SAFETY_MARGIN |
| 8570 |
|
| 8571 |
obj = NotifyMatrix( |
| 8572 |
host="h", |
| 8573 |
user="u", |
| 8574 |
password="pass", |
| 8575 |
targets=["!r:h"], |
| 8576 |
e2ee=True, |
| 8577 |
secure=True, |
| 8578 |
discovery=False, |
| 8579 |
) |
| 8580 |
obj.access_token = "tok" |
| 8581 |
obj.home_server = "h" |
| 8582 |
obj.user_id = "@u:h" |
| 8583 |
# Unknown at sizing time: _build_send_calls() uses the fallback. |
| 8584 |
obj.device_id = None |
| 8585 |
obj._e2ee_account = MatrixOlmAccount() |
| 8586 |
|
| 8587 |
# A small, fixed body/title: content isn't what's under test here, |
| 8588 |
# device_id's contribution is. device_id sits outside the encrypted |
| 8589 |
# ciphertext (a plain sibling JSON field), so every extra character |
| 8590 |
# added to it adds exactly one byte to the final encrypted payload, |
| 8591 |
# letting the boundary below be targeted precisely. |
| 8592 |
calls = list( |
| 8593 |
obj._build_send_calls( |
| 8594 |
body="hello", title="", overflow=OverflowMode.SPLIT |
| 8595 |
) |
| 8596 |
) |
| 8597 |
first = calls[0] |
| 8598 |
|
| 8599 |
session = MatrixMegOlmSession() |
| 8600 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 8601 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 8602 |
obj.store.set("e2ee_key_shared_!r:h", session.session_id) |
| 8603 |
|
| 8604 |
def send_with_device_id(device_id_len): |
| 8605 |
# The real device_id becomes known only now, as if login |
| 8606 |
# happened after sizing already ran. |
| 8607 |
obj.device_id = "D" * device_id_len |
| 8608 |
with ( |
| 8609 |
mock.patch.object(obj, "_e2ee_share_room_key", return_value=True), |
| 8610 |
mock.patch.object( |
| 8611 |
obj, "_fetch", return_value=(True, {}, 200) |
| 8612 |
) as mock_fetch, |
| 8613 |
): |
| 8614 |
result = obj._e2ee_send_to_room( |
| 8615 |
"!r:h", |
| 8616 |
first["body"], |
| 8617 |
first["title"], |
| 8618 |
NotifyType.INFO, |
| 8619 |
NotifyFormat.HTML, |
| 8620 |
False, |
| 8621 |
) |
| 8622 |
sent = mock_fetch.call_count > 0 |
| 8623 |
assert result is sent |
| 8624 |
if sent: |
| 8625 |
payload = mock_fetch.call_args.kwargs["payload"] |
| 8626 |
return len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 8627 |
return None |
| 8628 |
|
| 8629 |
# Measure this content's baseline (device_id excluded) once. |
| 8630 |
baseline_bytes = send_with_device_id(0) |
| 8631 |
|
| 8632 |
# Exactly at the safe budget: still accepted. |
| 8633 |
at_budget_len = safe_byte_budget - baseline_bytes |
| 8634 |
assert send_with_device_id(at_budget_len) == safe_byte_budget |
| 8635 |
|
| 8636 |
# One byte into the reserved margin -- between the safe budget and |
| 8637 |
# the hard ceiling, previously accepted by mistake -- must now be |
| 8638 |
# refused. |
| 8639 |
past_budget_len = at_budget_len + 1 |
| 8640 |
assert send_with_device_id(past_budget_len) is None |
| 8641 |
|
| 8642 |
# Comfortably past the full ceiling: also refused. |
| 8643 |
assert send_with_device_id(MATRIX_EVENT_BYTE_LIMIT) is None |
| 8644 |
|
| 8645 |
|
| 8646 |
@mock.patch("requests.put") |
| 8647 |
@mock.patch("requests.get") |
| 8648 |
@mock.patch("requests.post") |
| 8649 |
@pytest.mark.skipif(not CRYPTOGRAPHY_AVAILABLE, reason="Requires cryptography") |
| 8650 |
def test_plugin_matrix_surrogate_sanitized_end_to_end( |
| 8651 |
mock_post, mock_get, mock_put |
| 8652 |
): |
| 8653 |
"""A lone UTF-16 surrogate in the body/title must not crash delivery |
| 8654 |
on any send path -- direct-server, E2EE, or webhook.""" |
| 8655 |
from apprise.common import NotifyFormat |
| 8656 |
from apprise.plugins.matrix.base import MatrixWebhookMode |
| 8657 |
from apprise.plugins.matrix.e2ee import MatrixMegOlmSession |
| 8658 |
|
| 8659 |
def _mk_resp(d): |
| 8660 |
r = _Response() |
| 8661 |
r.status_code = requests.codes.ok |
| 8662 |
r.content = dumps(d).encode() |
| 8663 |
return r |
| 8664 |
|
| 8665 |
lone_surrogate_body = "hello " + chr(0xD800) + " world" |
| 8666 |
lone_surrogate_title = "t" + chr(0xDC00) + "t" |
| 8667 |
|
| 8668 |
# Direct-server plaintext path. |
| 8669 |
response_obj = { |
| 8670 |
"room_id": "!abc:localhost", |
| 8671 |
"room_alias": "#abc:localhost", |
| 8672 |
"joined_rooms": ["!abc:localhost"], |
| 8673 |
"access_token": "abcd1234", |
| 8674 |
"home_server": "localhost", |
| 8675 |
} |
| 8676 |
mock_get.return_value = _mk_resp(response_obj) |
| 8677 |
mock_post.return_value = _mk_resp(response_obj) |
| 8678 |
mock_put.return_value = _mk_resp({}) |
| 8679 |
obj = NotifyMatrix(host="hostname", user="user", password="passwd") |
| 8680 |
assert bool(obj.notify(body=lone_surrogate_body)) is True |
| 8681 |
payload = loads(mock_put.call_args.kwargs["data"]) |
| 8682 |
# The lone surrogate is replaced, never crashing serialization. |
| 8683 |
payload["body"].encode("utf-8") |
| 8684 |
|
| 8685 |
# E2EE path. |
| 8686 |
mock_get.return_value = _mk_resp({}) |
| 8687 |
mock_put.return_value = _mk_resp({}) |
| 8688 |
mock_post.return_value = _mk_resp({}) |
| 8689 |
obj = NotifyMatrix( |
| 8690 |
host="h", |
| 8691 |
user="u", |
| 8692 |
password="pass", |
| 8693 |
targets=["!r:h"], |
| 8694 |
e2ee=True, |
| 8695 |
secure=True, |
| 8696 |
discovery=False, |
| 8697 |
) |
| 8698 |
session = MatrixMegOlmSession() |
| 8699 |
obj.store.set("e2ee_room_enc_!r:h", True) |
| 8700 |
obj.store.set("e2ee_megolm_!r:h", session.to_dict()) |
| 8701 |
obj.store.set("e2ee_key_shared_!r:h", session.session_id) |
| 8702 |
obj.access_token = "tok" |
| 8703 |
obj.home_server = "h" |
| 8704 |
obj.user_id = "@u:h" |
| 8705 |
obj.device_id = "DEV" |
| 8706 |
assert ( |
| 8707 |
bool( |
| 8708 |
obj.notify( |
| 8709 |
body="hello", |
| 8710 |
title=lone_surrogate_title, |
| 8711 |
body_format=NotifyFormat.HTML, |
| 8712 |
) |
| 8713 |
) |
| 8714 |
is True |
| 8715 |
) |
| 8716 |
|
| 8717 |
# Webhook (Slack-compatible) path. |
| 8718 |
mock_post.return_value = _mk_resp({}) |
| 8719 |
obj = NotifyMatrix( |
| 8720 |
host="h", user="u", token="tok", mode=MatrixWebhookMode.SLACK |
| 8721 |
) |
| 8722 |
assert bool(obj.notify(body=lone_surrogate_body)) is True |
| 8723 |
|
| 8724 |
|
| 8725 |
@mock.patch("requests.put") |
| 8726 |
@mock.patch("requests.get") |
| 8727 |
@mock.patch("requests.post") |
| 8728 |
def test_plugin_matrix_caps_before_scanning_density( |
| 8729 |
mock_post, mock_get, mock_put |
| 8730 |
): |
| 8731 |
"""The payload cap is applied before UTF-8 density is scanned.""" |
| 8732 |
from apprise.asset import AppriseAsset |
| 8733 |
from apprise.common import OverflowMode |
| 8734 |
|
| 8735 |
response_obj = { |
| 8736 |
"room_id": "!abc123:localhost", |
| 8737 |
"room_alias": "#abc123:localhost", |
| 8738 |
"joined_rooms": ["!abc123:localhost"], |
| 8739 |
"access_token": "abcd1234", |
| 8740 |
"home_server": "localhost", |
| 8741 |
} |
| 8742 |
request = _Response() |
| 8743 |
request.content = dumps(response_obj) |
| 8744 |
request.status_code = requests.codes.ok |
| 8745 |
|
| 8746 |
mock_get.return_value = request |
| 8747 |
mock_post.return_value = request |
| 8748 |
mock_put.return_value = request |
| 8749 |
|
| 8750 |
asset = AppriseAsset(payload_max_size=100) |
| 8751 |
obj = NotifyMatrix( |
| 8752 |
host="hostname", user="user", password="passwd", asset=asset |
| 8753 |
) |
| 8754 |
|
| 8755 |
# Only the capped 100 characters should be scanned. |
| 8756 |
huge_body = "a" * 10_000_000 |
| 8757 |
assert ( |
| 8758 |
bool(obj.notify(body=huge_body, overflow=OverflowMode.SPLIT)) is True |
| 8759 |
) |
| 8760 |
|
| 8761 |
# Capped to 100 characters up front, so a single small event is sent. |
| 8762 |
assert mock_put.call_count == 1 |
| 8763 |
payload = loads(mock_put.call_args.kwargs["data"]) |
| 8764 |
assert len(payload["body"]) <= 100 |
| 8765 |
|
| 8766 |
|
| 8767 |
@mock.patch("requests.put") |
| 8768 |
@mock.patch("requests.get") |
| 8769 |
@mock.patch("requests.post") |
| 8770 |
def test_plugin_matrix_caps_before_sanitizing(mock_post, mock_get, mock_put): |
| 8771 |
"""Apply the payload cap before scanning text for invalid surrogates. |
| 8772 |
|
| 8773 |
Webhook mode isolates the cap performed by ``_build_send_calls()``. |
| 8774 |
""" |
| 8775 |
from apprise.asset import AppriseAsset |
| 8776 |
from apprise.plugins.matrix.base import MatrixWebhookMode |
| 8777 |
|
| 8778 |
request = _Response() |
| 8779 |
request.content = dumps({}) |
| 8780 |
request.status_code = requests.codes.ok |
| 8781 |
mock_post.return_value = request |
| 8782 |
|
| 8783 |
asset = AppriseAsset(payload_max_size=100) |
| 8784 |
obj = NotifyMatrix( |
| 8785 |
host="h", |
| 8786 |
user="u", |
| 8787 |
token="tok", |
| 8788 |
mode=MatrixWebhookMode.SLACK, |
| 8789 |
asset=asset, |
| 8790 |
) |
| 8791 |
|
| 8792 |
seen_lengths = [] |
| 8793 |
from apprise.plugins.matrix import ( |
| 8794 |
base as matrix_base, |
| 8795 |
sizing as matrix_sizing, |
| 8796 |
) |
| 8797 |
|
| 8798 |
real_sanitize_fn = matrix_sizing.sanitize_text |
| 8799 |
|
| 8800 |
def spy_sanitize(text): |
| 8801 |
seen_lengths.append(len(text) if text else 0) |
| 8802 |
return real_sanitize_fn(text) |
| 8803 |
|
| 8804 |
huge_body = "a" * 10_000_000 |
| 8805 |
with ( |
| 8806 |
mock.patch.object(matrix_sizing, "sanitize_text", spy_sanitize), |
| 8807 |
mock.patch.object(matrix_base, "_matrix_sanitize_text", spy_sanitize), |
| 8808 |
): |
| 8809 |
assert bool(obj.notify(body=huge_body)) is True |
| 8810 |
|
| 8811 |
# Every call into the sanitizer saw only the already-capped text, never |
| 8812 |
# the original 10,000,000-character body. |
| 8813 |
assert seen_lengths |
| 8814 |
assert max(seen_lengths) <= 100 |
| 8815 |
|
| 8816 |
|
| 8817 |
def test_plugin_matrix_preview_avoids_extra_full_strip(): |
| 8818 |
"""Avoid stripping and copying a large input during sizing. |
| 8819 |
|
| 8820 |
The framework performs the one required full-input strip. The sizing |
| 8821 |
preview finds trim boundaries without making another full-size copy. |
| 8822 |
""" |
| 8823 |
from apprise.asset import AppriseAsset |
| 8824 |
from apprise.common import OverflowMode |
| 8825 |
|
| 8826 |
calls = [] |
| 8827 |
|
| 8828 |
class _TrackingStr(str): |
| 8829 |
def rstrip(self, *args, **kwargs): |
| 8830 |
calls.append(("rstrip", len(self))) |
| 8831 |
return super().rstrip(*args, **kwargs) |
| 8832 |
|
| 8833 |
def strip(self, *args, **kwargs): |
| 8834 |
calls.append(("strip", len(self))) |
| 8835 |
return super().strip(*args, **kwargs) |
| 8836 |
|
| 8837 |
asset = AppriseAsset(payload_max_size=100) |
| 8838 |
obj = NotifyMatrix( |
| 8839 |
host="h", user="u", password="pass", targets=["#r"], asset=asset |
| 8840 |
) |
| 8841 |
|
| 8842 |
huge_body = _TrackingStr("a" * 10_000_000 + " ") |
| 8843 |
huge_title = _TrackingStr(" " * 10_000_000 + "hi") |
| 8844 |
|
| 8845 |
list( |
| 8846 |
obj._build_send_calls( |
| 8847 |
body=huge_body, |
| 8848 |
title=huge_title, |
| 8849 |
overflow=OverflowMode.SPLIT, |
| 8850 |
) |
| 8851 |
) |
| 8852 |
|
| 8853 |
full_length_rstrip_calls = [ |
| 8854 |
c for c in calls if c == ("rstrip", len(huge_body)) |
| 8855 |
] |
| 8856 |
full_length_strip_calls = [ |
| 8857 |
c for c in calls if c == ("strip", len(huge_title)) |
| 8858 |
] |
| 8859 |
assert len(full_length_rstrip_calls) == 1 |
| 8860 |
assert len(full_length_strip_calls) == 1 |
| 8861 |
|
| 8862 |
|
| 8863 |
@mock.patch("requests.put") |
| 8864 |
@mock.patch("requests.get") |
| 8865 |
@mock.patch("requests.post") |
| 8866 |
def test_plugin_matrix_whitespace_title_does_not_steal_cap( |
| 8867 |
mock_post, mock_get, mock_put |
| 8868 |
): |
| 8869 |
"""Whitespace-only titles must not consume the payload cap. |
| 8870 |
|
| 8871 |
The sizing preview follows the framework's strip-then-cap order so the |
| 8872 |
useful body receives the space vacated by the title. |
| 8873 |
""" |
| 8874 |
from apprise.asset import AppriseAsset |
| 8875 |
from apprise.common import OverflowMode |
| 8876 |
|
| 8877 |
response_obj = { |
| 8878 |
"room_id": "!abc123:localhost", |
| 8879 |
"room_alias": "#abc123:localhost", |
| 8880 |
"joined_rooms": ["!abc123:localhost"], |
| 8881 |
"access_token": "abcd1234", |
| 8882 |
"home_server": "localhost", |
| 8883 |
} |
| 8884 |
request = _Response() |
| 8885 |
request.content = dumps(response_obj) |
| 8886 |
request.status_code = requests.codes.ok |
| 8887 |
mock_get.return_value = request |
| 8888 |
mock_post.return_value = request |
| 8889 |
mock_put.return_value = request |
| 8890 |
|
| 8891 |
asset = AppriseAsset(payload_max_size=300) |
| 8892 |
obj = NotifyMatrix( |
| 8893 |
host="hostname", user="user", password="passwd", asset=asset |
| 8894 |
) |
| 8895 |
|
| 8896 |
title = " " * 250 |
| 8897 |
body = "x" * 300 |
| 8898 |
|
| 8899 |
assert bool( |
| 8900 |
obj.notify(body=body, title=title, overflow=OverflowMode.SPLIT) |
| 8901 |
) |
| 8902 |
payload = loads(mock_put.call_args_list[0].kwargs["data"]) |
| 8903 |
# The whitespace-only title contributes nothing once stripped, so the |
| 8904 |
# full body -- not a truncated fragment -- fits within the cap. |
| 8905 |
assert payload["body"] == body |
| 8906 |
|
| 8907 |
|
| 8908 |
def test_plugin_matrix_title_leading_whitespace_past_cap(): |
| 8909 |
"""Keep meaningful title text beyond leading whitespace. |
| 8910 |
|
| 8911 |
The preview must follow the framework's trim-then-cap behavior so title |
| 8912 |
overhead is measured correctly. |
| 8913 |
""" |
| 8914 |
from apprise.asset import AppriseAsset |
| 8915 |
from apprise.common import NotifyFormat, OverflowMode |
| 8916 |
|
| 8917 |
asset = AppriseAsset(payload_max_size=100) |
| 8918 |
obj = NotifyMatrix( |
| 8919 |
host="h", user="u", password="pass", targets=["#r"], asset=asset |
| 8920 |
) |
| 8921 |
|
| 8922 |
# More leading whitespace than the cap, followed by an escape-heavy |
| 8923 |
# meaningful title (each char costs 6 JSON-escaped bytes). |
| 8924 |
title = (" " * 150) + ("\x01" * 50) |
| 8925 |
body = "hello world" |
| 8926 |
|
| 8927 |
from apprise.plugins.matrix import sizing as matrix_sizing |
| 8928 |
|
| 8929 |
observed = {} |
| 8930 |
real_overhead_fn = matrix_sizing.title_overhead_bytes |
| 8931 |
|
| 8932 |
def spy_title_overhead(title_arg, body_format, escape_html): |
| 8933 |
observed["title_arg"] = title_arg |
| 8934 |
return real_overhead_fn(title_arg, body_format, escape_html) |
| 8935 |
|
| 8936 |
with mock.patch.object( |
| 8937 |
matrix_sizing, "title_overhead_bytes", spy_title_overhead |
| 8938 |
): |
| 8939 |
list( |
| 8940 |
obj._build_send_calls( |
| 8941 |
body=body, |
| 8942 |
title=title, |
| 8943 |
body_format=NotifyFormat.HTML, |
| 8944 |
overflow=OverflowMode.SPLIT, |
| 8945 |
) |
| 8946 |
) |
| 8947 |
|
| 8948 |
# The preview must have seen the real, meaningful title content -- |
| 8949 |
# not an empty string produced by slicing into the leading whitespace. |
| 8950 |
assert observed["title_arg"] == "\x01" * 50 |
| 8951 |
|
| 8952 |
|
| 8953 |
@mock.patch("requests.put") |
| 8954 |
@mock.patch("requests.get") |
| 8955 |
@mock.patch("requests.post") |
| 8956 |
def test_plugin_matrix_truncation_warning_fires(mock_post, mock_get, mock_put): |
| 8957 |
"""A genuinely oversized payload must still log the framework's normal |
| 8958 |
truncation warning -- sizing this content-aware must not suppress it |
| 8959 |
by pre-trimming before the framework's own check ever runs.""" |
| 8960 |
from apprise.asset import AppriseAsset |
| 8961 |
from apprise.common import OverflowMode |
| 8962 |
|
| 8963 |
response_obj = { |
| 8964 |
"room_id": "!abc123:localhost", |
| 8965 |
"room_alias": "#abc123:localhost", |
| 8966 |
"joined_rooms": ["!abc123:localhost"], |
| 8967 |
"access_token": "abcd1234", |
| 8968 |
"home_server": "localhost", |
| 8969 |
} |
| 8970 |
request = _Response() |
| 8971 |
request.content = dumps(response_obj) |
| 8972 |
request.status_code = requests.codes.ok |
| 8973 |
mock_get.return_value = request |
| 8974 |
mock_post.return_value = request |
| 8975 |
mock_put.return_value = request |
| 8976 |
|
| 8977 |
asset = AppriseAsset(payload_max_size=100) |
| 8978 |
obj = NotifyMatrix( |
| 8979 |
host="hostname", user="user", password="passwd", asset=asset |
| 8980 |
) |
| 8981 |
|
| 8982 |
with mock.patch.object(obj, "logger") as mock_logger: |
| 8983 |
assert bool( |
| 8984 |
obj.notify( |
| 8985 |
body="x" * 300, title="Alert", overflow=OverflowMode.SPLIT |
| 8986 |
) |
| 8987 |
) |
| 8988 |
assert any( |
| 8989 |
"trimmed" in call.args[0] |
| 8990 |
for call in mock_logger.warning.call_args_list |
| 8991 |
) |
| 8992 |
|
| 8993 |
|
| 8994 |
def test_plugin_matrix_body_limit_thread_isolation(): |
| 8995 |
"""Keep content-aware body limits isolated across threads. |
| 8996 |
|
| 8997 |
The context variable is exercised directly so the test is deterministic |
| 8998 |
and does not depend on reproducing a timing-sensitive race. |
| 8999 |
""" |
| 9000 |
import threading |
| 9001 |
|
| 9002 |
from apprise.plugins.matrix import base as matrix_base |
| 9003 |
|
| 9004 |
obj = NotifyMatrix( |
| 9005 |
host="h", user="u", password="pass", targets=["#r"], secure=True |
| 9006 |
) |
| 9007 |
|
| 9008 |
# Sizing state lives in a context var, not on the instance itself. |
| 9009 |
assert "_matrix_effective_body_maxlen" not in obj.__dict__ |
| 9010 |
|
| 9011 |
var = matrix_base._matrix_effective_body_maxlen_var |
| 9012 |
seen_in_other_thread = {} |
| 9013 |
|
| 9014 |
def set_and_check_from_other_thread(): |
| 9015 |
token = var.set(999) |
| 9016 |
try: |
| 9017 |
seen_in_other_thread["value"] = var.get() |
| 9018 |
finally: |
| 9019 |
var.reset(token) |
| 9020 |
|
| 9021 |
token = var.set(111) |
| 9022 |
try: |
| 9023 |
t = threading.Thread(target=set_and_check_from_other_thread) |
| 9024 |
t.start() |
| 9025 |
t.join(timeout=5) |
| 9026 |
|
| 9027 |
# The other thread's write must not have leaked into this one. |
| 9028 |
assert var.get() == 111 |
| 9029 |
finally: |
| 9030 |
var.reset(token) |
| 9031 |
|
| 9032 |
# And this thread's write must not have leaked into the other one. |
| 9033 |
assert seen_in_other_thread["value"] == 999 |
| 9034 |
|
| 9035 |
|
| 9036 |
@mock.patch("requests.put") |
| 9037 |
@mock.patch("requests.get") |
| 9038 |
@mock.patch("requests.post") |
| 9039 |
def test_plugin_matrix_emoji_split_preserves_content( |
| 9040 |
mock_post, mock_get, mock_put |
| 9041 |
): |
| 9042 |
"""Emoji splitting preserves content within the byte limit.""" |
| 9043 |
from apprise.common import OverflowMode |
| 9044 |
|
| 9045 |
response_obj = { |
| 9046 |
"room_id": "!abc123:localhost", |
| 9047 |
"room_alias": "#abc123:localhost", |
| 9048 |
"joined_rooms": ["!abc123:localhost"], |
| 9049 |
"access_token": "abcd1234", |
| 9050 |
"home_server": "localhost", |
| 9051 |
} |
| 9052 |
request = _Response() |
| 9053 |
request.content = dumps(response_obj) |
| 9054 |
request.status_code = requests.codes.ok |
| 9055 |
|
| 9056 |
mock_get.return_value = request |
| 9057 |
mock_post.return_value = request |
| 9058 |
mock_put.return_value = request |
| 9059 |
|
| 9060 |
obj = NotifyMatrix(host="hostname", user="user", password="passwd") |
| 9061 |
|
| 9062 |
original_body = "\U0001f600" * 20000 |
| 9063 |
assert ( |
| 9064 |
bool(obj.notify(body=original_body, overflow=OverflowMode.SPLIT)) |
| 9065 |
is True |
| 9066 |
) |
| 9067 |
|
| 9068 |
# Each event must independently fit Matrix's byte limit. |
| 9069 |
assert mock_put.call_count > 1 |
| 9070 |
reconstructed = "" |
| 9071 |
for call in mock_put.call_args_list: |
| 9072 |
payload = loads(call.kwargs["data"]) |
| 9073 |
encoded_len = len(dumps(payload, ensure_ascii=False).encode("utf-8")) |
| 9074 |
assert encoded_len <= 65536 |
| 9075 |
reconstructed += payload["body"] |
| 9076 |
|
| 9077 |
# No emoji was dropped or duplicated across the split events. |
| 9078 |
assert reconstructed == original_body |
| 9079 |
|
| 9080 |
|
| 9081 |
@mock.patch("requests.put") |
| 9082 |
@mock.patch("requests.get") |
| 9083 |
@mock.patch("requests.post") |
| 9084 |
def test_plugin_matrix_emoji_split_counters(mock_post, mock_get, mock_put): |
| 9085 |
"""Emoji split counters match the number of events sent.""" |
| 9086 |
from apprise.common import OverflowMode |
| 9087 |
|
| 9088 |
response_obj = { |
| 9089 |
"room_id": "!abc123:localhost", |
| 9090 |
"room_alias": "#abc123:localhost", |
| 9091 |
"joined_rooms": ["!abc123:localhost"], |
| 9092 |
"access_token": "abcd1234", |
| 9093 |
"home_server": "localhost", |
| 9094 |
} |
| 9095 |
request = _Response() |
| 9096 |
request.content = dumps(response_obj) |
| 9097 |
request.status_code = requests.codes.ok |
| 9098 |
|
| 9099 |
mock_get.return_value = request |
| 9100 |
mock_post.return_value = request |
| 9101 |
mock_put.return_value = request |
| 9102 |
|
| 9103 |
obj = NotifyMatrix(host="hostname", user="user", password="passwd") |
| 9104 |
|
| 9105 |
assert ( |
| 9106 |
bool( |
| 9107 |
obj.notify( |
| 9108 |
title="Title", |
| 9109 |
body="\U0001f600" * 20000, |
| 9110 |
overflow=OverflowMode.SPLIT, |
| 9111 |
) |
| 9112 |
) |
| 9113 |
is True |
| 9114 |
) |
| 9115 |
|
| 9116 |
total = mock_put.call_count |
| 9117 |
assert total > 1 |
| 9118 |
|
| 9119 |
# Counters use the framework's zero-padded width. |
| 9120 |
digits = len(str(total)) |
| 9121 |
last_payload = loads(mock_put.call_args_list[-1].kwargs["data"]) |
| 9122 |
assert f"[{total:0{digits}d}/{total:0{digits}d}]" in last_payload["body"] |
| 9123 |
|
| 9124 |
|
| 9125 |
@mock.patch("requests.put") |
| 9126 |
@mock.patch("requests.get") |
| 9127 |
@mock.patch("requests.post") |
| 9128 |
def test_plugin_matrix_discovery_is_unauthenticated( |
| 9129 |
mock_post, mock_get, mock_put |
| 9130 |
): |
| 9131 |
"""Keep the access token out of every discovery request.""" |
| 9132 |
|
| 9133 |
def _resp(payload): |
| 9134 |
response = _Response() |
| 9135 |
response.status_code = requests.codes.ok |
| 9136 |
response.content = dumps(payload).encode("utf-8") |
| 9137 |
response.headers = {} |
| 9138 |
return response |
| 9139 |
|
| 9140 |
well_known = { |
| 9141 |
"m.homeserver": {"base_url": "https://matrix.example.com"}, |
| 9142 |
"m.identity_server": {"base_url": "https://identity.example.com"}, |
| 9143 |
} |
| 9144 |
mock_get.side_effect = [_resp(well_known), _resp({}), _resp({})] |
| 9145 |
mock_post.return_value = _resp({}) |
| 9146 |
mock_put.return_value = _resp({}) |
| 9147 |
|
| 9148 |
obj = Apprise.instantiate( |
| 9149 |
"matrixs://user:[email protected]/#general?v=2&discovery=yes" |
| 9150 |
) |
| 9151 |
|
| 9152 |
# Pretend we already hold a session from an earlier notification |
| 9153 |
obj.access_token = "secret-token" |
| 9154 |
assert obj.base_url == "https://matrix.example.com" |
| 9155 |
|
| 9156 |
# The well-known lookup and both probes went out without it |
| 9157 |
assert mock_get.call_count == 3 |
| 9158 |
for call in mock_get.call_args_list: |
| 9159 |
assert "Authorization" not in call[1]["headers"] |
| 9160 |
|
| 9161 |
del obj |
| 9162 |
_force_del_cleanup() |