diff --git a/Lib/test/test_venv.py b/Lib/test/test_venv.py index 4b7860e757d79f..c5ef907fbfa719 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 0653a43a8b1776..e2c5aebeb73bf5 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 00000000000000..d143e742f52b0e --- /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.