Skip to content

bpo-38332: catch KeyError from unknown cte in encoded-word #16503

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

Merged
merged 2 commits into from
Oct 5, 2019
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
2 changes: 1 addition & 1 deletion Lib/email/_header_value_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1057,7 +1057,7 @@ def get_encoded_word(value):
value = ''.join(remainder)
try:
text, charset, lang, defects = _ew.decode('=?' + tok + '?=')
except ValueError:
except (ValueError, KeyError):
raise _InvalidEwError(
"encoded word format invalid: '{}'".format(ew.cte))
ew.charset = charset
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_email/test__encoded_words.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ def test_wrong_format_input_raises(self):
_ew.decode('=?')
with self.assertRaises(ValueError):
_ew.decode('')
with self.assertRaises(KeyError):
_ew.decode('=?utf-8?X?somevalue?=')

def _test(self, source, result, charset='us-ascii', lang='', defects=[]):
res, char, l, d = _ew.decode(source)
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_email/test__header_value_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ def test_get_encoded_word_missing_middle_raises(self):
with self.assertRaises(errors.HeaderParseError):
parser.get_encoded_word('=?abc?=')

def test_get_encoded_word_invalid_cte(self):
with self.assertRaises(errors.HeaderParseError):
parser.get_encoded_word('=?utf-8?X?somevalue?=')

def test_get_encoded_word_valid_ew(self):
self._test_get_x(parser.get_encoded_word,
'=?us-ascii?q?this_is_a_test?= bird',
Expand Down Expand Up @@ -399,6 +403,14 @@ def test_get_unstructured_invalid_ew(self):
[],
'')

def test_get_unstructured_invalid_ew_cte(self):
self._test_get_x(self._get_unst,
'=?utf-8?X?=somevalue?=',
'=?utf-8?X?=somevalue?=',
'=?utf-8?X?=somevalue?=',
[],
'')

# get_qp_ctext

def test_get_qp_ctext_only(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Prevent :exc:`KeyError` thrown by :func:`_encoded_words.decode` when given
an encoded-word with invalid content-type encoding from propagating all the
way to :func:`email.message.get`.