Skip to content

Commit 9286ab3

Browse files
authored
[3.10] gh-124651: Quote template strings in venv activation scripts (GH-124712) (GH-126185) (GH-126269) (GH-126300)
(cherry picked from commit ae961ae)
1 parent 6a2f12a commit 9286ab3

File tree

7 files changed

+134
-20
lines changed

7 files changed

+134
-20
lines changed

Lib/test/test_venv.py

+81
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import subprocess
1616
import sys
1717
import tempfile
18+
import shlex
1819
from test.support import (captured_stdout, captured_stderr, requires_zlib,
1920
skip_if_broken_multiprocessing_synchronize)
2021
from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree)
@@ -85,6 +86,10 @@ def get_text_file_contents(self, *args, encoding='utf-8'):
8586
result = f.read()
8687
return result
8788

89+
def assertEndsWith(self, string, tail):
90+
if not string.endswith(tail):
91+
self.fail(f"String {string!r} does not end with {tail!r}")
92+
8893
class BasicTest(BaseTest):
8994
"""Test venv module functionality."""
9095

@@ -342,6 +347,82 @@ def test_executable_symlinks(self):
342347
'import sys; print(sys.executable)'])
343348
self.assertEqual(out.strip(), envpy.encode())
344349

350+
# gh-124651: test quoted strings
351+
@unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
352+
def test_special_chars_bash(self):
353+
"""
354+
Test that the template strings are quoted properly (bash)
355+
"""
356+
rmtree(self.env_dir)
357+
bash = shutil.which('bash')
358+
if bash is None:
359+
self.skipTest('bash required for this test')
360+
env_name = '"\';&&$e|\'"'
361+
env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
362+
builder = venv.EnvBuilder(clear=True)
363+
builder.create(env_dir)
364+
activate = os.path.join(env_dir, self.bindir, 'activate')
365+
test_script = os.path.join(self.env_dir, 'test_special_chars.sh')
366+
with open(test_script, "w") as f:
367+
f.write(f'source {shlex.quote(activate)}\n'
368+
'python -c \'import sys; print(sys.executable)\'\n'
369+
'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
370+
'deactivate\n')
371+
out, err = check_output([bash, test_script])
372+
lines = out.splitlines()
373+
self.assertTrue(env_name.encode() in lines[0])
374+
self.assertEndsWith(lines[1], env_name.encode())
375+
376+
# gh-124651: test quoted strings
377+
@unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
378+
def test_special_chars_csh(self):
379+
"""
380+
Test that the template strings are quoted properly (csh)
381+
"""
382+
rmtree(self.env_dir)
383+
csh = shutil.which('tcsh') or shutil.which('csh')
384+
if csh is None:
385+
self.skipTest('csh required for this test')
386+
env_name = '"\';&&$e|\'"'
387+
env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
388+
builder = venv.EnvBuilder(clear=True)
389+
builder.create(env_dir)
390+
activate = os.path.join(env_dir, self.bindir, 'activate.csh')
391+
test_script = os.path.join(self.env_dir, 'test_special_chars.csh')
392+
with open(test_script, "w") as f:
393+
f.write(f'source {shlex.quote(activate)}\n'
394+
'python -c \'import sys; print(sys.executable)\'\n'
395+
'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
396+
'deactivate\n')
397+
out, err = check_output([csh, test_script])
398+
lines = out.splitlines()
399+
self.assertTrue(env_name.encode() in lines[0])
400+
self.assertEndsWith(lines[1], env_name.encode())
401+
402+
# gh-124651: test quoted strings on Windows
403+
@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
404+
def test_special_chars_windows(self):
405+
"""
406+
Test that the template strings are quoted properly on Windows
407+
"""
408+
rmtree(self.env_dir)
409+
env_name = "'&&^$e"
410+
env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
411+
builder = venv.EnvBuilder(clear=True)
412+
builder.create(env_dir)
413+
activate = os.path.join(env_dir, self.bindir, 'activate.bat')
414+
test_batch = os.path.join(self.env_dir, 'test_special_chars.bat')
415+
with open(test_batch, "w") as f:
416+
f.write('@echo off\n'
417+
f'"{activate}" & '
418+
f'{self.exe} -c "import sys; print(sys.executable)" & '
419+
f'{self.exe} -c "import os; print(os.environ[\'VIRTUAL_ENV\'])" & '
420+
'deactivate')
421+
out, err = check_output([test_batch])
422+
lines = out.splitlines()
423+
self.assertTrue(env_name.encode() in lines[0])
424+
self.assertEndsWith(lines[1], env_name.encode())
425+
345426
@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
346427
def test_unicode_in_batch_file(self):
347428
"""

Lib/venv/__init__.py

+37-5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import sys
1212
import sysconfig
1313
import types
14+
import shlex
1415

1516

1617
CORE_VENV_DEPS = ('pip', 'setuptools')
@@ -364,11 +365,41 @@ def replace_variables(self, text, context):
364365
:param context: The information for the environment creation request
365366
being processed.
366367
"""
367-
text = text.replace('__VENV_DIR__', context.env_dir)
368-
text = text.replace('__VENV_NAME__', context.env_name)
369-
text = text.replace('__VENV_PROMPT__', context.prompt)
370-
text = text.replace('__VENV_BIN_NAME__', context.bin_name)
371-
text = text.replace('__VENV_PYTHON__', context.env_exe)
368+
replacements = {
369+
'__VENV_DIR__': context.env_dir,
370+
'__VENV_NAME__': context.env_name,
371+
'__VENV_PROMPT__': context.prompt,
372+
'__VENV_BIN_NAME__': context.bin_name,
373+
'__VENV_PYTHON__': context.env_exe,
374+
}
375+
376+
def quote_ps1(s):
377+
"""
378+
This should satisfy PowerShell quoting rules [1], unless the quoted
379+
string is passed directly to Windows native commands [2].
380+
[1]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules
381+
[2]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing#passing-arguments-that-contain-quote-characters
382+
"""
383+
s = s.replace("'", "''")
384+
return f"'{s}'"
385+
386+
def quote_bat(s):
387+
return s
388+
389+
# gh-124651: need to quote the template strings properly
390+
quote = shlex.quote
391+
script_path = context.script_path
392+
if script_path.endswith('.ps1'):
393+
quote = quote_ps1
394+
elif script_path.endswith('.bat'):
395+
quote = quote_bat
396+
else:
397+
# fallbacks to POSIX shell compliant quote
398+
quote = shlex.quote
399+
400+
replacements = {key: quote(s) for key, s in replacements.items()}
401+
for key, quoted in replacements.items():
402+
text = text.replace(key, quoted)
372403
return text
373404

