Skip to content

Commit b77b329

Browse files
jh0kertsnoam
authored andcommitted
Handle utf8 decoding errors (python-telegram-bot#1076)
1 parent 5efd5e2 commit b77b329

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

telegram/utils/request.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,14 @@ def _parse(json_data):
145145
dict: A JSON parsed as Python dict with results - on error this dict will be empty.
146146
147147
"""
148-
decoded_s = json_data.decode('utf-8')
148+
149149
try:
150+
decoded_s = json_data.decode('utf-8')
150151
data = json.loads(decoded_s)
152+
except UnicodeDecodeError:
153+
logging.getLogger(__name__).debug(
154+
'Logging raw invalid UTF-8 response:\n%r', json_data)
155+
raise TelegramError('Server response could not be decoded using UTF-8')
151156
except ValueError:
152157
raise TelegramError('Invalid server response')
153158

tests/test_request.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env python
2+
#
3+
# A library that provides a Python interface to the Telegram Bot API
4+
# Copyright (C) 2015-2018
5+
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
6+
#
7+
# This program is free software: you can redistribute it and/or modify
8+
# it under the terms of the GNU Lesser Public License as published by
9+
# the Free Software Foundation, either version 3 of the License, or
10+
# (at your option) any later version.
11+
#
12+
# This program is distributed in the hope that it will be useful,
13+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+
# GNU Lesser Public License for more details.
16+
#
17+
# You should have received a copy of the GNU Lesser Public License
18+
# along with this program. If not, see [http://www.gnu.org/licenses/].
19+
20+
import pytest
21+
22+
from telegram import TelegramError
23+
from telegram.utils.request import Request
24+
25+
26+
def test_parse_illegal_callback_data():
27+
"""
28+
Clients can send arbitrary bytes in callback data.
29+
Make sure the correct error is raised in this case.
30+
"""
31+
server_response = b'{"invalid utf-8": "\x80"}'
32+
33+
with pytest.raises(TelegramError, match='Server response could not be decoded using UTF-8'):
34+
Request._parse(server_response)

0 commit comments

Comments
 (0)