Skip to content
Myr

Document and fix command string sanitizing with `shlex.split`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Removes last use of `shell=True` use for command invokation for defense-in-depth. Refs: #1026, #1477 and #2775

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 04ef3a6 · Browse files · 3 files+170 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+170 added−14 removed

  • tests:+116 added−0 removed
  • other:+54 added−14 removed

3 files+170 added−14 removed

modified:src/click/_termui_impl.py+51 added-14 removed
365 unmodified lines
366 self.render_progress()367368369def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:370 """Decide what method to use for paging through text."""370 """Decide what method to use for paging through text.371372 The ``PAGER`` environment variable is split into an ``argv`` list with373 :func:`shlex.split` in its default POSIX mode so that quotes are374 stripped from tokens and quoted Windows paths are preserved.375376 .. note::377 ``posix=False`` `was considered but rejected378 <https://github.com/pallets/click/pull/1477#issuecomment-620231711>`_379 because it retains quote characters in tokens. The380 :func:`shlex.quote` approach was also reverted in :pr:`1543`.381382 .. seealso::383 :issue:`1026`, :pr:`1477` and :pr:`2775`.384 """385 stdout = _default_text_stdout()386387 # There are no standard streams attached to write to. For example,388 # pythonw on Windows.
2 unmodified lines
391392 if not isatty(sys.stdin) or not isatty(stdout):393 return _nullpager(stdout, generator, color)394381 # Split and normalize the pager command into parts.382 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False)395 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))396 if pager_cmd_parts:397 if WIN:398 if _tempfilepager(generator, pager_cmd_parts, color):399 return
23 unmodified lines
423424def _pipepager(425 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None426) -> bool:414 """Page through text by feeding it to another program. Invoking a415 pager through this might support colors.427 """Page through text by feeding it to another program.428417 Returns `True` if the command was found, `False` otherwise and thus another418 pager should be attempted.429 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list430 produced by :func:`shlex.split`. The command is resolved to an absolute431 path with :func:`shutil.which` as recommended by the432 :mod:`subprocess` docs for Windows compatibility.433434 Invoking a pager through this might support colors: if piping to435 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set436 automatically.437438 Returns ``True`` if the command was found and executed, ``False``439 otherwise so another pager can be attempted.440441 .. seealso::442 :pr:`2775` improved error handling: :exc:`BrokenPipeError` is443 caught specifically, generator exceptions terminate the pager, and444 ``stdin.close()`` is always called in a ``finally`` block.445 """446 # Split the command into the invoked CLI and its parameters.447 if not cmd_parts:448 return False
85 unmodified lines
534 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None535) -> bool:536 """Page through text by invoking a program on a temporary file.537512 Returns `True` if the command was found, `False` otherwise and thus another513 pager should be attempted.538 Used as the primary pager strategy on Windows (where piping to539 ``more`` adds spurious ``\\r\\n``), and as a fallback on other540 platforms. The command is resolved to an absolute path with541 :func:`shutil.which`.542543 Returns ``True`` if the command was found and executed, ``False``544 otherwise so another pager can be attempted.545 """546 # Split the command into the invoked CLI and its parameters.547 if not cmd_parts:548 return False
73 unmodified lines
622 return editor623 return "vi"624625 def edit_files(self, filenames: cabc.Iterable[str]) -> None:626 """Open files in the user's editor.627628 The editor command is split into an ``argv`` list with629 :func:`shlex.split` in POSIX mode; see :func:`pager` for rationale.630631 .. seealso::632 :issue:`1026` and :pr:`1477`.633 """634 import shlex635 import subprocess636637 editor = self.get_editor()638 environ: dict[str, str] | None = None
1 unmodified line
640 if self.env:641 environ = os.environ.copy()642 environ.update(self.env)643604 exc_filename = " ".join(f'"{filename}"' for filename in filenames)605644 try:645 c = subprocess.Popen(608 args=f"{editor} {exc_filename}", env=environ, shell=True646 args=shlex.split(editor) + list(filenames),647 env=environ,648 )649 exit_code = c.wait()650 if exit_code != 0:651 raise ClickException(
140 unmodified lines
792793 if ch == "\x1a" and WIN: # Windows, Ctrl+Z794 raise EOFError()795757 return None796759797if sys.platform == "win32":798 import msvcrt799800 @contextlib.contextmanager
89 unmodified lines
modified:tests/test_termui.py+116 added
1import platform2import tempfile3import time4from unittest.mock import patch56import pytest78import click._termui_impl9from click._compat import WIN10from click._termui_impl import Editor11from click.exceptions import BadParameter12from click.exceptions import MissingParameter1314
391 unmodified lines
406 assert reopened_file.read() == "aTest\nbTest\n"407408409@pytest.mark.parametrize(410 ("editor_cmd", "filenames", "expected_args"),411 [412 pytest.param(413 "myeditor --wait --flag",414 ["file1.txt", "file2.txt"],415 ["myeditor", "--wait", "--flag", "file1.txt", "file2.txt"],416 id="editor with args",417 ),418 pytest.param(419 "vi",420 ['file"; rm -rf / ; echo "'],421 ["vi", 'file"; rm -rf / ; echo "'],422 id="shell metacharacters in filename",423 ),424 # Issue #1026: editor path with spaces must be quoted.425 pytest.param(426 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"',427 ["f.txt"],428 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"],429 id="quoted windows path with spaces (issue 1026)",430 ),431 # PR #1477: pager/editor command with flags, like ``less -FRSX``.432 pytest.param(433 "less -FRSX",434 ["f.txt"],435 ["less", "-FRSX", "f.txt"],436 id="command with flags (pr 1477)",437 ),438 # Issue #1026: quoted command with ``--wait`` flag.439 pytest.param(440 '"my command" --option value arg',441 ["f.txt"],442 ["my command", "--option", "value", "arg", "f.txt"],443 id="quoted command with args (issue 1026)",444 ),445 # PR #1477: unquoted unix path.446 pytest.param(447 "/usr/bin/vim",448 ["f.txt"],449 ["/usr/bin/vim", "f.txt"],450 id="unix absolute path",451 ),452 # Issue #1026: macOS path with escaped space.453 pytest.param(454 "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl",455 ["f.txt"],456 ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "f.txt"],457 id="escaped space in unix path (issue 1026)",458 ),459 ],460)461def test_editor_path_normalization(editor_cmd, filenames, expected_args):462 with patch("subprocess.Popen") as mock_popen:463 mock_popen.return_value.wait.return_value = 0464 Editor(editor=editor_cmd).edit_files(filenames)465466 mock_popen.assert_called_once()467 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]468 assert args == expected_args469 assert mock_popen.call_args[1].get("shell") is None470471472@pytest.mark.skipif(not WIN, reason="Windows-specific editor paths")473@pytest.mark.parametrize(474 ("editor_cmd", "expected_cmd"),475 [476 pytest.param(477 "notepad",478 ["notepad"],479 id="plain notepad",480 ),481 pytest.param(482 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe" --wait',483 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "--wait"],484 id="quoted path with flag",485 ),486 ],487)488def test_editor_windows_path_normalization(editor_cmd, expected_cmd):489 """Windows-specific tests: verify ``Popen`` receives unquoted paths that490 ``subprocess.list2cmdline`` can re-quote for ``CreateProcess``."""491 with patch("subprocess.Popen") as mock_popen:492 mock_popen.return_value.wait.return_value = 0493 Editor(editor=editor_cmd).edit_files(["f.txt"])494495 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]496 assert args == expected_cmd + ["f.txt"]497 assert mock_popen.call_args[1].get("shell") is None498499500def test_editor_env_passed_through():501 with patch("subprocess.Popen") as mock_popen:502 mock_popen.return_value.wait.return_value = 0503 Editor(editor="vi", env={"MY_VAR": "1"}).edit_files(["f.txt"])504505 env = mock_popen.call_args[1].get("env")506 assert env is not None507 assert env["MY_VAR"] == "1"508509510def test_editor_failure_exception():511 with patch("subprocess.Popen") as mock_popen:512 mock_popen.return_value.wait.return_value = 1513 with pytest.raises(click.ClickException, match="Editing failed"):514 Editor(editor="vi").edit_files(["f.txt"])515516517def test_editor_nonexistent_exception():518 with patch("subprocess.Popen", side_effect=OSError("not found")):519 with pytest.raises(click.ClickException, match="not found"):520 Editor(editor="nonexistent").edit_files(["f.txt"])521522523@pytest.mark.parametrize(524 ("prompt_required", "required", "args", "expect"),525 [526 (True, False, None, "prompt"),527 (True, False, ["-v"], "Option '-v' requires an argument."),
301 unmodified lines
modified:CHANGES.rst+3 added
15 unmodified lines
16 isolation. Add high-iteration stress tests behind a ``stress`` marker17 with a dedicated CI job. :pr:`3139`18- Fix callable ``flag_value`` being instantiated when used as a default via19 ``default=True``. :issue:`3121` :pr:`3201` :pr:`3213` :pr:`3225`20- Use :func:`shlex.split` to split pager and editor commands into ``argv``21 lists for :class:`subprocess.Popen`, removing ``shell=True``.22 :issue:`1026` :pr:`1477` :pr:`2775`2324Version 8.3.125--------------26
1305 unmodified lines