gh-127794: Validate email header names according to RFC 5322 (#127820)

`email.message.Message` objects now validate header names specified via `__setitem__`
or `add_header` according to RFC 5322, §2.2 [1].

In particular, callers should expect a ValueError to be raised for invalid header names.

[1]: https://datatracker.ietf.org/doc/html/rfc5322#section-2.2

---------

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: R. David Murray <rdmurray@bitdance.com>
This commit is contained in:
Srinivas Reddy Thatiparthy (తాటిపర్తి శ్రీనివాస్ రెడ్డి) 2025-03-30 17:59:29 +05:30 committed by GitHub
parent 55150a79ca
commit c432d0147b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 71 additions and 1 deletions

View file

@ -728,6 +728,31 @@ class TestMessageAPI(TestEmailBase):
"attachment; filename*=utf-8''Fu%C3%9Fballer%20%5Bfilename%5D.ppt",
msg['Content-Disposition'])
def test_invalid_header_names(self):
invalid_headers = [
('Invalid Header', 'contains space'),
('Tab\tHeader', 'contains tab'),
('Colon:Header', 'contains colon'),
('', 'Empty name'),
(' LeadingSpace', 'starts with space'),
('TrailingSpace ', 'ends with space'),
('Header\x7F', 'Non-ASCII character'),
('Header\x80', 'Extended ASCII'),
]
for policy in (email.policy.default, email.policy.compat32):
for setter in (Message.__setitem__, Message.add_header):
for name, value in invalid_headers:
self.do_test_invalid_header_names(
policy, setter,name, value)
def do_test_invalid_header_names(self, policy, setter, name, value):
with self.subTest(policy=policy, setter=setter, name=name, value=value):
message = Message(policy=policy)
pattern = r'(?i)(?=.*invalid)(?=.*header)(?=.*name)'
with self.assertRaisesRegex(ValueError, pattern) as cm:
setter(message, name, value)
self.assertIn(f"{name!r}", str(cm.exception))
def test_binary_quopri_payload(self):
for charset in ('latin-1', 'ascii'):
msg = Message()