Repository navigation
Expand file tree
/
Copy pathurl.py
More file actions
1986 lines (1762 loc) · 77.9 KB
/
Copy pathurl.py
File metadata and controls
1986 lines (1762 loc) · 77.9 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/lib/blob/main/CONTRIBUTING.md
"""Get for example HTML or JSON from an URL."""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026102401'
import base64
import collections.abc
import json
import os
import re
import socket
import ssl
import time
import urllib.parse
from . import human, txt
# httpx and httpcore take about 50 ms to import, most of a short-lived process's startup.
# `_import_httpx()` loads them on the first request, so a consumer that imports this module
# without fetching anything, or pulls it in only transitively (e.g. via `lib.net`), neither
# pays for them nor fails on a host where httpx is not installed. Verified with
# `python3.9 -X importtime` on Fedora 44, httpx 0.28.1.
_NOT_IMPORTED = object()
httpx = _NOT_IMPORTED
httpcore = _NOT_IMPORTED
# stdlib ssl version names; '1.0' first because it is the most permissive minimum.
# `ssl.TLSVersion` was added in Python 3.7. Build the dict only when available so
# `import lib.url` still works on older interpreters (e.g. RHEL 8's default `python3`
# = 3.6) - a consumer that doesn't actually use TLS version pinning then continues
# to work. Callers that pass `tls_min` / `tls_max` get a clearer RuntimeError in
# `_build_ssl_context()` instead of an AttributeError at import time.
_TLS_VERSIONS = {}
if hasattr(ssl, 'TLSVersion'):
_TLS_VERSIONS = {
'1.0': ssl.TLSVersion.TLSv1,
'1.1': ssl.TLSVersion.TLSv1_1,
'1.2': ssl.TLSVersion.TLSv1_2,
'1.3': ssl.TLSVersion.TLSv1_3,
}
# Transport headers that are safe to keep when a redirect crosses the origin.
# httpx only strips `Authorization` and `Cookie` on a cross-origin redirect, so
# any other credential header a caller set (an API session token such as
# Redfish's `X-Auth-Token`, an API key, ...) would still be sent to the new,
# possibly attacker-controlled host. Rather than enumerate every auth header a
# caller might use, keep only these benign transport headers on a cross-origin
# hop and drop everything else the caller supplied.
_REDIRECT_SAFE_HEADERS = frozenset(
{
'accept',
'accept-encoding',
'accept-language',
'connection',
'content-length',
'content-type',
'host',
'transfer-encoding',
'user-agent',
}
)
# Upper bound for a response body, counted after decompression, so a server cannot
# exhaust the memory of the caller with an endless or inflated answer. The timeout does
# not help here, because it bounds every phase on its own, not the whole transfer.
# Largest legitimate answers measured: 0.9 MiB (WordPress plugin checksums), 2.7 MiB
# (the complete endoflife.date catalogue), an estimated 20 MiB for a REST API listing
# 100'000 objects. A caller expecting more passes `max_bytes`.
DEFAULT_MAX_BYTES = 64 * 1024 * 1024
# The longest `timeout` `fetch()` accepts, in seconds: a bit over eleven days. A larger
# value is a mistake, and the arithmetic of a deadline fails on an absurdly large one.
MAX_TIMEOUT = 1_000_000
# `timeout` is the time every connect, read and write may take on its own, and keeps
# that meaning: a transfer that goes on steadily, a big download or a redirect chain,
# runs as long as it needs. A server that keeps sending just inside every read would
# hold a request for ever though, so the request as a whole gets this many times the
# `timeout` as a backstop. Ten is what a transfer measured on its own phases would
# need at the very most for ten phases (connect, a few redirects, the read of the
# answer) and still leaves every one that completed before untouched; the endless
# drip is ended all the same. `deadline` sets it explicitly.
DEADLINE_FACTOR = 10
def _check_github_name(value, name):
"""Reject anything that is not a GitHub owner or repository name.
Owner and repository names end up in the path of the API request. Upstream limits
them to letters, digits and `.`, `_`, `-`, so anything else is either a typo or an
attempt to reach a different endpoint through the path. `..` is refused separately
because the regex alone would let it pass and it is exactly what a path traversal
needs.
Returns a `(success, result)` tuple suitable for `lib.base.coe()`.
"""
if (
not isinstance(value, str)
or '..' in value
or not re.match(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$', value)
):
return False, f'Refusing {name} that is not a GitHub name: {value}'
return True, value
def _check_github_ref(value, name):
"""Reject anything that is not a usable git ref (branch or tag).
Same reasoning as `_check_github_name()`, except that a ref legitimately carries
slashes (`feature/some-branch`), so those stay allowed while `..`, query strings and
everything else that would change the shape of the request do not.
Returns a `(success, result)` tuple suitable for `lib.base.coe()`.
"""
if (
not isinstance(value, str)
or '..' in value
or not re.match(r'^[A-Za-z0-9][A-Za-z0-9._/-]{0,254}$', value)
):
return False, f'Refusing {name} that is not a git ref: {value}'
return True, value
def _fetch_github_json(url, insecure, no_proxy, proxy, timeout, header):
"""Fetch a GitHub API endpoint, telling "nothing there" apart from "could not ask".
GitHub answers 404 both for a repository that does not exist and for one that has no
release yet. A consumer cannot tell those apart and does not need to, because both
mean there is nothing here to compare against, so that case comes back as `(True,
None)`. A request that never got an answer comes back as `(False, errormessage)` and
stays distinguishable. The two errors an administrator can act on get a message that
names the remedy: 401 is a token GitHub does not accept, 403 and 429 are the
exhausted rate limit.
Returns a `(success, result)` tuple.
"""
success, result = fetch_json(
url,
extended=True,
header=header,
insecure=insecure,
no_proxy=no_proxy,
proxy=proxy,
response_on_error=True,
timeout=timeout,
)
status_code = result.get('status_code') if isinstance(result, dict) else None
if status_code == 404:
return True, None
if status_code == 401:
return False, (
'GitHub rejected the API token. Check that it is still valid and has not'
' expired.'
)
if status_code in (403, 429):
return False, (
f'GitHub refused the request with HTTP {status_code}. Without a token'
f' the API allows 60 requests per hour and IP address; supply one or'
f' ask less often.'
)
if not success:
if isinstance(result, str):
return False, result
return False, f'GitHub answered with HTTP {status_code}.'
if not isinstance(result, dict):
return False, 'GitHub answered with an unreadable response.'
return True, result.get('response_json')
def compare_github_refs(
user,
repo,
base,
head,
insecure=False,
no_proxy=False,
proxy=None,
timeout=8,
header=None,
):
"""
Count how far a GitHub repository's `head` ref is ahead of its `base` ref.
Answers "how many commits has this branch gained since the release I am running",
which is what a consumer needs to say something concrete about an installation
tracking a development branch instead of a release.
Note that GitHub also reports a non-zero count when the two refs have diverged, so
the number says how many commits are on `head` and not on `base` - not that `base`
is simply an ancestor of `head`.
Parameters
----------
user : str
The GitHub username or organization name.
repo : str
The GitHub repository name.
base : str
The ref to compare from, typically the installed tag.
head : str
The ref to compare to, typically a branch such as `main`.
insecure, no_proxy, proxy, timeout, header
See `get_latest_version_from_github()`.
Returns
-------
tuple
- **success** (`bool`): True if the comparison was successfully fetched, False
otherwise.
- **result** (`int` | `bool`):
- The number of commits `head` carries that `base` does not.
- `False` if GitHub did not answer with a comparison, for example because
one of the two refs does not exist.
Examples
--------
>>> compare_github_refs('Linuxfabrik', 'monitoring-plugins', 'v1.2.3', 'main')
(True, 38)
"""
success, result = _check_github_name(user, 'GitHub user')
if not success:
return success, result
success, result = _check_github_name(repo, 'GitHub repository')
if not success:
return success, result
success, result = _check_github_ref(base, 'GitHub base ref')
if not success:
return success, result
success, result = _check_github_ref(head, 'GitHub head ref')
if not success:
return success, result
url = f'https://api.github.com/repos/{user}/{repo}/compare/{base}...{head}'
success, result = _fetch_github_json(
url, insecure, no_proxy, proxy, timeout, header
)
if not success:
return success, result
if not isinstance(result, dict) or 'ahead_by' not in result:
return True, False
try:
return True, int(result['ahead_by'])
except (TypeError, ValueError):
return True, False
# Certificate verification failures an operator runs into in practice, keyed by
# the OpenSSL X509_V_ERR_* code that `ssl.SSLCertVerificationError` reports in
# `verify_code`. The code is matched instead of the message text, which is not
# stable across OpenSSL releases. Codes measured against OpenSSL 3.5 with the
# badssl.com endpoints plus a real host serving an incomplete chain.
_TLS_CHAIN_HINT = (
'The server sends no intermediate certificate to link its own certificate to '
"a trusted root, or the issuing authority is not in this host's trust store. "
'A browser papers over this by fetching the missing certificate itself, other '
'clients do not. Compare with '
'"openssl s_client -connect HOST:PORT -servername HOST": a chain listing only '
'the server certificate has to be completed on the server, a private issuer '
"has to be added to this host's trust store."
)
TLS_VERIFY_HINTS = {
2: _TLS_CHAIN_HINT, # unable to get issuer certificate
9: (
'The server certificate is not valid yet. Compare the clock on this host '
'with the clock on the server.'
),
10: 'The server certificate has expired and has to be renewed on the server.',
18: (
"The server presents a self-signed certificate. Add it to this host's "
'trust store, or accept an unverified connection for this endpoint on '
'purpose.'
),
19: (
'The chain ends in a certificate authority this host does not trust. Add '
"that authority's certificate to this host's trust store."
),
20: _TLS_CHAIN_HINT, # unable to get local issuer certificate
21: _TLS_CHAIN_HINT, # unable to verify the first certificate
62: (
'The certificate was not issued for the name that was requested. Use a '
'name the certificate covers, or have one issued for the name you check.'
),
}
def _tls_verify_error(exc):
"""Return the certificate verification error behind an exception, if any.
Transport libraries wrap the original `ssl` exception, so the cause chain is
walked rather than the outermost type inspected. Returns None when the
failure was not a certificate verification failure.
"""
seen = []
while exc is not None and exc not in seen:
if isinstance(exc, ssl.SSLCertVerificationError):
return exc
seen.append(exc)
exc = exc.__cause__ or exc.__context__
return None
def _tls_verify_message(exc, url_safe):
"""Return a full error message for a certificate that does not verify.
Replaces the raw library wording, which names the failure twice and buries
what an operator has to do about it. Returns None when the request failed
for another reason.
"""
verify_error = _tls_verify_error(exc)
if verify_error is None:
return None
reason = (getattr(verify_error, 'verify_message', '') or '').strip().rstrip('.')
hint = TLS_VERIFY_HINTS.get(verify_error.verify_code, '')
message = f'TLS certificate verification failed for {url_safe}'
if reason:
message += f': {reason}'
return message + '.' + (f' {hint}' if hint else '')
def _default_port(url):
"""Return the URL's port, filling in the scheme default when it is implicit."""
if url.port is not None:
return url.port
return 443 if url.scheme == 'https' else 80
def _leaks_credentials_on_redirect(src, dst):
"""Return True if a redirect from `src` to `dst` crosses the origin in a way
that must not carry credential headers or the request body. Mirrors httpx's
own condition for stripping `Authorization`: a plain same-host HTTP-to-HTTPS
upgrade is allowed, every other scheme/host/port change is treated as
cross-origin."""
same_origin = (
src.scheme == dst.scheme
and src.host == dst.host
and _default_port(src) == _default_port(dst)
)
if same_origin:
return False
https_upgrade = (
src.host == dst.host
and src.scheme == 'http'
and _default_port(src) == 80
and dst.scheme == 'https'
and _default_port(dst) == 443
)
return not https_upgrade
class _DeadlineError(Exception):
"""The overall deadline of a request has passed."""
class _RefusedError(Exception):
"""A request `fetch()` refuses to complete on purpose. It is never retried, since
the next attempt would be refused the same way."""
def _has_body(request):
"""Tell whether an httpx request carries a body. `request.content` only exists on a
request httpx built from bytes: one it rebuilt for a redirect raises
`RequestNotRead`, which made every redirect chain longer than one hop fail. The
headers tell then, the framing of a body is `Content-Length` or chunked."""
try:
return bool(request.content)
except Exception:
return request.headers.get('content-length', '0') not in ('', '0') or (
'transfer-encoding' in request.headers
)
def _read_limited(response, max_bytes, deadline=None):
"""Return the decoded body of a streamed httpx response, raising `_RefusedError`
as soon as it grows past `max_bytes` (`None` reads without a limit). Only gzip and
deflate are decoded, which inflate a received block by about a thousandfold at
most, so a single block overshoots the limit by a bounded amount before it is
refused. Past `deadline` (a `time.monotonic()` value) it raises `_DeadlineError`,
which backs up the per-read timeout where the pool could not be given the deadline."""
if max_bytes is None and deadline is None:
return response.read()
message = 'Refused to read a response larger than '
if max_bytes is not None:
message += human.bytes2human(max_bytes)
declared = response.headers.get('content-length', '')
if max_bytes is not None and declared.isdigit() and int(declared) > max_bytes:
raise _RefusedError(message)
chunks = []
size = 0
for chunk in response.iter_bytes():
size += len(chunk)
if max_bytes is not None and size > max_bytes:
raise _RefusedError(message)
if deadline is not None and time.monotonic() >= deadline:
raise _DeadlineError()
chunks.append(chunk)
return b''.join(chunks)
def _install_safe_redirect_stripping(client, max_bytes=None, deadline=None):
"""Wrap an httpx client's redirect logic so nothing a caller sent to one
origin reaches another one. Credential headers are dropped when a redirect
crosses the origin, and a redirect that would resend the request body there
is refused. The body of every redirect response is read within `max_bytes`
and `deadline`, like the final one. Patched on the instance (not via subclassing) so it also works
when a caller has replaced `httpx.Client` with a test double, and so
importing lib.url never touches `httpx` at module scope. httpx looks both
internals up on the instance, so each wrapper shadows the original bound
method."""
# A test double or a future httpx without one of these internals leaves that
# one unwrapped; the unit tests run against the real httpx to catch the latter.
original_headers = getattr(client, '_redirect_headers', None)
original_build = getattr(client, '_build_redirect_request', None)
def _redirect_headers(request, url, method):
headers = original_headers(request, url, method)
if _leaks_credentials_on_redirect(request.url, url):
for name in list(headers.keys()):
if name.lower() not in _REDIRECT_SAFE_HEADERS:
del headers[name]
return headers
def _build_redirect_request(request, response):
# A 307 or 308 keeps the method and resends the body unchanged; only 301,
# 302 and 303 turn it into a GET without one. A body can carry a password
# (an OAuth password grant, a JSON login), so it must not follow a
# redirect to another origin. Dropping it instead would send a request
# the caller never built, so refuse the redirect.
# Verified against httpx 0.26.0 to 0.28.1 (`_redirect_method`,
# `_redirect_stream`).
redirect = original_build(request, response)
if (
redirect.stream is request.stream
and _has_body(request)
and _leaks_credentials_on_redirect(request.url, redirect.url)
):
raise _RefusedError(
f'Refused to resend the request body to another host after an'
f' HTTP {response.status_code} redirect to'
f' {txt.sanitize_sensitive_data(str(redirect.url))}'
)
# httpx reads the body of a redirect response in full with `response.read()`
# right after this returns, before the caller sees any of it, so a server
# could answer every hop with a body of any size, or a small gzip that
# inflates enormously. Reading it here, within the limits, leaves httpx the
# cached content: `read()` only reads while `_content` is unset.
# Verified against httpx 0.26.0 and 0.28.1 (`_send_handling_redirects`,
# `Response.read`).
if max_bytes is not None or deadline is not None:
response._content = _read_limited(response, max_bytes, deadline)
return redirect
if original_build is not None:
client._build_redirect_request = _build_redirect_request
if original_headers is not None:
client._redirect_headers = _redirect_headers
return client
def _body_hint(data):
"""Describe a request body for an error message without disclosing its values.
Request bodies routinely carry credentials (a login `password`, an API key, a bearer
token). Rendering the body itself would put them into the caller's output, and
`txt.sanitize_sensitive_data()` cannot be relied on to catch that: a Python mapping renders
as `{'password': 'x'}`, which is neither the `password=x` nor the `"password": "x"` form its
patterns match. Only the field names are reported, which is what identifies the offending
field while the values stay out of the message.
"""
if isinstance(data, dict):
return (
'body fields: ' + ', '.join(sorted(map(str, data)))
if data
else 'empty body'
)
return f'body of type {type(data).__name__}'
def _add_certifi_roots(ctx):
"""Add the root certificates of the `certifi` bundle to `ctx`, where it is installed.
On Windows, `create_default_context()` loads the certificates the Windows store holds at
that moment. Windows fills its root store on demand: CryptoAPI downloads a missing root
the first time it builds a chain that needs it, OpenSSL never does. A host without a
browser or Windows Update therefore lacks common roots such as ISRG Root X1 (Let's
Encrypt), and every connection to a site it signed fails with "unable to get local
issuer certificate". Verified on Windows Server 2025 with Python 3.13, whose store held
18 roots. The bundle is the Mozilla set that `httpx` uses by default; the roots of the
Windows store, a private CA among them, stay trusted.
"""
try:
import certifi
except ImportError:
return
try:
ctx.load_verify_locations(cafile=certifi.where())
except (OSError, ssl.SSLError):
pass
def _build_ssl_context(insecure, tls_min, tls_max, cacert=None):
"""Build an SSL context with optional version pinning and ALPN advertised.
ALPN ('h2', 'http/1.1') is advertised regardless of the requested HTTP version so the
negotiated protocol can be inspected via `extended=True` for a compliance check.
`cacert` names a CA bundle to verify against, either a file or a directory of hashed
certificates. It replaces the trust store of the host rather than adding to it, which is
what `curl --cacert` and `REQUESTS_CA_BUNDLE` do as well: an endpoint whose certificate a
private CA signed is then the only thing that verifies, and a certificate from a public CA
no longer does. Handing the bundle to `create_default_context()` is what makes the
difference; `load_verify_locations()` on a context that already holds the trust store
would leave every public CA valid. Verified against Python 3.14 on Fedora 44.
A bundle that cannot be read raises a ValueError rather than leaving the caller with a
connection that verifies against something else than it asked for. With `insecure`
the bundle is not read at all: nothing is verified against it, so a missing one must
not fail the request.
"""
if insecure:
cacert = None
try:
if not cacert:
ctx = ssl.create_default_context()
if os.name == 'nt':
_add_certifi_roots(ctx)
elif os.path.isdir(cacert):
ctx = ssl.create_default_context(capath=cacert)
else:
ctx = ssl.create_default_context(cafile=cacert)
except (OSError, ssl.SSLError) as e:
raise ValueError(f'Cannot read the CA bundle "{cacert}": {e}') from e
if insecure:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
if tls_min is not None or tls_max is not None:
if not _TLS_VERSIONS:
raise RuntimeError(
'TLS version pinning (`tls_min` / `tls_max`) requires Python 3.7+ '
'(`ssl.TLSVersion`); this interpreter is too old.'
)
if tls_min is not None:
if tls_min not in _TLS_VERSIONS:
raise ValueError(
f'Invalid tls_min "{tls_min}"; expected one of {sorted(_TLS_VERSIONS)}'
)
ctx.minimum_version = _TLS_VERSIONS[tls_min]
if tls_max is not None:
if tls_max not in _TLS_VERSIONS:
raise ValueError(
f'Invalid tls_max "{tls_max}"; expected one of {sorted(_TLS_VERSIONS)}'
)
ctx.maximum_version = _TLS_VERSIONS[tls_max]
ctx.set_alpn_protocols(['h2', 'http/1.1'])
return ctx
def _capture_tls_info(response):
"""Extract TLS metadata from a streaming httpx response. Returns a 3-tuple
`(tls_version, alpn, peer_cert_der)`. All entries are `None` over plain HTTP, when the
network stream has already been released, or when httpx does not expose the SSL object
(for example when a multiplexed HTTP/2 stream reuses an earlier connection).
"""
stream = response.extensions.get('network_stream')
if stream is None:
return None, None, None
ssl_obj = stream.get_extra_info('ssl_object')
if ssl_obj is None:
return None, None, None
try:
# getpeercert takes its `binary_form` argument positionally in some httpx/httpcore
# configurations the SSL object hands us the C-level _sslobj, which rejects keyword
# arguments
return (
ssl_obj.version(),
ssl_obj.selected_alpn_protocol(),
ssl_obj.getpeercert(True) or None,
)
except (AttributeError, TypeError, ValueError):
return None, None, None
def _build_deadline_backend(deadline):
"""Return a factory that wraps an httpcore network backend so that the sum of all
its phases, not each phase on its own, ends at `deadline` (a `time.monotonic()`
value). Every connect, TLS handshake, read and write gets the time that is left
as its timeout, and one that finds none left raises the timeout error httpcore
has for it. Returns `None` when httpcore does not expose the public
`NetworkBackend` / `NetworkStream` base classes.
httpx hands its timeout to every read separately, so a server that sends one byte
just inside it never ends the request. Verified against httpx 0.28.1 and httpcore
1.0.9 (`ConnectionPool._network_backend`).
"""
if httpcore is None or not hasattr(httpcore, 'NetworkBackend'):
return None
def left(timeout, error):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise error('overall deadline reached')
return remaining if timeout is None else min(timeout, remaining)
class _DeadlineStream(httpcore.NetworkStream):
def __init__(self, inner):
self._inner = inner
def read(self, max_bytes, timeout=None):
return self._inner.read(max_bytes, left(timeout, httpcore.ReadTimeout))
def write(self, buffer, timeout=None):
self._inner.write(buffer, left(timeout, httpcore.WriteTimeout))
def close(self):
return self._inner.close()
def start_tls(self, ssl_context, server_hostname=None, timeout=None):
return _DeadlineStream(
self._inner.start_tls(
ssl_context,
server_hostname=server_hostname,
timeout=left(timeout, httpcore.ConnectTimeout),
)
)
def get_extra_info(self, info):
return self._inner.get_extra_info(info)
class _DeadlineBackend(httpcore.NetworkBackend):
def __init__(self, inner):
self._inner = inner
def connect_tcp(self, host, port, timeout=None, **kwargs):
if getattr(self._inner, 'resolves_within_timeout', False):
return _DeadlineStream(
self._inner.connect_tcp(
host,
port,
timeout=left(timeout, httpcore.ConnectTimeout),
**kwargs,
)
)
# httpcore's own backend resolves the name in socket.create_connection(),
# which has no timeout, so a hanging resolver would outlast the deadline.
# Resolve here within the time that is left and connect to one address
# after the other, the way create_connection() does. The TLS server name
# is the host of the URL either way (`server_hostname` of start_tls()).
from . import net # net imports this module
try:
addrs = net.getaddrinfo(
host,
port,
socktype=socket.SOCK_STREAM,
timeout=left(timeout, httpcore.ConnectTimeout),
)
except socket.timeout as e: # before OSError, it is one since 3.10
raise httpcore.ConnectTimeout(str(e)) from e
except OSError as e:
raise httpcore.ConnectError(str(e)) from e
error = httpcore.ConnectError(f'no address for {host}')
for _, _, _, _, sockaddr in addrs:
remaining = left(timeout, httpcore.ConnectTimeout)
try:
return _DeadlineStream(
self._inner.connect_tcp(
sockaddr[0], port, timeout=remaining, **kwargs
)
)
except (httpcore.ConnectError, httpcore.ConnectTimeout) as e:
error = e
raise error
def connect_unix_socket(self, path, timeout=None, **kwargs):
return _DeadlineStream(
self._inner.connect_unix_socket(
path, timeout=left(timeout, httpcore.ConnectTimeout), **kwargs
)
)
def sleep(self, seconds):
self._inner.sleep(seconds)
return _DeadlineBackend
def _apply_deadline(client, deadline):
"""Put the overall `deadline` on every connection pool of an httpx client. Returns
False when the client has a shape this does not know, in which case only the
timeout httpx applies to each phase holds."""
wrap = _build_deadline_backend(deadline)
if wrap is None:
return False
transports = [client._transport, *client._mounts.values()]
pools = [getattr(t, '_pool', None) for t in transports if t is not None]
if not pools or any(not hasattr(p, '_network_backend') for p in pools):
return False
for pool in pools:
pool._network_backend = wrap(pool._network_backend)
return True
# Phase-by-phase timing instrumentation for `extended=True`. We swap httpcore's default
# network backend with a custom one that records the wall-clock time spent on DNS resolution,
# TCP connect, TLS handshake, TTFB (request-write to first response byte) and transfer
# (first response byte to last). The custom backend is opt-in: `fetch(extended=False)`
# takes the default fast path with zero instrumentation overhead.
def _build_timing_classes():
"""Build the timing-aware NetworkBackend / NetworkStream subclasses tied to the runtime
httpcore module. Returns `(backend_cls, stream_cls)` or `(None, None)` when httpcore
does not expose the public `NetworkBackend` / `NetworkStream` base classes (very old
httpcore where the API was still private).
"""
if httpcore is None or not hasattr(httpcore, 'NetworkBackend'):
return None, None
class _TimingNetworkStream(httpcore.NetworkStream):
"""Wraps an existing httpcore NetworkStream and times TLS handshake, TTFB and
transfer. The underlying stream still does the I/O; we only record timestamps.
"""
def __init__(self, inner, timings):
self._inner = inner
self._timings = timings
self._request_sent_at = None
self._first_byte_at = None
def read(self, max_bytes, timeout=None):
data = self._inner.read(max_bytes, timeout)
now = time.monotonic()
if data:
if self._first_byte_at is None and self._request_sent_at is not None:
self._first_byte_at = now
self._timings['ttfb'] = now - self._request_sent_at
if self._first_byte_at is not None:
self._timings['transfer'] = now - self._first_byte_at
return data
def write(self, buffer, timeout=None):
self._inner.write(buffer, timeout)
self._request_sent_at = time.monotonic()
def close(self):
return self._inner.close()
def start_tls(self, ssl_context, server_hostname=None, timeout=None):
t = time.monotonic()
wrapped = self._inner.start_tls(
ssl_context,
server_hostname=server_hostname,
timeout=timeout,
)
self._timings['tls'] = time.monotonic() - t
return _TimingNetworkStream(wrapped, self._timings)
def get_extra_info(self, info):
return self._inner.get_extra_info(info)
class _TimingBackend(httpcore.NetworkBackend):
"""NetworkBackend that resolves DNS and opens the TCP socket itself so DNS and
connect can be timed separately. Falls back to a plain httpcore default backend
for unix sockets (not used by HTTP(S) checks).
"""
# resolves within the connect timeout itself, so the deadline backend must not
# resolve in its place and leave nothing to time
resolves_within_timeout = True
def __init__(self):
self.timings = {}
# The default sync backend is used as a fallback for connect_unix_socket.
# Importing it lazily so a missing private path doesn't crash the lib import.
try:
from httpcore._backends.sync import SyncBackend
self._default = SyncBackend()
except Exception:
self._default = None
def connect_tcp(
self,
host,
port,
timeout=None,
local_address=None,
socket_options=None,
):
from . import net # net imports this module
t = time.monotonic()
try:
addrs = net.getaddrinfo(
host, port, socktype=socket.SOCK_STREAM, timeout=timeout
)
except socket.timeout as e: # before OSError, it is one since 3.10
raise httpcore.ConnectTimeout(str(e)) from e
except OSError as e:
raise httpcore.ConnectError(str(e)) from e
self.timings['dns'] = time.monotonic() - t
# A name usually resolves to more than one address, and only one of
# them may be listening. "localhost" on a dual-stacked host is the
# everyday case: it yields ::1 before 127.0.0.1, while a service
# bound to 0.0.0.0 answers on the second address only. Walk the
# whole list the way socket.create_connection() does, so a refused
# or unreachable first address does not end the attempt.
sock = None
last_error = None
t = time.monotonic()
for family, socktype, proto, _, sockaddr in addrs:
try:
sock = socket.socket(family, socktype, proto)
if local_address is not None:
sock.bind((local_address, 0))
if socket_options is not None:
for opt in socket_options:
sock.setsockopt(*opt)
sock.settimeout(timeout)
sock.connect(sockaddr)
except (OSError, socket.timeout) as e:
last_error = e
if sock is not None:
sock.close()
sock = None
continue
break
if sock is None:
raise httpcore.ConnectError(str(last_error)) from last_error
self.timings['connect'] = time.monotonic() - t
# Wrap the raw socket in httpcore's standard sync stream so that read/write
# semantics match httpcore's expectations, then wrap again in our timing
# stream to capture TLS / TTFB / transfer.
from httpcore._backends.sync import SyncStream
inner = SyncStream(sock)
return _TimingNetworkStream(inner, self.timings)
def connect_unix_socket(self, path, timeout=None, socket_options=None):
if self._default is None:
raise httpcore.ConnectError('unix sockets unsupported in this backend')
return self._default.connect_unix_socket(
path,
timeout=timeout,
socket_options=socket_options,
)
def sleep(self, seconds):
time.sleep(seconds)
return _TimingBackend, _TimingNetworkStream
def _build_timing_transport(ssl_context, http1, http2, proxy):
"""Construct an httpx.HTTPTransport whose underlying connection pool uses our timing
backend. Returns (transport, backend) or (None, None) if the runtime httpcore API
does not expose the hooks we need; the caller falls back to default httpx behaviour
and reports only `total` in the timings dict.
`proxy` is the proxy URL the request has to take, or None for a direct connection.
It has to be handled here rather than by the client: httpx only consults the
environment for proxies while it builds the transport itself
(`allow_env_proxies = trust_env and transport is None`), and a proxy handed to the
client would be served by a mount of its own, which would bypass this transport and
with it the phase timings. So the pool itself has to speak to the proxy.
"""
backend_cls, _ = _build_timing_classes()
if backend_cls is None:
return None, None
backend = backend_cls()
transport = httpx.HTTPTransport(
verify=ssl_context,
http1=http1,
http2=http2,
trust_env=False,
)
if proxy:
# httpcore sends Proxy-Authorization only for `proxy_auth` and ignores a
# `user:password@` in the proxy URL, so the proxy answered 407. Split it off
# the way httpx's own transport does (httpx 0.28.1, _transports/default.py;
# the same attributes exist since 0.26).
proxy_config = httpx.Proxy(url=proxy)
transport._pool = httpcore.HTTPProxy(
proxy_url=httpcore.URL(
scheme=proxy_config.url.raw_scheme,
host=proxy_config.url.raw_host,
port=proxy_config.url.port,
target=proxy_config.url.raw_path,
),
proxy_auth=proxy_config.raw_auth,
proxy_headers=proxy_config.headers.raw,
ssl_context=ssl_context,
http1=http1,
http2=http2,
network_backend=backend,
)
else:
transport._pool = httpcore.ConnectionPool(
ssl_context=ssl_context,
http1=http1,
http2=http2,
network_backend=backend,
)
return transport, backend
# Status codes worth another attempt. Every other error status is the server's
# considered answer and comes back the same, and `fetch()` does not wait between
# attempts, so a 425 or 429 (come back later) would only be repeated too early.
_RETRY_STATUS_CODES = frozenset({408, 500, 502, 503, 504})
def _is_transient(exc):
"""Say whether an httpx error may clear up on the next attempt.
Timeouts, broken connections, a server that closed the connection mid-answer and a
failing proxy may. A certificate that does not verify, a request httpx considers
malformed, an unsupported scheme, a redirect loop and a body that cannot be decoded
come back the same. Verified against the exception hierarchy of httpx 0.26.0 and
0.28.1, which is identical.
"""
if _tls_verify_error(exc) is not None:
return False
return isinstance(exc, httpx.TransportError) and not isinstance(
exc, (httpx.LocalProtocolError, httpx.UnsupportedProtocol)
)
def _import_httpx():
"""Import httpx and httpcore on first use and bind them to this module. A module
that is not installed is bound as `None`."""
global httpx, httpcore
if httpx is _NOT_IMPORTED:
try:
import httpx
except ImportError:
httpx = None
if httpcore is _NOT_IMPORTED:
try:
import httpcore
except ImportError:
httpcore = None
# What h11 accepts as the name and the value of a header (RFC 9110, section 5), as its
# own `_abnf` module spells it. A value with a line break or a NUL is the usual shape of
# a token read from a file, with its newline.
_HEADER_NAME_REGEX = re.compile(r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+")
_HEADER_VALUE_REGEX = re.compile(r'([^\x00\s]+(?:[ \t]+[^\x00\s]+)*)?')
def _as_text(value):
return value.decode('latin-1') if isinstance(value, bytes) else value
def _check_headers(header):
"""Return a message naming the first header h11 would refuse, or None. The message
names the header and never carries its value: the value is a credential more often
than not, and the error h11 raises quotes it."""
for name, value in header.items():
if not _HEADER_NAME_REGEX.fullmatch(_as_text(name)):
return f'The header name "{_as_text(name)}" is not valid.'
if not _HEADER_VALUE_REGEX.fullmatch(_as_text(value)):
return (
f'The value of the header "{_as_text(name)}" contains a line break, '
'a control character or a NUL.'
)
return None
_AUTHORIZATION_HEADERS = ('authorization', 'proxy-authorization')
def _hide_header_values(text, header):
"""Replace the values of the headers that look like credentials in `text`, in the
forms an exception quotes them: as they are, and as a `str` or `bytes` literal.
Whether a header carries a secret is decided by `txt.sanitize_sensitive_data()`, the
one place that knows the names. `Authorization` and `Proxy-Authorization` always do:
that function only knows them with a scheme (`Bearer ...`), and some services take
the bare token there."""
for name, value in (header or {}).items():
line = f'{_as_text(name)}: {_as_text(value)}'
value = _as_text(value)
if not value:
continue
if _as_text(name).lower() not in _AUTHORIZATION_HEADERS and (