session.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. """PipSession and supporting code, containing all pip-specific
  2. network request configuration and behavior.
  3. """
  4. import email.utils
  5. import io
  6. import ipaddress
  7. import json
  8. import logging
  9. import mimetypes
  10. import os
  11. import platform
  12. import shutil
  13. import subprocess
  14. import sys
  15. import urllib.parse
  16. import warnings
  17. from typing import (
  18. TYPE_CHECKING,
  19. Any,
  20. Dict,
  21. Generator,
  22. List,
  23. Mapping,
  24. Optional,
  25. Sequence,
  26. Tuple,
  27. Union,
  28. )
  29. from pip._vendor import requests, urllib3
  30. from pip._vendor.cachecontrol import CacheControlAdapter as _BaseCacheControlAdapter
  31. from pip._vendor.requests.adapters import DEFAULT_POOLBLOCK, BaseAdapter
  32. from pip._vendor.requests.adapters import HTTPAdapter as _BaseHTTPAdapter
  33. from pip._vendor.requests.models import PreparedRequest, Response
  34. from pip._vendor.requests.structures import CaseInsensitiveDict
  35. from pip._vendor.urllib3.connectionpool import ConnectionPool
  36. from pip._vendor.urllib3.exceptions import InsecureRequestWarning
  37. from pip import __version__
  38. from pip._internal.metadata import get_default_environment
  39. from pip._internal.models.link import Link
  40. from pip._internal.network.auth import MultiDomainBasicAuth
  41. from pip._internal.network.cache import SafeFileCache
  42. # Import ssl from compat so the initial import occurs in only one place.
  43. from pip._internal.utils.compat import has_tls
  44. from pip._internal.utils.glibc import libc_ver
  45. from pip._internal.utils.misc import build_url_from_netloc, parse_netloc
  46. from pip._internal.utils.urls import url_to_path
  47. if TYPE_CHECKING:
  48. from ssl import SSLContext
  49. from pip._vendor.urllib3.poolmanager import PoolManager
  50. logger = logging.getLogger(__name__)
  51. SecureOrigin = Tuple[str, str, Optional[Union[int, str]]]
  52. # Ignore warning raised when using --trusted-host.
  53. warnings.filterwarnings("ignore", category=InsecureRequestWarning)
  54. SECURE_ORIGINS: List[SecureOrigin] = [
  55. # protocol, hostname, port
  56. # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)
  57. ("https", "*", "*"),
  58. ("*", "localhost", "*"),
  59. ("*", "127.0.0.0/8", "*"),
  60. ("*", "::1/128", "*"),
  61. ("file", "*", None),
  62. # ssh is always secure.
  63. ("ssh", "*", "*"),
  64. ]
  65. # These are environment variables present when running under various
  66. # CI systems. For each variable, some CI systems that use the variable
  67. # are indicated. The collection was chosen so that for each of a number
  68. # of popular systems, at least one of the environment variables is used.
  69. # This list is used to provide some indication of and lower bound for
  70. # CI traffic to PyPI. Thus, it is okay if the list is not comprehensive.
  71. # For more background, see: https://github.com/pypa/pip/issues/5499
  72. CI_ENVIRONMENT_VARIABLES = (
  73. # Azure Pipelines
  74. "BUILD_BUILDID",
  75. # Jenkins
  76. "BUILD_ID",
  77. # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI
  78. "CI",
  79. # Explicit environment variable.
  80. "PIP_IS_CI",
  81. )
  82. def looks_like_ci() -> bool:
  83. """
  84. Return whether it looks like pip is running under CI.
  85. """
  86. # We don't use the method of checking for a tty (e.g. using isatty())
  87. # because some CI systems mimic a tty (e.g. Travis CI). Thus that
  88. # method doesn't provide definitive information in either direction.
  89. return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES)
  90. def user_agent() -> str:
  91. """
  92. Return a string representing the user agent.
  93. """
  94. data: Dict[str, Any] = {
  95. "installer": {"name": "pip", "version": __version__},
  96. "python": platform.python_version(),
  97. "implementation": {
  98. "name": platform.python_implementation(),
  99. },
  100. }
  101. if data["implementation"]["name"] == "CPython":
  102. data["implementation"]["version"] = platform.python_version()
  103. elif data["implementation"]["name"] == "PyPy":
  104. pypy_version_info = sys.pypy_version_info # type: ignore
  105. if pypy_version_info.releaselevel == "final":
  106. pypy_version_info = pypy_version_info[:3]
  107. data["implementation"]["version"] = ".".join(
  108. [str(x) for x in pypy_version_info]
  109. )
  110. elif data["implementation"]["name"] == "Jython":
  111. # Complete Guess
  112. data["implementation"]["version"] = platform.python_version()
  113. elif data["implementation"]["name"] == "IronPython":
  114. # Complete Guess
  115. data["implementation"]["version"] = platform.python_version()
  116. if sys.platform.startswith("linux"):
  117. from pip._vendor import distro
  118. linux_distribution = distro.name(), distro.version(), distro.codename()
  119. distro_infos: Dict[str, Any] = dict(
  120. filter(
  121. lambda x: x[1],
  122. zip(["name", "version", "id"], linux_distribution),
  123. )
  124. )
  125. libc = dict(
  126. filter(
  127. lambda x: x[1],
  128. zip(["lib", "version"], libc_ver()),
  129. )
  130. )
  131. if libc:
  132. distro_infos["libc"] = libc
  133. if distro_infos:
  134. data["distro"] = distro_infos
  135. if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
  136. data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}
  137. if platform.system():
  138. data.setdefault("system", {})["name"] = platform.system()
  139. if platform.release():
  140. data.setdefault("system", {})["release"] = platform.release()
  141. if platform.machine():
  142. data["cpu"] = platform.machine()
  143. if has_tls():
  144. import _ssl as ssl
  145. data["openssl_version"] = ssl.OPENSSL_VERSION
  146. setuptools_dist = get_default_environment().get_distribution("setuptools")
  147. if setuptools_dist is not None:
  148. data["setuptools_version"] = str(setuptools_dist.version)
  149. if shutil.which("rustc") is not None:
  150. # If for any reason `rustc --version` fails, silently ignore it
  151. try:
  152. rustc_output = subprocess.check_output(
  153. ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5
  154. )
  155. except Exception:
  156. pass
  157. else:
  158. if rustc_output.startswith(b"rustc "):
  159. # The format of `rustc --version` is:
  160. # `b'rustc 1.52.1 (9bc8c42bb 2021-05-09)\n'`
  161. # We extract just the middle (1.52.1) part
  162. data["rustc_version"] = rustc_output.split(b" ")[1].decode()
  163. # Use None rather than False so as not to give the impression that
  164. # pip knows it is not being run under CI. Rather, it is a null or
  165. # inconclusive result. Also, we include some value rather than no
  166. # value to make it easier to know that the check has been run.
  167. data["ci"] = True if looks_like_ci() else None
  168. user_data = os.environ.get("PIP_USER_AGENT_USER_DATA")
  169. if user_data is not None:
  170. data["user_data"] = user_data
  171. return "{data[installer][name]}/{data[installer][version]} {json}".format(
  172. data=data,
  173. json=json.dumps(data, separators=(",", ":"), sort_keys=True),
  174. )
  175. class LocalFSAdapter(BaseAdapter):
  176. def send(
  177. self,
  178. request: PreparedRequest,
  179. stream: bool = False,
  180. timeout: Optional[Union[float, Tuple[float, float]]] = None,
  181. verify: Union[bool, str] = True,
  182. cert: Optional[Union[str, Tuple[str, str]]] = None,
  183. proxies: Optional[Mapping[str, str]] = None,
  184. ) -> Response:
  185. pathname = url_to_path(request.url)
  186. resp = Response()
  187. resp.status_code = 200
  188. resp.url = request.url
  189. try:
  190. stats = os.stat(pathname)
  191. except OSError as exc:
  192. # format the exception raised as a io.BytesIO object,
  193. # to return a better error message:
  194. resp.status_code = 404
  195. resp.reason = type(exc).__name__
  196. resp.raw = io.BytesIO(f"{resp.reason}: {exc}".encode("utf8"))
  197. else:
  198. modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
  199. content_type = mimetypes.guess_type(pathname)[0] or "text/plain"
  200. resp.headers = CaseInsensitiveDict(
  201. {
  202. "Content-Type": content_type,
  203. "Content-Length": stats.st_size,
  204. "Last-Modified": modified,
  205. }
  206. )
  207. resp.raw = open(pathname, "rb")
  208. resp.close = resp.raw.close
  209. return resp
  210. def close(self) -> None:
  211. pass
  212. class _SSLContextAdapterMixin:
  213. """Mixin to add the ``ssl_context`` constructor argument to HTTP adapters.
  214. The additional argument is forwarded directly to the pool manager. This allows us
  215. to dynamically decide what SSL store to use at runtime, which is used to implement
  216. the optional ``truststore`` backend.
  217. """
  218. def __init__(
  219. self,
  220. *,
  221. ssl_context: Optional["SSLContext"] = None,
  222. **kwargs: Any,
  223. ) -> None:
  224. self._ssl_context = ssl_context
  225. super().__init__(**kwargs)
  226. def init_poolmanager(
  227. self,
  228. connections: int,
  229. maxsize: int,
  230. block: bool = DEFAULT_POOLBLOCK,
  231. **pool_kwargs: Any,
  232. ) -> "PoolManager":
  233. if self._ssl_context is not None:
  234. pool_kwargs.setdefault("ssl_context", self._ssl_context)
  235. return super().init_poolmanager( # type: ignore[misc]
  236. connections=connections,
  237. maxsize=maxsize,
  238. block=block,
  239. **pool_kwargs,
  240. )
  241. class HTTPAdapter(_SSLContextAdapterMixin, _BaseHTTPAdapter):
  242. pass
  243. class CacheControlAdapter(_SSLContextAdapterMixin, _BaseCacheControlAdapter):
  244. pass
  245. class InsecureHTTPAdapter(HTTPAdapter):
  246. def cert_verify(
  247. self,
  248. conn: ConnectionPool,
  249. url: str,
  250. verify: Union[bool, str],
  251. cert: Optional[Union[str, Tuple[str, str]]],
  252. ) -> None:
  253. super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
  254. class InsecureCacheControlAdapter(CacheControlAdapter):
  255. def cert_verify(
  256. self,
  257. conn: ConnectionPool,
  258. url: str,
  259. verify: Union[bool, str],
  260. cert: Optional[Union[str, Tuple[str, str]]],
  261. ) -> None:
  262. super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
  263. class PipSession(requests.Session):
  264. timeout: Optional[int] = None
  265. def __init__(
  266. self,
  267. *args: Any,
  268. retries: int = 0,
  269. cache: Optional[str] = None,
  270. trusted_hosts: Sequence[str] = (),
  271. index_urls: Optional[List[str]] = None,
  272. ssl_context: Optional["SSLContext"] = None,
  273. **kwargs: Any,
  274. ) -> None:
  275. """
  276. :param trusted_hosts: Domains not to emit warnings for when not using
  277. HTTPS.
  278. """
  279. super().__init__(*args, **kwargs)
  280. # Namespace the attribute with "pip_" just in case to prevent
  281. # possible conflicts with the base class.
  282. self.pip_trusted_origins: List[Tuple[str, Optional[int]]] = []
  283. # Attach our User Agent to the request
  284. self.headers["User-Agent"] = user_agent()
  285. # Attach our Authentication handler to the session
  286. self.auth = MultiDomainBasicAuth(index_urls=index_urls)
  287. # Create our urllib3.Retry instance which will allow us to customize
  288. # how we handle retries.
  289. retries = urllib3.Retry(
  290. # Set the total number of retries that a particular request can
  291. # have.
  292. total=retries,
  293. # A 503 error from PyPI typically means that the Fastly -> Origin
  294. # connection got interrupted in some way. A 503 error in general
  295. # is typically considered a transient error so we'll go ahead and
  296. # retry it.
  297. # A 500 may indicate transient error in Amazon S3
  298. # A 520 or 527 - may indicate transient error in CloudFlare
  299. status_forcelist=[500, 503, 520, 527],
  300. # Add a small amount of back off between failed requests in
  301. # order to prevent hammering the service.
  302. backoff_factor=0.25,
  303. ) # type: ignore
  304. # Our Insecure HTTPAdapter disables HTTPS validation. It does not
  305. # support caching so we'll use it for all http:// URLs.
  306. # If caching is disabled, we will also use it for
  307. # https:// hosts that we've marked as ignoring
  308. # TLS errors for (trusted-hosts).
  309. insecure_adapter = InsecureHTTPAdapter(max_retries=retries)
  310. # We want to _only_ cache responses on securely fetched origins or when
  311. # the host is specified as trusted. We do this because
  312. # we can't validate the response of an insecurely/untrusted fetched
  313. # origin, and we don't want someone to be able to poison the cache and
  314. # require manual eviction from the cache to fix it.
  315. if cache:
  316. secure_adapter = CacheControlAdapter(
  317. cache=SafeFileCache(cache),
  318. max_retries=retries,
  319. ssl_context=ssl_context,
  320. )
  321. self._trusted_host_adapter = InsecureCacheControlAdapter(
  322. cache=SafeFileCache(cache),
  323. max_retries=retries,
  324. )
  325. else:
  326. secure_adapter = HTTPAdapter(max_retries=retries, ssl_context=ssl_context)
  327. self._trusted_host_adapter = insecure_adapter
  328. self.mount("https://", secure_adapter)
  329. self.mount("http://", insecure_adapter)
  330. # Enable file:// urls
  331. self.mount("file://", LocalFSAdapter())
  332. for host in trusted_hosts:
  333. self.add_trusted_host(host, suppress_logging=True)
  334. def update_index_urls(self, new_index_urls: List[str]) -> None:
  335. """
  336. :param new_index_urls: New index urls to update the authentication
  337. handler with.
  338. """
  339. self.auth.index_urls = new_index_urls
  340. def add_trusted_host(
  341. self, host: str, source: Optional[str] = None, suppress_logging: bool = False
  342. ) -> None:
  343. """
  344. :param host: It is okay to provide a host that has previously been
  345. added.
  346. :param source: An optional source string, for logging where the host
  347. string came from.
  348. """
  349. if not suppress_logging:
  350. msg = f"adding trusted host: {host!r}"
  351. if source is not None:
  352. msg += f" (from {source})"
  353. logger.info(msg)
  354. host_port = parse_netloc(host)
  355. if host_port not in self.pip_trusted_origins:
  356. self.pip_trusted_origins.append(host_port)
  357. self.mount(
  358. build_url_from_netloc(host, scheme="http") + "/", self._trusted_host_adapter
  359. )
  360. self.mount(build_url_from_netloc(host) + "/", self._trusted_host_adapter)
  361. if not host_port[1]:
  362. self.mount(
  363. build_url_from_netloc(host, scheme="http") + ":",
  364. self._trusted_host_adapter,
  365. )
  366. # Mount wildcard ports for the same host.
  367. self.mount(build_url_from_netloc(host) + ":", self._trusted_host_adapter)
  368. def iter_secure_origins(self) -> Generator[SecureOrigin, None, None]:
  369. yield from SECURE_ORIGINS
  370. for host, port in self.pip_trusted_origins:
  371. yield ("*", host, "*" if port is None else port)
  372. def is_secure_origin(self, location: Link) -> bool:
  373. # Determine if this url used a secure transport mechanism
  374. parsed = urllib.parse.urlparse(str(location))
  375. origin_protocol, origin_host, origin_port = (
  376. parsed.scheme,
  377. parsed.hostname,
  378. parsed.port,
  379. )
  380. # The protocol to use to see if the protocol matches.
  381. # Don't count the repository type as part of the protocol: in
  382. # cases such as "git+ssh", only use "ssh". (I.e., Only verify against
  383. # the last scheme.)
  384. origin_protocol = origin_protocol.rsplit("+", 1)[-1]
  385. # Determine if our origin is a secure origin by looking through our
  386. # hardcoded list of secure origins, as well as any additional ones
  387. # configured on this PackageFinder instance.
  388. for secure_origin in self.iter_secure_origins():
  389. secure_protocol, secure_host, secure_port = secure_origin
  390. if origin_protocol != secure_protocol and secure_protocol != "*":
  391. continue
  392. try:
  393. addr = ipaddress.ip_address(origin_host or "")
  394. network = ipaddress.ip_network(secure_host)
  395. except ValueError:
  396. # We don't have both a valid address or a valid network, so
  397. # we'll check this origin against hostnames.
  398. if (
  399. origin_host
  400. and origin_host.lower() != secure_host.lower()
  401. and secure_host != "*"
  402. ):
  403. continue
  404. else:
  405. # We have a valid address and network, so see if the address
  406. # is contained within the network.
  407. if addr not in network:
  408. continue
  409. # Check to see if the port matches.
  410. if (
  411. origin_port != secure_port
  412. and secure_port != "*"
  413. and secure_port is not None
  414. ):
  415. continue
  416. # If we've gotten here, then this origin matches the current
  417. # secure origin and we should return True
  418. return True
  419. # If we've gotten to this point, then the origin isn't secure and we
  420. # will not accept it as a valid location to search. We will however
  421. # log a warning that we are ignoring it.
  422. logger.warning(
  423. "The repository located at %s is not a trusted or secure host and "
  424. "is being ignored. If this repository is available via HTTPS we "
  425. "recommend you use HTTPS instead, otherwise you may silence "
  426. "this warning and allow it anyway with '--trusted-host %s'.",
  427. origin_host,
  428. origin_host,
  429. )
  430. return False
  431. def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Response:
  432. # Allow setting a default timeout on a session
  433. kwargs.setdefault("timeout", self.timeout)
  434. # Allow setting a default proxies on a session
  435. kwargs.setdefault("proxies", self.proxies)
  436. # Dispatch the actual request
  437. return super().request(method, url, *args, **kwargs)