Skip to content

Commit a74010f

Browse files
authored
🐛 Escape terminal control characters in error messages (#1972)
1 parent 11b083b commit a74010f

6 files changed

Lines changed: 141 additions & 8 deletions

File tree

‎docs/tutorial/printing.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,12 @@ If you have some `bytes` objects, you would probably want to decode them intenti
204204

205205
And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.
206206

207+
### Untrusted Text
208+
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+
207213
### Color
208214

209215
/// note | Technical Details
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import re
2+
from typing import Annotated
3+
4+
import pytest
5+
import typer
6+
from typer._click.exceptions import NoSuchOption
7+
from typer.testing import CliRunner
8+
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 cover
19+
20+
@app.command()
21+
def read_file(value: typer.FileText) -> None:
22+
pass # pragma: no cover
23+
24+
@app.command()
25+
def parse(
26+
value: Annotated[int, typer.Argument(parser=lambda x: int(x, 0))],
27+
) -> None:
28+
pass # pragma: no cover
29+
30+
return app
31+
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_utils
70+
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 == 2
78+
# 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 output
81+
assert prefix + "input-" + escaped in output
82+
assert re.search(r"[\x00-\x09\x0b-\x1f\x7f-\x9f]", output) is None
83+
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 == value
90+
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 == 0
104+
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 == 0
118+
assert result.stdout_bytes == value.encode()

‎typer/_click/core.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from .globals import pop_context, push_context
2424
from .parser import _OptionParser
2525
from .termui import style
26-
from .utils import echo, make_default_short_help
26+
from .utils import _escape_control_characters, echo, make_default_short_help
2727

2828
if TYPE_CHECKING:
2929
from ..core import TyperOption
@@ -719,7 +719,8 @@ def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
719719
_, args = param.handle_parse_result(ctx, opts, args)
720720

721721
if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
722-
ctx.fail(f"Got unexpected extra argument(s) ({' '.join(map(str, args))})")
722+
extra_args = " ".join(_escape_control_characters(str(arg)) for arg in args)
723+
ctx.fail(f"Got unexpected extra argument(s) ({extra_args})")
723724

724725
ctx.args = args
725726
ctx._opt_prefixes.update(parser._opt_prefixes)

‎typer/_click/exceptions.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from ..exceptions import TyperException
55
from ._compat import get_text_stderr
66
from .globals import resolve_color_default
7-
from .utils import echo, format_filename
7+
from .utils import _escape_control_characters, echo, format_filename
88

99
if TYPE_CHECKING:
1010
from .core import Command, Context, Parameter
@@ -178,7 +178,7 @@ def __init__(
178178
ctx: Union["Context", None] = None,
179179
) -> None:
180180
if message is None:
181-
message = f"No such option: {option_name}"
181+
message = f"No such option: {_escape_control_characters(option_name)}"
182182

183183
super().__init__(message, ctx)
184184
self.option_name = option_name

‎typer/_click/types.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
from ._compat import _get_argv_encoding, open_stream
2020
from .exceptions import BadParameter
21-
from .utils import LazyFile, format_filename, safecall
21+
from .utils import LazyFile, _escape_control_characters, format_filename, safecall
2222

2323
if TYPE_CHECKING:
2424
from .core import Context, Parameter
@@ -138,7 +138,7 @@ def convert(
138138
assert isinstance(value, bytes)
139139
value = value.decode("utf-8", "replace")
140140

141-
self.fail(value, param, ctx)
141+
self.fail(_escape_control_characters(value), param, ctx)
142142

143143

144144
class StringParamType(ParamType):
@@ -559,8 +559,9 @@ def convert(
559559
ctx.call_on_close(safecall(f.flush))
560560

561561
return f
562-
except OSError as e: # pragma: no cover
563-
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)
564565

565566
def shell_complete(
566567
self, ctx: "Context", param: "Parameter", incomplete: str

‎typer/_click/utils.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@
3434
R = TypeVar("R")
3535

3636

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}", value
41+
)
42+
43+
3744
def _posixify(name: str) -> str:
3845
return "-".join(name.split()).lower()
3946

0 commit comments

Comments
 (0)