374405
def install_scripts(self, context, path):
@@ -408,6 +439,7 @@ def install_scripts(self, context, path):
408439
with open(srcfile, 'rb') as f:
409440
data = f.read()
410441
if not srcfile.endswith(('.exe', '.pdb')):
442+
context.script_path = srcfile
411443
try:
412444
data = data.decode('utf-8')
413445
data = self.replace_variables(data, context)

Lib/venv/scripts/common/activate

+4-4
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,11 @@ deactivate () {
3838
# unset irrelevant variables
3939
deactivate nondestructive
4040

41-
VIRTUAL_ENV="__VENV_DIR__"
41+
VIRTUAL_ENV=__VENV_DIR__
4242
export VIRTUAL_ENV
4343

4444
_OLD_VIRTUAL_PATH="$PATH"
45-
PATH="$VIRTUAL_ENV/__VENV_BIN_NAME__:$PATH"
45+
PATH="$VIRTUAL_ENV/"__VENV_BIN_NAME__":$PATH"
4646
export PATH
4747

4848
# unset PYTHONHOME if set
@@ -55,9 +55,9 @@ fi
5555

5656
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
5757
_OLD_VIRTUAL_PS1="${PS1:-}"
58-
PS1="__VENV_PROMPT__${PS1:-}"
58+
PS1=__VENV_PROMPT__"${PS1:-}"
5959
export PS1
60-
VIRTUAL_ENV_PROMPT="__VENV_PROMPT__"
60+
VIRTUAL_ENV_PROMPT=__VENV_PROMPT__
6161
export VIRTUAL_ENV_PROMPT
6262
fi
6363

Lib/venv/scripts/nt/activate.bat

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ if defined _OLD_CODEPAGE (
88
"%SystemRoot%\System32\chcp.com" 65001 > nul
99
)
1010

11-
set VIRTUAL_ENV=__VENV_DIR__
11+
set "VIRTUAL_ENV=__VENV_DIR__"
1212

1313
if not defined PROMPT set PROMPT=$P$G
1414

@@ -24,8 +24,8 @@ set PYTHONHOME=
2424
if defined _OLD_VIRTUAL_PATH set PATH=%_OLD_VIRTUAL_PATH%
2525
if not defined _OLD_VIRTUAL_PATH set _OLD_VIRTUAL_PATH=%PATH%
2626

27-
set PATH=%VIRTUAL_ENV%\__VENV_BIN_NAME__;%PATH%
28-
set VIRTUAL_ENV_PROMPT=__VENV_PROMPT__
27+
set "PATH=%VIRTUAL_ENV%\__VENV_BIN_NAME__;%PATH%"
28+
set "VIRTUAL_ENV_PROMPT=__VENV_PROMPT__"
2929

3030
:END
3131
if defined _OLD_CODEPAGE (

Lib/venv/scripts/posix/activate.csh

+4-4
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PA
88
# Unset irrelevant variables.
99
deactivate nondestructive
1010

11-
setenv VIRTUAL_ENV "__VENV_DIR__"
11+
setenv VIRTUAL_ENV __VENV_DIR__
1212

1313
set _OLD_VIRTUAL_PATH="$PATH"
14-
setenv PATH "$VIRTUAL_ENV/__VENV_BIN_NAME__:$PATH"
14+
setenv PATH "$VIRTUAL_ENV/"__VENV_BIN_NAME__":$PATH"
1515

1616

1717
set _OLD_VIRTUAL_PROMPT="$prompt"
1818

1919
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
20-
set prompt = "__VENV_PROMPT__$prompt"
21-
setenv VIRTUAL_ENV_PROMPT "__VENV_PROMPT__"
20+
set prompt = __VENV_PROMPT__"$prompt"
21+
setenv VIRTUAL_ENV_PROMPT __VENV_PROMPT__
2222
endif
2323

2424
alias pydoc python -m pydoc

Lib/venv/scripts/posix/activate.fish

+4-4
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ end
3333
# Unset irrelevant variables.
3434
deactivate nondestructive
3535

36-
set -gx VIRTUAL_ENV "__VENV_DIR__"
36+
set -gx VIRTUAL_ENV __VENV_DIR__
3737

3838
set -gx _OLD_VIRTUAL_PATH $PATH
39-
set -gx PATH "$VIRTUAL_ENV/__VENV_BIN_NAME__" $PATH
39+
set -gx PATH "$VIRTUAL_ENV/"__VENV_BIN_NAME__ $PATH
4040

4141
# Unset PYTHONHOME if set.
4242
if set -q PYTHONHOME
@@ -56,7 +56,7 @@ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
5656
set -l old_status $status
5757

5858
# Output the venv prompt; color taken from the blue of the Python logo.
59-
printf "%s%s%s" (set_color 4B8BBE) "__VENV_PROMPT__" (set_color normal)
59+
printf "%s%s%s" (set_color 4B8BBE) __VENV_PROMPT__ (set_color normal)
6060

6161
# Restore the return status of the previous command.
6262
echo "exit $old_status" | .
@@ -65,5 +65,5 @@ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
6565
end
6666

6767
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
68-
set -gx VIRTUAL_ENV_PROMPT "__VENV_PROMPT__"
68+
set -gx VIRTUAL_ENV_PROMPT __VENV_PROMPT__
6969
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Properly quote template strings in :mod:`venv` activation scripts.

0 commit comments

Comments
 (0)