Add valdation for header name (#6154)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Nate Prewitt · committed by GitHub · parent 60865f2 · Browse files · 3 files·+72 added−62 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+72 added−62 removed
- tests:+45 added−43 removed
- other:+27 added−19 removed
Provenance
- Commit
e36f345- Tree
996defe- Author
Nate Prewitt <nate.prewitt@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
60865f2
3 files changed+72 added−62 removed
modified:requests/_internal_utils.py+11 added
3 unmodified lines4 5 Provides utility functions that are consumed internally by Requests6 which depend on extremely few external helpers (such as compat)7 """8+import re9 10 from .compat import builtin_str11 12+_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")13+_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")14+_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")15+_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")16 17+HEADER_VALIDATORS = {18+ bytes: (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE),19+ str: (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR),20+}21+22+23 def to_native_string(string, encoding="ascii"):24 """Given a string object, regardless of type, returns a representation of25 that string in the native string type, encoding and decoding where26 necessary. This assumes ASCII unless told otherwise.22 unmodified linesmodified:requests/utils.py+16 added-19 removed
23 unmodified lines24 from . import certs25 from .__version__ import __version__26 27 # to_native_string is unused here, but imported here for backwards compatibility28-from ._internal_utils import to_native_string # noqa: F40128+from ._internal_utils import HEADER_VALIDATORS, to_native_string # noqa: F40129 from .compat import (30 Mapping,31 basestring,32 bytes,990 unmodified lines1023 1024 return auth1025 1026 1027-# Moved outside of function to avoid recompile every call1028-_CLEAN_HEADER_REGEX_BYTE = re.compile(b"^\\S[^\\r\\n]*$|^$")1029-_CLEAN_HEADER_REGEX_STR = re.compile(r"^\S[^\r\n]*$|^$")1030-1031-1027 def check_header_validity(header):1033- """Verifies that header value is a string which doesn't contain1034- leading whitespace or return characters. This prevents unintended1035- header injection.1028+ """Verifies that header parts don't contain leading whitespace1029+ reserved characters, or return characters.1030 1031 :param header: tuple, in the format (name, value).1032 """1033 name, value = header1034 1041- if isinstance(value, bytes):1042- pat = _CLEAN_HEADER_REGEX_BYTE1043- else:1044- pat = _CLEAN_HEADER_REGEX_STR1045- try:1046- if not pat.match(value):1035+ for part in header:1036+ if type(part) not in HEADER_VALIDATORS:1037 raise InvalidHeader(1048- f"Invalid return character or leading space in header: {name}"1038+ f"Header part ({part!r}) from {{{name!r}: {value!r}}} must be "1039+ f"of type str or bytes, not {type(part)}"1040 )1050- except TypeError:1041+1042+ _validate_header_part(name, "name", HEADER_VALIDATORS[type(name)][0])1043+ _validate_header_part(value, "value", HEADER_VALIDATORS[type(value)][1])1044+1045+1046+def _validate_header_part(header_part, header_kind, validator):1047+ if not validator.match(header_part):1048 raise InvalidHeader(1052- f"Value for header {{{name}: {value}}} must be of type "1053- f"str or bytes, not {type(value)}"1049+ f"Invalid leading whitespace, reserved character(s), or return"1050+ f"character(s) in header {header_kind}: {header_part!r}"1051 )1052 1053 1054 def urldefragauth(url):32 unmodified linesmodified:tests/test_requests.py+45 added-43 removed
1094 unmodified lines1095 1096 def test_custom_content_type(self, httpbin):1097 with open(__file__, "rb") as f1:1098 with open(__file__, "rb") as f2:1099- data={"stuff": json.dumps({"a": 123})}1099+ data = {"stuff": json.dumps({"a": 123})}1100 files = {1101 "file1": ("test_requests.py", f1),1102 "file2": ("test_requests", f2, "text/py-content-type"),1103 }577 unmodified lines1681 assert "byte" in p.headers.keys()1682 1683 def test_header_validation(self, httpbin):1684 """Ensure prepare_headers regex isn't flagging valid header contents."""1685- headers_ok = {1685+ valid_headers = {1686 "foo": "bar baz qux",1687 "bar": b"fbbq",1688 "baz": "",1689 "qux": "1",1690 }1691- r = requests.get(httpbin("get"), headers=headers_ok)1692- assert r.request.headers["foo"] == headers_ok["foo"]1691+ r = requests.get(httpbin("get"), headers=valid_headers)1692+ for key in valid_headers.keys():1693+ valid_headers[key] == r.request.headers[key]1694 1695+ @pytest.mark.parametrize(1696+ "invalid_header, key",1697+ (1698+ ({"foo": 3}, "foo"),1699+ ({"bar": {"foo": "bar"}}, "bar"),1700+ ({"baz": ["foo", "bar"]}, "baz"),1701+ ),1702+ )1694- def test_header_value_not_str(self, httpbin):1703+ def test_header_value_not_str(self, httpbin, invalid_header, key):1704 """Ensure the header value is of type string or bytes as1705 per discussion in GH issue #33861706 """1698- headers_int = {"foo": 3}1699- headers_dict = {"bar": {"foo": "bar"}}1700- headers_list = {"baz": ["foo", "bar"]}1701-1702- # Test for int1707 with pytest.raises(InvalidHeader) as excinfo:1704- requests.get(httpbin("get"), headers=headers_int)1705- assert "foo" in str(excinfo.value)1706- # Test for dict1707- with pytest.raises(InvalidHeader) as excinfo:1708- requests.get(httpbin("get"), headers=headers_dict)1709- assert "bar" in str(excinfo.value)1710- # Test for list1711- with pytest.raises(InvalidHeader) as excinfo:1712- requests.get(httpbin("get"), headers=headers_list)1713- assert "baz" in str(excinfo.value)1708+ requests.get(httpbin("get"), headers=invalid_header)1709+ assert key in str(excinfo.value)1710 1711+ @pytest.mark.parametrize(1712+ "invalid_header",1713+ (1714+ {"foo": "bar\r\nbaz: qux"},1715+ {"foo": "bar\n\rbaz: qux"},1716+ {"foo": "bar\nbaz: qux"},1717+ {"foo": "bar\rbaz: qux"},1718+ {"fo\ro": "bar"},1719+ {"fo\r\no": "bar"},1720+ {"fo\n\ro": "bar"},1721+ {"fo\no": "bar"},1722+ ),1723+ )1715- def test_header_no_return_chars(self, httpbin):1724+ def test_header_no_return_chars(self, httpbin, invalid_header):1725 """Ensure that a header containing return character sequences raise an1726 exception. Otherwise, multiple headers are created from single string.1727 """1719- headers_ret = {"foo": "bar\r\nbaz: qux"}1720- headers_lf = {"foo": "bar\nbaz: qux"}1721- headers_cr = {"foo": "bar\rbaz: qux"}1722-1723- # Test for newline1728 with pytest.raises(InvalidHeader):1725- requests.get(httpbin("get"), headers=headers_ret)1726- # Test for line feed1727- with pytest.raises(InvalidHeader):1728- requests.get(httpbin("get"), headers=headers_lf)1729- # Test for carriage return1730- with pytest.raises(InvalidHeader):1731- requests.get(httpbin("get"), headers=headers_cr)1729+ requests.get(httpbin("get"), headers=invalid_header)1730 1731+ @pytest.mark.parametrize(1732+ "invalid_header",1733+ (1734+ {" foo": "bar"},1735+ {"\tfoo": "bar"},1736+ {" foo": "bar"},1737+ {"foo": " bar"},1738+ {"foo": " bar"},1739+ {"foo": "\tbar"},1740+ {" ": "bar"},1741+ ),1742+ )1733- def test_header_no_leading_space(self, httpbin):1743+ def test_header_no_leading_space(self, httpbin, invalid_header):1744 """Ensure headers containing leading whitespace raise1745 InvalidHeader Error before sending.1746 """1737- headers_space = {"foo": " bar"}1738- headers_tab = {"foo": " bar"}1739-1740- # Test for whitespace1747 with pytest.raises(InvalidHeader):1742- requests.get(httpbin("get"), headers=headers_space)1748+ requests.get(httpbin("get"), headers=invalid_header)1749 1744- # Test for tab1745- with pytest.raises(InvalidHeader):1746- requests.get(httpbin("get"), headers=headers_tab)1747-1750 @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))1751 def test_can_send_objects_with_files(self, httpbin, files):1752 data = {"a": "this is a string"}1753 files = {"b": files}1007 unmodified lines