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