| 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 base64 |
| 30 |
import logging |
| 31 |
import os |
| 32 |
import shutil |
| 33 |
import sys |
| 34 |
from unittest import mock |
| 35 |
|
| 36 |
import pytest |
| 37 |
|
| 38 |
from apprise import AppriseAsset |
| 39 |
from apprise.utils import pgp as pgp_module |
| 40 |
from apprise.utils.pgp import ApprisePGPController, _ensure_imghdr_shim |
| 41 |
|
| 42 |
logging.disable(logging.CRITICAL) |
| 43 |
|
| 44 |
# Path to the pre-generated key fixtures used by signing/autocrypt tests |
| 45 |
_VAR_DIR = os.path.join(os.path.dirname(__file__), "var", "pgp") |
| 46 |
_VALID_PRV_ASC = os.path.join(_VAR_DIR, "valid-prv.asc") |
| 47 |
_VALID_PUB_ASC = os.path.join(_VAR_DIR, "valid-pub.asc") |
| 48 |
|
| 49 |
|
| 50 |
# imghdr shim |
| 51 |
|
| 52 |
|
| 53 |
def test_imghdr_shim_when_present(): |
| 54 |
"""_ensure_imghdr_shim() leaves sys.modules intact when imghdr imports.""" |
| 55 |
|
| 56 |
# Guarantee imghdr is importable for this test |
| 57 |
real_imghdr = sys.modules.get("imghdr") |
| 58 |
try: |
| 59 |
import imghdr as _real |
| 60 |
|
| 61 |
# If we got here, imghdr is available on this Python version |
| 62 |
_ensure_imghdr_shim() |
| 63 |
|
| 64 |
# sys.modules entry must not have been replaced by our shim |
| 65 |
assert sys.modules.get("imghdr") is _real |
| 66 |
|
| 67 |
except ImportError: |
| 68 |
# Python 3.13 and newer removed imghdr. |
| 69 |
pytest.skip("imghdr not present on this Python version") |
| 70 |
|
| 71 |
finally: |
| 72 |
# Restore whatever was there before |
| 73 |
if real_imghdr is None: |
| 74 |
sys.modules.pop("imghdr", None) |
| 75 |
else: |
| 76 |
sys.modules["imghdr"] = real_imghdr |
| 77 |
|
| 78 |
|
| 79 |
def test_imghdr_shim_when_absent(): |
| 80 |
"""_ensure_imghdr_shim() installs a working shim when imghdr is missing.""" |
| 81 |
|
| 82 |
# Remove any real imghdr from sys.modules and make import fail |
| 83 |
saved = sys.modules.pop("imghdr", None) |
| 84 |
try: |
| 85 |
# Setting the key to None causes 'import imghdr' to raise ImportError |
| 86 |
sys.modules["imghdr"] = None |
| 87 |
|
| 88 |
_ensure_imghdr_shim() |
| 89 |
|
| 90 |
shim = sys.modules.get("imghdr") |
| 91 |
assert shim is not None |
| 92 |
assert callable(shim.what) |
| 93 |
|
| 94 |
# The shim must return None (safe fallback for all inputs) |
| 95 |
assert shim.what() is None |
| 96 |
assert shim.what(file=None, h=b"\xff\xd8\xff") is None |
| 97 |
assert shim.what(None, h=b"some data") is None |
| 98 |
|
| 99 |
finally: |
| 100 |
# Restore original state |
| 101 |
if saved is None: |
| 102 |
sys.modules.pop("imghdr", None) |
| 103 |
else: |
| 104 |
sys.modules["imghdr"] = saved |
| 105 |
|
| 106 |
|
| 107 |
# ApprisePGPController WKD integration |
| 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 |
# The second call must use the parsed-key cache. |
| 193 |
mock_wkd.fetch.reset_mock() |
| 194 |
result2 = ctrl._fetch_wkd_key("[email protected]") |
| 195 |
assert result2 is not None |
| 196 |
mock_wkd.fetch.assert_not_called() |
| 197 |
|
| 198 |
|
| 199 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 200 |
def test_fetch_wkd_key_expired_cache_refetches(tmpdir): |
| 201 |
"""_fetch_wkd_key() drops an expired parsed-key cache entry and |
| 202 |
re-fetches from WKD rather than returning the stale key.""" |
| 203 |
from datetime import datetime, timedelta, timezone |
| 204 |
import hashlib |
| 205 |
|
| 206 |
import pgpy |
| 207 |
|
| 208 |
# Generate a key to serve as the fresh WKD result |
| 209 |
key = pgpy.PGPKey.new( |
| 210 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 211 |
) |
| 212 |
uid = pgpy.PGPUID.new("Fresh", email="[email protected]") |
| 213 |
key.add_uid( |
| 214 |
uid, |
| 215 |
usage={ |
| 216 |
pgpy.constants.KeyFlags.Sign, |
| 217 |
pgpy.constants.KeyFlags.EncryptCommunications, |
| 218 |
}, |
| 219 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 220 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 221 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 222 |
) |
| 223 |
pub_bytes = str(key.pubkey).encode() |
| 224 |
|
| 225 |
mock_wkd = mock.Mock() |
| 226 |
mock_wkd.fetch.return_value = pub_bytes |
| 227 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 228 |
|
| 229 |
# Seed the parsed-key cache with an already-expired entry |
| 230 |
cache_key = hashlib.sha1(b"wkd:[email protected]").hexdigest() |
| 231 |
# Use the private name-mangled attribute |
| 232 |
ctrl._ApprisePGPController__key_lookup[cache_key] = { |
| 233 |
"public_key": None, |
| 234 |
"expires": datetime.now(timezone.utc) - timedelta(seconds=1), |
| 235 |
} |
| 236 |
|
| 237 |
# The expired entry is discarded; WKD is fetched and result returned |
| 238 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 239 |
assert result is not None |
| 240 |
mock_wkd.fetch.assert_called_once_with("[email protected]") |
| 241 |
|
| 242 |
|
| 243 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 244 |
def test_fetch_wkd_key_prefers_recipient_over_sender(tmpdir): |
| 245 |
"""_fetch_wkd_key() tries recipient emails before self.email so that |
| 246 |
the recipient's public key (not the sender's) is used for encryption.""" |
| 247 |
import pgpy |
| 248 |
|
| 249 |
# Generate a key to represent the recipient's WKD result |
| 250 |
key = pgpy.PGPKey.new( |
| 251 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 252 |
) |
| 253 |
uid = pgpy.PGPUID.new("Recipient", email="[email protected]") |
| 254 |
key.add_uid( |
| 255 |
uid, |
| 256 |
usage={ |
| 257 |
pgpy.constants.KeyFlags.Sign, |
| 258 |
pgpy.constants.KeyFlags.EncryptCommunications, |
| 259 |
}, |
| 260 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 261 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 262 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 263 |
) |
| 264 |
pub_bytes = str(key.pubkey).encode() |
| 265 |
|
| 266 |
# WKD returns a key only for the recipient address |
| 267 |
def fake_fetch(email): |
| 268 |
if email == "[email protected]": |
| 269 |
return pub_bytes |
| 270 |
return None |
| 271 |
|
| 272 |
mock_wkd = mock.Mock(side_effect=fake_fetch) |
| 273 |
mock_wkd.fetch.side_effect = fake_fetch |
| 274 |
ctrl = ApprisePGPController( |
| 275 |
path=str(tmpdir), |
| 276 |
email="[email protected]", |
| 277 |
wkd=mock_wkd, |
| 278 |
) |
| 279 |
|
| 280 |
# The recipient's email is passed as a positional argument |
| 281 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 282 |
assert result is not None |
| 283 |
# [email protected] must NOT have been tried before the recipient hit |
| 284 |
calls = [call.args[0] for call in mock_wkd.fetch.call_args_list] |
| 285 |
assert calls[0] == "[email protected]" |
| 286 |
assert "[email protected]" not in calls |
| 287 |
|
| 288 |
|
| 289 |
@pytest.mark.skipif( |
| 290 |
pgp_module.PGP_SUPPORT, reason="Tests behavior when pgpy is absent" |
| 291 |
) |
| 292 |
def test_fetch_wkd_key_pgpy_not_installed(tmpdir): |
| 293 |
"""_fetch_wkd_key() skips silently when pgpy raises NameError.""" |
| 294 |
mock_wkd = mock.Mock() |
| 295 |
mock_wkd.fetch.return_value = b"fake-key-bytes" |
| 296 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 297 |
# In a minimal env pgpy is not installed, so pgpy.PGPKey.from_blob |
| 298 |
# raises NameError naturally, so no mock is needed. |
| 299 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 300 |
assert result is None |
| 301 |
|
| 302 |
|
| 303 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 304 |
def test_fetch_wkd_key_corrupt_data(tmpdir): |
| 305 |
"""_fetch_wkd_key() skips and tries next candidate on parse failure.""" |
| 306 |
mock_wkd = mock.Mock() |
| 307 |
mock_wkd.fetch.return_value = b"this-is-not-a-pgp-key" |
| 308 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 309 |
|
| 310 |
# Patch the canonical pgpy module directly (not the pgp module's copy) |
| 311 |
# so the mock works whether pgpy was imported by name or attribute. |
| 312 |
with mock.patch( |
| 313 |
"pgpy.PGPKey.from_blob", |
| 314 |
side_effect=Exception("bad key"), |
| 315 |
): |
| 316 |
result = ctrl._fetch_wkd_key("[email protected]") |
| 317 |
|
| 318 |
assert result is None |
| 319 |
|
| 320 |
|
| 321 |
def test_fetch_wkd_key_uses_self_email_as_candidate(tmpdir): |
| 322 |
"""_fetch_wkd_key() includes self.email in the candidate list.""" |
| 323 |
mock_wkd = mock.Mock() |
| 324 |
mock_wkd.fetch.return_value = None |
| 325 |
ctrl = ApprisePGPController( |
| 326 |
path=str(tmpdir), email="[email protected]", wkd=mock_wkd |
| 327 |
) |
| 328 |
|
| 329 |
ctrl._fetch_wkd_key() |
| 330 |
|
| 331 |
# self.email must have been tried |
| 332 |
mock_wkd.fetch.assert_called_with("[email protected]") |
| 333 |
|
| 334 |
|
| 335 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 336 |
def test_public_key_falls_through_to_wkd(tmpdir): |
| 337 |
"""public_key() uses WKD when no local key file exists.""" |
| 338 |
import pgpy |
| 339 |
|
| 340 |
# Generate a minimal key for the mock WKD response |
| 341 |
key = pgpy.PGPKey.new( |
| 342 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 343 |
) |
| 344 |
uid = pgpy.PGPUID.new("WKD User", email="[email protected]") |
| 345 |
key.add_uid( |
| 346 |
uid, |
| 347 |
usage={ |
| 348 |
pgpy.constants.KeyFlags.Sign, |
| 349 |
pgpy.constants.KeyFlags.EncryptCommunications, |
| 350 |
}, |
| 351 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 352 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 353 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 354 |
) |
| 355 |
pub_bytes = str(key.pubkey).encode() |
| 356 |
|
| 357 |
mock_wkd = mock.Mock() |
| 358 |
mock_wkd.fetch.return_value = pub_bytes |
| 359 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 360 |
|
| 361 |
# No local key file exists, so WKD must be tried |
| 362 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 363 |
assert result is not None |
| 364 |
mock_wkd.fetch.assert_called() |
| 365 |
|
| 366 |
|
| 367 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 368 |
def test_public_key_wkd_fails_falls_through_to_autogen(tmpdir): |
| 369 |
"""public_key() falls through to autogen when WKD also returns None.""" |
| 370 |
mock_wkd = mock.Mock() |
| 371 |
mock_wkd.fetch.return_value = None |
| 372 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 373 |
# No local key file exists; WKD fails; autogen=False => None returned |
| 374 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 375 |
assert result is None |
| 376 |
mock_wkd.fetch.assert_called() |
| 377 |
|
| 378 |
|
| 379 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 380 |
def test_public_key_malformed_local_file_returns_none(tmpdir): |
| 381 |
"""public_key() returns None gracefully when the local .asc file is |
| 382 |
not valid PGP data (pgpy raises during parse).""" |
| 383 |
# Write a file with non-PGP content under a name that public_keyfile() |
| 384 |
# will discover automatically |
| 385 |
bad_key_path = tmpdir.join("pub.asc") |
| 386 |
bad_key_path.write("this is not a pgp key\n") |
| 387 |
|
| 388 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 389 |
# No autogen so the only candidate is the malformed file above |
| 390 |
result = ctrl.public_key(autogen=False) |
| 391 |
assert result is None |
| 392 |
|
| 393 |
|
| 394 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 395 |
@pytest.mark.parametrize("use_keyfile", (False, True)) |
| 396 |
def test_keygen_checks_eligibility_before_rsa(tmpdir, use_keyfile): |
| 397 |
"""Disabled key generation does not perform expensive RSA work.""" |
| 398 |
|
| 399 |
ctrl = ApprisePGPController( |
| 400 |
path=str(tmpdir) if use_keyfile else None, |
| 401 |
pub_keyfile=_VALID_PUB_ASC if use_keyfile else None, |
| 402 |
email="[email protected]", |
| 403 |
) |
| 404 |
|
| 405 |
with mock.patch.object(pgp_module.pgpy.PGPKey, "new") as mock_new: |
| 406 |
assert ctrl.keygen() is False |
| 407 |
mock_new.assert_not_called() |
| 408 |
|
| 409 |
|
| 410 |
# autocrypt_header() |
| 411 |
|
| 412 |
|
| 413 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 414 |
def test_autocrypt_header_no_sender_key(tmpdir): |
| 415 |
"""Autocrypt is omitted when no sender key is available.""" |
| 416 |
|
| 417 |
asset = AppriseAsset(pgp_autogen=False) |
| 418 |
ctrl = ApprisePGPController( |
| 419 |
path=str(tmpdir), email="[email protected]", asset=asset |
| 420 |
) |
| 421 |
assert ctrl.autocrypt_header() is None |
| 422 |
|
| 423 |
|
| 424 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 425 |
@pytest.mark.parametrize("missing_email", (None, "")) |
| 426 |
def test_autocrypt_header_none_without_email(tmpdir, missing_email): |
| 427 |
"""Autocrypt requires an address even when a sender key exists.""" |
| 428 |
|
| 429 |
ctrl = ApprisePGPController( |
| 430 |
path=str(tmpdir), |
| 431 |
prv_keyfile=_VALID_PRV_ASC, |
| 432 |
email=missing_email, |
| 433 |
) |
| 434 |
# Only the address is missing. |
| 435 |
assert ctrl.private_key() is not None |
| 436 |
assert ctrl.autocrypt_header() is None |
| 437 |
|
| 438 |
|
| 439 |
def _fingerprint_of(path): |
| 440 |
"""Loads a key fixture from disk and returns its fingerprint string.""" |
| 441 |
import pgpy |
| 442 |
|
| 443 |
with open(path) as key_file: |
| 444 |
key, _ = pgpy.PGPKey.from_blob(key_file.read()) |
| 445 |
return str(key.fingerprint) |
| 446 |
|
| 447 |
|
| 448 |
def _keydata_fingerprint(header): |
| 449 |
"""Decodes an Autocrypt header's keydata= and returns its fingerprint.""" |
| 450 |
import pgpy |
| 451 |
|
| 452 |
keydata = header.split("keydata=", 1)[1] |
| 453 |
key, _ = pgpy.PGPKey.from_blob(base64.b64decode(keydata)) |
| 454 |
return str(key.fingerprint) |
| 455 |
|
| 456 |
|
| 457 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 458 |
def test_autocrypt_header_valid_key(tmpdir): |
| 459 |
"""Autocrypt advertises the public half of a generated sender key.""" |
| 460 |
|
| 461 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 462 |
assert ctrl.keygen() is True |
| 463 |
|
| 464 |
header = ctrl.autocrypt_header() |
| 465 |
assert header is not None |
| 466 |
assert header.startswith( |
| 467 |
"[email protected]; prefer-encrypt=mutual; keydata=" |
| 468 |
) |
| 469 |
|
| 470 |
# Compare fingerprints so an unrelated but valid key cannot pass. |
| 471 |
assert _keydata_fingerprint(header) == str(ctrl.private_key().fingerprint) |
| 472 |
|
| 473 |
|
| 474 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 475 |
def test_autocrypt_header_ignores_recipient_pgppub(tmpdir): |
| 476 |
"""Autocrypt uses our signing key instead of recipient pgppub=.""" |
| 477 |
|
| 478 |
# Generate the sender key before configuring a recipient override. |
| 479 |
keygen_ctrl = ApprisePGPController( |
| 480 |
path=str(tmpdir), email="[email protected]" |
| 481 |
) |
| 482 |
assert keygen_ctrl.keygen() is True |
| 483 |
own_fingerprint = str(keygen_ctrl.private_key().fingerprint) |
| 484 |
|
| 485 |
# The fixture represents an unrelated recipient's key |
| 486 |
assert own_fingerprint != _fingerprint_of(_VALID_PUB_ASC) |
| 487 |
|
| 488 |
# The sender key remains discoverable beside the recipient override. |
| 489 |
ctrl = ApprisePGPController( |
| 490 |
path=str(tmpdir), |
| 491 |
pub_keyfile=_VALID_PUB_ASC, |
| 492 |
email="[email protected]", |
| 493 |
) |
| 494 |
header = ctrl.autocrypt_header() |
| 495 |
assert header is not None |
| 496 |
assert _keydata_fingerprint(header) == own_fingerprint |
| 497 |
|
| 498 |
|
| 499 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 500 |
def test_autocrypt_header_ignores_recipient_only_key(tmpdir): |
| 501 |
"""Autocrypt omits a recipient pgppub= when no sender key exists.""" |
| 502 |
|
| 503 |
asset = AppriseAsset(pgp_autogen=False) |
| 504 |
ctrl = ApprisePGPController( |
| 505 |
path=str(tmpdir), |
| 506 |
pub_keyfile=_VALID_PUB_ASC, |
| 507 |
email="[email protected]", |
| 508 |
asset=asset, |
| 509 |
) |
| 510 |
assert ctrl.autocrypt_header() is None |
| 511 |
|
| 512 |
|
| 513 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 514 |
@pytest.mark.parametrize( |
| 515 |
"filename", |
| 516 |
( |
| 517 |
# Sender-specific names still require a matching private key. |
| 518 |
"[email protected]", |
| 519 |
"sender-pub.asc", |
| 520 |
"pgp-public.asc", |
| 521 |
"pgp-pub.asc", |
| 522 |
"public.asc", |
| 523 |
"pub.asc", |
| 524 |
), |
| 525 |
) |
| 526 |
def test_autocrypt_header_ignores_public_only_local_files(tmpdir, filename): |
| 527 |
"""Autocrypt ignores local public keys without a matching private key.""" |
| 528 |
|
| 529 |
shutil.copy(_VALID_PUB_ASC, str(tmpdir.join(filename))) |
| 530 |
|
| 531 |
asset = AppriseAsset(pgp_autogen=False) |
| 532 |
ctrl = ApprisePGPController( |
| 533 |
path=str(tmpdir), email="[email protected]", asset=asset |
| 534 |
) |
| 535 |
assert ctrl.autocrypt_header() is None |
| 536 |
|
| 537 |
|
| 538 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 539 |
def test_autocrypt_header_autogen_generates_own_key(tmpdir): |
| 540 |
"""Autocrypt may generate and advertise a sender-owned key pair.""" |
| 541 |
|
| 542 |
asset = AppriseAsset(pgp_autogen=True) |
| 543 |
ctrl = ApprisePGPController( |
| 544 |
path=str(tmpdir), email="[email protected]", asset=asset |
| 545 |
) |
| 546 |
assert ctrl.private_key() is None |
| 547 |
|
| 548 |
header = ctrl.autocrypt_header() |
| 549 |
assert header is not None |
| 550 |
assert header.startswith("[email protected];") |
| 551 |
|
| 552 |
# A private key must now exist, and it must be the one advertised |
| 553 |
private_key = ctrl.private_key() |
| 554 |
assert private_key is not None |
| 555 |
assert _keydata_fingerprint(header) == str(private_key.fingerprint) |
| 556 |
|
| 557 |
|
| 558 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 559 |
def test_autocrypt_header_respects_autogen_disabled(tmpdir): |
| 560 |
"""Autocrypt respects disabled key generation.""" |
| 561 |
|
| 562 |
asset = AppriseAsset(pgp_autogen=False) |
| 563 |
ctrl = ApprisePGPController( |
| 564 |
path=str(tmpdir), email="[email protected]", asset=asset |
| 565 |
) |
| 566 |
assert ctrl.autocrypt_header() is None |
| 567 |
assert ctrl.private_key() is None |
| 568 |
|
| 569 |
|
| 570 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 571 |
def test_autocrypt_header_enforces_size_limit(tmpdir): |
| 572 |
"""Autocrypt rejects headers over its 10 KiB limit.""" |
| 573 |
|
| 574 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 575 |
assert ctrl.keygen() is True |
| 576 |
|
| 577 |
# Sanity: the real key comfortably fits within the real limit |
| 578 |
assert ctrl.autocrypt_header() is not None |
| 579 |
|
| 580 |
# Force the limit far below anything a real key could satisfy |
| 581 |
ctrl.max_autocrypt_header_size = 10 |
| 582 |
assert ctrl.autocrypt_header() is None |
| 583 |
|
| 584 |
|
| 585 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 586 |
def test_autocrypt_header_rejects_key_without_encryption_subkey(tmpdir): |
| 587 |
"""Autocrypt rejects a private key without an encryption subkey.""" |
| 588 |
|
| 589 |
ctrl = ApprisePGPController( |
| 590 |
path=str(tmpdir), |
| 591 |
prv_keyfile=_VALID_PRV_ASC, |
| 592 |
email="[email protected]", |
| 593 |
) |
| 594 |
private_key = ctrl.private_key() |
| 595 |
assert private_key is not None |
| 596 |
assert not ApprisePGPController._has_encryption_subkey(private_key) |
| 597 |
|
| 598 |
assert ctrl.autocrypt_header() is None |
| 599 |
|
| 600 |
|
| 601 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 602 |
def test_autocrypt_header_accepts_key_with_encryption_subkey(tmpdir): |
| 603 |
"""_has_encryption_subkey() recognizes a properly structured key.""" |
| 604 |
|
| 605 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 606 |
assert ctrl.keygen() is True |
| 607 |
|
| 608 |
private_key = ctrl.private_key() |
| 609 |
assert ApprisePGPController._has_encryption_subkey(private_key) |
| 610 |
|
| 611 |
|
| 612 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 613 |
def test_autocrypt_header_rejects_key_with_extra_userid(tmpdir): |
| 614 |
"""Autocrypt rejects an otherwise valid key with multiple UIDs.""" |
| 615 |
|
| 616 |
import pgpy |
| 617 |
from pgpy.constants import ( |
| 618 |
CompressionAlgorithm, |
| 619 |
HashAlgorithm, |
| 620 |
KeyFlags, |
| 621 |
PubKeyAlgorithm, |
| 622 |
SymmetricKeyAlgorithm, |
| 623 |
) |
| 624 |
|
| 625 |
primary = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 626 |
for name, email in ( |
| 627 |
("Test", "[email protected]"), |
| 628 |
("Test (work)", "[email protected]"), |
| 629 |
): |
| 630 |
primary.add_uid( |
| 631 |
pgpy.PGPUID.new(name, email=email), |
| 632 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 633 |
hashes=[HashAlgorithm.SHA256], |
| 634 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 635 |
compression=[CompressionAlgorithm.ZLIB], |
| 636 |
) |
| 637 |
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 638 |
primary.add_subkey( |
| 639 |
subkey, |
| 640 |
usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, |
| 641 |
) |
| 642 |
|
| 643 |
prv_path = str(tmpdir.join("multi-uid-prv.asc")) |
| 644 |
with open(prv_path, "w") as f: |
| 645 |
f.write(str(primary)) |
| 646 |
|
| 647 |
ctrl = ApprisePGPController( |
| 648 |
path=str(tmpdir), prv_keyfile=prv_path, email="[email protected]" |
| 649 |
) |
| 650 |
private_key = ctrl.private_key() |
| 651 |
assert private_key is not None |
| 652 |
assert not ApprisePGPController._has_encryption_subkey(private_key) |
| 653 |
assert ctrl.autocrypt_header() is None |
| 654 |
|
| 655 |
|
| 656 |
def _mock_uid_with_one_selfsig(): |
| 657 |
"""A mock UID with exactly the one self-signature a compliant key |
| 658 |
is expected to have, so tests can focus on the subkey side.""" |
| 659 |
uid = mock.Mock() |
| 660 |
selfsig = mock.Mock() |
| 661 |
uid.selfsig = selfsig |
| 662 |
uid._signatures = [selfsig] |
| 663 |
return uid |
| 664 |
|
| 665 |
|
| 666 |
def test_has_encryption_subkey_skips_subkey_without_selfsig(): |
| 667 |
"""A lone subkey with no self-signature at all is not usable.""" |
| 668 |
|
| 669 |
no_selfsig_subkey = mock.Mock() |
| 670 |
no_selfsig_subkey.revocation_signatures = [] |
| 671 |
no_selfsig_subkey.self_signatures = iter(()) |
| 672 |
|
| 673 |
key = mock.Mock() |
| 674 |
key.userattributes = [] |
| 675 |
key.revocation_signatures = [] |
| 676 |
key.userids = [_mock_uid_with_one_selfsig()] |
| 677 |
key.subkeys = {"a": no_selfsig_subkey} |
| 678 |
|
| 679 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 680 |
|
| 681 |
|
| 682 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 683 |
def test_has_encryption_subkey_skips_subkey_with_wrong_flags(): |
| 684 |
"""A signed subkey without encryption usage is not usable.""" |
| 685 |
|
| 686 |
wrong_flags_subkey = mock.Mock() |
| 687 |
wrong_flags_subkey.revocation_signatures = [] |
| 688 |
wrong_flags_subkey.self_signatures = iter( |
| 689 |
[mock.Mock(key_flags={pgp_module.pgpy.constants.KeyFlags.Sign})] |
| 690 |
) |
| 691 |
|
| 692 |
key = mock.Mock() |
| 693 |
key.userattributes = [] |
| 694 |
key.revocation_signatures = [] |
| 695 |
key.userids = [_mock_uid_with_one_selfsig()] |
| 696 |
key.subkeys = {"a": wrong_flags_subkey} |
| 697 |
|
| 698 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 699 |
|
| 700 |
|
| 701 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 702 |
def test_has_encryption_subkey_rejects_multiple_userids(): |
| 703 |
"""Autocrypt rejects keys with multiple identities.""" |
| 704 |
|
| 705 |
good_subkey = mock.Mock() |
| 706 |
good_subkey.self_signatures = iter( |
| 707 |
[ |
| 708 |
mock.Mock( |
| 709 |
key_flags={ |
| 710 |
pgp_module.pgpy.constants.KeyFlags.EncryptCommunications |
| 711 |
} |
| 712 |
) |
| 713 |
] |
| 714 |
) |
| 715 |
|
| 716 |
key = mock.Mock() |
| 717 |
key.userattributes = [] |
| 718 |
key.revocation_signatures = [] |
| 719 |
key.userids = ["[email protected]", "[email protected]"] |
| 720 |
key.subkeys = {"a": good_subkey} |
| 721 |
|
| 722 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 723 |
|
| 724 |
|
| 725 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 726 |
def test_has_encryption_subkey_rejects_multiple_subkeys(): |
| 727 |
"""Autocrypt Level 1 requires exactly one subkey.""" |
| 728 |
|
| 729 |
def make_subkey(): |
| 730 |
subkey = mock.Mock() |
| 731 |
subkey.self_signatures = iter( |
| 732 |
[ |
| 733 |
mock.Mock( |
| 734 |
key_flags={ |
| 735 |
pgp_module.pgpy.constants.KeyFlags.EncryptCommunications |
| 736 |
} |
| 737 |
) |
| 738 |
] |
| 739 |
) |
| 740 |
return subkey |
| 741 |
|
| 742 |
key = mock.Mock() |
| 743 |
key.userattributes = [] |
| 744 |
key.revocation_signatures = [] |
| 745 |
key.userids = ["[email protected]"] |
| 746 |
key.subkeys = {"a": make_subkey(), "b": make_subkey()} |
| 747 |
|
| 748 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 749 |
|
| 750 |
|
| 751 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 752 |
def test_has_encryption_subkey_rejects_extra_uid_selfsig(): |
| 753 |
"""Autocrypt rejects a UID with an extra self-signature.""" |
| 754 |
|
| 755 |
uid = mock.Mock() |
| 756 |
uid._signatures = [mock.Mock(), mock.Mock()] |
| 757 |
|
| 758 |
subkey = mock.Mock() |
| 759 |
subkey.self_signatures = iter( |
| 760 |
[ |
| 761 |
mock.Mock( |
| 762 |
key_flags={ |
| 763 |
pgp_module.pgpy.constants.KeyFlags.EncryptCommunications |
| 764 |
} |
| 765 |
) |
| 766 |
] |
| 767 |
) |
| 768 |
|
| 769 |
key = mock.Mock() |
| 770 |
key.userattributes = [] |
| 771 |
key.revocation_signatures = [] |
| 772 |
key.userids = [uid] |
| 773 |
key.subkeys = {"a": subkey} |
| 774 |
|
| 775 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 776 |
|
| 777 |
|
| 778 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 779 |
def test_has_encryption_subkey_rejects_extra_subkey_binding_sig(): |
| 780 |
"""Autocrypt rejects a subkey with an extra binding signature.""" |
| 781 |
|
| 782 |
uid = mock.Mock() |
| 783 |
uid._signatures = [mock.Mock()] |
| 784 |
|
| 785 |
subkey = mock.Mock() |
| 786 |
subkey.revocation_signatures = [] |
| 787 |
subkey.self_signatures = iter( |
| 788 |
[ |
| 789 |
mock.Mock( |
| 790 |
key_flags={ |
| 791 |
pgp_module.pgpy.constants.KeyFlags.EncryptCommunications |
| 792 |
} |
| 793 |
), |
| 794 |
mock.Mock( |
| 795 |
key_flags={ |
| 796 |
pgp_module.pgpy.constants.KeyFlags.EncryptCommunications |
| 797 |
} |
| 798 |
), |
| 799 |
] |
| 800 |
) |
| 801 |
|
| 802 |
key = mock.Mock() |
| 803 |
key.userattributes = [] |
| 804 |
key.revocation_signatures = [] |
| 805 |
key.userids = [uid] |
| 806 |
key.subkeys = {"a": subkey} |
| 807 |
|
| 808 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 809 |
|
| 810 |
|
| 811 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 812 |
def test_has_encryption_subkey_rejects_uid_without_selfsig(): |
| 813 |
"""Reject a UID whose only signature is from a third party.""" |
| 814 |
|
| 815 |
uid = mock.Mock() |
| 816 |
uid.selfsig = None |
| 817 |
uid._signatures = [mock.Mock()] |
| 818 |
|
| 819 |
subkey = mock.Mock() |
| 820 |
subkey.self_signatures = iter( |
| 821 |
[ |
| 822 |
mock.Mock( |
| 823 |
key_flags={ |
| 824 |
pgp_module.pgpy.constants.KeyFlags.EncryptCommunications |
| 825 |
} |
| 826 |
) |
| 827 |
] |
| 828 |
) |
| 829 |
|
| 830 |
key = mock.Mock() |
| 831 |
key.userattributes = [] |
| 832 |
key.revocation_signatures = [] |
| 833 |
key.userids = [uid] |
| 834 |
key.subkeys = {"a": subkey} |
| 835 |
|
| 836 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 837 |
|
| 838 |
|
| 839 |
def test_has_encryption_subkey_rejects_missing_signature_list(): |
| 840 |
"""Reject the key if PGPy's private signature collection is absent.""" |
| 841 |
|
| 842 |
uid = mock.Mock(spec=["selfsig"]) |
| 843 |
uid.selfsig = mock.Mock() |
| 844 |
|
| 845 |
key = mock.Mock() |
| 846 |
key.userattributes = [] |
| 847 |
key.revocation_signatures = [] |
| 848 |
key.userids = [uid] |
| 849 |
key.subkeys = {"a": mock.Mock()} |
| 850 |
|
| 851 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 852 |
|
| 853 |
|
| 854 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 855 |
def test_autocrypt_header_rejects_third_party_only_uid(tmpdir): |
| 856 |
"""Reject a serialized key with only a third-party UID signature.""" |
| 857 |
|
| 858 |
import pgpy |
| 859 |
from pgpy.constants import ( |
| 860 |
CompressionAlgorithm, |
| 861 |
HashAlgorithm, |
| 862 |
KeyFlags, |
| 863 |
PubKeyAlgorithm, |
| 864 |
SymmetricKeyAlgorithm, |
| 865 |
) |
| 866 |
|
| 867 |
victim = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 868 |
uid = pgpy.PGPUID.new("Victim", email="[email protected]") |
| 869 |
victim.add_uid( |
| 870 |
uid, |
| 871 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 872 |
hashes=[HashAlgorithm.SHA256], |
| 873 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 874 |
compression=[CompressionAlgorithm.ZLIB], |
| 875 |
) |
| 876 |
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 877 |
victim.add_subkey( |
| 878 |
subkey, |
| 879 |
usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, |
| 880 |
) |
| 881 |
|
| 882 |
# A third party certifies the UID instead of the primary itself |
| 883 |
thirdparty = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 884 |
tp_uid = pgpy.PGPUID.new("ThirdParty", email="[email protected]") |
| 885 |
thirdparty.add_uid( |
| 886 |
tp_uid, |
| 887 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 888 |
hashes=[HashAlgorithm.SHA256], |
| 889 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 890 |
compression=[CompressionAlgorithm.ZLIB], |
| 891 |
) |
| 892 |
cert_sig = thirdparty.certify(uid) |
| 893 |
|
| 894 |
# Replace the genuine self-signature with the third-party one, so |
| 895 |
# the UID's only signature is not from its own primary key |
| 896 |
uid._signatures.clear() |
| 897 |
uid._signatures.append(cert_sig) |
| 898 |
|
| 899 |
prv_path = str(tmpdir.join("thirdparty-only-prv.asc")) |
| 900 |
with open(prv_path, "w") as f: |
| 901 |
f.write(str(victim)) |
| 902 |
|
| 903 |
ctrl = ApprisePGPController( |
| 904 |
path=str(tmpdir), prv_keyfile=prv_path, email="[email protected]" |
| 905 |
) |
| 906 |
private_key = ctrl.private_key() |
| 907 |
assert private_key is not None |
| 908 |
assert private_key.userids[0].selfsig is None |
| 909 |
assert not ApprisePGPController._has_encryption_subkey(private_key) |
| 910 |
assert ctrl.autocrypt_header() is None |
| 911 |
|
| 912 |
|
| 913 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 914 |
def test_autocrypt_header_rejects_key_with_extra_uid_signature(tmpdir): |
| 915 |
"""Autocrypt rejects an extra UID signature after serialization.""" |
| 916 |
|
| 917 |
import pgpy |
| 918 |
from pgpy.constants import ( |
| 919 |
CompressionAlgorithm, |
| 920 |
HashAlgorithm, |
| 921 |
KeyFlags, |
| 922 |
PubKeyAlgorithm, |
| 923 |
SymmetricKeyAlgorithm, |
| 924 |
) |
| 925 |
|
| 926 |
primary = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 927 |
uid = pgpy.PGPUID.new("Test", email="[email protected]") |
| 928 |
primary.add_uid( |
| 929 |
uid, |
| 930 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 931 |
hashes=[HashAlgorithm.SHA256], |
| 932 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 933 |
compression=[CompressionAlgorithm.ZLIB], |
| 934 |
) |
| 935 |
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 936 |
primary.add_subkey( |
| 937 |
subkey, |
| 938 |
usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, |
| 939 |
) |
| 940 |
|
| 941 |
# Add another genuine self-certification to the same UID. |
| 942 |
extra_sig = primary.certify(uid, expires=None) |
| 943 |
uid._signatures.insert(0, extra_sig) |
| 944 |
|
| 945 |
prv_path = str(tmpdir.join("extra-sig-prv.asc")) |
| 946 |
with open(prv_path, "w") as f: |
| 947 |
f.write(str(primary)) |
| 948 |
|
| 949 |
ctrl = ApprisePGPController( |
| 950 |
path=str(tmpdir), prv_keyfile=prv_path, email="[email protected]" |
| 951 |
) |
| 952 |
private_key = ctrl.private_key() |
| 953 |
assert private_key is not None |
| 954 |
assert len(private_key.userids[0]._signatures) == 2 |
| 955 |
assert not ApprisePGPController._has_encryption_subkey(private_key) |
| 956 |
assert ctrl.autocrypt_header() is None |
| 957 |
|
| 958 |
|
| 959 |
def test_has_encryption_subkey_rejects_user_attribute(): |
| 960 |
"""Reject user attributes because they add packets to the key.""" |
| 961 |
|
| 962 |
key = mock.Mock() |
| 963 |
key.userattributes = [mock.Mock()] |
| 964 |
|
| 965 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 966 |
|
| 967 |
|
| 968 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 969 |
def test_autocrypt_header_rejects_photo_attribute(tmpdir): |
| 970 |
"""Reject a serialized key containing a photo attribute.""" |
| 971 |
|
| 972 |
import pgpy |
| 973 |
from pgpy.constants import ( |
| 974 |
CompressionAlgorithm, |
| 975 |
HashAlgorithm, |
| 976 |
KeyFlags, |
| 977 |
PubKeyAlgorithm, |
| 978 |
SymmetricKeyAlgorithm, |
| 979 |
) |
| 980 |
|
| 981 |
primary = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 982 |
uid = pgpy.PGPUID.new("Test", email="[email protected]") |
| 983 |
primary.add_uid( |
| 984 |
uid, |
| 985 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 986 |
hashes=[HashAlgorithm.SHA256], |
| 987 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 988 |
compression=[CompressionAlgorithm.ZLIB], |
| 989 |
) |
| 990 |
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 991 |
primary.add_subkey( |
| 992 |
subkey, |
| 993 |
usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, |
| 994 |
) |
| 995 |
|
| 996 |
# A minimal (fake, but structurally-tagged) JPEG photo attribute |
| 997 |
photo_bytes = bytearray(b"\xff\xd8\xff\xe0" + b"\x00" * 100 + b"\xff\xd9") |
| 998 |
photo_uid = pgpy.PGPUID.new(photo_bytes) |
| 999 |
primary.add_uid(photo_uid) |
| 1000 |
|
| 1001 |
prv_path = str(tmpdir.join("photo-prv.asc")) |
| 1002 |
with open(prv_path, "w") as f: |
| 1003 |
f.write(str(primary)) |
| 1004 |
|
| 1005 |
ctrl = ApprisePGPController( |
| 1006 |
path=str(tmpdir), prv_keyfile=prv_path, email="[email protected]" |
| 1007 |
) |
| 1008 |
private_key = ctrl.private_key() |
| 1009 |
assert private_key is not None |
| 1010 |
assert len(private_key.userattributes) == 1 |
| 1011 |
assert not ApprisePGPController._has_encryption_subkey(private_key) |
| 1012 |
assert ctrl.autocrypt_header() is None |
| 1013 |
|
| 1014 |
|
| 1015 |
def test_has_encryption_subkey_rejects_revoked_primary_key(): |
| 1016 |
"""Reject a revoked primary key despite its valid UID and subkey.""" |
| 1017 |
|
| 1018 |
key = mock.Mock() |
| 1019 |
key.userattributes = [] |
| 1020 |
key.revocation_signatures = [mock.Mock()] |
| 1021 |
|
| 1022 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 1023 |
|
| 1024 |
|
| 1025 |
def test_has_encryption_subkey_rejects_revoked_subkey(): |
| 1026 |
"""Reject an encryption subkey carrying a revocation signature.""" |
| 1027 |
|
| 1028 |
subkey = mock.Mock() |
| 1029 |
subkey.revocation_signatures = [mock.Mock()] |
| 1030 |
|
| 1031 |
key = mock.Mock() |
| 1032 |
key.userattributes = [] |
| 1033 |
key.revocation_signatures = [] |
| 1034 |
key.userids = [_mock_uid_with_one_selfsig()] |
| 1035 |
key.subkeys = {"a": subkey} |
| 1036 |
|
| 1037 |
assert ApprisePGPController._has_encryption_subkey(key) is False |
| 1038 |
|
| 1039 |
|
| 1040 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 1041 |
def test_autocrypt_header_rejects_revoked_primary_key(tmpdir): |
| 1042 |
"""Reject a serialized key with a revoked primary key.""" |
| 1043 |
|
| 1044 |
import pgpy |
| 1045 |
from pgpy.constants import ( |
| 1046 |
CompressionAlgorithm, |
| 1047 |
HashAlgorithm, |
| 1048 |
KeyFlags, |
| 1049 |
PubKeyAlgorithm, |
| 1050 |
SymmetricKeyAlgorithm, |
| 1051 |
) |
| 1052 |
|
| 1053 |
primary = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 1054 |
uid = pgpy.PGPUID.new("Test", email="[email protected]") |
| 1055 |
primary.add_uid( |
| 1056 |
uid, |
| 1057 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 1058 |
hashes=[HashAlgorithm.SHA256], |
| 1059 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 1060 |
compression=[CompressionAlgorithm.ZLIB], |
| 1061 |
) |
| 1062 |
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 1063 |
primary.add_subkey( |
| 1064 |
subkey, |
| 1065 |
usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, |
| 1066 |
) |
| 1067 |
|
| 1068 |
# Revoke the primary key itself |
| 1069 |
revoke_sig = primary.revoke(primary) |
| 1070 |
primary |= revoke_sig |
| 1071 |
|
| 1072 |
prv_path = str(tmpdir.join("revoked-primary-prv.asc")) |
| 1073 |
with open(prv_path, "w") as f: |
| 1074 |
f.write(str(primary)) |
| 1075 |
|
| 1076 |
ctrl = ApprisePGPController( |
| 1077 |
path=str(tmpdir), prv_keyfile=prv_path, email="[email protected]" |
| 1078 |
) |
| 1079 |
private_key = ctrl.private_key() |
| 1080 |
assert private_key is not None |
| 1081 |
assert len(list(private_key.revocation_signatures)) == 1 |
| 1082 |
assert not ApprisePGPController._has_encryption_subkey(private_key) |
| 1083 |
assert ctrl.autocrypt_header() is None |
| 1084 |
|
| 1085 |
|
| 1086 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 1087 |
def test_autocrypt_header_rejects_revoked_subkey(tmpdir): |
| 1088 |
"""Reject a serialized key with a revoked encryption subkey.""" |
| 1089 |
|
| 1090 |
import pgpy |
| 1091 |
from pgpy.constants import ( |
| 1092 |
CompressionAlgorithm, |
| 1093 |
HashAlgorithm, |
| 1094 |
KeyFlags, |
| 1095 |
PubKeyAlgorithm, |
| 1096 |
SymmetricKeyAlgorithm, |
| 1097 |
) |
| 1098 |
|
| 1099 |
primary = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 1100 |
uid = pgpy.PGPUID.new("Test", email="[email protected]") |
| 1101 |
primary.add_uid( |
| 1102 |
uid, |
| 1103 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 1104 |
hashes=[HashAlgorithm.SHA256], |
| 1105 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 1106 |
compression=[CompressionAlgorithm.ZLIB], |
| 1107 |
) |
| 1108 |
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 1109 |
primary.add_subkey( |
| 1110 |
subkey, |
| 1111 |
usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, |
| 1112 |
) |
| 1113 |
|
| 1114 |
# Revoke only the subkey, not the primary |
| 1115 |
revoke_sig = primary.revoke(subkey) |
| 1116 |
subkey |= revoke_sig |
| 1117 |
|
| 1118 |
prv_path = str(tmpdir.join("revoked-subkey-prv.asc")) |
| 1119 |
with open(prv_path, "w") as f: |
| 1120 |
f.write(str(primary)) |
| 1121 |
|
| 1122 |
ctrl = ApprisePGPController( |
| 1123 |
path=str(tmpdir), prv_keyfile=prv_path, email="[email protected]" |
| 1124 |
) |
| 1125 |
private_key = ctrl.private_key() |
| 1126 |
assert private_key is not None |
| 1127 |
assert not list(private_key.revocation_signatures) # primary is fine |
| 1128 |
reparsed_subkey = next(iter(private_key.subkeys.values())) |
| 1129 |
assert len(list(reparsed_subkey.revocation_signatures)) == 1 |
| 1130 |
assert not ApprisePGPController._has_encryption_subkey(private_key) |
| 1131 |
assert ctrl.autocrypt_header() is None |
| 1132 |
|
| 1133 |
|
| 1134 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 1135 |
def test_autocrypt_header_preserves_exported_fingerprint(tmpdir): |
| 1136 |
"""The advertised key retains the exported key's fingerprint.""" |
| 1137 |
|
| 1138 |
import pgpy |
| 1139 |
|
| 1140 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1141 |
assert ctrl.keygen() is True |
| 1142 |
|
| 1143 |
private_key = ctrl.private_key() |
| 1144 |
exported = bytes(private_key.pubkey) |
| 1145 |
reparsed, _ = pgpy.PGPKey.from_blob(exported) |
| 1146 |
|
| 1147 |
header = ctrl.autocrypt_header() |
| 1148 |
assert header is not None |
| 1149 |
|
| 1150 |
# The advertised key must retain the exported primary-key identity. |
| 1151 |
assert _keydata_fingerprint(header) == str(reparsed.fingerprint) |
| 1152 |
|
| 1153 |
|
| 1154 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 1155 |
def test_autocrypt_header_accepts_nonexportable_signature(tmpdir): |
| 1156 |
"""Validate the exported form of a key. |
| 1157 |
|
| 1158 |
PGPy drops the extra non-exportable signature, leaving one valid UID |
| 1159 |
signature in the advertised key. |
| 1160 |
""" |
| 1161 |
|
| 1162 |
import pgpy |
| 1163 |
from pgpy.constants import ( |
| 1164 |
CompressionAlgorithm, |
| 1165 |
HashAlgorithm, |
| 1166 |
KeyFlags, |
| 1167 |
PubKeyAlgorithm, |
| 1168 |
SymmetricKeyAlgorithm, |
| 1169 |
) |
| 1170 |
|
| 1171 |
primary = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 1172 |
uid = pgpy.PGPUID.new("Test", email="[email protected]") |
| 1173 |
primary.add_uid( |
| 1174 |
uid, |
| 1175 |
usage={KeyFlags.Sign, KeyFlags.Certify}, |
| 1176 |
hashes=[HashAlgorithm.SHA256], |
| 1177 |
ciphers=[SymmetricKeyAlgorithm.AES256], |
| 1178 |
compression=[CompressionAlgorithm.ZLIB], |
| 1179 |
) |
| 1180 |
subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048) |
| 1181 |
primary.add_subkey( |
| 1182 |
subkey, |
| 1183 |
usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage}, |
| 1184 |
) |
| 1185 |
|
| 1186 |
# A second, non-exportable certification over the same UID |
| 1187 |
extra_sig = primary.certify(uid, exportable=False) |
| 1188 |
uid._signatures.insert(0, extra_sig) |
| 1189 |
|
| 1190 |
# The live in-memory object has two signatures and fails validation |
| 1191 |
assert len(uid._signatures) == 2 |
| 1192 |
assert not ApprisePGPController._has_encryption_subkey(primary) |
| 1193 |
|
| 1194 |
# PGPy omits the extra signature from the exported key. |
| 1195 |
exported = bytes(primary.pubkey) |
| 1196 |
reparsed, _ = pgpy.PGPKey.from_blob(exported) |
| 1197 |
assert len(reparsed.userids[0]._signatures) == 1 |
| 1198 |
assert ApprisePGPController._has_encryption_subkey(reparsed) |
| 1199 |
|
| 1200 |
prv_path = str(tmpdir.join("nonexportable-extra-prv.asc")) |
| 1201 |
with open(prv_path, "w") as f: |
| 1202 |
f.write(str(primary)) |
| 1203 |
|
| 1204 |
ctrl = ApprisePGPController( |
| 1205 |
path=str(tmpdir), prv_keyfile=prv_path, email="[email protected]" |
| 1206 |
) |
| 1207 |
# The header validates the exported key rather than the live object. |
| 1208 |
header = ctrl.autocrypt_header() |
| 1209 |
assert header is not None |
| 1210 |
assert _keydata_fingerprint(header) == str(reparsed.fingerprint) |
| 1211 |
|
| 1212 |
|
| 1213 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 1214 |
def test_autocrypt_header_handles_reparse_failure(tmpdir): |
| 1215 |
"""Omit the header when the exported key cannot be parsed.""" |
| 1216 |
|
| 1217 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1218 |
assert ctrl.keygen() is True |
| 1219 |
|
| 1220 |
# Warm the cache so the mock affects only the exported-key reparse. |
| 1221 |
assert ctrl.private_key() is not None |
| 1222 |
|
| 1223 |
with mock.patch.object( |
| 1224 |
pgp_module.pgpy.PGPKey, |
| 1225 |
"from_blob", |
| 1226 |
side_effect=ValueError("corrupt export"), |
| 1227 |
): |
| 1228 |
assert ctrl.autocrypt_header() is None |
| 1229 |
|
| 1230 |
|
| 1231 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 1232 |
def test_autocrypt_header_folds_long_keydata(tmpdir): |
| 1233 |
"""Folded keydata stays within line limits and remains decodable.""" |
| 1234 |
|
| 1235 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1236 |
assert ctrl.keygen() is True |
| 1237 |
|
| 1238 |
header = ctrl.autocrypt_header() |
| 1239 |
assert header is not None |
| 1240 |
|
| 1241 |
# Keep every physical header line within RFC 5322's hard limit. |
| 1242 |
rendered = f"Autocrypt: {header}" |
| 1243 |
for line in rendered.split("\r\n"): |
| 1244 |
assert len(line) <= 998 |
| 1245 |
|
| 1246 |
# Folding must have actually happened for a real 2048-bit RSA key |
| 1247 |
assert "\r\n " in header |
| 1248 |
|
| 1249 |
# addr= and prefer-encrypt= must stay intact and unfolded |
| 1250 |
assert header.startswith( |
| 1251 |
"[email protected]; prefer-encrypt=mutual; keydata=" |
| 1252 |
) |
| 1253 |
|
| 1254 |
# Folding must not alter the advertised key. |
| 1255 |
assert _keydata_fingerprint(header) == str(ctrl.private_key().fingerprint) |
| 1256 |
|
| 1257 |
|
| 1258 |
# prune() WKD delegation |
| 1259 |
|
| 1260 |
|
| 1261 |
def test_prune_delegates_to_wkd(tmpdir): |
| 1262 |
"""prune() calls prune() on the WKD controller when one is set.""" |
| 1263 |
mock_wkd = mock.Mock() |
| 1264 |
ctrl = ApprisePGPController(path=str(tmpdir), wkd=mock_wkd) |
| 1265 |
ctrl.prune() |
| 1266 |
mock_wkd.prune.assert_called_once() |
| 1267 |
|
| 1268 |
|
| 1269 |
def test_prune_without_wkd(tmpdir): |
| 1270 |
"""prune() runs without error when no WKD controller is set.""" |
| 1271 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1272 |
ctrl.prune() # must not raise |
| 1273 |
|
| 1274 |
|
| 1275 |
# PGP_SUPPORT consistency |
| 1276 |
|
| 1277 |
|
| 1278 |
def test_pgp_support_flag_present(): |
| 1279 |
"""PGP_SUPPORT is a boolean exported from the pgp module.""" |
| 1280 |
assert isinstance(pgp_module.PGP_SUPPORT, bool) |
| 1281 |
|
| 1282 |
|
| 1283 |
# private_keyfile() path resolution |
| 1284 |
|
| 1285 |
|
| 1286 |
def test_private_keyfile_no_path(): |
| 1287 |
"""private_keyfile() returns None when neither path nor prv_keyfile set.""" |
| 1288 |
ctrl = ApprisePGPController(path=None) |
| 1289 |
assert ctrl.private_keyfile() is None |
| 1290 |
|
| 1291 |
|
| 1292 |
def test_private_keyfile_explicit_valid(tmpdir): |
| 1293 |
"""private_keyfile() returns a path for a valid explicit prv_keyfile.""" |
| 1294 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1295 |
result = ctrl.private_keyfile() |
| 1296 |
# Should be an existing file path |
| 1297 |
assert result and os.path.isfile(result) |
| 1298 |
|
| 1299 |
|
| 1300 |
def test_private_keyfile_explicit_invalid(tmpdir): |
| 1301 |
"""private_keyfile() returns False when an explicit file is unreachable.""" |
| 1302 |
ctrl = ApprisePGPController( |
| 1303 |
path=str(tmpdir), |
| 1304 |
prv_keyfile="/nonexistent/path/key.asc", |
| 1305 |
) |
| 1306 |
# The attachment itself is invalid, so the property returns False |
| 1307 |
result = ctrl.private_keyfile() |
| 1308 |
assert result is False |
| 1309 |
|
| 1310 |
|
| 1311 |
def test_private_keyfile_auto_discover_by_email(tmpdir): |
| 1312 |
"""private_keyfile() finds an auto-generated key named by email prefix.""" |
| 1313 |
# Place a fake private key named after the email prefix |
| 1314 |
key_path = str(tmpdir.join("user-prv.asc")) |
| 1315 |
with open(key_path, "w") as f: |
| 1316 |
f.write("dummy") |
| 1317 |
|
| 1318 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1319 |
result = ctrl.private_keyfile() |
| 1320 |
assert result == key_path |
| 1321 |
|
| 1322 |
|
| 1323 |
def test_private_keyfile_fallback_generic_name(tmpdir): |
| 1324 |
"""private_keyfile() falls back to pgp-prv.asc when no email-named key.""" |
| 1325 |
key_path = str(tmpdir.join("pgp-prv.asc")) |
| 1326 |
with open(key_path, "w") as f: |
| 1327 |
f.write("dummy") |
| 1328 |
|
| 1329 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1330 |
result = ctrl.private_keyfile() |
| 1331 |
assert result == key_path |
| 1332 |
|
| 1333 |
|
| 1334 |
def test_private_keyfile_not_found(tmpdir): |
| 1335 |
"""private_keyfile() returns None when no private key exists on disk.""" |
| 1336 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1337 |
assert ctrl.private_keyfile() is None |
| 1338 |
|
| 1339 |
|
| 1340 |
def test_prv_keyfile_property_none_when_not_set(tmpdir): |
| 1341 |
"""prv_keyfile property returns None when no explicit key was provided.""" |
| 1342 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1343 |
assert ctrl.prv_keyfile is None |
| 1344 |
|
| 1345 |
|
| 1346 |
def test_prv_keyfile_property_path_when_valid(tmpdir): |
| 1347 |
"""prv_keyfile property returns the resolved path for a valid key.""" |
| 1348 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1349 |
# Property accesses the attachment; it may return None before loading |
| 1350 |
# because the attachment is resolved lazily. It must not be False. |
| 1351 |
assert ctrl.prv_keyfile is not False |
| 1352 |
|
| 1353 |
|
| 1354 |
def test_prv_keyfile_property_false_when_invalid(tmpdir): |
| 1355 |
"""prv_keyfile property returns False for an unreachable explicit file.""" |
| 1356 |
ctrl = ApprisePGPController( |
| 1357 |
path=str(tmpdir), |
| 1358 |
prv_keyfile="/no/such/file.asc", |
| 1359 |
) |
| 1360 |
assert ctrl.prv_keyfile is False |
| 1361 |
|
| 1362 |
|
| 1363 |
# Loading private PGP keys |
| 1364 |
|
| 1365 |
|
| 1366 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 1367 |
def test_private_key_loads_valid_fixture(tmpdir): |
| 1368 |
"""private_key() returns a PGPKey object from a valid private key file.""" |
| 1369 |
import pgpy |
| 1370 |
|
| 1371 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1372 |
key = ctrl.private_key() |
| 1373 |
assert key is not None |
| 1374 |
assert isinstance(key, pgpy.PGPKey) |
| 1375 |
|
| 1376 |
|
| 1377 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 1378 |
def test_private_key_cached_on_second_call(tmpdir): |
| 1379 |
"""private_key() returns the same object on repeated calls (cached).""" |
| 1380 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1381 |
first = ctrl.private_key() |
| 1382 |
second = ctrl.private_key() |
| 1383 |
assert first is not None |
| 1384 |
assert first is second |
| 1385 |
|
| 1386 |
|
| 1387 |
def test_private_key_returns_none_when_not_found(tmpdir): |
| 1388 |
"""private_key() returns None when no private key file exists.""" |
| 1389 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1390 |
assert ctrl.private_key() is None |
| 1391 |
|
| 1392 |
|
| 1393 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 1394 |
def test_private_key_expired_cache_reloads(tmpdir): |
| 1395 |
"""private_key() drops an expired cache entry and reloads from disk.""" |
| 1396 |
from datetime import datetime, timedelta, timezone |
| 1397 |
import hashlib |
| 1398 |
|
| 1399 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1400 |
|
| 1401 |
# Load the key once to prime the cache |
| 1402 |
first = ctrl.private_key() |
| 1403 |
assert first is not None |
| 1404 |
|
| 1405 |
# Artificially expire the cached entry by back-dating its expiry time |
| 1406 |
cache_key = hashlib.sha1( |
| 1407 |
("prv:" + os.path.abspath(_VALID_PRV_ASC)).encode("utf-8") |
| 1408 |
).hexdigest() |
| 1409 |
ctrl._ApprisePGPController__key_lookup[cache_key]["expires"] = ( |
| 1410 |
datetime.now(timezone.utc) - timedelta(seconds=1) |
| 1411 |
) |
| 1412 |
|
| 1413 |
# Second call must detect the expiry and re-load from disk |
| 1414 |
second = ctrl.private_key() |
| 1415 |
assert second is not None |
| 1416 |
|
| 1417 |
|
| 1418 |
def test_private_key_returns_none_when_pgpy_missing(tmpdir): |
| 1419 |
"""private_key() returns None gracefully when PGPy is not installed.""" |
| 1420 |
import contextlib |
| 1421 |
|
| 1422 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1423 |
with contextlib.ExitStack() as stack: |
| 1424 |
# Force PGP_SUPPORT=True so the key-loading branch is reached |
| 1425 |
stack.enter_context(mock.patch.object(pgp_module, "PGP_SUPPORT", True)) |
| 1426 |
# Supply any readable content for the open() call |
| 1427 |
stack.enter_context( |
| 1428 |
mock.patch("builtins.open", mock.mock_open(read_data="data")) |
| 1429 |
) |
| 1430 |
if "pgpy" in sys.modules: |
| 1431 |
# When pgpy IS installed, simulate its absence by making |
| 1432 |
# from_blob raise NameError (same as if the name were undefined) |
| 1433 |
stack.enter_context( |
| 1434 |
mock.patch("pgpy.PGPKey.from_blob", side_effect=NameError) |
| 1435 |
) |
| 1436 |
# Without pgpy installed the NameError arises naturally at the |
| 1437 |
# 'pgpy.PGPKey.from_blob(...)' call in private_key(); either way |
| 1438 |
# private_key() must swallow the error and return None |
| 1439 |
result = ctrl.private_key() |
| 1440 |
assert result is None |
| 1441 |
|
| 1442 |
|
| 1443 |
def test_private_key_returns_none_when_keyfile_inaccessible(tmpdir): |
| 1444 |
"""private_key() returns None when private_keyfile() returns False.""" |
| 1445 |
# Provide an invalid path so the attachment reports the file as unreachable |
| 1446 |
ctrl = ApprisePGPController( |
| 1447 |
path=str(tmpdir), prv_keyfile="/no/such/file.asc" |
| 1448 |
) |
| 1449 |
# private_keyfile() will return False; private_key() must not raise |
| 1450 |
result = ctrl.private_key() |
| 1451 |
assert result is None |
| 1452 |
|
| 1453 |
|
| 1454 |
def test_private_key_returns_none_on_io_error(tmpdir): |
| 1455 |
"""private_key() returns None when the file cannot be read.""" |
| 1456 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1457 |
with mock.patch("builtins.open", side_effect=OSError("disk error")): |
| 1458 |
result = ctrl.private_key() |
| 1459 |
assert result is None |
| 1460 |
|
| 1461 |
|
| 1462 |
def test_private_key_returns_none_on_malformed_key(tmpdir): |
| 1463 |
"""private_key() returns None when the file contains non-PGP data.""" |
| 1464 |
bad_key = str(tmpdir.join("bad-prv.asc")) |
| 1465 |
with open(bad_key, "w") as f: |
| 1466 |
f.write("this is not a pgp key") |
| 1467 |
|
| 1468 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=bad_key) |
| 1469 |
result = ctrl.private_key() |
| 1470 |
assert result is None |
| 1471 |
|
| 1472 |
|
| 1473 |
def test_private_key_returns_none_when_file_disappears(tmpdir): |
| 1474 |
"""private_key() handles a key file that vanishes between stat and open.""" |
| 1475 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1476 |
with mock.patch("builtins.open", side_effect=FileNotFoundError("gone")): |
| 1477 |
result = ctrl.private_key() |
| 1478 |
assert result is None |
| 1479 |
|
| 1480 |
|
| 1481 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 1482 |
def test_private_key_rejects_passphrase_protected(tmpdir): |
| 1483 |
"""private_key() returns None for a passphrase-protected key.""" |
| 1484 |
import pgpy |
| 1485 |
|
| 1486 |
# Generate a fresh key and protect it with a passphrase |
| 1487 |
key = pgpy.PGPKey.new( |
| 1488 |
pgpy.constants.PubKeyAlgorithm.RSAEncryptOrSign, 2048 |
| 1489 |
) |
| 1490 |
uid = pgpy.PGPUID.new("Locked", email="[email protected]") |
| 1491 |
key.add_uid( |
| 1492 |
uid, |
| 1493 |
usage={pgpy.constants.KeyFlags.Sign}, |
| 1494 |
hashes=[pgpy.constants.HashAlgorithm.SHA256], |
| 1495 |
ciphers=[pgpy.constants.SymmetricKeyAlgorithm.AES256], |
| 1496 |
compression=[pgpy.constants.CompressionAlgorithm.ZLIB], |
| 1497 |
) |
| 1498 |
key.protect( |
| 1499 |
"s3cr3t", |
| 1500 |
pgpy.constants.SymmetricKeyAlgorithm.AES256, |
| 1501 |
pgpy.constants.HashAlgorithm.SHA256, |
| 1502 |
) |
| 1503 |
|
| 1504 |
locked_path = str(tmpdir.join("locked-prv.asc")) |
| 1505 |
with open(locked_path, "w") as f: |
| 1506 |
f.write(str(key)) |
| 1507 |
|
| 1508 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=locked_path) |
| 1509 |
result = ctrl.private_key() |
| 1510 |
assert result is None |
| 1511 |
|
| 1512 |
|
| 1513 |
@pytest.mark.skipif(not pgp_module.PGP_SUPPORT, reason="Requires PGPy") |
| 1514 |
def test_private_key_rejects_public_only_file(tmpdir): |
| 1515 |
"""private_key() rejects public-only files supplied by pgpprv=.""" |
| 1516 |
|
| 1517 |
ctrl = ApprisePGPController( |
| 1518 |
path=str(tmpdir), prv_keyfile=_VALID_PUB_ASC, email="[email protected]" |
| 1519 |
) |
| 1520 |
result = ctrl.private_key() |
| 1521 |
assert result is None |
| 1522 |
|
| 1523 |
# autocrypt_header() must not advertise it either |
| 1524 |
assert ctrl.autocrypt_header() is None |
| 1525 |
|
| 1526 |
|
| 1527 |
# Detached PGP signatures |
| 1528 |
|
| 1529 |
|
| 1530 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 1531 |
def test_sign_returns_signature_and_micalg(tmpdir): |
| 1532 |
"""sign() returns a (sig_str, micalg) tuple for valid message + key.""" |
| 1533 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1534 |
result = ctrl.sign("Hello, World!") |
| 1535 |
assert result is not None |
| 1536 |
sig_str, micalg = result |
| 1537 |
# The signature must be a non-empty armored block |
| 1538 |
assert "BEGIN PGP SIGNATURE" in sig_str |
| 1539 |
# The micalg must start with 'pgp-' |
| 1540 |
assert micalg.startswith("pgp-") |
| 1541 |
|
| 1542 |
|
| 1543 |
def test_sign_returns_none_when_no_private_key(tmpdir): |
| 1544 |
"""sign() returns None when no private key is available.""" |
| 1545 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1546 |
assert ctrl.sign("test message") is None |
| 1547 |
|
| 1548 |
|
| 1549 |
@pytest.mark.skipif("pgpy" not in sys.modules, reason="Requires PGPy") |
| 1550 |
def test_sign_returns_none_on_pgp_error(tmpdir): |
| 1551 |
"""sign() returns None when pgpy raises PGPError during signing.""" |
| 1552 |
import pgpy |
| 1553 |
|
| 1554 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1555 |
with mock.patch.object( |
| 1556 |
ctrl.private_key().__class__, |
| 1557 |
"sign", |
| 1558 |
side_effect=pgpy.errors.PGPError("fail"), |
| 1559 |
): |
| 1560 |
result = ctrl.sign("test") |
| 1561 |
assert result is None |
| 1562 |
|
| 1563 |
|
| 1564 |
def test_sign_returns_none_when_pgpy_missing(tmpdir): |
| 1565 |
"""sign() returns None gracefully when PGPy is not installed.""" |
| 1566 |
ctrl = ApprisePGPController(path=str(tmpdir), prv_keyfile=_VALID_PRV_ASC) |
| 1567 |
# Patch private_key() to return a mock that raises NameError on sign() |
| 1568 |
mock_key = mock.Mock() |
| 1569 |
mock_key.sign.side_effect = NameError("pgpy not installed") |
| 1570 |
with mock.patch.object(ctrl, "private_key", return_value=mock_key): |
| 1571 |
result = ctrl.sign("test") |
| 1572 |
assert result is None |
| 1573 |
|
| 1574 |
|
| 1575 |
# Public-key candidate order |
| 1576 |
|
| 1577 |
|
| 1578 |
def test_pub_key_candidates_no_email(tmpdir): |
| 1579 |
"""_pub_key_candidates() returns the four generic fallbacks when no email |
| 1580 |
is known and no extra addresses are supplied.""" |
| 1581 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1582 |
# No self.email and no caller-supplied email |
| 1583 |
candidates = ctrl._pub_key_candidates() |
| 1584 |
# Only the four generic names should appear |
| 1585 |
assert candidates == [ |
| 1586 |
"pgp-public.asc", |
| 1587 |
"pgp-pub.asc", |
| 1588 |
"public.asc", |
| 1589 |
"pub.asc", |
| 1590 |
] |
| 1591 |
|
| 1592 |
|
| 1593 |
def test_pub_key_candidates_with_email(tmpdir): |
| 1594 |
"""_pub_key_candidates() prepends email-specific names ahead of generics, |
| 1595 |
highest priority first (full-email before localpart).""" |
| 1596 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1597 |
candidates = ctrl._pub_key_candidates() |
| 1598 |
# Full lowercase email is highest priority (index 0) |
| 1599 |
assert candidates[0] == "[email protected]" |
| 1600 |
# Localpart shorthand is next |
| 1601 |
assert candidates[1] == "chris-pub.asc" |
| 1602 |
# Generic fallbacks follow |
| 1603 |
assert "pgp-pub.asc" in candidates |
| 1604 |
|
| 1605 |
|
| 1606 |
def test_pub_key_candidates_extra_email(tmpdir): |
| 1607 |
"""Recipient lookups never fall back to the sender's key.""" |
| 1608 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1609 |
# Simulate a lookup for a recipient address |
| 1610 |
candidates = ctrl._pub_key_candidates("[email protected]") |
| 1611 |
assert candidates[0] == "[email protected]" |
| 1612 |
assert candidates[1] == "recipient-pub.asc" |
| 1613 |
# Sender entries must not appear in a recipient lookup. |
| 1614 |
assert "[email protected]" not in candidates |
| 1615 |
assert "sender-pub.asc" not in candidates |
| 1616 |
|
| 1617 |
|
| 1618 |
# Private-key candidate order |
| 1619 |
|
| 1620 |
|
| 1621 |
def test_prv_key_candidates_no_email(tmpdir): |
| 1622 |
"""_prv_key_candidates() returns the four generic fallbacks when no sender |
| 1623 |
email is configured.""" |
| 1624 |
ctrl = ApprisePGPController(path=str(tmpdir)) |
| 1625 |
candidates = ctrl._prv_key_candidates() |
| 1626 |
assert candidates == [ |
| 1627 |
"pgp-private.asc", |
| 1628 |
"pgp-prv.asc", |
| 1629 |
"private.asc", |
| 1630 |
"prv.asc", |
| 1631 |
] |
| 1632 |
|
| 1633 |
|
| 1634 |
def test_prv_key_candidates_with_email(tmpdir): |
| 1635 |
"""_prv_key_candidates() prepends email-specific names ahead of generics, |
| 1636 |
highest priority first (full-email before localpart).""" |
| 1637 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1638 |
candidates = ctrl._prv_key_candidates() |
| 1639 |
# Full lowercase email is highest priority |
| 1640 |
assert candidates[0] == "[email protected]" |
| 1641 |
# Localpart shorthand is next |
| 1642 |
assert candidates[1] == "sender-prv.asc" |
| 1643 |
# Generic fallbacks follow |
| 1644 |
assert "pgp-prv.asc" in candidates |
| 1645 |
|
| 1646 |
|
| 1647 |
# Missing public-key diagnostics |
| 1648 |
|
| 1649 |
|
| 1650 |
def test_public_key_no_key_emits_path_debug(tmpdir): |
| 1651 |
"""public_key() emits a DEBUG message listing relative cache paths when |
| 1652 |
no public key is found and autogen is disabled. The message is debug- |
| 1653 |
level so the caller's warning remains the only user-visible line.""" |
| 1654 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1655 |
logging.disable(logging.NOTSET) |
| 1656 |
try: |
| 1657 |
with mock.patch.object(pgp_module, "PGP_SUPPORT", True): |
| 1658 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 1659 |
finally: |
| 1660 |
logging.disable(logging.CRITICAL) |
| 1661 |
|
| 1662 |
# Key not found; result must be None |
| 1663 |
assert result is None |
| 1664 |
|
| 1665 |
|
| 1666 |
def test_public_key_no_key_no_path_emits_generic_debug(): |
| 1667 |
"""public_key() emits a generic 'No PGP public key found' debug message |
| 1668 |
in memory-only mode (no path to search, so no filenames to list).""" |
| 1669 |
ctrl = ApprisePGPController(path=None) |
| 1670 |
logging.disable(logging.NOTSET) |
| 1671 |
try: |
| 1672 |
with mock.patch.object(pgp_module, "PGP_SUPPORT", True): |
| 1673 |
result = ctrl.public_key("[email protected]", autogen=False) |
| 1674 |
finally: |
| 1675 |
logging.disable(logging.CRITICAL) |
| 1676 |
assert result is None |
| 1677 |
|
| 1678 |
|
| 1679 |
# Missing private-key diagnostics |
| 1680 |
|
| 1681 |
|
| 1682 |
def test_private_key_not_found_emits_path_debug(tmpdir): |
| 1683 |
"""private_key() emits a DEBUG message listing searched relative paths |
| 1684 |
when no private key file exists on disk. The message is debug-level so |
| 1685 |
the caller's warning remains the only user-visible line.""" |
| 1686 |
ctrl = ApprisePGPController(path=str(tmpdir), email="[email protected]") |
| 1687 |
logging.disable(logging.NOTSET) |
| 1688 |
try: |
| 1689 |
result = ctrl.private_key() |
| 1690 |
finally: |
| 1691 |
logging.disable(logging.CRITICAL) |
| 1692 |
assert result is None |
| 1693 |
|
| 1694 |
|
| 1695 |
def test_private_key_not_found_no_path_emits_generic_debug(): |
| 1696 |
"""private_key() emits a generic 'No PGP private key found' debug |
| 1697 |
message in memory-only mode (no storage path, nothing to search).""" |
| 1698 |
ctrl = ApprisePGPController(path=None) |
| 1699 |
logging.disable(logging.NOTSET) |
| 1700 |
try: |
| 1701 |
result = ctrl.private_key() |
| 1702 |
finally: |
| 1703 |
logging.disable(logging.CRITICAL) |
| 1704 |
assert result is None |