environment.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. """
  2. Environments are a way to activate different Python versions or Virtualenvs for
  3. static analysis. The Python binary in that environment is going to be executed.
  4. """
  5. import os
  6. import sys
  7. import hashlib
  8. import filecmp
  9. from collections import namedtuple
  10. from shutil import which
  11. from typing import TYPE_CHECKING
  12. from jedi.cache import memoize_method, time_cache
  13. from jedi.inference.compiled.subprocess import CompiledSubprocess, \
  14. InferenceStateSameProcess, InferenceStateSubprocess
  15. import parso
  16. if TYPE_CHECKING:
  17. from jedi.inference import InferenceState
  18. _VersionInfo = namedtuple('VersionInfo', 'major minor micro') # type: ignore[name-match]
  19. _SUPPORTED_PYTHONS = ['3.13', '3.12', '3.11', '3.10', '3.9', '3.8', '3.7', '3.6']
  20. _SAFE_PATHS = ['/usr/bin', '/usr/local/bin']
  21. _CONDA_VAR = 'CONDA_PREFIX'
  22. _CURRENT_VERSION = '%s.%s' % (sys.version_info.major, sys.version_info.minor)
  23. class InvalidPythonEnvironment(Exception):
  24. """
  25. If you see this exception, the Python executable or Virtualenv you have
  26. been trying to use is probably not a correct Python version.
  27. """
  28. class _BaseEnvironment:
  29. @memoize_method
  30. def get_grammar(self):
  31. version_string = '%s.%s' % (self.version_info.major, self.version_info.minor)
  32. return parso.load_grammar(version=version_string)
  33. @property
  34. def _sha256(self):
  35. try:
  36. return self._hash
  37. except AttributeError:
  38. self._hash = _calculate_sha256_for_file(self.executable)
  39. return self._hash
  40. def _get_info():
  41. return (
  42. sys.executable,
  43. sys.prefix,
  44. sys.version_info[:3],
  45. )
  46. class Environment(_BaseEnvironment):
  47. """
  48. This class is supposed to be created by internal Jedi architecture. You
  49. should not create it directly. Please use create_environment or the other
  50. functions instead. It is then returned by that function.
  51. """
  52. _subprocess = None
  53. def __init__(self, executable, env_vars=None):
  54. self._start_executable = executable
  55. self._env_vars = env_vars
  56. # Initialize the environment
  57. self._get_subprocess()
  58. def _get_subprocess(self):
  59. if self._subprocess is not None and not self._subprocess.is_crashed:
  60. return self._subprocess
  61. try:
  62. self._subprocess = CompiledSubprocess(self._start_executable,
  63. env_vars=self._env_vars)
  64. info = self._subprocess._send(None, _get_info)
  65. except Exception as exc:
  66. raise InvalidPythonEnvironment(
  67. "Could not get version information for %r: %r" % (
  68. self._start_executable,
  69. exc))
  70. # Since it could change and might not be the same(?) as the one given,
  71. # set it here.
  72. self.executable = info[0]
  73. """
  74. The Python executable, matches ``sys.executable``.
  75. """
  76. self.path = info[1]
  77. """
  78. The path to an environment, matches ``sys.prefix``.
  79. """
  80. self.version_info = _VersionInfo(*info[2])
  81. """
  82. Like :data:`sys.version_info`: a tuple to show the current
  83. Environment's Python version.
  84. """
  85. return self._subprocess
  86. def __repr__(self):
  87. version = '.'.join(str(i) for i in self.version_info)
  88. return '<%s: %s in %s>' % (self.__class__.__name__, version, self.path)
  89. def get_inference_state_subprocess(
  90. self,
  91. inference_state: 'InferenceState',
  92. ) -> InferenceStateSubprocess:
  93. return InferenceStateSubprocess(inference_state, self._get_subprocess())
  94. @memoize_method
  95. def get_sys_path(self):
  96. """
  97. The sys path for this environment. Does not include potential
  98. modifications from e.g. appending to :data:`sys.path`.
  99. :returns: list of str
  100. """
  101. # It's pretty much impossible to generate the sys path without actually
  102. # executing Python. The sys path (when starting with -S) itself depends
  103. # on how the Python version was compiled (ENV variables).
  104. # If you omit -S when starting Python (normal case), additionally
  105. # site.py gets executed.
  106. return self._get_subprocess().get_sys_path()
  107. class _SameEnvironmentMixin:
  108. def __init__(self):
  109. self._start_executable = self.executable = sys.executable
  110. self.path = sys.prefix
  111. self.version_info = _VersionInfo(*sys.version_info[:3])
  112. self._env_vars = None
  113. class SameEnvironment(_SameEnvironmentMixin, Environment):
  114. pass
  115. class InterpreterEnvironment(_SameEnvironmentMixin, _BaseEnvironment):
  116. def get_inference_state_subprocess(
  117. self,
  118. inference_state: 'InferenceState',
  119. ) -> InferenceStateSameProcess:
  120. return InferenceStateSameProcess(inference_state)
  121. def get_sys_path(self):
  122. return sys.path
  123. def _get_virtual_env_from_var(env_var='VIRTUAL_ENV'):
  124. """Get virtualenv environment from VIRTUAL_ENV environment variable.
  125. It uses `safe=False` with ``create_environment``, because the environment
  126. variable is considered to be safe / controlled by the user solely.
  127. """
  128. var = os.environ.get(env_var)
  129. if var:
  130. # Under macOS in some cases - notably when using Pipenv - the
  131. # sys.prefix of the virtualenv is /path/to/env/bin/.. instead of
  132. # /path/to/env so we need to fully resolve the paths in order to
  133. # compare them.
  134. if os.path.realpath(var) == os.path.realpath(sys.prefix):
  135. return _try_get_same_env()
  136. try:
  137. return create_environment(var, safe=False)
  138. except InvalidPythonEnvironment:
  139. pass
  140. def _calculate_sha256_for_file(path):
  141. sha256 = hashlib.sha256()
  142. with open(path, 'rb') as f:
  143. for block in iter(lambda: f.read(filecmp.BUFSIZE), b''):
  144. sha256.update(block)
  145. return sha256.hexdigest()
  146. def get_default_environment():
  147. """
  148. Tries to return an active Virtualenv or conda environment.
  149. If there is no VIRTUAL_ENV variable or no CONDA_PREFIX variable set
  150. set it will return the latest Python version installed on the system. This
  151. makes it possible to use as many new Python features as possible when using
  152. autocompletion and other functionality.
  153. :returns: :class:`.Environment`
  154. """
  155. virtual_env = _get_virtual_env_from_var()
  156. if virtual_env is not None:
  157. return virtual_env
  158. conda_env = _get_virtual_env_from_var(_CONDA_VAR)
  159. if conda_env is not None:
  160. return conda_env
  161. return _try_get_same_env()
  162. def _try_get_same_env():
  163. env = SameEnvironment()
  164. if not os.path.basename(env.executable).lower().startswith('python'):
  165. # This tries to counter issues with embedding. In some cases (e.g.
  166. # VIM's Python Mac/Windows, sys.executable is /foo/bar/vim. This
  167. # happens, because for Mac a function called `_NSGetExecutablePath` is
  168. # used and for Windows `GetModuleFileNameW`. These are both platform
  169. # specific functions. For all other systems sys.executable should be
  170. # alright. However here we try to generalize:
  171. #
  172. # 1. Check if the executable looks like python (heuristic)
  173. # 2. In case it's not try to find the executable
  174. # 3. In case we don't find it use an interpreter environment.
  175. #
  176. # The last option will always work, but leads to potential crashes of
  177. # Jedi - which is ok, because it happens very rarely and even less,
  178. # because the code below should work for most cases.
  179. if os.name == 'nt':
  180. # The first case would be a virtualenv and the second a normal
  181. # Python installation.
  182. checks = (r'Scripts\python.exe', 'python.exe')
  183. else:
  184. # For unix it looks like Python is always in a bin folder.
  185. checks = (
  186. 'bin/python%s.%s' % (sys.version_info[0], sys.version[1]),
  187. 'bin/python%s' % (sys.version_info[0]),
  188. 'bin/python',
  189. )
  190. for check in checks:
  191. guess = os.path.join(sys.exec_prefix, check)
  192. if os.path.isfile(guess):
  193. # Bingo - We think we have our Python.
  194. return Environment(guess)
  195. # It looks like there is no reasonable Python to be found.
  196. return InterpreterEnvironment()
  197. # If no virtualenv is found, use the environment we're already
  198. # using.
  199. return env
  200. def get_cached_default_environment():
  201. var = os.environ.get('VIRTUAL_ENV') or os.environ.get(_CONDA_VAR)
  202. environment = _get_cached_default_environment()
  203. # Under macOS in some cases - notably when using Pipenv - the
  204. # sys.prefix of the virtualenv is /path/to/env/bin/.. instead of
  205. # /path/to/env so we need to fully resolve the paths in order to
  206. # compare them.
  207. if var and os.path.realpath(var) != os.path.realpath(environment.path):
  208. _get_cached_default_environment.clear_cache()
  209. return _get_cached_default_environment()
  210. return environment
  211. @time_cache(seconds=10 * 60) # 10 Minutes
  212. def _get_cached_default_environment():
  213. try:
  214. return get_default_environment()
  215. except InvalidPythonEnvironment:
  216. # It's possible that `sys.executable` is wrong. Typically happens
  217. # when Jedi is used in an executable that embeds Python. For further
  218. # information, have a look at:
  219. # https://github.com/davidhalter/jedi/issues/1531
  220. return InterpreterEnvironment()
  221. def find_virtualenvs(paths=None, *, safe=True, use_environment_vars=True):
  222. """
  223. :param paths: A list of paths in your file system to be scanned for
  224. Virtualenvs. It will search in these paths and potentially execute the
  225. Python binaries.
  226. :param safe: Default True. In case this is False, it will allow this
  227. function to execute potential `python` environments. An attacker might
  228. be able to drop an executable in a path this function is searching by
  229. default. If the executable has not been installed by root, it will not
  230. be executed.
  231. :param use_environment_vars: Default True. If True, the VIRTUAL_ENV
  232. variable will be checked if it contains a valid VirtualEnv.
  233. CONDA_PREFIX will be checked to see if it contains a valid conda
  234. environment.
  235. :yields: :class:`.Environment`
  236. """
  237. if paths is None:
  238. paths = []
  239. _used_paths = set()
  240. if use_environment_vars:
  241. # Using this variable should be safe, because attackers might be
  242. # able to drop files (via git) but not environment variables.
  243. virtual_env = _get_virtual_env_from_var()
  244. if virtual_env is not None:
  245. yield virtual_env
  246. _used_paths.add(virtual_env.path)
  247. conda_env = _get_virtual_env_from_var(_CONDA_VAR)
  248. if conda_env is not None:
  249. yield conda_env
  250. _used_paths.add(conda_env.path)
  251. for directory in paths:
  252. if not os.path.isdir(directory):
  253. continue
  254. directory = os.path.abspath(directory)
  255. for path in os.listdir(directory):
  256. path = os.path.join(directory, path)
  257. if path in _used_paths:
  258. # A path shouldn't be inferred twice.
  259. continue
  260. _used_paths.add(path)
  261. try:
  262. executable = _get_executable_path(path, safe=safe)
  263. yield Environment(executable)
  264. except InvalidPythonEnvironment:
  265. pass
  266. def find_system_environments(*, env_vars=None):
  267. """
  268. Ignores virtualenvs and returns the Python versions that were installed on
  269. your system. This might return nothing, if you're running Python e.g. from
  270. a portable version.
  271. The environments are sorted from latest to oldest Python version.
  272. :yields: :class:`.Environment`
  273. """
  274. for version_string in _SUPPORTED_PYTHONS:
  275. try:
  276. yield get_system_environment(version_string, env_vars=env_vars)
  277. except InvalidPythonEnvironment:
  278. pass
  279. # TODO: this function should probably return a list of environments since
  280. # multiple Python installations can be found on a system for the same version.
  281. def get_system_environment(version, *, env_vars=None):
  282. """
  283. Return the first Python environment found for a string of the form 'X.Y'
  284. where X and Y are the major and minor versions of Python.
  285. :raises: :exc:`.InvalidPythonEnvironment`
  286. :returns: :class:`.Environment`
  287. """
  288. exe = which('python' + version)
  289. if exe:
  290. if exe == sys.executable:
  291. return SameEnvironment()
  292. return Environment(exe)
  293. if os.name == 'nt':
  294. for exe in _get_executables_from_windows_registry(version):
  295. try:
  296. return Environment(exe, env_vars=env_vars)
  297. except InvalidPythonEnvironment:
  298. pass
  299. raise InvalidPythonEnvironment("Cannot find executable python%s." % version)
  300. def create_environment(path, *, safe=True, env_vars=None):
  301. """
  302. Make it possible to manually create an Environment object by specifying a
  303. Virtualenv path or an executable path and optional environment variables.
  304. :raises: :exc:`.InvalidPythonEnvironment`
  305. :returns: :class:`.Environment`
  306. """
  307. if os.path.isfile(path):
  308. _assert_safe(path, safe)
  309. return Environment(path, env_vars=env_vars)
  310. return Environment(_get_executable_path(path, safe=safe), env_vars=env_vars)
  311. def _get_executable_path(path, safe=True):
  312. """
  313. Returns None if it's not actually a virtual env.
  314. """
  315. if os.name == 'nt':
  316. pythons = [os.path.join(path, 'Scripts', 'python.exe'), os.path.join(path, 'python.exe')]
  317. else:
  318. pythons = [os.path.join(path, 'bin', 'python')]
  319. for python in pythons:
  320. if os.path.exists(python):
  321. break
  322. else:
  323. raise InvalidPythonEnvironment("%s seems to be missing." % python)
  324. _assert_safe(python, safe)
  325. return python
  326. def _get_executables_from_windows_registry(version):
  327. import winreg
  328. # TODO: support Python Anaconda.
  329. sub_keys = [
  330. r'SOFTWARE\Python\PythonCore\{version}\InstallPath',
  331. r'SOFTWARE\Wow6432Node\Python\PythonCore\{version}\InstallPath',
  332. r'SOFTWARE\Python\PythonCore\{version}-32\InstallPath',
  333. r'SOFTWARE\Wow6432Node\Python\PythonCore\{version}-32\InstallPath'
  334. ]
  335. for root_key in [winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE]:
  336. for sub_key in sub_keys:
  337. sub_key = sub_key.format(version=version)
  338. try:
  339. with winreg.OpenKey(root_key, sub_key) as key:
  340. prefix = winreg.QueryValueEx(key, '')[0]
  341. exe = os.path.join(prefix, 'python.exe')
  342. if os.path.isfile(exe):
  343. yield exe
  344. except WindowsError:
  345. pass
  346. def _assert_safe(executable_path, safe):
  347. if safe and not _is_safe(executable_path):
  348. raise InvalidPythonEnvironment(
  349. "The python binary is potentially unsafe.")
  350. def _is_safe(executable_path):
  351. # Resolve sym links. A venv typically is a symlink to a known Python
  352. # binary. Only virtualenvs copy symlinks around.
  353. real_path = os.path.realpath(executable_path)
  354. if _is_unix_safe_simple(real_path):
  355. return True
  356. # Just check the list of known Python versions. If it's not in there,
  357. # it's likely an attacker or some Python that was not properly
  358. # installed in the system.
  359. for environment in find_system_environments():
  360. if environment.executable == real_path:
  361. return True
  362. # If the versions don't match, just compare the binary files. If we
  363. # don't do that, only venvs will be working and not virtualenvs.
  364. # venvs are symlinks while virtualenvs are actual copies of the
  365. # Python files.
  366. # This still means that if the system Python is updated and the
  367. # virtualenv's Python is not (which is probably never going to get
  368. # upgraded), it will not work with Jedi. IMO that's fine, because
  369. # people should just be using venv. ~ dave
  370. if environment._sha256 == _calculate_sha256_for_file(real_path):
  371. return True
  372. return False
  373. def _is_unix_safe_simple(real_path):
  374. if _is_unix_admin():
  375. # In case we are root, just be conservative and
  376. # only execute known paths.
  377. return any(real_path.startswith(p) for p in _SAFE_PATHS)
  378. uid = os.stat(real_path).st_uid
  379. # The interpreter needs to be owned by root. This means that it wasn't
  380. # written by a user and therefore attacking Jedi is not as simple.
  381. # The attack could look like the following:
  382. # 1. A user clones a repository.
  383. # 2. The repository has an innocent looking folder called foobar. jedi
  384. # searches for the folder and executes foobar/bin/python --version if
  385. # there's also a foobar/bin/activate.
  386. # 3. The attacker has gained code execution, since he controls
  387. # foobar/bin/python.
  388. return uid == 0
  389. def _is_unix_admin():
  390. try:
  391. return os.getuid() == 0
  392. except AttributeError:
  393. return False # Windows