Skip to content

Commit f6ca80a

Browse files
aft90Jake Taylor
authored and
Jake Taylor
committed
bpo-38332: Catch KeyError from unknown cte in encoded-word. (pythonGH-16503)
KeyError should cause a failure in parsing the encoded word and should be caught and raised as a _InvalidEWError instead.
1 parent e4240e3 commit f6ca80a

File tree

4 files changed

+18
-1
lines changed

4 files changed

+18
-1
lines changed

Lib/email/_header_value_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1057,7 +1057,7 @@ def get_encoded_word(value):
10571057
value = ''.join(remainder)
10581058
try:
10591059
text, charset, lang, defects = _ew.decode('=?' + tok + '?=')
1060-
except ValueError:
1060+
except (ValueError, KeyError):
10611061
raise _InvalidEwError(
10621062
"encoded word format invalid: '{}'".format(ew.cte))
10631063
ew.charset = charset

Lib/test/test_email/test__encoded_words.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ def test_wrong_format_input_raises(self):
5858
_ew.decode('=?')
5959
with self.assertRaises(ValueError):
6060
_ew.decode('')
61+
with self.assertRaises(KeyError):
62+
_ew.decode('=?utf-8?X?somevalue?=')
6163

6264
def _test(self, source, result, charset='us-ascii', lang='', defects=[]):
6365
res, char, l, d = _ew.decode(source)

Lib/test/test_email/test__header_value_parser.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ def test_get_encoded_word_missing_middle_raises(self):
8989
with self.assertRaises(errors.HeaderParseError):
9090
parser.get_encoded_word('=?abc?=')
9191

92+
def test_get_encoded_word_invalid_cte(self):
93+
with self.assertRaises(errors.HeaderParseError):
94+
parser.get_encoded_word('=?utf-8?X?somevalue?=')
95+
9296
def test_get_encoded_word_valid_ew(self):
9397
self._test_get_x(parser.get_encoded_word,
9498
'=?us-ascii?q?this_is_a_test?= bird',
@@ -399,6 +403,14 @@ def test_get_unstructured_invalid_ew(self):
399403
[],
400404
'')
401405

406+
def test_get_unstructured_invalid_ew_cte(self):
407+
self._test_get_x(self._get_unst,
408+
'=?utf-8?X?=somevalue?=',
409+
'=?utf-8?X?=somevalue?=',
410+
'=?utf-8?X?=somevalue?=',
411+
[],
412+
'')
413+
402414
# get_qp_ctext
403415

404416
def test_get_qp_ctext_only(self):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Prevent :exc:`KeyError` thrown by :func:`_encoded_words.decode` when given
2+
an encoded-word with invalid content-type encoding from propagating all the
3+
way to :func:`email.message.get`.

0 commit comments

Comments
 (0)