Debian Codegraph @

tests/test_utils_wkd.py

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