From 7c2ba4a181c65cf408466f7f4b9738a7c3c6cca1 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Mon, 26 Oct 2026 22:02:50 -0700 Subject: [PATCH] gh-160279: Keep the venv directory off the import path when running pip (GH-160282) (cherry picked from commit d9825d504ad738a5160d3c3ecd8cd575a1713e98) Co-authored-by: Jelle Zijlstra --- Lib/test/test_venv.py | 6 ++++++ Lib/venv/__init__.py | 7 ++++--- .../2026-10-22-11-09-30.gh-issue-160279.9BtxeF.rst | 2 ++ 3 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 Misc/NEWS.d/next/Security/2026-10-22-11-09-30.gh-issue-160279.9BtxeF.rst diff --git a/Lib/test/test_venv.py b/Lib/test/test_venv.py index 4b7860e757d79ff..c5ef907fbfa7190 100644 --- a/Lib/test/test_venv.py +++ b/Lib/test/test_venv.py @@ -1003,7 +1003,13 @@ def test_devnull(self): def do_test_with_pip(self, system_site_packages): rmtree(self.env_dir) + os.mkdir(self.env_dir) + # Both ensurepip and its pip subprocess run with the venv as cwd. + for name in ('ensurepip.py', 'subprocess.py'): + pathlib.Path(self.env_dir, name).write_text( + 'raise AssertionError(__file__)\n', encoding='utf-8') with EnvironmentVarGuard() as envvars: + envvars["PYTHONSAFEPATH"] = "" # pip's cross-version compatibility may trigger deprecation # warnings in current versions of Python. Ensure related # environment settings don't cause venv to fail. diff --git a/Lib/venv/__init__.py b/Lib/venv/__init__.py index 0653a43a8b17766..e2c5aebeb73bf5f 100644 --- a/Lib/venv/__init__.py +++ b/Lib/venv/__init__.py @@ -437,14 +437,15 @@ def setup_python(self, context): def _call_new_python(self, context, *py_args, **kwargs): """Executes the newly created Python using safe-ish options""" # gh-98251: We do not want to just use '-I' because that masks - # legitimate user preferences (such as not writing bytecode). All we - # really need is to ensure that the path variables do not overrule - # normal venv handling. + # legitimate user preferences (such as not writing bytecode). args = [context.env_exec_cmd, *py_args] kwargs['env'] = env = os.environ.copy() env['VIRTUAL_ENV'] = context.env_dir env.pop('PYTHONHOME', None) env.pop('PYTHONPATH', None) + # Keep the working directory off sys.path, including in the + # subprocess that ensurepip starts to run pip. + env['PYTHONSAFEPATH'] = '1' kwargs['cwd'] = context.env_dir kwargs['executable'] = context.env_exec_cmd subprocess.check_output(args, **kwargs) diff --git a/Misc/NEWS.d/next/Security/2026-10-22-11-09-30.gh-issue-160279.9BtxeF.rst b/Misc/NEWS.d/next/Security/2026-10-22-11-09-30.gh-issue-160279.9BtxeF.rst new file mode 100644 index 000000000000000..d143e742f52b0e1 --- /dev/null +++ b/Misc/NEWS.d/next/Security/2026-10-22-11-09-30.gh-issue-160279.9BtxeF.rst @@ -0,0 +1,2 @@ +Prevent :mod:`venv` from importing modules from the root of an existing +virtual environment when installing or upgrading pip.