session.py 16 KB

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