bpo-32178: Fix IndexError trying to parse 'To' header starting with ':'. (GH-15044)
authorAbhilash Raj <maxking@users.noreply.github.com>
Sun, 11 Aug 2019 20:45:09 +0000 (13:45 -0700)
committerMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 11 Aug 2019 20:45:09 +0000 (13:45 -0700)
This should fix the IndexError trying to retrieve `DisplayName.display_name` and `DisplayName.value` when the `value` is basically an empty string.

https://bugs.python.org/issue32178

Lib/email/_header_value_parser.py
Lib/test/test_email/test__header_value_parser.py
Misc/NEWS.d/next/Library/2019-07-30-22-41-05.bpo-32178.X-IFLe.rst [new file with mode: 0644]

index 641e0979f3d78548469087b11b3ab5c01cf7e227..ea33bd8eda7d39ddce1079ebdbd32d0a8bcb746f 100644 (file)
@@ -561,6 +561,8 @@ class DisplayName(Phrase):
     @property
     def display_name(self):
         res = TokenList(self)
+        if len(res) == 0:
+            return res.value
         if res[0].token_type == 'cfws':
             res.pop(0)
         else:
@@ -582,7 +584,7 @@ class DisplayName(Phrase):
             for x in self:
                 if x.token_type == 'quoted-string':
                     quote = True
-        if quote:
+        if len(self) != 0 and quote:
             pre = post = ''
             if self[0].token_type=='cfws' or self[0][0].token_type=='cfws':
                 pre = ' '
index f6e5886f7571fccbed859a772d368216b064937f..b3e6b2661524e9c410aa62df11962ccd88d1ae89 100644 (file)
@@ -1700,6 +1700,14 @@ class TestParser(TestParserMixin, TestEmailBase):
         self.assertEqual(display_name[3].comments, ['with trailing comment'])
         self.assertEqual(display_name.display_name, 'simple phrase.')
 
+    def test_get_display_name_for_invalid_address_field(self):
+        # bpo-32178: Test that address fields starting with `:` don't cause
+        # IndexError when parsing the display name.
+        display_name = self._test_get_x(
+            parser.get_display_name,
+            ':Foo ', '', '', [errors.InvalidHeaderDefect], ':Foo ')
+        self.assertEqual(display_name.value, '')
+
     # get_name_addr
 
     def test_get_name_addr_angle_addr_only(self):
diff --git a/Misc/NEWS.d/next/Library/2019-07-30-22-41-05.bpo-32178.X-IFLe.rst b/Misc/NEWS.d/next/Library/2019-07-30-22-41-05.bpo-32178.X-IFLe.rst
new file mode 100644 (file)
index 0000000..5e7a2e9
--- /dev/null
@@ -0,0 +1 @@
+Fix IndexError in :mod:`email` package when trying to parse invalid address fields starting with ``:``.