Debian Codegraph @

tests/test_utils_pgp.py

raw symbols SCIP
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 # Disable logging for a cleaner testing output
29 import logging
30 import 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 # Path to the pre-generated private key fixture used by signing tests
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 # imghdr shim
48 # ---------------------------------------------------------------------------
49
50
51 def test_imghdr_shim_when_present():
52 """_ensure_imghdr_shim() leaves sys.modules intact when imghdr imports."""
53
54 # Guarantee imghdr is importable for this test
55 real_imghdr = sys.modules.get("imghdr")
56 try:
57 import imghdr as _real
58
59 # If we got here, imghdr is available on this Python version
60 _ensure_imghdr_shim()
61
62 # sys.modules entry must not have been replaced by our shim
63 assert sys.modules.get("imghdr") is _real
64
65 except ImportError:
66 # Python 3.13+ -- imghdr is gone; skip this branch
67 pytest.skip("imghdr not present on this Python version")
68
69 finally:
70 # Restore whatever was there before
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 # Remove any real imghdr from sys.modules and make import fail
81 saved = sys.modules.pop("imghdr", None)
82 try:
83 # Setting the key to None causes 'import imghdr' to raise ImportError
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 # The shim must return None (safe fallback for all inputs)
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 # Restore original state
99 if saved is None:
100 sys.modules.pop("imghdr", None)
101 else:
102 sys.modules["imghdr"] = saved
103
104
105 # ---------------------------------------------------------------------------
106 # ApprisePGPController -- WKD integration
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 # No self.email set and no positional emails
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 # None is a valid positional argument; it must be skipped, not crash
146 result = ctrl._fetch_wkd_key(None, "[email protected]")
147 assert result is None
148 # fetch must only be called for the valid address, not for None
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 # Generate a fresh key pair to use as our fake WKD payload
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 # Second call must use the parsed-key cache -- wkd.fetch must NOT be
193 # called again (the cache check now happens before wkd.fetch())
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 # Generate a key to serve as the fresh WKD result
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 # Seed the parsed-key cache with an already-expired entry
231 cache_key = hashlib.sha1(b"wkd:[email protected]").hexdigest()
232 # Use the private name-mangled attribute
233 ctrl._ApprisePGPController__key_lookup[cache_key] = {
234 "public_key": None,
235 "expires": datetime.now(timezone.utc) - timedelta(seconds=1),
236 }
237
238 # The expired entry is discarded; WKD is fetched and result returned
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 # Generate a key to represent the recipient's WKD result
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 # WKD returns a key only for the recipient address
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 # The recipient's email is passed as a positional argument
282 result = ctrl._fetch_wkd_key("[email protected]")
283 assert result is not None
284 # [email protected] must NOT have been tried before the recipient hit
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 # In a minimal env pgpy is not installed, so pgpy.PGPKey.from_blob
299 # raises NameError naturally -- no mock needed.
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 # Patch the canonical pgpy module directly (not the pgp module's copy)
312 # so the mock works whether pgpy was imported by name or attribute.
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 # self.email must have been tried
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 # Generate a minimal key for the mock WKD response
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 # No local key file exists, so WKD must be tried
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 # No local key file exists; WKD fails; autogen=False => None returned
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 # Write a file with non-PGP content under a name that public_keyfile()
385 # will discover automatically
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 # No autogen so the only candidate is the malformed file above
391 result = ctrl.public_key(autogen=False)
392 assert result is None
393
394
395 # ---------------------------------------------------------------------------
396 # prune() -- WKD delegation
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() # must not raise
412
413
414 # ---------------------------------------------------------------------------
415 # PGP_SUPPORT flag consistency
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 # private_keyfile() -- path resolution
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 # Should be an existing file path
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 # The attachment itself is invalid, so the property returns False
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 # Place a fake private key named after the email prefix
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 # Property accesses the attachment; it may return None before loading
493 # because the attachment is resolved lazily -- just confirm it is not False
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 # private_key() -- loading the private PGP key object
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 # Load the key once to prime the cache
547 first = ctrl.private_key()
548 assert first is not None
549
550 # Artificially expire the cached entry by back-dating its expiry time
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 # Second call must detect the expiry and re-load from disk
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 # Force PGP_SUPPORT=True so the key-loading branch is reached
570 stack.enter_context(mock.patch.object(pgp_module, "PGP_SUPPORT", True))
571 # Supply any readable content for the open() call
572 stack.enter_context(
573 mock.patch("builtins.open", mock.mock_open(read_data="data"))
574 )
575 if "pgpy" in sys.modules:
576 # When pgpy IS installed, simulate its absence by making
577 # from_blob raise NameError (same as if the name were undefined)
578 stack.enter_context(
579 mock.patch("pgpy.PGPKey.from_blob", side_effect=NameError)
580 )
581 # Without pgpy installed the NameError arises naturally at the
582 # 'pgpy.PGPKey.from_blob(...)' call in private_key(); either way
583 # private_key() must swallow the error and return None
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 # Provide an invalid path so the attachment reports the file as unreachable
591 ctrl = ApprisePGPController(
592 path=str(tmpdir), prv_keyfile="/no/such/file.asc"
593 )
594 # private_keyfile() will return False; private_key() must not raise
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 # Generate a fresh key and protect it with a passphrase
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 # sign() -- creating detached PGP signatures
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 # The signature must be a non-empty armored block
671 assert "BEGIN PGP SIGNATURE" in sig_str
672 # The micalg must start with 'pgp-'
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 # Patch private_key() to return a mock that raises NameError on sign()
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 # _pub_key_candidates() -- candidate filename ordering
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 # No self.email and no caller-supplied email
718 candidates = ctrl._pub_key_candidates()
719 # Only the four generic names should appear
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 # Full lowercase email is highest priority (index 0)
734 assert candidates[0] == "[email protected]"
735 # Localpart shorthand is next
736 assert candidates[1] == "chris-pub.asc"
737 # Generic fallbacks follow
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 # Simulate a lookup for a recipient address
747 candidates = ctrl._pub_key_candidates("[email protected]")
748 # Caller-supplied (recipient) address is processed last in the loop,
749 # so its entries end up at the front of the list (highest priority)
750 assert candidates[0] == "[email protected]"
751 assert candidates[1] == "recipient-pub.asc"
752 # self.email (sender) entries appear after
753 assert "[email protected]" in candidates
754 assert "sender-pub.asc" in candidates
755
756
757 # ---------------------------------------------------------------------------
758 # _prv_key_candidates() -- candidate filename ordering
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 # Full lowercase email is highest priority
781 assert candidates[0] == "[email protected]"
782 # Localpart shorthand is next
783 assert candidates[1] == "sender-prv.asc"
784 # Generic fallbacks follow
785 assert "pgp-prv.asc" in candidates
786
787
788 # ---------------------------------------------------------------------------
789 # public_key() -- diagnostic warning when no key is found
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 # Key not found; result must be None
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 # private_key() -- diagnostic debug message when no key is found
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