Debian Codegraph @

tests/test_utils_http.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 """Tests for opt-in HTTP destination policy.
29
30 The socket option tests below describe each option shape by hand rather
31 than installing urllib3-future to produce one. That keeps the whole file
32 passing on RHEL and Rocky Linux, which ship the urllib3 1.26 series, and it
33 means the compatibility branch is covered everywhere instead of only where
34 an extra package happens to be present. Please do not swap them for a
35 skipif that needs urllib3-future installed.
36 """
37
38 from concurrent.futures import TimeoutError as FutureTimeoutError
39 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
40 import socket
41 import threading
42 from unittest import mock
43
44 import pytest
45 import requests
46 from urllib3.exceptions import ConnectTimeoutError, NewConnectionError
47
48 from apprise.utils import http
49 from apprise.utils.http import (
50 HTTPPolicy,
51 HTTPPolicySession,
52 is_public_ip_address,
53 is_secure_http_url,
54 )
55
56
57 def test_public_ip_classification():
58 """Only public unicast addresses pass the shared classifier."""
59 assert is_public_ip_address("93.184.215.14")
60 assert not is_public_ip_address("127.0.0.1")
61 assert not is_public_ip_address("10.0.0.1")
62 assert not is_public_ip_address("100.64.0.1")
63 assert not is_public_ip_address("ff02::1")
64 assert not is_public_ip_address("::ffff:127.0.0.1")
65 assert not is_public_ip_address("64:ff9b::127.0.0.1")
66 assert is_public_ip_address("64:ff9b::8.8.8.8")
67 assert not is_public_ip_address("not-an-address")
68
69
70 @pytest.mark.parametrize(
71 "address",
72 (
73 "169.254.1.1",
74 "224.0.0.1",
75 "240.0.0.1",
76 "0.0.0.0",
77 "fec0::1",
78 ),
79 )
80 def test_non_public_address_categories(address):
81 """Every special-use address category is rejected."""
82 assert not is_public_ip_address(address)
83
84
85 def test_transition_address_categories():
86 """IPv4 transition addresses inherit their embedded address safety."""
87 assert is_public_ip_address("::ffff:8.8.8.8")
88
89 # Simulate Python releases that mark the IPv6 wrapper as reserved. The
90 # embedded IPv4 address must still decide whether the address is safe.
91 with mock.patch.object(
92 http.ipaddress.IPv6Address,
93 "is_reserved",
94 new_callable=mock.PropertyMock,
95 return_value=True,
96 ):
97 assert is_public_ip_address("::ffff:8.8.8.8")
98 assert not is_public_ip_address("::ffff:10.0.0.1")
99
100 # Older Python releases do not classify these prefixes as private.
101 with mock.patch.object(
102 http.ipaddress.IPv6Address,
103 "is_private",
104 new_callable=mock.PropertyMock,
105 return_value=False,
106 ):
107 assert not is_public_ip_address("2002:0a00:0001::1")
108 assert not is_public_ip_address(
109 "2001:0000:4136:e378:8000:63bf:f5ff:fffe"
110 )
111
112 # A Teredo address whose server and client are both public must
113 # still be accepted once the embedded addresses are checked.
114 assert is_public_ip_address("2001:0:4136:e378::f7f7:f7f7")
115
116
117 def test_secure_url_classification():
118 """Secure URLs require HTTPS, a valid host, and no credentials."""
119 # Well formed addresses we accept
120 assert is_secure_http_url("https://example.com/key") is True
121 assert is_secure_http_url("HTTPS://Example.com") is True
122 assert is_secure_http_url("https://example.com:8443/path") is True
123 assert is_secure_http_url("https://localhost") is True
124
125 # Private and loopback addresses are fine for self hosted services
126 assert is_secure_http_url("https://127.0.0.1:8080") is True
127 assert is_secure_http_url("https://[2001:db8::1]:8443/p") is True
128
129 # We must be given a string
130 assert is_secure_http_url(None) is False
131 assert is_secure_http_url(42) is False
132 assert is_secure_http_url(b"https://example.com") is False
133
134 # Only HTTPS gets through
135 assert is_secure_http_url("http://example.com/key") is False
136 assert is_secure_http_url("ftp://example.com") is False
137 assert is_secure_http_url("example.com") is False
138
139 # There has to be a host to talk to
140 assert is_secure_http_url("https:///key") is False
141
142 # Credentials are never accepted, not even empty ones
143 assert is_secure_http_url("https://user:[email protected]/key") is False
144 assert is_secure_http_url("https://[email protected]") is False
145 assert is_secure_http_url("https://@example.com") is False
146 assert is_secure_http_url("https://:@example.com") is False
147
148 # A port we cannot read, or cannot connect to, and an unterminated
149 # IPv6 address
150 assert is_secure_http_url("https://example.com:notaport") is False
151 assert is_secure_http_url("https://example.com:65536") is False
152 assert is_secure_http_url("https://example.com:0") is False
153 assert is_secure_http_url("https://[broken/key") is False
154
155 # The host itself still has to make sense
156 assert is_secure_http_url("https://-bad-.example.com") is False
157 assert is_secure_http_url("https://exa mple.com") is False
158
159 # A fragment never reaches a server, so it is not a request target
160 assert is_secure_http_url("https://example.com/base#frag") is False
161 assert is_secure_http_url("https://example.com/#") is False
162
163
164 def test_policy_filters_and_preserves_dns_answers():
165 """Approved resolver entries retain their original socket address."""
166 answers = [
167 (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 443)),
168 (
169 socket.AF_INET,
170 socket.SOCK_STREAM,
171 6,
172 "",
173 ("93.184.215.14", 443),
174 ),
175 ]
176 policy = HTTPPolicy(address_filter=is_public_ip_address)
177
178 with mock.patch("socket.getaddrinfo", return_value=answers) as resolver:
179 assert policy.resolve("example.com", 443) == [answers[1]]
180
181 resolver.assert_called_once()
182
183
184 def test_url_policy_callback_failure_is_closed():
185 """An unexpected URL callback error becomes a normal request failure."""
186 policy = HTTPPolicy(
187 url_filter=mock.Mock(side_effect=RuntimeError("bad policy"))
188 )
189
190 with pytest.raises(requests.exceptions.InvalidURL) as error:
191 policy.validate_url("https://example.com/")
192
193 assert isinstance(error.value.__cause__, RuntimeError)
194
195
196 def test_empty_url_policy_allows_validation():
197 """A policy without a URL callback leaves URL selection to its caller."""
198 HTTPPolicy().validate_url("https://example.com/")
199
200
201 def test_policy_denies_unusable_dns_answers():
202 """A lookup fails closed when no answer passes its policy."""
203 answers = [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 443))]
204 policy = HTTPPolicy(address_filter=is_public_ip_address)
205
206 with (
207 mock.patch("socket.getaddrinfo", return_value=answers),
208 pytest.raises(socket.gaierror),
209 ):
210 policy.resolve("internal.example", 443)
211
212
213 def test_policy_rejects_work_when_resolver_is_full():
214 """A saturated resolver rejects new work without queuing it."""
215 slots = mock.Mock()
216 slots.acquire.return_value = False
217 with (
218 mock.patch.object(http, "_DNS_SLOTS", slots),
219 mock.patch.object(http, "_DNS_POOL") as pool,
220 pytest.raises(socket.gaierror),
221 ):
222 HTTPPolicy().resolve("busy.example", 443)
223
224 pool.submit.assert_not_called()
225
226
227 def test_policy_normalizes_executor_failure():
228 """An unavailable executor becomes a normal DNS failure."""
229 slots = mock.Mock()
230 slots.acquire.return_value = True
231 with (
232 mock.patch.object(http, "_DNS_SLOTS", slots),
233 mock.patch.object(http, "_DNS_POOL") as pool,
234 pytest.raises(socket.gaierror),
235 ):
236 pool.submit.side_effect = RuntimeError("executor stopped")
237 HTTPPolicy().resolve("example.com", 443)
238
239 slots.release.assert_called_once_with()
240
241
242 def test_policy_normalizes_lookup_failure():
243 """A resolver future exception becomes a normal DNS failure."""
244 future = mock.Mock()
245 future.result.side_effect = UnicodeError("bad hostname")
246 with (
247 mock.patch.object(http, "_DNS_POOL") as pool,
248 pytest.raises(socket.gaierror),
249 ):
250 pool.submit.return_value = future
251 HTTPPolicy().resolve("example.com", 443)
252
253
254 def test_socket_options_are_left_alone():
255 """Nothing is configured when urllib3 asks for no options."""
256 sock = mock.Mock()
257 http._set_socket_options(sock, None)
258
259 # An absent option list is not the same as an empty one.
260 sock.setsockopt.assert_not_called()
261
262
263 def test_socket_options_urllib3_standard_form():
264 """A standard urllib3 option reaches setsockopt untouched."""
265 sock = mock.Mock()
266 option = (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
267 http._set_socket_options(sock, [option])
268
269 sock.setsockopt.assert_called_once_with(*option)
270
271
272 def test_socket_options_urllib3_future_tcp_form():
273 """An urllib3-future TCP option is applied to a stream socket.
274
275 Apprise never requires urllib3-future, but a host can have it installed
276 alongside Requests, and the option it hands us must still work.
277 """
278 sock = mock.Mock()
279 sock.type = socket.SOCK_STREAM
280 http._set_socket_options(
281 sock, [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1, "tcp")]
282 )
283
284 sock.setsockopt.assert_called_once_with(
285 socket.IPPROTO_TCP, socket.TCP_NODELAY, 1
286 )
287
288
289 def test_socket_options_skip_wrong_protocol():
290 """An urllib3-future UDP option is skipped for a stream socket."""
291 sock = mock.Mock()
292 sock.type = socket.SOCK_STREAM
293 http._set_socket_options(
294 sock, [(socket.SOL_SOCKET, socket.SO_BROADCAST, 1, "udp")]
295 )
296
297 sock.setsockopt.assert_not_called()
298
299
300 def test_socket_options_native_length_form():
301 """Python's native four-argument length form remains supported."""
302 sock = mock.Mock()
303 http._set_socket_options(
304 sock, [(socket.SOL_SOCKET, socket.SO_RCVBUF, None, 8)]
305 )
306
307 sock.setsockopt.assert_called_once_with(
308 socket.SOL_SOCKET, socket.SO_RCVBUF, None, 8
309 )
310
311
312 def test_socket_options_applied_in_order():
313 """Every option is configured, whatever mix of forms is supplied."""
314 sock = mock.Mock()
315 sock.type = socket.SOCK_STREAM
316 http._set_socket_options(
317 sock,
318 [
319 (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
320 (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1, "tcp"),
321 (socket.SOL_SOCKET, socket.SO_BROADCAST, 1, "udp"),
322 (socket.SOL_SOCKET, socket.SO_RCVBUF, None, 8),
323 ],
324 )
325
326 assert sock.setsockopt.call_args_list == [
327 mock.call(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
328 mock.call(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),
329 mock.call(socket.SOL_SOCKET, socket.SO_RCVBUF, None, 8),
330 ]
331
332
333 def test_policy_skips_malformed_answer():
334 """Malformed resolver entries do not hide a usable answer."""
335 valid = (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443))
336 with mock.patch("socket.getaddrinfo", return_value=[None, valid]):
337 assert HTTPPolicy().resolve("example.com", 443) == [valid]
338
339
340 def test_policy_callback_failure_is_closed():
341 """An address callback exception cannot allow a destination."""
342 answer = (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443))
343 policy = HTTPPolicy(address_filter=mock.Mock(side_effect=ValueError))
344 with (
345 mock.patch("socket.getaddrinfo", return_value=[answer]),
346 pytest.raises(socket.gaierror),
347 ):
348 policy.resolve("example.com", 443)
349
350
351 def test_policy_timeout_retains_slot_until_lookup_stops():
352 """Timed-out native DNS work keeps its slot until the worker exits."""
353 future = mock.Mock()
354 future.result.side_effect = FutureTimeoutError
355 slots = mock.Mock()
356 slots.acquire.return_value = True
357
358 with (
359 mock.patch.object(http, "_DNS_POOL") as pool,
360 mock.patch.object(http, "_DNS_SLOTS", slots),
361 pytest.raises(socket.gaierror),
362 ):
363 pool.submit.return_value = future
364 HTTPPolicy(resolve_timeout=0.01).resolve("slow.example", 443)
365
366 future.add_done_callback.assert_called_once_with(http._release_dns_slot)
367 future.cancel.assert_called_once_with()
368 slots.release.assert_not_called()
369
370
371 def test_connection_uses_pinned_sockaddr():
372 """The socket connects to the approved answer without another lookup."""
373 answer = (
374 socket.AF_INET,
375 socket.SOCK_STREAM,
376 6,
377 "",
378 ("93.184.215.14", 443),
379 )
380 policy = HTTPPolicy()
381 sock = mock.Mock()
382 sock.getpeername.return_value = ("93.184.215.14", 443)
383
384 with (
385 mock.patch.object(
386 policy,
387 "resolve",
388 return_value=[answer],
389 ) as resolver,
390 mock.patch("socket.socket", return_value=sock) as socket_factory,
391 ):
392 assert policy.create_connection("example.com", 443, timeout=4) is sock
393
394 resolver.assert_called_once_with("example.com", 443)
395 socket_factory.assert_called_once_with(
396 socket.AF_INET,
397 socket.SOCK_STREAM,
398 6,
399 )
400 sock.connect.assert_called_once_with(("93.184.215.14", 443))
401
402
403 def test_connection_retries_approved_answers():
404 """A failed approved address is closed before trying the next one."""
405 answers = [
406 (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443)),
407 (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.4.4", 443)),
408 ]
409 first = mock.Mock()
410 first.connect.side_effect = OSError("unreachable")
411 second = mock.Mock()
412 second.getpeername.return_value = ("8.8.4.4", 443)
413 policy = HTTPPolicy()
414
415 with (
416 mock.patch.object(policy, "resolve", return_value=answers),
417 mock.patch("socket.socket", side_effect=(first, second)),
418 ):
419 result = policy.create_connection(
420 "example.com",
421 443,
422 source_address=("0.0.0.0", 0),
423 )
424
425 assert result is second
426 first.close.assert_called_once_with()
427 second.bind.assert_called_once_with(("0.0.0.0", 0))
428 second.settimeout.assert_not_called()
429
430
431 def test_connection_retries_peer_address_mismatch():
432 """A socket reaching a different peer is closed and never returned."""
433 answers = [
434 (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443)),
435 (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.4.4", 443)),
436 ]
437 first = mock.Mock()
438 first.getpeername.return_value = ("10.0.0.5", 443)
439 second = mock.Mock()
440 second.getpeername.return_value = ("8.8.4.4", 443)
441 policy = HTTPPolicy()
442
443 with (
444 mock.patch.object(policy, "resolve", return_value=answers),
445 mock.patch("socket.socket", side_effect=(first, second)),
446 ):
447 assert policy.create_connection("example.com", 443) is second
448
449 first.close.assert_called_once_with()
450
451
452 def test_connection_normalizes_ipv6_peer_address():
453 """Equivalent compressed and expanded IPv6 peers compare equally."""
454 answer = (
455 socket.AF_INET6,
456 socket.SOCK_STREAM,
457 6,
458 "",
459 ("2001:4860:4860::8888", 443, 0, 0),
460 )
461 sock = mock.Mock()
462 sock.getpeername.return_value = (
463 "2001:4860:4860:0:0:0:0:8888",
464 443,
465 0,
466 0,
467 )
468 policy = HTTPPolicy()
469
470 with (
471 mock.patch.object(policy, "resolve", return_value=[answer]),
472 mock.patch("socket.socket", return_value=sock),
473 ):
474 assert policy.create_connection("example.com", 443) is sock
475
476
477 def test_connection_rejects_invalid_peer_address():
478 """An unusable peer address fails closed and releases its socket."""
479 answer = (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443))
480 sock = mock.Mock()
481 sock.getpeername.return_value = None
482 policy = HTTPPolicy()
483
484 with (
485 mock.patch.object(policy, "resolve", return_value=[answer]),
486 mock.patch("socket.socket", return_value=sock),
487 pytest.raises(OSError, match="invalid peer address"),
488 ):
489 policy.create_connection("example.com", 443)
490
491 sock.close.assert_called_once_with()
492
493
494 def test_connection_raises_last_socket_error():
495 """The last connection error is returned after all answers fail."""
496 answer = (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443))
497 policy = HTTPPolicy()
498 with (
499 mock.patch.object(policy, "resolve", return_value=[answer]),
500 mock.patch("socket.socket", side_effect=OSError("socket failed")),
501 pytest.raises(OSError, match="socket failed"),
502 ):
503 policy.create_connection("example.com", 443)
504
505
506 def test_connection_rejects_empty_resolver_result():
507 """An unexpectedly empty resolver result fails closed."""
508 policy = HTTPPolicy()
509 with (
510 mock.patch.object(policy, "resolve", return_value=[]),
511 pytest.raises(OSError, match="no usable addresses"),
512 ):
513 policy.create_connection("example.com", 443)
514
515
516 @pytest.mark.parametrize(
517 ("error", "expected"),
518 (
519 (socket.gaierror("denied"), NewConnectionError),
520 (socket.timeout("timed out"), ConnectTimeoutError),
521 (OSError("failed"), NewConnectionError),
522 ),
523 )
524 def test_policy_connection_normalizes_socket_errors(error, expected):
525 """urllib3 receives its normal connection exception categories."""
526 policy = mock.Mock()
527 policy.create_connection.side_effect = error
528 connection_class = http._policy_pool_classes(policy)["http"].ConnectionCls
529 connection = connection_class("example.com", 443)
530
531 with pytest.raises(expected):
532 connection._new_conn()
533
534
535 def test_policy_connection_returns_socket():
536 """A successful policy connection is returned to urllib3."""
537 policy = mock.Mock()
538 sock = mock.Mock()
539 policy.create_connection.return_value = sock
540 connection_class = http._policy_pool_classes(policy)["http"].ConnectionCls
541 connection = connection_class("example.com", 443)
542
543 with mock.patch("sys.audit") as audit:
544 assert connection._new_conn() is sock
545
546 audit.assert_called_once_with(
547 "http.client.connect",
548 connection,
549 "example.com",
550 443,
551 )
552
553
554 def test_session_validates_every_prepared_request():
555 """Each send, including redirect sends, receives a fresh URL check."""
556 checked = []
557 policy = HTTPPolicy(
558 url_filter=lambda url: checked.append(url) or "safe" in url
559 )
560 session = HTTPPolicySession(policy)
561 safe = requests.Request("GET", "https://safe.example/a").prepare()
562 denied = requests.Request("GET", "https://blocked.example/b").prepare()
563
564 with mock.patch.object(requests.Session, "send", return_value=mock.Mock()):
565 session.send(safe)
566 with pytest.raises(requests.exceptions.InvalidURL):
567 session.send(denied)
568
569 assert checked == [safe.url, denied.url]
570
571
572 def test_session_disables_proxies_by_default():
573 """Checked requests cannot be silently rerouted through a proxy."""
574 session = HTTPPolicySession(HTTPPolicy())
575 assert session.trust_env is False
576
577 adapter = session.get_adapter("https://example.com")
578 with pytest.raises(requests.exceptions.ProxyError):
579 adapter.proxy_manager_for("http://proxy.example")
580
581
582 def test_session_connects_through_policy_adapter():
583 """The complete adapter can fetch through an approved pinned socket."""
584
585 class Handler(BaseHTTPRequestHandler):
586 def do_GET(self):
587 self.send_response(200)
588 self.end_headers()
589 self.wfile.write(b"ok")
590
591 def log_message(self, _format, *args):
592 # Keep the test server quiet.
593 pass
594
595 server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
596 thread = threading.Thread(target=server.serve_forever)
597 thread.start()
598 try:
599 # This test permits loopback only to exercise the transport locally.
600 with HTTPPolicySession(
601 HTTPPolicy(address_filter=lambda _address: True)
602 ) as session:
603 # Address the socket the server bound; "localhost" resolves to
604 # ::1 first on a dual-stack host and has to fail over.
605 response = session.get(
606 f"http://127.0.0.1:{server.server_port}/",
607 timeout=2,
608 )
609 assert response.status_code == requests.codes.ok
610 assert response.content == b"ok"
611 finally:
612 server.shutdown()
613 thread.join()
614 server.server_close()
615
616
617 def test_policy_connects_with_urllib3_future_option():
618 """A real socket accepts the protocol form urllib3-future supplies.
619
620 The unit tests above use a mock, which tolerates any call signature.
621 Only a real socket proves setsockopt itself is happy.
622 """
623
624 class Handler(BaseHTTPRequestHandler):
625 def do_GET(self):
626 self.send_response(200)
627 self.end_headers()
628 self.wfile.write(b"ok")
629
630 def log_message(self, _format, *args):
631 # Keep the test server quiet.
632 pass
633
634 server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
635 thread = threading.Thread(target=server.serve_forever)
636 thread.start()
637
638 # Describe the option the way urllib3-future does alongside Requests.
639 options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1, "tcp")]
640 try:
641 # This test permits loopback only to exercise the transport locally.
642 policy = HTTPPolicy(address_filter=lambda _address: True)
643 sock = policy.create_connection(
644 "127.0.0.1",
645 server.server_port,
646 timeout=2,
647 socket_options=options,
648 )
649 try:
650 sock.sendall(b"GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n")
651 assert b"200 OK" in sock.recv(1024)
652
653 finally:
654 sock.close()
655
656 finally:
657 server.shutdown()
658 thread.join()
659 server.server_close()
660
661
662 def test_session_validates_redirect_before_second_request():
663 """A denied redirect target is rejected before it reaches the server."""
664
665 class Handler(BaseHTTPRequestHandler):
666 paths = []
667
668 def do_GET(self):
669 self.paths.append(self.path)
670 if self.path == "/start":
671 self.send_response(302)
672 self.send_header(
673 "Location",
674 f"http://localhost:{self.server.server_port}/blocked",
675 )
676 self.end_headers()
677 return
678
679 self.send_response(200)
680 self.end_headers()
681
682 def log_message(self, _format, *args):
683 # Keep the test server quiet.
684 pass
685
686 server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
687 thread = threading.Thread(target=server.serve_forever)
688 thread.start()
689 try:
690 policy = HTTPPolicy(
691 url_filter=lambda url: not url.endswith("/blocked"),
692 address_filter=lambda _address: True,
693 )
694 with (
695 HTTPPolicySession(policy) as session,
696 pytest.raises(requests.exceptions.InvalidURL),
697 ):
698 # Address the socket the server bound, as above
699 session.get(
700 f"http://127.0.0.1:{server.server_port}/start",
701 timeout=2,
702 )
703
704 assert Handler.paths == ["/start"]
705 finally:
706 server.shutdown()
707 thread.join()
708 server.server_close()