Debian Codegraph @

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