| 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 |
|
| 29 |
import logging |
| 30 |
import os |
| 31 |
import sys |
| 32 |
from unittest import mock |
| 33 |
|
| 34 |
import pytest |
| 35 |
|
| 36 |
from apprise.utils import pgp as pgp_module |
| 37 |
from apprise.utils.pgp import ApprisePGPController, _ensure_imghdr_shim |
| 38 |
|
| 39 |
logging.disable(logging.CRITICAL) |
| 40 |
|
| 41 |
|
| 42 |
_VAR_DIR = os.path.join(os.path.dirname(__file__), "var", "pgp") |
| 43 |
_VALID_PRV_ASC = os.path.join(_VAR_DIR, "valid-prv.asc") |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
def test_imghdr_shim_when_present(): |
| 52 |
"""_ensure_imghdr_shim() leaves sys.modules intact when imghdr imports.""" |
| 53 |
|
| 54 |
|
| 55 |
real_imghdr = sys.modules.get("imghdr") |
| 56 |
try: |
| 57 |
import imghdr as _real |
| 58 |
|
| 59 |
|
| 60 |
_ensure_imghdr_shim() |
| 61 |
|
| 62 |
|
| 63 |
assert sys.modules.get("imghdr") is _real |
| 64 |
|
| 65 |
except ImportError: |
| 66 |
|
| 67 |
pytest.skip("imghdr not present on this Python version") |
| 68 |
|
| 69 |
finally: |
| 70 |
|
| 71 |
if real_imghdr is None: |
| 72 |
sys.modules.pop("imghdr", None) |
| 73 |
else: |
| 74 |
sys.modules["imghdr"] = real_imghdr |
| 75 |
|
| 76 |
|
| 77 |
def test_imghdr_shim_when_absent(): |
| 78 |
"""_ensure_imghdr_shim() installs a working shim when imghdr is missing.""" |
| 79 |
|
| 80 |
|
| 81 |
saved = sys.modules.pop("imghdr", None) |
| 82 |
try: |
| 83 |
|
| 84 |
sys.modules["imghdr"] = None |
| 85 |
|
| 86 |
_ensure_imghdr_shim() |
| 87 |
|
| 88 |
shim = sys.modules.get("imghdr") |
| 89 |
assert shim is not None |
| 90 |
assert callable(shim.what) |
| 91 |
|
| 92 |
|
| 93 |
assert shim.what() is None |
| 94 |
assert shim.what(file=None, h=b"\xff\xd8\xff") is None |
| 95 |
assert shim.what(None, h=b"some data") is None |
| 96 |
|
| 97 |
finally: |
| 98 |
|
| 99 |
if saved is None: |
| 100 |
sys.modules.pop("imghdr", None) |
| 101 |
else: |
| 102 |
sys.modules["imghdr"] = saved |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
def test_pgp_controller_wkd_none_by_default(tmpdir): |
| 111 |
"""ApprisePGPController has wkd=None unless explicitly provided.""" |
| 112 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 113 |
assert ctrl.wkd is None |
| 114 |
|
| 115 |
|
| 116 |
def test_pgp_controller_accepts_wkd(tmpdir): |
| 117 |
"""ApprisePGPController stores the WKD controller it is given.""" |
| 118 |
mock_wkd = mock.Mock() |
| 119 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 120 |
assert ctrl.wkd is mock_wkd |
| 121 |
|
| 122 |
|
| 123 |
def test_fetch_wkd_key_no_controller(tmpdir): |
| 124 |
"""_fetch_wkd_key() returns None when no WKD controller is set.""" |
| 125 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 126 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 127 |
assert result is None |
| 128 |
|
| 129 |
|
| 130 |
def test_fetch_wkd_key_empty_emails(tmpdir): |
| 131 |
"""_fetch_wkd_key() returns None when no email candidates exist.""" |
| 132 |
mock_wkd = mock.Mock() |
| 133 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 134 |
|
| 135 |
result = ctrl._fetch_wkd_key() |
| 136 |
assert result is None |
| 137 |
mock_wkd.fetch.assert_not_called() |
| 138 |
|
| 139 |
|
| 140 |
def test_fetch_wkd_key_skips_none_in_candidate_list(tmpdir): |
| 141 |
"""_fetch_wkd_key() skips None/empty entries in the email candidates.""" |
| 142 |
mock_wkd = mock.Mock() |
| 143 |
mock_wkd.fetch.return_value = None |
| 144 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 145 |
|
| 146 |
result = ctrl._fetch_wkd_key(None, "[email protected]") |
| 147 |
assert result is None |
| 148 |
|
| 149 |
mock_wkd.fetch.assert_called_once_with("[email protected]") |
| 150 |
|
| 151 |
|
| 152 |
def test_fetch_wkd_key_wkd_returns_none(tmpdir): |
| 153 |
"""_fetch_wkd_key() returns None when WKD fetch yields nothing.""" |
| 154 |
mock_wkd = mock.Mock() |
| 155 |
mock_wkd.fetch.return_value = None |
| 156 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 157 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 158 |
assert result is None |
| 159 |
|
| 160 |
|
| 161 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 162 |
def test_fetch_wkd_key_success(tmpdir): |
| 163 |
"""_fetch_wkd_key() parses and caches a key returned by WKD.""" |
| 164 |
import pgpy |
| 165 |
|
| 166 |
|
| 167 |
key = pgpy.PGPKey.new( |
| 168 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 169 |
) |
| 170 |
uid = pgpy.PGPUID.new("Test", email="[email protected]") |
| 171 |
key.add_uid( |
| 172 |
uid, |
| 173 |
usage={ |
| 174 |
pgpy.constants.KeyFlags.Sign, |
| 175 |
pgpy.constants.KeyFlags.EncryptCommunications, |
| 176 |
}, |
| 177 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 178 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 179 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 180 |
) |
| 181 |
pub_bytes = str(key.pubkey).encode() |
| 182 |
|
| 183 |
mock_wkd = mock.Mock() |
| 184 |
mock_wkd.fetch.return_value = pub_bytes |
| 185 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 186 |
|
| 187 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 188 |
assert result is not None |
| 189 |
assert isinstance(result, pgpy.PGPKey) |
| 190 |
mock_wkd.fetch.assert_called_once_with("[email protected]") |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
mock_wkd.fetch.reset_mock() |
| 195 |
result2 = ctrl._fetch_wkd_key("[email protected]") |
| 196 |
assert result2 is not None |
| 197 |
mock_wkd.fetch.assert_not_called() |
| 198 |
|
| 199 |
|
| 200 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 201 |
def test_fetch_wkd_key_expired_cache_refetches(tmpdir): |
| 202 |
"""_fetch_wkd_key() drops an expired parsed-key cache entry and |
| 203 |
re-fetches from WKD rather than returning the stale key.""" |
| 204 |
from datetime import datetime, timedelta, timezone |
| 205 |
import hashlib |
| 206 |
|
| 207 |
import pgpy |
| 208 |
|
| 209 |
|
| 210 |
key = pgpy.PGPKey.new( |
| 211 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 212 |
) |
| 213 |
uid = pgpy.PGPUID.new("Fresh", email="[email protected]") |
| 214 |
key.add_uid( |
| 215 |
uid, |
| 216 |
usage={ |
| 217 |
pgpy.constants.KeyFlags.Sign, |
| 218 |
pgpy.constants.KeyFlags.EncryptCommunications, |
| 219 |
}, |
| 220 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 221 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 222 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 223 |
) |
| 224 |
pub_bytes = str(key.pubkey).encode() |
| 225 |
|
| 226 |
mock_wkd = mock.Mock() |
| 227 |
mock_wkd.fetch.return_value = pub_bytes |
| 228 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 229 |
|
| 230 |
|
| 231 |
cache_key = hashlib.sha1(b"wkd:[email protected]").hexdigest() |
| 232 |
|
| 233 |
ctrl._ApprisePGPController__key_lookup[cache_key] = { |
| 234 |
"public_key": None, |
| 235 |
"expires": datetime.now(timezone.utc) - timedelta(seconds=1), |
| 236 |
} |
| 237 |
|
| 238 |
|
| 239 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 240 |
assert result is not None |
| 241 |
mock_wkd.fetch.assert_called_once_with("[email protected]") |
| 242 |
|
| 243 |
|
| 244 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 245 |
def test_fetch_wkd_key_prefers_recipient_over_sender(tmpdir): |
| 246 |
"""_fetch_wkd_key() tries recipient emails before self.email so that |
| 247 |
the recipient's public key (not the sender's) is used for encryption.""" |
| 248 |
import pgpy |
| 249 |
|
| 250 |
|
| 251 |
key = pgpy.PGPKey.new( |
| 252 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 253 |
) |
| 254 |
uid = pgpy.PGPUID.new("Recipient", email="[email protected]") |
| 255 |
key.add_uid( |
| 256 |
uid, |
| 257 |
usage={ |
| 258 |
pgpy.constants.KeyFlags.Sign, |
| 259 |
pgpy.constants.KeyFlags.EncryptCommunications, |
| 260 |
}, |
| 261 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 262 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 263 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 264 |
) |
| 265 |
pub_bytes = str(key.pubkey).encode() |
| 266 |
|
| 267 |
|
| 268 |
def fake_fetch(email): |
| 269 |
if email == "[email protected]": |
| 270 |
return pub_bytes |
| 271 |
return None |
| 272 |
|
| 273 |
mock_wkd = mock.Mock(side_effect=fake_fetch) |
| 274 |
mock_wkd.fetch.side_effect = fake_fetch |
| 275 |
ctrl = ApprisePGPController( |
| 276 |
path=str(tmpdir), |
| 277 |
email="[email protected]", |
| 278 |
wkd=mock_wkd, |
| 279 |
) |
| 280 |
|
| 281 |
|
| 282 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 283 |
assert result is not None |
| 284 |
|
| 285 |
calls = [call.args[0] for call in mock_wkd.fetch.call_args_list] |
| 286 |
assert calls[0] == "[email protected]" |
| 287 |
assert "[email protected]" not in calls |
| 288 |
|
| 289 |
|
| 290 |
@pytest.mark.skipif( |
| 291 |
pgp_module.PGP_SUPPORT, reason="Tests behavior when pgpy is absent" |
| 292 |
) |
| 293 |
def test_fetch_wkd_key_pgpy_not_installed(tmpdir): |
| 294 |
"""_fetch_wkd_key() skips silently when pgpy raises NameError.""" |
| 295 |
mock_wkd = mock.Mock() |
| 296 |
mock_wkd.fetch.return_value = b"fake-key-bytes" |
| 297 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 298 |
|
| 299 |
|
| 300 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 301 |
assert result is None |
| 302 |
|
| 303 |
|
| 304 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 305 |
def test_fetch_wkd_key_corrupt_data(tmpdir): |
| 306 |
"""_fetch_wkd_key() skips and tries next candidate on parse failure.""" |
| 307 |
mock_wkd = mock.Mock() |
| 308 |
mock_wkd.fetch.return_value = b"this-is-not-a-pgp-key" |
| 309 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
with mock.patch( |
| 314 |
"pgpy.PGPKey.from_blob", |
| 315 |
side_effect=Exception("bad key"), |
| 316 |
): |
| 317 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 318 |
|
| 319 |
assert result is None |
| 320 |
|
| 321 |
|
| 322 |
def test_fetch_wkd_key_uses_self_email_as_candidate(tmpdir): |
| 323 |
"""_fetch_wkd_key() includes self.email in the candidate list.""" |
| 324 |
mock_wkd = mock.Mock() |
| 325 |
mock_wkd.fetch.return_value = None |
| 326 |
ctrl = ApprisePGPController( |
| 327 |
path=str(tmpdir), email="[email protected]", wkd=mock_wkd |
| 328 |
) |
| 329 |
|
| 330 |
ctrl._fetch_wkd_key() |
| 331 |
|
| 332 |
|
| 333 |
mock_wkd.fetch.assert_called_with("[email protected]") |
| 334 |
|
| 335 |
|
| 336 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 337 |
def test_public_key_falls_through_to_wkd(tmpdir): |
| 338 |
"""public_key() uses WKD when no local key file exists.""" |
| 339 |
import pgpy |
| 340 |
|
| 341 |
|
| 342 |
key = pgpy.PGPKey.new( |
| 343 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 344 |
) |
| 345 |
uid = pgpy.PGPUID.new("WKD User", email="[email protected]") |
| 346 |
key.add_uid( |
| 347 |
uid, |
| 348 |
usage={ |
| 349 |
pgpy.constants.KeyFlags.Sign, |
| 350 |
pgpy.constants.KeyFlags.EncryptCommunications, |
| 351 |
}, |
| 352 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 353 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 354 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 355 |
) |
| 356 |
pub_bytes = str(key.pubkey).encode() |
| 357 |
|
| 358 |
mock_wkd = mock.Mock() |
| 359 |
mock_wkd.fetch.return_value = pub_bytes |
| 360 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 361 |
|
| 362 |
|
| 363 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 364 |
assert result is not None |
| 365 |
mock_wkd.fetch.assert_called() |
| 366 |
|
| 367 |
|
| 368 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 369 |
def test_public_key_wkd_fails_falls_through_to_autogen(tmpdir): |
| 370 |
"""public_key() falls through to autogen when WKD also returns None.""" |
| 371 |
mock_wkd = mock.Mock() |
| 372 |
mock_wkd.fetch.return_value = None |
| 373 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 374 |
|
| 375 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 376 |
assert result is None |
| 377 |
mock_wkd.fetch.assert_called() |
| 378 |
|
| 379 |
|
| 380 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 381 |
def test_public_key_malformed_local_file_returns_none(tmpdir): |
| 382 |
"""public_key() returns None gracefully when the local .asc file is |
| 383 |
not valid PGP data (pgpy raises during parse).""" |
| 384 |
|
| 385 |
|
| 386 |
bad_key_path = tmpdir.join("pub.asc") |
| 387 |
bad_key_path.write("this is not a pgp key\n") |
| 388 |
|
| 389 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 390 |
|
| 391 |
result = ctrl.public_key(autogen=False) |
| 392 |
assert result is None |
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
def test_prune_delegates_to_wkd(tmpdir): |
| 401 |
"""prune() calls prune() on the WKD controller when one is set.""" |
| 402 |
mock_wkd = mock.Mock() |
| 403 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 404 |
ctrl.prune() |
| 405 |
mock_wkd.prune.assert_called_once() |
| 406 |
|
| 407 |
|
| 408 |
def test_prune_without_wkd(tmpdir): |
| 409 |
"""prune() runs without error when no WKD controller is set.""" |
| 410 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 411 |
ctrl.prune() |
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
def test_pgp_support_flag_present(): |
| 420 |
"""PGP_SUPPORT is a boolean exported from the pgp module.""" |
| 421 |
assert isinstance(pgp_module.PGP_SUPPORT, bool) |
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
def test_private_keyfile_no_path(): |
| 430 |
"""private_keyfile() returns None when neither path nor prv_keyfile set.""" |
| 431 |
ctrl = ApprisePGPController(path=None) |
| 432 |
assert ctrl.private_keyfile() is None |
| 433 |
|
| 434 |
|
| 435 |
def test_private_keyfile_explicit_valid(tmpdir): |
| 436 |
"""private_keyfile() returns a path for a valid explicit prv_keyfile.""" |
| 437 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 438 |
result = ctrl.private_keyfile() |
| 439 |
|
| 440 |
assert result and os.path.isfile(result) |
| 441 |
|
| 442 |
|
| 443 |
def test_private_keyfile_explicit_invalid(tmpdir): |
| 444 |
"""private_keyfile() returns False when an explicit file is unreachable.""" |
| 445 |
ctrl = ApprisePGPController( |
| 446 |
path=str(tmpdir), |
| 447 |
prv_keyfile="/nonexistent/path/key.asc", |
| 448 |
) |
| 449 |
|
| 450 |
result = ctrl.private_keyfile() |
| 451 |
assert result is False |
| 452 |
|
| 453 |
|
| 454 |
def test_private_keyfile_auto_discover_by_email(tmpdir): |
| 455 |
"""private_keyfile() finds an auto-generated key named by email prefix.""" |
| 456 |
|
| 457 |
key_path = str(tmpdir.join("user-prv.asc")) |
| 458 |
with open(key_path, "w") as f: |
| 459 |
f.write("dummy") |
| 460 |
|
| 461 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 462 |
result = ctrl.private_keyfile() |
| 463 |
assert result == key_path |
| 464 |
|
| 465 |
|
| 466 |
def test_private_keyfile_fallback_generic_name(tmpdir): |
| 467 |
"""private_keyfile() falls back to pgp-prv.asc when no email-named key.""" |
| 468 |
key_path = str(tmpdir.join("pgp-prv.asc")) |
| 469 |
with open(key_path, "w") as f: |
| 470 |
f.write("dummy") |
| 471 |
|
| 472 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 473 |
result = ctrl.private_keyfile() |
| 474 |
assert result == key_path |
| 475 |
|
| 476 |
|
| 477 |
def test_private_keyfile_not_found(tmpdir): |
| 478 |
"""private_keyfile() returns None when no private key exists on disk.""" |
| 479 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 480 |
assert ctrl.private_keyfile() is None |
| 481 |
|
| 482 |
|
| 483 |
def test_prv_keyfile_property_none_when_not_set(tmpdir): |
| 484 |
"""prv_keyfile property returns None when no explicit key was provided.""" |
| 485 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 486 |
assert ctrl.prv_keyfile is None |
| 487 |
|
| 488 |
|
| 489 |
def test_prv_keyfile_property_path_when_valid(tmpdir): |
| 490 |
"""prv_keyfile property returns the resolved path for a valid key.""" |
| 491 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 492 |
|
| 493 |
|
| 494 |
assert ctrl.prv_keyfile is not False |
| 495 |
|
| 496 |
|
| 497 |
def test_prv_keyfile_property_false_when_invalid(tmpdir): |
| 498 |
"""prv_keyfile property returns False for an unreachable explicit file.""" |
| 499 |
ctrl = ApprisePGPController( |
| 500 |
path=str(tmpdir), |
| 501 |
prv_keyfile="/no/such/file.asc", |
| 502 |
) |
| 503 |
assert ctrl.prv_keyfile is False |
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 512 |
def test_private_key_loads_valid_fixture(tmpdir): |
| 513 |
"""private_key() returns a PGPKey object from a valid private key file.""" |
| 514 |
import pgpy |
| 515 |
|
| 516 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 517 |
key = ctrl.private_key() |
| 518 |
assert key is not None |
| 519 |
assert isinstance(key, pgpy.PGPKey) |
| 520 |
|
| 521 |
|
| 522 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 523 |
def test_private_key_cached_on_second_call(tmpdir): |
| 524 |
"""private_key() returns the same object on repeated calls (cached).""" |
| 525 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 526 |
first = ctrl.private_key() |
| 527 |
second = ctrl.private_key() |
| 528 |
assert first is not None |
| 529 |
assert first is second |
| 530 |
|
| 531 |
|
| 532 |
def test_private_key_returns_none_when_not_found(tmpdir): |
| 533 |
"""private_key() returns None when no private key file exists.""" |
| 534 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 535 |
assert ctrl.private_key() is None |
| 536 |
|
| 537 |
|
| 538 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 539 |
def test_private_key_expired_cache_reloads(tmpdir): |
| 540 |
"""private_key() drops an expired cache entry and reloads from disk.""" |
| 541 |
from datetime import datetime, timedelta, timezone |
| 542 |
import hashlib |
| 543 |
|
| 544 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 545 |
|
| 546 |
|
| 547 |
first = ctrl.private_key() |
| 548 |
assert first is not None |
| 549 |
|
| 550 |
|
| 551 |
cache_key = hashlib.sha1( |
| 552 |
("prv:" + os.path.abspath(_VALID_PRV_ASC)).encode("utf-8") |
| 553 |
).hexdigest() |
| 554 |
ctrl._ApprisePGPController__key_lookup[cache_key]["expires"] = ( |
| 555 |
datetime.now(timezone.utc) - timedelta(seconds=1) |
| 556 |
) |
| 557 |
|
| 558 |
|
| 559 |
second = ctrl.private_key() |
| 560 |
assert second is not None |
| 561 |
|
| 562 |
|
| 563 |
def test_private_key_returns_none_when_pgpy_missing(tmpdir): |
| 564 |
"""private_key() returns None gracefully when PGPy is not installed.""" |
| 565 |
import contextlib |
| 566 |
|
| 567 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 568 |
with contextlib.ExitStack() as stack: |
| 569 |
|
| 570 |
stack.enter_context(mock.patch.object(pgp_module, "PGP_SUPPORT", True)) |
| 571 |
|
| 572 |
stack.enter_context( |
| 573 |
mock.patch("builtins.open", mock.mock_open(read_data="data")) |
| 574 |
) |
| 575 |
if "pgpy" in sys.modules: |
| 576 |
|
| 577 |
|
| 578 |
stack.enter_context( |
| 579 |
mock.patch("pgpy.PGPKey.from_blob", side_effect=NameError) |
| 580 |
) |
| 581 |
|
| 582 |
|
| 583 |
|
| 584 |
result = ctrl.private_key() |
| 585 |
assert result is None |
| 586 |
|
| 587 |
|
| 588 |
def test_private_key_returns_none_when_keyfile_inaccessible(tmpdir): |
| 589 |
"""private_key() returns None when private_keyfile() returns False.""" |
| 590 |
|
| 591 |
ctrl = ApprisePGPController( |
| 592 |
path=str(tmpdir), prv_keyfile="/no/such/file.asc" |
| 593 |
) |
| 594 |
|
| 595 |
result = ctrl.private_key() |
| 596 |
assert result is None |
| 597 |
|
| 598 |
|
| 599 |
def test_private_key_returns_none_on_io_error(tmpdir): |
| 600 |
"""private_key() returns None when the file cannot be read.""" |
| 601 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 602 |
with mock.patch("builtins.open", side_effect=OSError("disk error")): |
| 603 |
result = ctrl.private_key() |
| 604 |
assert result is None |
| 605 |
|
| 606 |
|
| 607 |
def test_private_key_returns_none_on_malformed_key(tmpdir): |
| 608 |
"""private_key() returns None when the file contains non-PGP data.""" |
| 609 |
bad_key = str(tmpdir.join("bad-prv.asc")) |
| 610 |
with open(bad_key, "w") as f: |
| 611 |
f.write("this is not a pgp key") |
| 612 |
|
| 613 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=bad_key) |
| 614 |
result = ctrl.private_key() |
| 615 |
assert result is None |
| 616 |
|
| 617 |
|
| 618 |
def test_private_key_returns_none_when_file_disappears(tmpdir): |
| 619 |
"""private_key() handles a key file that vanishes between stat and open.""" |
| 620 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 621 |
with mock.patch("builtins.open", side_effect=FileNotFoundError("gone")): |
| 622 |
result = ctrl.private_key() |
| 623 |
assert result is None |
| 624 |
|
| 625 |
|
| 626 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 627 |
def test_private_key_rejects_passphrase_protected(tmpdir): |
| 628 |
"""private_key() returns None for a passphrase-protected key.""" |
| 629 |
import pgpy |
| 630 |
|
| 631 |
|
| 632 |
key = pgpy.PGPKey.new( |
| 633 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 634 |
) |
| 635 |
uid = pgpy.PGPUID.new("Locked", email="[email protected]") |
| 636 |
key.add_uid( |
| 637 |
uid, |
| 638 |
usage={pgpy.constants.KeyFlags.Sign}, |
| 639 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 640 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 641 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 642 |
) |
| 643 |
key.protect( |
| 644 |
"s3cr3t", |
| 645 |
pgpy.constants.SymmetricKeyAlgorithm.AES256, |
| 646 |
pgpy.constants.HashAlgorithm.SHA256, |
| 647 |
) |
| 648 |
|
| 649 |
locked_path = str(tmpdir.join("locked-prv.asc")) |
| 650 |
with open(locked_path, "w") as f: |
| 651 |
f.write(str(key)) |
| 652 |
|
| 653 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=locked_path) |
| 654 |
result = ctrl.private_key() |
| 655 |
assert result is None |
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 664 |
def test_sign_returns_signature_and_micalg(tmpdir): |
| 665 |
"""sign() returns a (sig_str, micalg) tuple for valid message + key.""" |
| 666 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 667 |
result = ctrl.sign("Hello, World!") |
| 668 |
assert result is not None |
| 669 |
sig_str, micalg = result |
| 670 |
|
| 671 |
assert "BEGIN PGP SIGNATURE" in sig_str |
| 672 |
|
| 673 |
assert micalg.startswith("pgp-") |
| 674 |
|
| 675 |
|
| 676 |
def test_sign_returns_none_when_no_private_key(tmpdir): |
| 677 |
"""sign() returns None when no private key is available.""" |
| 678 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 679 |
assert ctrl.sign("test message") is None |
| 680 |
|
| 681 |
|
| 682 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 683 |
def test_sign_returns_none_on_pgp_error(tmpdir): |
| 684 |
"""sign() returns None when pgpy raises PGPError during signing.""" |
| 685 |
import pgpy |
| 686 |
|
| 687 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 688 |
with mock.patch.object( |
| 689 |
ctrl.private_key().__class__, |
| 690 |
"sign", |
| 691 |
side_effect=pgpy.errors.PGPError("fail"), |
| 692 |
): |
| 693 |
result = ctrl.sign("test") |
| 694 |
assert result is None |
| 695 |
|
| 696 |
|
| 697 |
def test_sign_returns_none_when_pgpy_missing(tmpdir): |
| 698 |
"""sign() returns None gracefully when PGPy is not installed.""" |
| 699 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 700 |
|
| 701 |
mock_key = mock.Mock() |
| 702 |
mock_key.sign.side_effect = NameError("pgpy not installed") |
| 703 |
with mock.patch.object(ctrl, "private_key", return_value=mock_key): |
| 704 |
result = ctrl.sign("test") |
| 705 |
assert result is None |
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
|
| 713 |
def test_pub_key_candidates_no_email(tmpdir): |
| 714 |
"""_pub_key_candidates() returns the four generic fallbacks when no email |
| 715 |
is known and no extra addresses are supplied.""" |
| 716 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 717 |
|
| 718 |
candidates = ctrl._pub_key_candidates() |
| 719 |
|
| 720 |
assert candidates == [ |
| 721 |
"pgp-public.asc", |
| 722 |
"pgp-pub.asc", |
| 723 |
"public.asc", |
| 724 |
"pub.asc", |
| 725 |
] |
| 726 |
|
| 727 |
|
| 728 |
def test_pub_key_candidates_with_email(tmpdir): |
| 729 |
"""_pub_key_candidates() prepends email-specific names ahead of generics, |
| 730 |
highest priority first (full-email before localpart).""" |
| 731 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 732 |
candidates = ctrl._pub_key_candidates() |
| 733 |
|
| 734 |
assert candidates[0] == "[email protected]" |
| 735 |
|
| 736 |
assert candidates[1] == "chris-pub.asc" |
| 737 |
|
| 738 |
assert "pgp-pub.asc" in candidates |
| 739 |
|
| 740 |
|
| 741 |
def test_pub_key_candidates_extra_email(tmpdir): |
| 742 |
"""_pub_key_candidates() gives caller-supplied addresses higher priority |
| 743 |
than self.email because a per-recipient key lookup should prefer the |
| 744 |
recipient-specific file over the controller's own identity key.""" |
| 745 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 746 |
|
| 747 |
candidates = ctrl._pub_key_candidates("[email protected]") |
| 748 |
|
| 749 |
|
| 750 |
assert candidates[0] == "[email protected]" |
| 751 |
assert candidates[1] == "recipient-pub.asc" |
| 752 |
|
| 753 |
assert "[email protected]" in candidates |
| 754 |
assert "sender-pub.asc" in candidates |
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
def test_prv_key_candidates_no_email(tmpdir): |
| 763 |
"""_prv_key_candidates() returns the four generic fallbacks when no sender |
| 764 |
email is configured.""" |
| 765 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 766 |
candidates = ctrl._prv_key_candidates() |
| 767 |
assert candidates == [ |
| 768 |
"pgp-private.asc", |
| 769 |
"pgp-prv.asc", |
| 770 |
"private.asc", |
| 771 |
"prv.asc", |
| 772 |
] |
| 773 |
|
| 774 |
|
| 775 |
def test_prv_key_candidates_with_email(tmpdir): |
| 776 |
"""_prv_key_candidates() prepends email-specific names ahead of generics, |
| 777 |
highest priority first (full-email before localpart).""" |
| 778 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 779 |
candidates = ctrl._prv_key_candidates() |
| 780 |
|
| 781 |
assert candidates[0] == "[email protected]" |
| 782 |
|
| 783 |
assert candidates[1] == "sender-prv.asc" |
| 784 |
|
| 785 |
assert "pgp-prv.asc" in candidates |
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
|
| 793 |
def test_public_key_no_key_emits_path_debug(tmpdir): |
| 794 |
"""public_key() emits a DEBUG message listing relative cache paths when |
| 795 |
no public key is found and autogen is disabled. The message is debug- |
| 796 |
level so the caller's warning remains the only user-visible line.""" |
| 797 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 798 |
logging.disable(logging.NOTSET) |
| 799 |
try: |
| 800 |
with mock.patch.object(pgp_module, "PGP_SUPPORT", True): |
| 801 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 802 |
finally: |
| 803 |
logging.disable(logging.CRITICAL) |
| 804 |
|
| 805 |
|
| 806 |
assert result is None |
| 807 |
|
| 808 |
|
| 809 |
def test_public_key_no_key_no_path_emits_generic_debug(): |
| 810 |
"""public_key() emits a generic 'No PGP public key found' debug message |
| 811 |
in memory-only mode (no path to search, so no filenames to list).""" |
| 812 |
ctrl = ApprisePGPController(path=None) |
| 813 |
logging.disable(logging.NOTSET) |
| 814 |
try: |
| 815 |
with mock.patch.object(pgp_module, "PGP_SUPPORT", True): |
| 816 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 817 |
finally: |
| 818 |
logging.disable(logging.CRITICAL) |
| 819 |
assert result is None |
| 820 |
|
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
def test_private_key_not_found_emits_path_debug(tmpdir): |
| 828 |
"""private_key() emits a DEBUG message listing searched relative paths |
| 829 |
when no private key file exists on disk. The message is debug-level so |
| 830 |
the caller's warning remains the only user-visible line.""" |
| 831 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 832 |
logging.disable(logging.NOTSET) |
| 833 |
try: |
| 834 |
result = ctrl.private_key() |
| 835 |
finally: |
| 836 |
logging.disable(logging.CRITICAL) |
| 837 |
assert result is None |
| 838 |
|
| 839 |
|
| 840 |
def test_private_key_not_found_no_path_emits_generic_debug(): |
| 841 |
"""private_key() emits a generic 'No PGP private key found' debug |
| 842 |
message in memory-only mode (no storage path, nothing to search).""" |
| 843 |
ctrl = ApprisePGPController(path=None) |
| 844 |
logging.disable(logging.NOTSET) |
| 845 |
try: |
| 846 |
result = ctrl.private_key() |
| 847 |
finally: |
| 848 |
logging.disable(logging.CRITICAL) |
| 849 |
assert result is None |