Debian Codegraph @

tests/test_utils_pem.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 import logging
29 import os
30 from unittest import mock
31
32 import pytest
33
34 from apprise import AppriseAsset, PersistentStoreMode, utils
35 from apprise.utils.pem import PEM_SUPPORT
36
37 # Disable logging for a cleaner testing output
38 logging.disable(logging.CRITICAL)
39
40 # Attachment Directory
41 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
42
43
44 @pytest.mark.skipif(not PEM_SUPPORT, reason="Requires cryptography")
45 def test_utils_pem_general(tmpdir):
46 """Utils:PEM."""
47
48 # string to manipulate/work with
49 unencrypted_str = "message"
50
51 tmpdir0 = tmpdir.mkdir("tmp00")
52
53 # Currently no files here
54 assert os.listdir(str(tmpdir0)) == []
55
56 asset = AppriseAsset(
57 storage_mode=PersistentStoreMode.MEMORY,
58 storage_path=str(tmpdir0),
59 pem_autogen=False,
60 )
61
62 # Create a PEM Controller
63 pem_c = utils.pem.ApprisePEMController(path=None, asset=asset)
64
65 # Nothing to lookup
66 assert pem_c.public_keyfile() is None
67 assert pem_c.public_key() is None
68 assert pem_c.x962_str == ""
69 assert pem_c.decrypt(b"data") is None
70 assert pem_c.encrypt(unencrypted_str) is None
71 # Keys can not be generated in memory mode
72 assert pem_c.keygen() is False
73 assert pem_c.sign(b"data") is None
74
75 asset = AppriseAsset(
76 storage_mode=PersistentStoreMode.FLUSH,
77 storage_path=str(tmpdir0),
78 pem_autogen=False,
79 )
80
81 # No new files
82 assert os.listdir(str(tmpdir0)) == []
83
84 # Our asset is now write mode, so we will be able to generate a key
85 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
86 # Nothing to lookup
87 assert pem_c.public_keyfile() is None
88 assert pem_c.public_key() is None
89 assert pem_c.x962_str == ""
90 assert pem_c.encrypt(unencrypted_str) is None
91
92 # Generate our keys
93 assert bool(pem_c) is False
94 assert pem_c.keygen() is True
95 assert bool(pem_c) is True
96
97 # We have 2 new key files generated
98 pub_keyfile = os.path.join(str(tmpdir0), "public_key.pem")
99 prv_keyfile = os.path.join(str(tmpdir0), "private_key.pem")
100 assert os.path.isfile(pub_keyfile)
101 assert os.path.isfile(prv_keyfile)
102 assert pem_c.public_keyfile() is not None
103 assert pem_c.decrypt("garbage") is None
104 assert pem_c.public_key() is not None
105
106 # Keys used later on as ref
107 pubkey_ref = pem_c.public_key()
108 prvkey_ref = pem_c.private_key()
109
110 assert isinstance(pem_c.x962_str, str)
111 assert len(pem_c.x962_str) > 20
112 content = pem_c.encrypt(unencrypted_str)
113 assert pem_c.decrypt(
114 pem_c.encrypt(unencrypted_str.encode("utf-8"))
115 ) == pem_c.decrypt(pem_c.encrypt(unencrypted_str))
116 assert pem_c.decrypt(
117 pem_c.encrypt(unencrypted_str, public_key=pem_c.public_key())
118 ) == pem_c.decrypt(pem_c.encrypt(unencrypted_str))
119 assert pem_c.decrypt(content) == unencrypted_str
120 assert isinstance(content, str)
121 assert pem_c.decrypt(content) == unencrypted_str
122 # support str as well
123 assert pem_c.decrypt(content) == unencrypted_str
124 assert pem_c.decrypt(content.encode("utf-8")) == unencrypted_str
125 # Sign test
126 assert isinstance(pem_c.sign(content.encode("utf-8")), bytes)
127
128 # Web Push handling
129 webpush_content = pem_c.encrypt_webpush(
130 unencrypted_str, public_key=pem_c.public_key(), auth_secret=b"secret"
131 )
132 assert isinstance(webpush_content, bytes)
133
134 webpush_content = pem_c.encrypt_webpush(
135 unencrypted_str.encode("utf-8"),
136 public_key=pem_c.public_key(),
137 auth_secret=b"secret",
138 )
139 assert isinstance(webpush_content, bytes)
140
141 # Non Bytes (garbage basically)
142 with pytest.raises(TypeError):
143 assert pem_c.decrypt(None) is None
144
145 with pytest.raises(TypeError):
146 assert pem_c.decrypt(5) is None
147
148 with pytest.raises(TypeError):
149 assert pem_c.decrypt(False) is None
150
151 with pytest.raises(TypeError):
152 assert pem_c.decrypt(object) is None
153
154 # Test our initialization
155 pem_c = utils.pem.ApprisePEMController(
156 path=None, prv_keyfile="invalid", asset=asset
157 )
158 assert pem_c.private_keyfile() is False
159 assert pem_c.public_keyfile() is None
160 assert pem_c.prv_keyfile is False
161 assert pem_c.pub_keyfile is None
162 assert pem_c.private_key() is None
163 assert pem_c.public_key() is None
164 assert pem_c.decrypt(content) is None
165
166 pem_c = utils.pem.ApprisePEMController(
167 path=None, pub_keyfile="invalid", asset=asset
168 )
169 assert pem_c.private_keyfile() is None
170 assert pem_c.public_keyfile() is False
171 assert pem_c.prv_keyfile is None
172 assert pem_c.pub_keyfile is False
173 assert pem_c.private_key() is None
174 assert pem_c.public_key() is None
175 assert pem_c.decrypt(content) is None
176
177 pem_c = utils.pem.ApprisePEMController(
178 path=None, prv_keyfile=prv_keyfile, asset=asset
179 )
180 assert pem_c.private_keyfile() == prv_keyfile
181 assert pem_c.public_keyfile() is None
182 assert pem_c.private_key() is not None
183 assert pem_c.prv_keyfile == prv_keyfile
184 assert pem_c.pub_keyfile is None
185 assert pem_c.public_key() is not None
186 assert pem_c.decrypt(content) == unencrypted_str
187
188 pem_c = utils.pem.ApprisePEMController(
189 path=None, pub_keyfile=pub_keyfile, asset=asset
190 )
191 assert pem_c.private_keyfile() is None
192 assert pem_c.public_keyfile() == pub_keyfile
193 assert pem_c.prv_keyfile is None
194 assert pem_c.pub_keyfile == pub_keyfile
195 assert pem_c.private_key() is None
196 assert pem_c.public_key() is not None
197 assert pem_c.decrypt(content) is None
198
199 # Test our path references
200 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
201 assert pem_c.load_private_key(path=None) is True
202 assert pem_c.private_keyfile() == prv_keyfile
203 assert pem_c.prv_keyfile is None
204 assert pem_c.pub_keyfile is None
205 assert pem_c.decrypt(content) == unencrypted_str
206
207 # Generate a new key referencing another location
208 pem_c = utils.pem.ApprisePEMController(
209 name="keygen-tests", path=str(tmpdir0), asset=asset
210 )
211
212 # generate ourselves some keys
213 assert pem_c.keygen() is True
214 keygen_prv_file = pem_c.prv_keyfile
215 keygen_pub_file = pem_c.pub_keyfile
216
217 # Remove 1 (but not both)
218 os.unlink(keygen_pub_file)
219
220 pem_c = utils.pem.ApprisePEMController(
221 name="keygen-tests", path=str(tmpdir0), asset=asset
222 )
223 # Private key was found, so this does not work
224 assert pem_c.keygen() is False
225 os.unlink(keygen_prv_file)
226
227 pem_c = utils.pem.ApprisePEMController(
228 name="keygen-tests", path=str(tmpdir0), asset=asset
229 )
230 # It works now
231 assert pem_c.keygen() is True
232
233 # Tests public_key generation failure only
234 with mock.patch("builtins.open", side_effect=OSError()):
235 assert pem_c.keygen(force=True) is False
236 with mock.patch("os.unlink", side_effect=OSError()):
237 assert pem_c.keygen(force=True) is False
238 with mock.patch("os.unlink", return_value=True):
239 assert pem_c.keygen(force=True) is False
240
241 # Tests private key generation
242 side_effect = [mock.mock_open(read_data="file contents").return_value] + [
243 OSError() for _ in range(10)
244 ]
245 with mock.patch("builtins.open", side_effect=side_effect):
246 assert pem_c.keygen(force=True) is False
247 with (
248 mock.patch("builtins.open", side_effect=side_effect),
249 mock.patch("os.unlink", side_effect=OSError()),
250 ):
251 assert pem_c.keygen(force=True) is False
252 with (
253 mock.patch("builtins.open", side_effect=side_effect),
254 mock.patch("os.unlink", return_value=True),
255 ):
256 assert pem_c.keygen(force=True) is False
257
258 # Generate a new key referencing another location
259 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
260 # We can't re-generate keys if ones already exist
261 assert pem_c.keygen() is False
262 # the keygen is the big difference here
263 assert pem_c.keygen(name="test") is True
264 # under the hood, a key is not regenerated (as one already exists)
265 assert pem_c.keygen(name="test") is False
266 # Generate it a second time by force
267 assert pem_c.keygen(name="test", force=True) is True
268
269 assert pem_c.private_keyfile() == os.path.join(
270 str(tmpdir0), "test-private_key.pem"
271 )
272 assert pem_c.public_keyfile() == os.path.join(
273 str(tmpdir0), "test-public_key.pem"
274 )
275 assert pem_c.private_key() is not None
276 assert pem_c.public_key() is not None
277 assert pem_c.prv_keyfile == os.path.join(
278 str(tmpdir0), "test-private_key.pem"
279 )
280 assert pem_c.pub_keyfile == os.path.join(
281 str(tmpdir0), "test-public_key.pem"
282 )
283 # 'content' was generated using a different key and can not be
284 # decrypted
285 assert pem_c.decrypt(content) is None
286
287 # Test Decryption files
288 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
289 # Calling decrypt triggers underlining code to auto-load
290 assert pem_c.decrypt(content) == unencrypted_str
291 # Using a private key by path
292 assert (
293 pem_c.decrypt(content, private_key=pem_c.private_key())
294 == unencrypted_str
295 )
296
297 # Test different edge cases of load_private_key()
298 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
299 assert pem_c.load_private_key() is True
300 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
301 assert pem_c.load_private_key(path=prv_keyfile) is True
302 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
303 with mock.patch("builtins.open", side_effect=TypeError()):
304 assert pem_c.load_private_key(path=prv_keyfile) is False
305 with mock.patch("builtins.open", side_effect=OSError()):
306 assert pem_c.load_private_key(path=prv_keyfile) is False
307 with mock.patch("builtins.open", side_effect=FileNotFoundError()):
308 assert pem_c.load_private_key(path=prv_keyfile) is False
309
310 # Test different edge cases of load_public_key()
311 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
312 assert pem_c.load_public_key() is True
313 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
314 assert pem_c.load_public_key(path=pub_keyfile) is True
315 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
316 with mock.patch("builtins.open", side_effect=TypeError()):
317 assert pem_c.load_public_key(path=pub_keyfile) is False
318 with mock.patch("builtins.open", side_effect=OSError()):
319 assert pem_c.load_public_key(path=pub_keyfile) is False
320 with mock.patch("builtins.open", side_effect=FileNotFoundError()):
321 assert pem_c.load_public_key(path=pub_keyfile) is False
322
323 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
324 assert pem_c.public_keyfile("test1", "test2") == pub_keyfile
325 assert pem_c.private_keyfile("test1", "test2") == prv_keyfile
326
327 pem_c = utils.pem.ApprisePEMController(
328 path=str(tmpdir0), name="pub1", asset=asset
329 )
330 assert pem_c.public_key(autogen=True)
331
332 pem_c = utils.pem.ApprisePEMController(
333 path=str(tmpdir0), name="pub2", asset=asset
334 )
335 assert pem_c.private_key(autogen=True)
336
337 #
338 # Auto key generation turned on
339 #
340 asset = AppriseAsset(
341 storage_mode=PersistentStoreMode.MEMORY,
342 storage_path=str(tmpdir0),
343 pem_autogen=True,
344 )
345 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
346 assert pem_c.load_public_key(path=pub_keyfile) is True
347 pem_c = utils.pem.ApprisePEMController(path=None, asset=asset)
348 assert pem_c.load_public_key(path=pub_keyfile) is True
349
350 tmpdir1 = tmpdir.mkdir("tmp01")
351
352 # Currently no files here
353 assert os.listdir(str(tmpdir1)) == []
354
355 asset = AppriseAsset(
356 storage_mode=PersistentStoreMode.MEMORY,
357 storage_path=str(tmpdir1),
358 pem_autogen=False,
359 )
360
361 # Auto-Gen is turned off, so weare not successful here
362 pem_c = utils.pem.ApprisePEMController(path=None, asset=asset)
363 assert pem_c.public_key() is None
364 assert pem_c.private_key() is None
365 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir1), asset=asset)
366 assert pem_c.public_key() is None
367 assert pem_c.private_key() is None
368
369 asset = AppriseAsset(
370 storage_mode=PersistentStoreMode.FLUSH,
371 storage_path=str(tmpdir1),
372 pem_autogen=True,
373 )
374 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir1), asset=asset)
375 # Generate ourselves a private key
376 assert pem_c.public_key() is not None
377 assert pem_c.private_key() is not None
378 pub_keyfile = os.path.join(str(tmpdir1), "public_key.pem")
379 prv_keyfile = os.path.join(str(tmpdir1), "private_key.pem")
380 assert os.path.isfile(pub_keyfile)
381 assert os.path.isfile(prv_keyfile)
382
383 with open(pub_keyfile, "w") as f:
384 f.write("garbage")
385
386 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir1), asset=asset)
387 # we can still load our data as the public key is generated
388 # from the private
389 assert pem_c.public_key() is not None
390 assert pem_c.private_key() is not None
391
392 tmpdir2 = tmpdir.mkdir("tmp02")
393 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir2), asset=asset)
394 pub_keyfile = os.path.join(str(tmpdir2), "public_key.pem")
395 prv_keyfile = os.path.join(str(tmpdir2), "private_key.pem")
396 assert not os.path.isfile(pub_keyfile)
397 assert not os.path.isfile(prv_keyfile)
398
399 #
400 # Public Key Edge Case Tests
401 #
402 with (
403 mock.patch.object(
404 pem_c, "public_keyfile", side_effect=[None, pub_keyfile]
405 ) as mock_keyfile,
406 mock.patch.object(
407 pem_c,
408 "keygen",
409 side_effect=lambda *_, **__: (
410 setattr(pem_c, "_ApprisePEMController__public_key", pubkey_ref)
411 or True
412 ),
413 ) as mock_keygen,
414 mock.patch.object(pem_c, "load_public_key", return_value=True),
415 ):
416 result = pem_c.public_key()
417 assert result is pubkey_ref
418 assert mock_keyfile.call_count == 2
419 mock_keygen.assert_called_once()
420
421 # - First call: None -> triggers keygen
422 # - Second call (recursive): None -> causes fallback
423 public_keyfile_side_effect = [None, None]
424
425 with (
426 mock.patch.object(
427 pem_c, "public_keyfile", side_effect=public_keyfile_side_effect
428 ) as mock_keyfile,
429 mock.patch.object(pem_c, "keygen", return_value=True) as mock_keygen,
430 mock.patch.object(
431 pem_c, "load_public_key", return_value=False
432 ) as mock_load,
433 ):
434 # Ensure no key is preset initially
435 pem_c._ApprisePEMController__public_key = None
436
437 result = pem_c.public_key()
438 assert result is None
439 # Once in outer call, once in recursive
440 assert mock_keyfile.call_count == 2
441 mock_keygen.assert_called_once()
442 mock_load.assert_not_called()
443
444 #
445 # Private Key Edge Case Tests
446 #
447 with (
448 mock.patch.object(
449 pem_c, "private_keyfile", side_effect=[None, prv_keyfile]
450 ) as mock_keyfile,
451 mock.patch.object(
452 pem_c,
453 "keygen",
454 side_effect=lambda *_, **__: (
455 setattr(
456 pem_c, "_ApprisePEMController__private_key", prvkey_ref
457 )
458 or True
459 ),
460 ) as mock_keygen,
461 mock.patch.object(pem_c, "load_private_key", return_value=True),
462 ):
463 result = pem_c.private_key()
464 assert result is prvkey_ref
465 assert mock_keyfile.call_count == 2
466 mock_keygen.assert_called_once()
467
468 # - First call: None -> triggers keygen
469 # - Second call (recursive): None -> causes fallback
470 private_keyfile_side_effect = [None, None]
471
472 with (
473 mock.patch.object(
474 pem_c, "private_keyfile", side_effect=private_keyfile_side_effect
475 ) as mock_keyfile,
476 mock.patch.object(pem_c, "keygen", return_value=True) as mock_keygen,
477 mock.patch.object(
478 pem_c, "load_private_key", return_value=False
479 ) as mock_load,
480 ):
481 # Ensure no key is preset initially
482 pem_c._ApprisePEMController__private_key = None
483
484 result = pem_c.private_key()
485 assert result is None
486 # Once in outer call, once in recursive
487 assert mock_keyfile.call_count == 2
488 mock_keygen.assert_called_once()
489 mock_load.assert_not_called()
490
491
492 @pytest.mark.skipif(
493 PEM_SUPPORT,
494 reason="Requires that cryptography NOT be installed",
495 )
496 def test_utils_pem_without_cryptography(tmpdir):
497 """Verify PEM operations fail cleanly without cryptography."""
498
499 tmpdir0 = tmpdir.mkdir("tmp00")
500
501 # Currently no files here
502 assert os.listdir(str(tmpdir0)) == []
503
504 asset = AppriseAsset(
505 storage_mode=PersistentStoreMode.MEMORY,
506 storage_path=str(tmpdir0),
507 pem_autogen=False,
508 )
509
510 # Create a PEM Controller
511 pem_c = utils.pem.ApprisePEMController(path=None, asset=asset)
512
513 # PEM operations require the cryptography library
514 with pytest.raises(utils.pem.ApprisePEMException):
515 pem_c.public_keyfile()
516
517 with pytest.raises(utils.pem.ApprisePEMException):
518 pem_c.public_key()
519
520 with pytest.raises(utils.pem.ApprisePEMException):
521 _ = pem_c.x962_str
522
523 with pytest.raises(utils.pem.ApprisePEMException):
524 pem_c.encrypt("message")
525
526 with pytest.raises(utils.pem.ApprisePEMException):
527 pem_c.keygen()
528
529 asset = AppriseAsset(
530 storage_mode=PersistentStoreMode.FLUSH,
531 storage_path=str(tmpdir0),
532 pem_autogen=False,
533 )
534
535 # No new files
536 assert os.listdir(str(tmpdir0)) == []
537
538 # Our asset is now write mode, so we will be able to generate a key
539 pem_c = utils.pem.ApprisePEMController(path=str(tmpdir0), asset=asset)
540 # Nothing to lookup
541 with pytest.raises(utils.pem.ApprisePEMException):
542 pem_c.private_keyfile()
543
544 with pytest.raises(utils.pem.ApprisePEMException):
545 pem_c.private_key()
546
547 with pytest.raises(utils.pem.ApprisePEMException):
548 _ = pem_c.x962_str
549
550 with pytest.raises(utils.pem.ApprisePEMException):
551 pem_c.encrypt("message")
552
553 # Keys can not be generated in memory mode
554 with pytest.raises(utils.pem.ApprisePEMException):
555 pem_c.keygen()
556
557 # No files loaded
558 assert os.listdir(str(tmpdir0)) == []
559
560 with pytest.raises(utils.pem.ApprisePEMException):
561 pem_c.public_keyfile()
562
563 with pytest.raises(utils.pem.ApprisePEMException):
564 pem_c.public_key()
565
566 with pytest.raises(utils.pem.ApprisePEMException):
567 _ = pem_c.x962_str
568
569 with pytest.raises(utils.pem.ApprisePEMException):
570 pem_c.encrypt("message")
571
572 with pytest.raises(utils.pem.ApprisePEMException):
573 pem_c.decrypt("abcd==")