session.py 16 KB

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