Skip to content

Commit

Permalink
Correctly urlencode email address parts (#659)
Browse files Browse the repository at this point in the history
Correctly urlencode the local-part of email addresses in the mailto target.

Fixes #658
  • Loading branch information
larseggert committed May 10, 2022
1 parent 481b146 commit 4f951d3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
9 changes: 8 additions & 1 deletion bleach/linkifier.py
@@ -1,5 +1,7 @@
import re

from urllib.parse import quote

from bleach import callbacks as linkify_callbacks
from bleach import html5lib_shim

Expand Down Expand Up @@ -298,10 +300,15 @@ def handle_email_addresses(self, src_iter):
{"type": "Characters", "data": text[end : match.start()]}
)

# URL-encode the "local-part" according to RFC6068
parts = match.group(0).split("@")
parts[0] = quote(parts[0])
address = "@".join(parts)

# Run attributes through the callbacks to see what we
# should do with this match
attrs = {
(None, "href"): "mailto:%s" % match.group(0),
(None, "href"): "mailto:%s" % address,
"_text": match.group(0),
}
attrs = self.apply_callbacks(attrs, True)
Expand Down
17 changes: 14 additions & 3 deletions tests/test_linkify.py
Expand Up @@ -104,6 +104,17 @@ def ft(attrs, new=False):
),
# Incorrect email
('"\\\n"@opa.ru', True, '"\\\n"@opa.ru'),
# RFC6068 special characters
(
"gorby%kremvax@example.com",
True,
'<a href="mailto:gorby%25kremvax@example.com">gorby%kremvax@example.com</a>',
),
(
"unlikely?address@example.com",
True,
'<a href="mailto:unlikely%3Faddress@example.com">unlikely?address@example.com</a>',
),
],
)
def test_email_link(data, parse_email, expected):
Expand All @@ -115,15 +126,15 @@ def test_email_link(data, parse_email, expected):
[
(
'"james"@example.com',
"""<a href='mailto:"james"@example.com'>"james"@example.com</a>""",
"""<a href="mailto:%22james%22@example.com">"james"@example.com</a>""",
),
(
'"j\'ames"@example.com',
"""<a href="mailto:&quot;j'ames&quot;@example.com">"j'ames"@example.com</a>""",
"""<a href="mailto:%22j%27ames%22@example.com">"j'ames"@example.com</a>""",
),
(
'"ja>mes"@example.com',
"""<a href='mailto:"ja>mes"@example.com'>"ja&gt;mes"@example.com</a>""",
"""<a href="mailto:%22ja%3Emes%22@example.com">"ja&gt;mes"@example.com</a>""",
),
],
)
Expand Down

0 comments on commit 4f951d3

Please sign in to comment.