🐛 Escape terminal control characters in error messages (#1972)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent 11b083b · Browse files · 6 files·+141 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+141 added−8 removed
- tests:+118 added−0 removed
- other:+23 added−8 removed
Provenance
- Commit
a74010f- Tree
55bc4f9- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
11b083b
6 files changed+141 added−8 removed
modified:docs/tutorial/printing.md+6 added
202 unmodified lines203 If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.204 205 And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.206 207+### Untrusted Text208+209+`typer.echo()` preserves terminal control sequences, including those used for colors. When displaying text from an untrusted source, escape control characters first. For a diagnostic representation of a string, you can use `typer.echo(repr(value))`.210+211+Setting `color=False` disables styling, but does not sanitize all terminal control sequences.212+213 ### Color214 215 /// note | Technical Details216 62 unmodified linesadded:tests/test_terminal_control_characters.py+118 added
1+import re2+from typing import Annotated3+4+import pytest5+import typer6+from typer._click.exceptions import NoSuchOption7+from typer.testing import CliRunner8+9+runner = CliRunner()10+11+12+@pytest.fixture(params=["rich", None], ids=["rich", "plain"])13+def app(request: pytest.FixtureRequest) -> typer.Typer:14+ app = typer.Typer(add_completion=False, rich_markup_mode=request.param)15+16+ @app.command()17+ def no_args() -> None:18+ pass # pragma: no cover19+20+ @app.command()21+ def read_file(value: typer.FileText) -> None:22+ pass # pragma: no cover23+24+ @app.command()25+ def parse(26+ value: Annotated[int, typer.Argument(parser=lambda x: int(x, 0))],27+ ) -> None:28+ pass # pragma: no cover29+30+ return app31+32+33+@pytest.mark.parametrize("color", [False, True])34+@pytest.mark.parametrize(35+ ("command", "prefix", "message"),36+ [37+ ("no-args", "", "Got unexpected extra argument(s)"),38+ ("no-args", "--", "No such option"),39+ ("read-file", "", "Invalid value"),40+ ("parse", "", "Invalid value"),41+ ],42+ ids=["extra-argument", "unknown-option", "file-open", "custom-parser"],43+)44+@pytest.mark.parametrize(45+ ("value", "escaped"),46+ [47+ ("\x1b[2J\x1b[H", r"\x1b[2J\x1b[H"),48+ ("\x1b]52;c;YWJj\x07", r"\x1b]52;c;YWJj\x07"),49+ ("\x1b]52;c;YWJj\x1b\\", "\\x1b]52;c;YWJj\\x1b\\"),50+ ("\x9b2J\x9d52;c;YWJj\x9c", r"\x9b2J\x9d52;c;YWJj\x9c"),51+ ("\r\n\t\b\x7f", r"\x0d\x0a\x09\x08\x7f"),52+ (53+ "text-\u00e9-\u65e5\u672c-\U0001f469\u200d\U0001f4bb-'quoted'-\\text",54+ "text-\u00e9-\u65e5\u672c-\U0001f469\u200d\U0001f4bb-'quoted'-\\text",55+ ),56+ ],57+ ids=["screen", "osc-bel", "osc-st", "c1", "whitespace-controls", "unicode"],58+)59+def test_error_values(60+ app: typer.Typer,61+ command: str,62+ prefix: str,63+ message: str,64+ value: str,65+ escaped: str,66+ color: bool,67+ monkeypatch: pytest.MonkeyPatch,68+) -> None:69+ from typer import rich_utils70+71+ monkeypatch.delenv("NO_COLOR", raising=False)72+ monkeypatch.setenv("TERM", "xterm-256color")73+ monkeypatch.setattr(rich_utils, "FORCE_TERMINAL", color)74+ monkeypatch.setattr(rich_utils, "MAX_WIDTH", 3000)75+ result = runner.invoke(app, [command, prefix + "input-" + value], color=color)76+77+ assert result.exit_code == 278+ # Remove only generated color styles so other terminal controls cannot hide.79+ output = re.sub(r"\x1b\[[0-9;]*m", "", result.stderr)80+ assert message in output81+ assert prefix + "input-" + escaped in output82+ assert re.search(r"[\x00-\x09\x0b-\x1f\x7f-\x9f]", output) is None83+84+85+def test_unknown_option_preserves_original_value() -> None:86+ value = "--input-\x00\x1f\x7f\x80\x9f"87+ error = NoSuchOption(value)88+89+ assert error.option_name == value90+ assert error.format_message() == r"No such option: --input-\x00\x1f\x7f\x80\x9f"91+92+93+def test_argument_preserves_original_value() -> None:94+ app = typer.Typer(add_completion=False)95+ value = "input-\x1b[2J\x1b]52;c;YWJj\x07"96+97+ @app.command()98+ def main(value: str) -> None:99+ typer.echo(repr(value))100+101+ result = runner.invoke(app, [value])102+103+ assert result.exit_code == 0104+ assert result.stdout == repr(value) + "\n"105+106+107+def test_echo_preserves_terminal_sequences() -> None:108+ app = typer.Typer(add_completion=False)109+ value = "\x1b[2J\x1b]52;c;YWJj\x07"110+111+ @app.command()112+ def main() -> None:113+ typer.echo(value, nl=False)114+115+ result = runner.invoke(app, color=True)116+117+ assert result.exit_code == 0118+ assert result.stdout_bytes == value.encode()modified:typer/_click/core.py+3 added-2 removed
21 unmodified lines22 from .formatting import HelpFormatter23 from .globals import pop_context, push_context24 from .parser import _OptionParser25 from .termui import style26-from .utils import echo, make_default_short_help26+from .utils import _escape_control_characters, echo, make_default_short_help27 28 if TYPE_CHECKING:29 from ..core import TyperOption30 from .shell_completion import CompletionItem687 unmodified lines718 for param in iter_params_for_processing(param_order, self.get_params(ctx)):719 _, args = param.handle_parse_result(ctx, opts, args)720 721 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:722+ extra_args = " ".join(_escape_control_characters(str(arg)) for arg in args)722- ctx.fail(f"Got unexpected extra argument(s) ({' '.join(map(str, args))})")723+ ctx.fail(f"Got unexpected extra argument(s) ({extra_args})")724 725 ctx.args = args726 ctx._opt_prefixes.update(parser._opt_prefixes)727 return args383 unmodified linesmodified:typer/_click/exceptions.py+2 added-2 removed
2 unmodified lines3 4 from ..exceptions import TyperException5 from ._compat import get_text_stderr6 from .globals import resolve_color_default7-from .utils import echo, format_filename7+from .utils import _escape_control_characters, echo, format_filename8 9 if TYPE_CHECKING:10 from .core import Command, Context, Parameter11 165 unmodified lines177 possibilities: Sequence[str] | None = None,178 ctx: Union["Context", None] = None,179 ) -> None:180 if message is None:181- message = f"No such option: {option_name}"181+ message = f"No such option: {_escape_control_characters(option_name)}"182 183 super().__init__(message, ctx)184 self.option_name = option_name185 self.possibilities = possibilities52 unmodified linesmodified:typer/_click/types.py+5 added-4 removed
16 unmodified lines17 )18 19 from ._compat import _get_argv_encoding, open_stream20 from .exceptions import BadParameter21-from .utils import LazyFile, format_filename, safecall21+from .utils import LazyFile, _escape_control_characters, format_filename, safecall22 23 if TYPE_CHECKING:24 from .core import Context, Parameter25 from .shell_completion import CompletionItem111 unmodified lines137 except UnicodeError: # pragma: no cover138 assert isinstance(value, bytes)139 value = value.decode("utf-8", "replace")140 141- self.fail(value, param, ctx)141+ self.fail(_escape_control_characters(value), param, ctx)142 143 144 class StringParamType(ParamType):145 name = "str"412 unmodified lines558 else:559 ctx.call_on_close(safecall(f.flush))560 561 return f562- except OSError as e: # pragma: no cover563- self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)562+ except OSError as e:563+ filename = _escape_control_characters(format_filename(value))564+ self.fail(f"'{filename}': {e.strerror}", param, ctx)565 566 def shell_complete(567 self, ctx: "Context", param: "Parameter", incomplete: str568 ) -> list["CompletionItem"]:128 unmodified linesmodified:typer/_click/utils.py+7 added
32 unmodified lines33 P = ParamSpec("P")34 R = TypeVar("R")35 36 37+def _escape_control_characters(value: str) -> str:38+ """Display untrusted diagnostic values without terminal control characters."""39+ return re.sub(40+ r"[\x00-\x1f\x7f-\x9f]", lambda match: f"\\x{ord(match[0]):02x}", value41+ )42+43+44 def _posixify(name: str) -> str:45 return "-".join(name.split()).lower()46 47 430 unmodified lines