Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RSPEED-403] Prevent binary stdin #92

Merged
merged 3 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion command_line_assistant/initialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
from argparse import ArgumentParser, Namespace

from command_line_assistant.commands import history, query, record
from command_line_assistant.rendering.decorators.colors import ColorDecorator
from command_line_assistant.rendering.decorators.text import EmojiDecorator
from command_line_assistant.rendering.renders.text import TextRenderer
from command_line_assistant.utils.cli import (
add_default_command,
create_argument_parser,
Expand Down Expand Up @@ -37,7 +40,19 @@ def initialize() -> int:
"""
parser = register_subcommands()

stdin = read_stdin()
stdin = None
try:
stdin = read_stdin()
except UnicodeDecodeError:
# Usually happens when the user try to cat a binary file and redirect that to us.
text_renderer = TextRenderer()
text_renderer.update(ColorDecorator(foreground="red"))
text_renderer.update(EmojiDecorator(emoji="U+1F641"))
text_renderer.render(
"The stdin provided could not be decoded. Please, make sure it is in textual format."
)
return 1

args = add_default_command(stdin, sys.argv)

# Small workaround to include the stdin in the namespace object in case it exists.
Expand Down
14 changes: 14 additions & 0 deletions tests/test_initialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,20 @@ def test_initialize_with_help(capsys):
assert "usage:" in captured.out


def test_initialize_bad_stdin(capsys):
with patch("command_line_assistant.initialize.read_stdin") as mock_stdin:
mock_stdin.side_effect = UnicodeDecodeError(
"utf-8", b"", 0, 1, "invalid start byte"
)
initialize()

captured = capsys.readouterr()
assert (
"The stdin provided could not be decoded. Please, make sure it is in textual format."
in captured.out
)


@pytest.mark.parametrize(
(
"argv",
Expand Down
Loading