Skip to content
Myr

🐛 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

6 files+141 added−8 removed

modified:docs/tutorial/printing.md+6 added
202 unmodified lines
203If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.204205And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.206207### Untrusted Text208209`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))`.210211Setting `color=False` disables styling, but does not sanitize all terminal control sequences.212213### Color214215/// note | Technical Details216
62 unmodified lines
added:tests/test_terminal_control_characters.py+118 added
1import re2from typing import Annotated34import pytest5import typer6from typer._click.exceptions import NoSuchOption7from typer.testing import CliRunner89runner = CliRunner()101112@pytest.fixture(params=["rich", None], ids=["rich", "plain"])13def app(request: pytest.FixtureRequest) -> typer.Typer:14 app = typer.Typer(add_completion=False, rich_markup_mode=request.param)1516 @app.command()17 def no_args() -> None:18 pass # pragma: no cover1920 @app.command()21 def read_file(value: typer.FileText) -> None:22 pass # pragma: no cover2324 @app.command()25 def parse(26 value: Annotated[int, typer.Argument(parser=lambda x: int(x, 0))],27 ) -> None:28 pass # pragma: no cover2930 return app313233@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)59def 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_utils7071 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)7677 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 None838485def test_unknown_option_preserves_original_value() -> None:86 value = "--input-\x00\x1f\x7f\x80\x9f"87 error = NoSuchOption(value)8889 assert error.option_name == value90 assert error.format_message() == r"No such option: --input-\x00\x1f\x7f\x80\x9f"919293def test_argument_preserves_original_value() -> None:94 app = typer.Typer(add_completion=False)95 value = "input-\x1b[2J\x1b]52;c;YWJj\x07"9697 @app.command()98 def main(value: str) -> None:99 typer.echo(repr(value))100101 result = runner.invoke(app, [value])102103 assert result.exit_code == 0104 assert result.stdout == repr(value) + "\n"105106107def test_echo_preserves_terminal_sequences() -> None:108 app = typer.Typer(add_completion=False)109 value = "\x1b[2J\x1b]52;c;YWJj\x07"110111 @app.command()112 def main() -> None:113 typer.echo(value, nl=False)114115 result = runner.invoke(app, color=True)116117 assert result.exit_code == 0118 assert result.stdout_bytes == value.encode()
modified:typer/_click/core.py+3 added-2 removed
21 unmodified lines
22from .formatting import HelpFormatter23from .globals import pop_context, push_context24from .parser import _OptionParser25from .termui import style26from .utils import echo, make_default_short_help26from .utils import _escape_control_characters, echo, make_default_short_help2728if TYPE_CHECKING:29 from ..core import TyperOption30 from .shell_completion import CompletionItem
687 unmodified lines
718 for param in iter_params_for_processing(param_order, self.get_params(ctx)):719 _, args = param.handle_parse_result(ctx, opts, args)720721 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})")724725 ctx.args = args726 ctx._opt_prefixes.update(parser._opt_prefixes)727 return args
383 unmodified lines
modified:typer/_click/exceptions.py+2 added-2 removed
2 unmodified lines
34from ..exceptions import TyperException5from ._compat import get_text_stderr6from .globals import resolve_color_default7from .utils import echo, format_filename7from .utils import _escape_control_characters, echo, format_filename89if TYPE_CHECKING:10 from .core import Command, Context, Parameter11
165 unmodified lines
177 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)}"182183 super().__init__(message, ctx)184 self.option_name = option_name185 self.possibilities = possibilities
52 unmodified lines
modified:typer/_click/types.py+5 added-4 removed
16 unmodified lines
17)1819from ._compat import _get_argv_encoding, open_stream20from .exceptions import BadParameter21from .utils import LazyFile, format_filename, safecall21from .utils import LazyFile, _escape_control_characters, format_filename, safecall2223if TYPE_CHECKING:24 from .core import Context, Parameter25 from .shell_completion import CompletionItem
111 unmodified lines
137 except UnicodeError: # pragma: no cover138 assert isinstance(value, bytes)139 value = value.decode("utf-8", "replace")140141 self.fail(value, param, ctx)141 self.fail(_escape_control_characters(value), param, ctx)142143144class StringParamType(ParamType):145 name = "str"
412 unmodified lines
558 else:559 ctx.call_on_close(safecall(f.flush))560561 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)565566 def shell_complete(567 self, ctx: "Context", param: "Parameter", incomplete: str568 ) -> list["CompletionItem"]:
128 unmodified lines
modified:typer/_click/utils.py+7 added
32 unmodified lines
33P = ParamSpec("P")34R = TypeVar("R")353637def _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 )424344def _posixify(name: str) -> str:45 return "-".join(name.split()).lower()4647
430 unmodified lines