| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
from datetime import datetime, timedelta, timezone |
| 30 |
import logging |
| 31 |
from unittest import mock |
| 32 |
from urllib.parse import urlparse |
| 33 |
|
| 34 |
import requests |
| 35 |
|
| 36 |
from apprise.utils.wkd import AppriseWKDController, AppriseWKDException |
| 37 |
|
| 38 |
logging.disable(logging.CRITICAL) |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
def test_wkd_exception_default_error_code(): |
| 47 |
"""AppriseWKDException uses error_code 610 by default.""" |
| 48 |
exc = AppriseWKDException("something went wrong") |
| 49 |
assert exc.error_code == 610 |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
def test_zb32_encode_all_zeros(): |
| 58 |
"""20 zero bytes encode to 32 'y' characters (index 0 of the alphabet).""" |
| 59 |
result = AppriseWKDController.zb32_encode(b"\x00" * 20) |
| 60 |
assert result == "y" * 32 |
| 61 |
|
| 62 |
|
| 63 |
def test_zb32_encode_all_ones(): |
| 64 |
"""20 0xFF bytes encode to 32 '9' characters (index 31 of the alphabet).""" |
| 65 |
result = AppriseWKDController.zb32_encode(b"\xff" * 20) |
| 66 |
assert result == "9" * 32 |
| 67 |
|
| 68 |
|
| 69 |
def test_zb32_encode_sha1_length(): |
| 70 |
"""SHA-1 digest (20 bytes) always produces exactly 32 z-base32 chars.""" |
| 71 |
import hashlib |
| 72 |
|
| 73 |
digest = hashlib.sha1(b"[email protected]").digest() |
| 74 |
result = AppriseWKDController.zb32_encode(digest) |
| 75 |
assert len(result) == 32 |
| 76 |
|
| 77 |
assert all(c in AppriseWKDController._ZB32 for c in result) |
| 78 |
|
| 79 |
|
| 80 |
def test_zb32_encode_empty(): |
| 81 |
"""Empty input produces an empty string.""" |
| 82 |
assert AppriseWKDController.zb32_encode(b"") == "" |
| 83 |
|
| 84 |
|
| 85 |
def test_zb32_encode_single_byte(): |
| 86 |
"""Single byte (5 bits + 3 leftover bits) produces 2 characters.""" |
| 87 |
|
| 88 |
result = AppriseWKDController.zb32_encode(b"\x00") |
| 89 |
assert len(result) == 2 |
| 90 |
assert result[0] == "y" |
| 91 |
|
| 92 |
|
| 93 |
def test_zb32_encode_known_vector(): |
| 94 |
"""Verify z-base32 encoding against independently computed single-byte |
| 95 |
reference values. |
| 96 |
|
| 97 |
These expected strings are derived from first principles: each 5-bit |
| 98 |
group maps directly to _ZB32[value], and leftover bits are |
| 99 |
left-aligned. They do NOT call zb32_encode() to generate the |
| 100 |
expected string, so a regression in the alphabet or bit-shifting |
| 101 |
logic will cause at least one assertion to fail. |
| 102 |
|
| 103 |
0xf8 = 11111000: |
| 104 |
group1 (bits 0-4): 11111 = 31 -> '9' |
| 105 |
leftover (bits 5-7) << 2: 00000 = 0 -> 'y' |
| 106 |
0xa8 = 10101000: |
| 107 |
group1 (bits 0-4): 10101 = 21 -> 'i' |
| 108 |
leftover (bits 5-7) << 2: 00000 = 0 -> 'y' |
| 109 |
0x08 = 00001000: |
| 110 |
group1 (bits 0-4): 00001 = 1 -> 'b' |
| 111 |
leftover (bits 5-7) << 2: 00000 = 0 -> 'y' |
| 112 |
""" |
| 113 |
assert AppriseWKDController.zb32_encode(b"\xf8") == "9y" |
| 114 |
assert AppriseWKDController.zb32_encode(b"\xa8") == "iy" |
| 115 |
assert AppriseWKDController.zb32_encode(b"\x08") == "by" |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
def test_wkd_urls_structure(): |
| 124 |
"""wkd_urls() returns properly formed subdomain and direct URLs.""" |
| 125 |
sub, direct = AppriseWKDController.wkd_urls("[email protected]") |
| 126 |
|
| 127 |
assert sub.startswith("https://openpgpkey.example.com/") |
| 128 |
assert "/.well-known/openpgpkey/example.com/hu/" in sub |
| 129 |
assert "?l=user" in sub |
| 130 |
|
| 131 |
assert direct.startswith("https://example.com/") |
| 132 |
assert "/.well-known/openpgpkey/hu/" in direct |
| 133 |
assert "?l=user" in direct |
| 134 |
|
| 135 |
|
| 136 |
def test_wkd_urls_case_normalised(): |
| 137 |
"""wkd_urls() produces the same hash and domain for differently-cased |
| 138 |
inputs, but preserves the original local-part case in ?l= (RFC 9080). |
| 139 |
|
| 140 |
The hash component uses the lower-cased local part (spec requirement), |
| 141 |
the domain is always lower-cased (URL canonicalisation), and the ?l= |
| 142 |
query parameter carries the unchanged original local part -- so two |
| 143 |
addresses that differ only in local-part capitalisation will share the |
| 144 |
same hash/path but differ in their ?l= value. |
| 145 |
""" |
| 146 |
sub_upper, dir_upper = AppriseWKDController.wkd_urls("[email protected]") |
| 147 |
sub_lower, dir_lower = AppriseWKDController.wkd_urls("[email protected]") |
| 148 |
|
| 149 |
|
| 150 |
assert sub_upper.split("?")[0] == sub_lower.split("?")[0] |
| 151 |
assert dir_upper.split("?")[0] == dir_lower.split("?")[0] |
| 152 |
|
| 153 |
|
| 154 |
assert "?l=User" in sub_upper |
| 155 |
assert "?l=user" in sub_lower |
| 156 |
|
| 157 |
|
| 158 |
assert urlparse(sub_lower).hostname == "openpgpkey.example.com" |
| 159 |
|
| 160 |
|
| 161 |
def test_wkd_urls_l_param_preserves_original_case(): |
| 162 |
"""?l= carries the unchanged local-part per RFC 9080. |
| 163 |
|
| 164 |
The spec example: [email protected] -> |
| 165 |
?l=Joe.Doe (original case, not lowercased) |
| 166 |
The hash is computed from the lowercased local part; only ?l= keeps |
| 167 |
the original capitalisation. |
| 168 |
""" |
| 169 |
sub, direct = AppriseWKDController.wkd_urls("[email protected]") |
| 170 |
assert "?l=Joe.Doe" in sub |
| 171 |
assert "?l=Joe.Doe" in direct |
| 172 |
|
| 173 |
assert urlparse(sub).hostname == "openpgpkey.example.org" |
| 174 |
assert urlparse(direct).hostname == "example.org" |
| 175 |
|
| 176 |
|
| 177 |
def test_wkd_urls_local_part_encoded(): |
| 178 |
"""wkd_urls() percent-encodes special characters in the local part.""" |
| 179 |
sub, direct = AppriseWKDController.wkd_urls("[email protected]") |
| 180 |
assert "first%2Blast" in sub |
| 181 |
assert "first%2Blast" in direct |
| 182 |
|
| 183 |
|
| 184 |
def test_wkd_urls_no_at_sign(): |
| 185 |
"""wkd_urls() returns (None, None) for an address without '@'.""" |
| 186 |
sub, direct = AppriseWKDController.wkd_urls("notanemail") |
| 187 |
assert sub is None |
| 188 |
assert direct is None |
| 189 |
|
| 190 |
|
| 191 |
def test_wkd_urls_empty_string(): |
| 192 |
"""wkd_urls() returns (None, None) for an empty string.""" |
| 193 |
sub, direct = AppriseWKDController.wkd_urls("") |
| 194 |
assert sub is None |
| 195 |
assert direct is None |
| 196 |
|
| 197 |
|
| 198 |
def test_wkd_urls_empty_local(): |
| 199 |
"""wkd_urls() returns (None, None) when the local part is empty.""" |
| 200 |
sub, direct = AppriseWKDController.wkd_urls("@example.com") |
| 201 |
assert sub is None |
| 202 |
assert direct is None |
| 203 |
|
| 204 |
|
| 205 |
def test_wkd_urls_empty_domain(): |
| 206 |
"""wkd_urls() returns (None, None) when the domain is empty.""" |
| 207 |
sub, direct = AppriseWKDController.wkd_urls("user@") |
| 208 |
assert sub is None |
| 209 |
assert direct is None |
| 210 |
|
| 211 |
|
| 212 |
def test_wkd_urls_none_input(): |
| 213 |
"""wkd_urls() returns (None, None) for None input.""" |
| 214 |
sub, direct = AppriseWKDController.wkd_urls(None) |
| 215 |
assert sub is None |
| 216 |
assert direct is None |
| 217 |
|
| 218 |
|
| 219 |
def test_wkd_urls_non_string_input(): |
| 220 |
"""wkd_urls() returns (None, None) for non-string truthy inputs. |
| 221 |
|
| 222 |
Without the isinstance guard, ``"@" not in 123`` raises TypeError |
| 223 |
before the try/except block can handle it. |
| 224 |
""" |
| 225 |
for bad in (123, 12.5, object(), ["[email protected]"]): |
| 226 |
sub, direct = AppriseWKDController.wkd_urls(bad) |
| 227 |
assert sub is None |
| 228 |
assert direct is None |
| 229 |
|
| 230 |
|
| 231 |
def test_wkd_urls_ipv4_domain_rejected(): |
| 232 |
"""wkd_urls() returns (None, None) for emails with an IPv4 domain. |
| 233 |
|
| 234 |
WKD is defined for DNS hostnames only (RFC 9080). Allowing IP |
| 235 |
literals as the domain creates an SSRF vector because WKD discovery |
| 236 |
turns recipient domains into outbound HTTPS requests. |
| 237 |
""" |
| 238 |
for addr in ( |
| 239 |
"[email protected]", |
| 240 |
"[email protected]", |
| 241 |
"[email protected]", |
| 242 |
): |
| 243 |
sub, direct = AppriseWKDController.wkd_urls(addr) |
| 244 |
assert sub is None, f"Expected None for IP domain: {addr}" |
| 245 |
assert direct is None, f"Expected None for IP domain: {addr}" |
| 246 |
|
| 247 |
|
| 248 |
def test_wkd_urls_lower_raises_attribute_error(): |
| 249 |
"""wkd_urls() returns (None, None) when email.split() raises. |
| 250 |
|
| 251 |
Covers the defensive except branch for string-like objects that pass |
| 252 |
the '@' membership check but fail during splitting. (After the |
| 253 |
RFC 9080 case-preservation fix, split() is called before lower(), so |
| 254 |
breaking split() is what exercises this path.) |
| 255 |
""" |
| 256 |
|
| 257 |
class BrokenStr(str): |
| 258 |
def split(self, *args, **kwargs): |
| 259 |
raise AttributeError("broken split") |
| 260 |
|
| 261 |
sub, direct = AppriseWKDController.wkd_urls(BrokenStr("[email protected]")) |
| 262 |
assert sub is None |
| 263 |
assert direct is None |
| 264 |
|
| 265 |
|
| 266 |
def test_wkd_urls_domain_injection_rejected(): |
| 267 |
"""wkd_urls() returns (None, None) for emails whose domain contains |
| 268 |
characters that would rewrite the URL host. |
| 269 |
|
| 270 |
[email protected]@attacker.test splits to domain='[email protected]' |
| 271 |
which, when embedded in an HTTPS URL, sends the request to attacker.test |
| 272 |
with legit.com as URL credentials. The is_hostname() guard rejects it. |
| 273 |
""" |
| 274 |
for bad_email in ( |
| 275 |
"[email protected]@attacker.test", |
| 276 |
"[email protected]/path", |
| 277 |
"[email protected]:8080", |
| 278 |
"[email protected] space", |
| 279 |
): |
| 280 |
sub, direct = AppriseWKDController.wkd_urls(bad_email) |
| 281 |
assert sub is None, f"Expected None for domain injection: {bad_email}" |
| 282 |
assert direct is None, ( |
| 283 |
f"Expected None for domain injection: {bad_email}" |
| 284 |
) |
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
def _make_resp(status_code, chunks=None, url=None): |
| 293 |
"""Build a context-manager-compatible requests.Response mock. |
| 294 |
|
| 295 |
``chunks`` is a list of byte strings that iter_content() will yield. |
| 296 |
Pass an empty list for an empty body. Leave as None when the status |
| 297 |
code is non-200 and the body will never be consumed. |
| 298 |
``url`` sets r.url (the final URL after any redirects). When omitted |
| 299 |
the attribute is a MagicMock, which passes the HTTPS check because |
| 300 |
MagicMock().lower().startswith() is truthy. |
| 301 |
""" |
| 302 |
resp = mock.MagicMock(status_code=status_code) |
| 303 |
resp.__enter__ = mock.Mock(return_value=resp) |
| 304 |
resp.__exit__ = mock.Mock(return_value=False) |
| 305 |
|
| 306 |
|
| 307 |
resp.headers = {} |
| 308 |
if url is not None: |
| 309 |
resp.url = url |
| 310 |
if chunks is not None: |
| 311 |
resp.iter_content.return_value = iter(chunks) |
| 312 |
return resp |
| 313 |
|
| 314 |
|
| 315 |
@mock.patch("requests.get") |
| 316 |
def test_fetch_subdomain_success(mock_get): |
| 317 |
"""fetch() returns key bytes when the subdomain URL responds with 200.""" |
| 318 |
|
| 319 |
key_bytes = b"\x99fake-openpgp-key-data" |
| 320 |
|
| 321 |
|
| 322 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[key_bytes]) |
| 323 |
|
| 324 |
ctrl = AppriseWKDController() |
| 325 |
result = ctrl.fetch("[email protected]") |
| 326 |
|
| 327 |
assert result == key_bytes |
| 328 |
assert mock_get.call_count == 1 |
| 329 |
|
| 330 |
|
| 331 |
@mock.patch("requests.get") |
| 332 |
def test_fetch_direct_fallback(mock_get): |
| 333 |
"""fetch() tries the direct URL when the subdomain URL fails.""" |
| 334 |
key_bytes = b"\x99another-fake-key" |
| 335 |
|
| 336 |
|
| 337 |
mock_get.side_effect = [ |
| 338 |
_make_resp(404), |
| 339 |
_make_resp(requests.codes.ok, chunks=[key_bytes]), |
| 340 |
] |
| 341 |
|
| 342 |
ctrl = AppriseWKDController() |
| 343 |
result = ctrl.fetch("[email protected]") |
| 344 |
|
| 345 |
assert result == key_bytes |
| 346 |
assert mock_get.call_count == 2 |
| 347 |
|
| 348 |
|
| 349 |
@mock.patch("requests.get") |
| 350 |
def test_fetch_both_fail(mock_get): |
| 351 |
"""fetch() returns None when both WKD URLs fail.""" |
| 352 |
mock_get.return_value = _make_resp(404) |
| 353 |
|
| 354 |
ctrl = AppriseWKDController() |
| 355 |
result = ctrl.fetch("[email protected]") |
| 356 |
|
| 357 |
assert result is None |
| 358 |
assert mock_get.call_count == 2 |
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
@mock.patch("requests.get") |
| 367 |
def test_fetch_caches_result(mock_get): |
| 368 |
"""A successful fetch is cached; subsequent calls skip the network.""" |
| 369 |
key_bytes = b"\x99cached-key" |
| 370 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[key_bytes]) |
| 371 |
|
| 372 |
ctrl = AppriseWKDController() |
| 373 |
result1 = ctrl.fetch("[email protected]") |
| 374 |
result2 = ctrl.fetch("[email protected]") |
| 375 |
|
| 376 |
assert result1 == key_bytes |
| 377 |
assert result2 == key_bytes |
| 378 |
|
| 379 |
assert mock_get.call_count == 1 |
| 380 |
|
| 381 |
|
| 382 |
@mock.patch("requests.get") |
| 383 |
def test_fetch_cache_case_insensitive(mock_get): |
| 384 |
"""Cache lookup normalises the email address.""" |
| 385 |
key_bytes = b"\x99normalised-key" |
| 386 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[key_bytes]) |
| 387 |
|
| 388 |
ctrl = AppriseWKDController() |
| 389 |
ctrl.fetch("[email protected]") |
| 390 |
result = ctrl.fetch("[email protected]") |
| 391 |
|
| 392 |
assert result == key_bytes |
| 393 |
assert mock_get.call_count == 1 |
| 394 |
|
| 395 |
|
| 396 |
@mock.patch("requests.get") |
| 397 |
def test_fetch_expired_cache_refetches(mock_get): |
| 398 |
"""An expired cache entry triggers a new network request.""" |
| 399 |
key_bytes = b"\x99refreshed-key" |
| 400 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[key_bytes]) |
| 401 |
|
| 402 |
ctrl = AppriseWKDController() |
| 403 |
|
| 404 |
|
| 405 |
ctrl._cache["[email protected]"] = { |
| 406 |
"data": b"stale-key", |
| 407 |
"expires": datetime.now(timezone.utc) - timedelta(seconds=1), |
| 408 |
} |
| 409 |
|
| 410 |
result = ctrl.fetch("[email protected]") |
| 411 |
|
| 412 |
assert result == key_bytes |
| 413 |
assert mock_get.call_count == 1 |
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
def test_fetch_no_at_sign(): |
| 422 |
"""fetch() returns None for an address without '@'.""" |
| 423 |
ctrl = AppriseWKDController() |
| 424 |
assert ctrl.fetch("notanemail") is None |
| 425 |
|
| 426 |
|
| 427 |
def test_fetch_empty_string(): |
| 428 |
"""fetch() returns None for an empty string.""" |
| 429 |
ctrl = AppriseWKDController() |
| 430 |
assert ctrl.fetch("") is None |
| 431 |
|
| 432 |
|
| 433 |
def test_fetch_none(): |
| 434 |
"""fetch() returns None when called with None.""" |
| 435 |
ctrl = AppriseWKDController() |
| 436 |
assert ctrl.fetch(None) is None |
| 437 |
|
| 438 |
|
| 439 |
def test_fetch_non_string_input(): |
| 440 |
"""fetch() returns None for non-string truthy inputs. |
| 441 |
|
| 442 |
Without the isinstance guard, ``"@" not in 123`` raises TypeError |
| 443 |
before the method can return None for invalid input. |
| 444 |
""" |
| 445 |
ctrl = AppriseWKDController() |
| 446 |
for bad in (123, 12.5, object(), ["[email protected]"]): |
| 447 |
assert ctrl.fetch(bad) is None |
| 448 |
|
| 449 |
|
| 450 |
def test_fetch_at_only(): |
| 451 |
"""fetch() returns None for '@' (empty local and empty domain). |
| 452 |
|
| 453 |
'@' passes the '@' membership check but wkd_urls() returns (None, None) |
| 454 |
because both local and domain parts are empty -- covers the guard at |
| 455 |
the second validation point inside fetch(). |
| 456 |
""" |
| 457 |
ctrl = AppriseWKDController() |
| 458 |
assert ctrl.fetch("@") is None |
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
@mock.patch("requests.get") |
| 467 |
def test_get_non_200_returns_none(mock_get): |
| 468 |
"""_get() returns None for any non-200 HTTP status.""" |
| 469 |
for code in (301, 400, 403, 404, 500): |
| 470 |
mock_get.return_value = _make_resp(code) |
| 471 |
ctrl = AppriseWKDController() |
| 472 |
assert ctrl._get("https://example.com/key") is None |
| 473 |
|
| 474 |
|
| 475 |
@mock.patch("requests.get") |
| 476 |
def test_get_empty_body_returns_none(mock_get): |
| 477 |
"""_get() returns None when the response body is empty.""" |
| 478 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[]) |
| 479 |
ctrl = AppriseWKDController() |
| 480 |
assert ctrl._get("https://example.com/key") is None |
| 481 |
|
| 482 |
|
| 483 |
@mock.patch("requests.get") |
| 484 |
def test_get_empty_chunk_is_skipped(mock_get): |
| 485 |
"""_get() skips empty bytestrings yielded by iter_content(). |
| 486 |
|
| 487 |
Some HTTP adapters yield b"" sentinel chunks between real chunks; |
| 488 |
the in-loop ``if not chunk: continue`` guard must skip them so they |
| 489 |
do not corrupt the accumulated content or trigger a false empty-body |
| 490 |
result. |
| 491 |
""" |
| 492 |
|
| 493 |
key_bytes = b"\x99" + b"\x00" * 8 |
| 494 |
mock_get.return_value = _make_resp( |
| 495 |
requests.codes.ok, chunks=[b"", key_bytes] |
| 496 |
) |
| 497 |
ctrl = AppriseWKDController() |
| 498 |
result = ctrl._get("https://example.com/key") |
| 499 |
assert result == key_bytes |
| 500 |
|
| 501 |
|
| 502 |
@mock.patch("requests.get") |
| 503 |
def test_get_oversized_via_content_length_returns_none(mock_get): |
| 504 |
"""_get() rejects early when Content-Length already exceeds the limit. |
| 505 |
|
| 506 |
iter_content() must not be called at all -- we detect the oversize |
| 507 |
from the header before reading any bytes. |
| 508 |
""" |
| 509 |
ctrl = AppriseWKDController() |
| 510 |
resp = _make_resp(requests.codes.ok) |
| 511 |
resp.headers = {"Content-Length": str(ctrl.max_response_size + 1)} |
| 512 |
mock_get.return_value = resp |
| 513 |
assert ctrl._get("https://example.com/key") is None |
| 514 |
resp.iter_content.assert_not_called() |
| 515 |
|
| 516 |
|
| 517 |
@mock.patch("requests.get") |
| 518 |
def test_get_valid_content_length_within_limit_proceeds(mock_get): |
| 519 |
"""_get() proceeds to read chunks when Content-Length is within the limit. |
| 520 |
|
| 521 |
This exercises the branch where content_length is not None and the |
| 522 |
parsed value does not exceed max_response_size. |
| 523 |
""" |
| 524 |
key_bytes = b"\x99valid-key" |
| 525 |
resp = _make_resp(requests.codes.ok, chunks=[key_bytes]) |
| 526 |
resp.headers = {"Content-Length": str(len(key_bytes))} |
| 527 |
mock_get.return_value = resp |
| 528 |
ctrl = AppriseWKDController() |
| 529 |
assert ctrl._get("https://example.com/key") == key_bytes |
| 530 |
|
| 531 |
|
| 532 |
@mock.patch("requests.get") |
| 533 |
def test_get_malformed_content_length_proceeds(mock_get): |
| 534 |
"""_get() ignores a malformed Content-Length and reads chunks normally.""" |
| 535 |
key_bytes = b"\x99valid-key" |
| 536 |
resp = _make_resp(requests.codes.ok, chunks=[key_bytes]) |
| 537 |
resp.headers = {"Content-Length": "not-a-number"} |
| 538 |
mock_get.return_value = resp |
| 539 |
ctrl = AppriseWKDController() |
| 540 |
assert ctrl._get("https://example.com/key") == key_bytes |
| 541 |
|
| 542 |
|
| 543 |
@mock.patch("requests.get") |
| 544 |
def test_get_oversized_body_returns_none(mock_get): |
| 545 |
"""_get() returns None when accumulated chunks exceed max_response_size.""" |
| 546 |
ctrl = AppriseWKDController() |
| 547 |
|
| 548 |
oversized = b"\x99" + b"x" * ctrl.max_response_size |
| 549 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[oversized]) |
| 550 |
assert ctrl._get("https://example.com/key") is None |
| 551 |
|
| 552 |
|
| 553 |
@mock.patch("requests.get") |
| 554 |
def test_get_non_pgp_body_returns_none(mock_get): |
| 555 |
"""_get() returns None when the response body is not PGP data. |
| 556 |
|
| 557 |
A subdomain endpoint that is a parked domain or CDN may return HTTP |
| 558 |
200 with HTML content. Without this guard, fetch() would cache the |
| 559 |
HTML bytes and never try the direct-method fallback URL. |
| 560 |
""" |
| 561 |
for non_pgp in ( |
| 562 |
b"<html><body>Not a key</body></html>", |
| 563 |
b"<!DOCTYPE html>", |
| 564 |
b"{}", |
| 565 |
b"Not PGP data", |
| 566 |
): |
| 567 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[non_pgp]) |
| 568 |
ctrl = AppriseWKDController() |
| 569 |
assert ctrl._get("https://example.com/key") is None, ( |
| 570 |
f"Expected None for non-PGP content: {non_pgp[:20]}" |
| 571 |
) |
| 572 |
|
| 573 |
|
| 574 |
@mock.patch("requests.get") |
| 575 |
def test_get_binary_pgp_packet_accepted(mock_get): |
| 576 |
"""_get() accepts a response whose first byte has bit 7 set (OpenPGP |
| 577 |
binary packet format).""" |
| 578 |
|
| 579 |
pgp_binary = b"\x99\x01\xd6" + b"\x00" * 100 |
| 580 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[pgp_binary]) |
| 581 |
ctrl = AppriseWKDController() |
| 582 |
assert ctrl._get("https://example.com/key") == pgp_binary |
| 583 |
|
| 584 |
|
| 585 |
@mock.patch("requests.get") |
| 586 |
def test_get_ascii_armoured_key_accepted(mock_get): |
| 587 |
"""_get() accepts ASCII-armoured PGP key material (starts with '-----').""" |
| 588 |
armoured = b"-----BEGIN PGP PUBLIC KEY BLOCK-----\n..." |
| 589 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[armoured]) |
| 590 |
ctrl = AppriseWKDController() |
| 591 |
assert ctrl._get("https://example.com/key") == armoured |
| 592 |
|
| 593 |
|
| 594 |
@mock.patch("requests.get", side_effect=requests.RequestException("timeout")) |
| 595 |
def test_get_request_exception_returns_none(mock_get): |
| 596 |
"""_get() returns None when requests raises any RequestException.""" |
| 597 |
ctrl = AppriseWKDController() |
| 598 |
assert ctrl._get("https://example.com/key") is None |
| 599 |
|
| 600 |
|
| 601 |
@mock.patch("requests.get") |
| 602 |
def test_get_stream_oserror_returns_none(mock_get): |
| 603 |
"""_get() returns None when iter_content() raises OSError mid-stream. |
| 604 |
|
| 605 |
Covers disk-full, connection-reset, and other IO-level failures that |
| 606 |
surface after the HTTP headers have been received successfully. |
| 607 |
""" |
| 608 |
resp = _make_resp(requests.codes.ok) |
| 609 |
resp.iter_content.side_effect = OSError("connection reset by peer") |
| 610 |
mock_get.return_value = resp |
| 611 |
ctrl = AppriseWKDController() |
| 612 |
assert ctrl._get("https://example.com/key") is None |
| 613 |
|
| 614 |
|
| 615 |
@mock.patch("requests.get") |
| 616 |
def test_get_stream_generic_exception_returns_none(mock_get): |
| 617 |
"""_get() returns None when iter_content() raises an unexpected exception. |
| 618 |
|
| 619 |
Covers urllib3 IncompleteRead, read-timeout mid-stream, and any other |
| 620 |
exception not otherwise categorised. |
| 621 |
""" |
| 622 |
resp = _make_resp(requests.codes.ok) |
| 623 |
resp.iter_content.side_effect = Exception("unexpected streaming error") |
| 624 |
mock_get.return_value = resp |
| 625 |
ctrl = AppriseWKDController() |
| 626 |
assert ctrl._get("https://example.com/key") is None |
| 627 |
|
| 628 |
|
| 629 |
@mock.patch("requests.get") |
| 630 |
def test_get_http_redirect_rejected(mock_get): |
| 631 |
"""_get() returns None when a redirect lands on a non-HTTPS URL. |
| 632 |
|
| 633 |
A redirect from HTTPS to HTTP would expose key material to interception |
| 634 |
and break the WKD trust model. |
| 635 |
""" |
| 636 |
resp = _make_resp( |
| 637 |
requests.codes.ok, |
| 638 |
chunks=[b"\x99key"], |
| 639 |
url="http://attacker.example.com/hu/abc", |
| 640 |
) |
| 641 |
mock_get.return_value = resp |
| 642 |
ctrl = AppriseWKDController() |
| 643 |
assert ctrl._get("https://example.com/key") is None |
| 644 |
|
| 645 |
|
| 646 |
@mock.patch("requests.get") |
| 647 |
def test_get_success_returns_bytes(mock_get): |
| 648 |
"""_get() returns the response bytes on HTTP 200 with content.""" |
| 649 |
payload = b"\x99\xaa\xbb\xcc" |
| 650 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[payload]) |
| 651 |
ctrl = AppriseWKDController() |
| 652 |
assert ctrl._get("https://example.com/key") == payload |
| 653 |
|
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
def test_prune_removes_expired_entries(): |
| 661 |
"""prune() discards entries whose expiry has passed.""" |
| 662 |
ctrl = AppriseWKDController() |
| 663 |
now = datetime.now(timezone.utc) |
| 664 |
|
| 665 |
ctrl._cache["[email protected]"] = { |
| 666 |
"data": b"old", |
| 667 |
"expires": now - timedelta(seconds=1), |
| 668 |
} |
| 669 |
ctrl._cache["[email protected]"] = { |
| 670 |
"data": b"new", |
| 671 |
"expires": now + timedelta(seconds=3600), |
| 672 |
} |
| 673 |
|
| 674 |
ctrl.prune() |
| 675 |
|
| 676 |
assert "[email protected]" not in ctrl._cache |
| 677 |
assert "[email protected]" in ctrl._cache |
| 678 |
|
| 679 |
|
| 680 |
def test_prune_empty_cache(): |
| 681 |
"""prune() does not raise when the cache is empty.""" |
| 682 |
ctrl = AppriseWKDController() |
| 683 |
ctrl.prune() |
| 684 |
assert ctrl._cache == {} |
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
|
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
def test_defaults(): |
| 693 |
"""AppriseWKDController initialises with expected default values.""" |
| 694 |
ctrl = AppriseWKDController() |
| 695 |
assert ctrl.verify_certificate is True |
| 696 |
assert ctrl.request_timeout == (4, 4) |
| 697 |
assert ctrl.allow_redirects is True |
| 698 |
assert ctrl._cache == {} |
| 699 |
|
| 700 |
|
| 701 |
def test_custom_timeout_and_verify(): |
| 702 |
"""Constructor stores custom timeout and verify_certificate values.""" |
| 703 |
ctrl = AppriseWKDController( |
| 704 |
verify_certificate=False, request_timeout=(2, 10) |
| 705 |
) |
| 706 |
assert ctrl.verify_certificate is False |
| 707 |
assert ctrl.request_timeout == (2, 10) |
| 708 |
|
| 709 |
|
| 710 |
def test_custom_allow_redirects(): |
| 711 |
"""Constructor stores a custom allow_redirects value.""" |
| 712 |
ctrl = AppriseWKDController(allow_redirects=False) |
| 713 |
assert ctrl.allow_redirects is False |
| 714 |
|
| 715 |
|
| 716 |
@mock.patch("requests.get") |
| 717 |
def test_get_passes_verify_and_timeout(mock_get): |
| 718 |
"""_get() forwards verify_certificate, request_timeout, allow_redirects, |
| 719 |
and stream=True to requests.""" |
| 720 |
mock_get.return_value = _make_resp(requests.codes.ok, chunks=[b"\x99key"]) |
| 721 |
ctrl = AppriseWKDController( |
| 722 |
verify_certificate=False, request_timeout=(1, 5), allow_redirects=False |
| 723 |
) |
| 724 |
ctrl._get("https://example.com/key") |
| 725 |
|
| 726 |
_, kwargs = mock_get.call_args |
| 727 |
assert kwargs["verify"] is False |
| 728 |
assert kwargs["timeout"] == (1, 5) |
| 729 |
assert kwargs["allow_redirects"] is False |
| 730 |
assert kwargs["stream"] is True |