Skip to content

Commit 924bd4c

Browse files
authored
Merge pull request #3469 from bdarnell/strict-header-names
httputil: Enforce RFC rules for header names
2 parents d5ac65c + bc7e2ac commit 924bd4c

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

tornado/httputil.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@
7171
# To be used with str.strip() and related methods.
7272
HTTP_WHITESPACE = " \t"
7373

74+
HTTP_TOKEN_RE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
75+
7476

7577
@lru_cache(1000)
7678
def _normalize_header(name: str) -> str:
@@ -143,6 +145,8 @@ def __init__(self, *args: typing.Any, **kwargs: str) -> None: # noqa: F811
143145

144146
def add(self, name: str, value: str) -> None:
145147
"""Adds a new value for the given key."""
148+
if not HTTP_TOKEN_RE.match(name):
149+
raise HTTPInputError("Invalid header name %r" % name)
146150
norm_name = _normalize_header(name)
147151
self._last_key = norm_name
148152
if norm_name in self:
@@ -859,7 +863,7 @@ def parse_multipart_form_data(
859863

860864

861865
def format_timestamp(
862-
ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
866+
ts: Union[int, float, tuple, time.struct_time, datetime.datetime],
863867
) -> str:
864868
"""Formats a timestamp in the format used by HTTP.
865869

tornado/test/httputil_test.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,22 @@ def test_string(self):
409409
headers2 = HTTPHeaders.parse(str(headers))
410410
self.assertEqual(headers, headers2)
411411

412+
def test_invalid_header_names(self):
413+
invalid_names = [
414+
"",
415+
"foo bar",
416+
"foo\tbar",
417+
"foo\nbar",
418+
"foo\x00bar",
419+
"foo ",
420+
" foo",
421+
"é",
422+
]
423+
for name in invalid_names:
424+
headers = HTTPHeaders()
425+
with self.assertRaises(HTTPInputError):
426+
headers.add(name, "bar")
427+
412428

413429
class FormatTimestampTest(unittest.TestCase):
414430
# Make sure that all the input types are supported.

0 commit comments

Comments
 (0)