Limit length of accepted email addresses (#9855)

This commit is contained in:
Erik Johnston 2021-04-22 17:49:11 +01:00 committed by GitHub
parent 69018acbd2
commit 177dae2704
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 100 additions and 7 deletions

View file

@ -18,6 +18,16 @@ import re
logger = logging.getLogger(__name__)
# it's unclear what the maximum length of an email address is. RFC3696 (as corrected
# by errata) says:
# the upper limit on address lengths should normally be considered to be 254.
#
# In practice, mail servers appear to be more tolerant and allow 400 characters
# or so. Let's allow 500, which should be plenty for everyone.
#
MAX_EMAIL_ADDRESS_LENGTH = 500
def check_3pid_allowed(hs, medium, address):
"""Checks whether a given format of 3PID is allowed to be used on this HS
@ -70,3 +80,23 @@ def canonicalise_email(address: str) -> str:
raise ValueError("Unable to parse email address")
return parts[0].casefold() + "@" + parts[1].lower()
def validate_email(address: str) -> str:
"""Does some basic validation on an email address.
Returns the canonicalised email, as returned by `canonicalise_email`.
Raises a ValueError if the email is invalid.
"""
# First we try canonicalising in case that fails
address = canonicalise_email(address)
# Email addresses have to be at least 3 characters.
if len(address) < 3:
raise ValueError("Unable to parse email address")
if len(address) > MAX_EMAIL_ADDRESS_LENGTH:
raise ValueError("Unable to parse email address")
return address