|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | + |
| 5 | +import ssl |
| 6 | +import sys |
| 7 | +import typing as T |
| 8 | +from json import dumps |
| 9 | + |
| 10 | +if sys.version_info >= (3, 12): |
| 11 | + from typing import override |
| 12 | +else: |
| 13 | + from typing_extensions import override |
| 14 | + |
| 15 | +import requests |
| 16 | +from requests.adapters import HTTPAdapter |
| 17 | + |
| 18 | + |
| 19 | +LOG = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +class HTTPSystemCertsAdapter(HTTPAdapter): |
| 23 | + """ |
| 24 | + This adapter uses the system's certificate store instead of the certifi module. |
| 25 | +
|
| 26 | + The implementation is based on the project https://pypi.org/project/pip-system-certs/, |
| 27 | + which has a system-wide effect. |
| 28 | + """ |
| 29 | + |
| 30 | + def init_poolmanager(self, *args, **kwargs): |
| 31 | + ssl_context = ssl.create_default_context() |
| 32 | + ssl_context.load_default_certs() |
| 33 | + kwargs["ssl_context"] = ssl_context |
| 34 | + |
| 35 | + super().init_poolmanager(*args, **kwargs) |
| 36 | + |
| 37 | + def cert_verify(self, *args, **kwargs): |
| 38 | + super().cert_verify(*args, **kwargs) |
| 39 | + |
| 40 | + # By default Python requests uses the ca_certs from the certifi module |
| 41 | + # But we want to use the certificate store instead. |
| 42 | + # By clearing the ca_certs variable we force it to fall back on that behaviour (handled in urllib3) |
| 43 | + if "conn" in kwargs: |
| 44 | + conn = kwargs["conn"] |
| 45 | + else: |
| 46 | + conn = args[0] |
| 47 | + |
| 48 | + conn.ca_certs = None |
| 49 | + |
| 50 | + |
| 51 | +class Session(requests.Session): |
| 52 | + # NOTE: This is a global flag that affects all Session instances |
| 53 | + USE_SYSTEM_CERTS: T.ClassVar[bool] = False |
| 54 | + # Instance variables |
| 55 | + disable_logging_request: bool = False |
| 56 | + disable_logging_response: bool = False |
| 57 | + # Avoid mounting twice |
| 58 | + _mounted: bool = False |
| 59 | + |
| 60 | + @override |
| 61 | + def request(self, method: str | bytes, url: str | bytes, *args, **kwargs): |
| 62 | + self._log_debug_request(method, url, *args, **kwargs) |
| 63 | + |
| 64 | + if Session.USE_SYSTEM_CERTS: |
| 65 | + if not self._mounted: |
| 66 | + self.mount("https://", HTTPSystemCertsAdapter()) |
| 67 | + self._mounted = True |
| 68 | + resp = super().request(method, url, *args, **kwargs) |
| 69 | + else: |
| 70 | + try: |
| 71 | + resp = super().request(method, url, *args, **kwargs) |
| 72 | + except requests.exceptions.SSLError as ex: |
| 73 | + if "SSLCertVerificationError" not in str(ex): |
| 74 | + raise ex |
| 75 | + Session.USE_SYSTEM_CERTS = True |
| 76 | + # HTTPSConnectionPool(host='graph.mapillary.com', port=443): Max retries exceeded with url: /login (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1018)'))) |
| 77 | + LOG.warning( |
| 78 | + "SSL error occurred, falling back to system SSL certificates: %s", |
| 79 | + ex, |
| 80 | + ) |
| 81 | + return self.request(method, url, *args, **kwargs) |
| 82 | + |
| 83 | + self._log_debug_response(resp) |
| 84 | + |
| 85 | + return resp |
| 86 | + |
| 87 | + def _log_debug_request(self, method: str | bytes, url: str | bytes, **kwargs): |
| 88 | + if self.disable_logging_request: |
| 89 | + return |
| 90 | + |
| 91 | + if logging.getLogger().getEffectiveLevel() <= logging.DEBUG: |
| 92 | + return |
| 93 | + |
| 94 | + if isinstance(method, str) and isinstance(url, str): |
| 95 | + msg = f"HTTP {method} {url}" |
| 96 | + else: |
| 97 | + msg = f"HTTP {method!r} {url!r}" |
| 98 | + |
| 99 | + if Session.USE_SYSTEM_CERTS: |
| 100 | + msg += " (w/sys_certs)" |
| 101 | + |
| 102 | + json = kwargs.get("json") |
| 103 | + if json is not None: |
| 104 | + t = _truncate(dumps(_sanitize(json))) |
| 105 | + msg += f" JSON={t}" |
| 106 | + |
| 107 | + params = kwargs.get("params") |
| 108 | + if params is not None: |
| 109 | + msg += f" PARAMS={_sanitize(params)}" |
| 110 | + |
| 111 | + headers = kwargs.get("headers") |
| 112 | + if headers is not None: |
| 113 | + msg += f" HEADERS={_sanitize(headers)}" |
| 114 | + |
| 115 | + timeout = kwargs.get("timeout") |
| 116 | + if timeout is not None: |
| 117 | + msg += f" TIMEOUT={timeout}" |
| 118 | + |
| 119 | + msg = msg.replace("\n", "\\n") |
| 120 | + |
| 121 | + LOG.debug(msg) |
| 122 | + |
| 123 | + def _log_debug_response(self, resp: requests.Response): |
| 124 | + if self.disable_logging_response: |
| 125 | + return |
| 126 | + |
| 127 | + if logging.getLogger().getEffectiveLevel() <= logging.DEBUG: |
| 128 | + return |
| 129 | + |
| 130 | + elapsed = resp.elapsed.total_seconds() * 1000 # Convert to milliseconds |
| 131 | + msg = f"HTTP {resp.status_code} {resp.reason} ({elapsed:.0f} ms): {str(_truncate_response_content(resp))}" |
| 132 | + |
| 133 | + LOG.debug(msg) |
| 134 | + |
| 135 | + |
| 136 | +def readable_http_error(ex: requests.HTTPError) -> str: |
| 137 | + return readable_http_response(ex.response) |
| 138 | + |
| 139 | + |
| 140 | +def readable_http_response(resp: requests.Response) -> str: |
| 141 | + return f"{resp.request.method} {resp.url} => {resp.status_code} {resp.reason}: {str(_truncate_response_content(resp))}" |
| 142 | + |
| 143 | + |
| 144 | +@T.overload |
| 145 | +def _truncate(s: bytes, limit: int = 256) -> bytes | str: ... |
| 146 | + |
| 147 | + |
| 148 | +@T.overload |
| 149 | +def _truncate(s: str, limit: int = 256) -> str: ... |
| 150 | + |
| 151 | + |
| 152 | +def _truncate(s, limit=256): |
| 153 | + if limit < len(s): |
| 154 | + if isinstance(s, bytes): |
| 155 | + try: |
| 156 | + s = s.decode("utf-8") |
| 157 | + except UnicodeDecodeError: |
| 158 | + pass |
| 159 | + remaining = len(s) - limit |
| 160 | + if isinstance(s, bytes): |
| 161 | + return s[:limit] + f"...({remaining} bytes truncated)".encode("utf-8") |
| 162 | + else: |
| 163 | + return str(s[:limit]) + f"...({remaining} chars truncated)" |
| 164 | + else: |
| 165 | + return s |
| 166 | + |
| 167 | + |
| 168 | +def _sanitize(headers: T.Mapping[T.Any, T.Any]) -> T.Mapping[T.Any, T.Any]: |
| 169 | + new_headers = {} |
| 170 | + |
| 171 | + for k, v in headers.items(): |
| 172 | + if k.lower() in [ |
| 173 | + "authorization", |
| 174 | + "cookie", |
| 175 | + "x-fb-access-token", |
| 176 | + "access-token", |
| 177 | + "access_token", |
| 178 | + "password", |
| 179 | + "user_upload_token", |
| 180 | + ]: |
| 181 | + new_headers[k] = "[REDACTED]" |
| 182 | + else: |
| 183 | + if isinstance(v, (str, bytes)): |
| 184 | + new_headers[k] = T.cast(T.Any, _truncate(v)) |
| 185 | + else: |
| 186 | + new_headers[k] = v |
| 187 | + |
| 188 | + return new_headers |
| 189 | + |
| 190 | + |
| 191 | +def _truncate_response_content(resp: requests.Response) -> str | bytes: |
| 192 | + try: |
| 193 | + json_data = resp.json() |
| 194 | + except requests.JSONDecodeError: |
| 195 | + if resp.content is not None: |
| 196 | + data = _truncate(resp.content) |
| 197 | + else: |
| 198 | + data = "" |
| 199 | + else: |
| 200 | + if isinstance(json_data, dict): |
| 201 | + data = _truncate(dumps(_sanitize(json_data))) |
| 202 | + else: |
| 203 | + data = _truncate(str(json_data)) |
| 204 | + |
| 205 | + if isinstance(data, bytes): |
| 206 | + return data.replace(b"\n", b"\\n") |
| 207 | + |
| 208 | + elif isinstance(data, str): |
| 209 | + return data.replace("\n", "\\n") |
| 210 | + |
| 211 | + return data |
0 commit comments