Skip to content

Commit b877a27

Browse files
lesnik512claude
andcommitted
fix: validate Request fields in __post_init__
Adds Request.__post_init__ that validates: - url is a non-empty str - headers, params, cookies, extensions are each a Mapping - header and cookie names/values are non-empty str, no CR or LF with_* methods inherit validation via dataclasses.replace; no per-method code needed. Header validation is minimal per spec (reject CR/LF, non-str, empty); full RFC 9110 token validation is out of scope. Closes deferred-work entries: "Header name/value validation", "URL validation" (Request.url part), "with_query(None) handling". Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 389c804 commit b877a27

2 files changed

Lines changed: 110 additions & 0 deletions

File tree

‎src/httpware/request.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,18 @@
66
from typing import Any, Self
77

88

9+
def _validate_header_or_cookie(name: str, value: str, *, kind: str) -> None:
10+
if not isinstance(name, str) or not isinstance(value, str):
11+
msg = f"{kind} name and value must be str"
12+
raise TypeError(msg)
13+
if not name or not value:
14+
msg = f"{kind} name and value must be non-empty"
15+
raise ValueError(msg)
16+
if any(c in name or c in value for c in ("\r", "\n")):
17+
msg = f"{kind} name and value must not contain CR or LF"
18+
raise ValueError(msg)
19+
20+
921
@dataclass(frozen=True, slots=True)
1022
class Request:
1123
"""Immutable HTTP request value type."""
@@ -18,6 +30,23 @@ class Request:
1830
body: bytes | None = None
1931
extensions: Mapping[str, Any] = field(default_factory=dict)
2032

33+
def __post_init__(self) -> None:
34+
if not isinstance(self.url, str):
35+
msg = "url must be str"
36+
raise TypeError(msg)
37+
if not self.url:
38+
msg = "url must be non-empty"
39+
raise ValueError(msg)
40+
for field_name in ("headers", "params", "cookies", "extensions"):
41+
field_value = getattr(self, field_name)
42+
if not isinstance(field_value, Mapping):
43+
msg = f"{field_name} must be a Mapping (got {type(field_value).__name__})"
44+
raise TypeError(msg)
45+
for name, value in self.headers.items():
46+
_validate_header_or_cookie(name, value, kind="header")
47+
for name, value in self.cookies.items():
48+
_validate_header_or_cookie(name, value, kind="cookie")
49+
2150
def with_header(self, name: str, value: str) -> Self:
2251
"""Return a copy with the given header added or replaced."""
2352
return dataclasses.replace(self, headers={**self.headers, name: value})

‎tests/test_request.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,3 +143,84 @@ class _Marker:
143143
new = r.with_extension("marker", marker)
144144
assert new.extensions == {"marker": marker}
145145
assert new.extensions["marker"] is marker
146+
147+
148+
def test_request_rejects_empty_url() -> None:
149+
with pytest.raises(ValueError, match="url must be non-empty"):
150+
Request(method="GET", url="")
151+
152+
153+
def test_request_rejects_non_str_url() -> None:
154+
with pytest.raises(TypeError, match="url must be str"):
155+
Request(method="GET", url=None) # ty: ignore[invalid-argument-type]
156+
157+
158+
def test_with_url_rejects_empty() -> None:
159+
r = Request(method="GET", url="/")
160+
with pytest.raises(ValueError, match="url must be non-empty"):
161+
r.with_url("")
162+
163+
164+
def test_request_rejects_header_with_crlf_in_value() -> None:
165+
with pytest.raises(ValueError, match="header name and value must not contain CR or LF"):
166+
Request(method="GET", url="/", headers={"X-Trace": "value\r\nInjected: yes"})
167+
168+
169+
def test_request_rejects_header_with_crlf_in_name() -> None:
170+
with pytest.raises(ValueError, match="header name and value must not contain CR or LF"):
171+
Request(method="GET", url="/", headers={"X-Bad\r\nInjected": "value"})
172+
173+
174+
def test_request_rejects_empty_header_name() -> None:
175+
with pytest.raises(ValueError, match="header name and value must be non-empty"):
176+
Request(method="GET", url="/", headers={"": "value"})
177+
178+
179+
def test_request_rejects_empty_header_value() -> None:
180+
with pytest.raises(ValueError, match="header name and value must be non-empty"):
181+
Request(method="GET", url="/", headers={"X-Trace": ""})
182+
183+
184+
def test_request_rejects_non_str_header_value() -> None:
185+
with pytest.raises(TypeError, match="header name and value must be str"):
186+
Request(method="GET", url="/", headers={"X-Trace": None}) # ty: ignore[invalid-argument-type]
187+
188+
189+
def test_request_rejects_cookie_with_crlf() -> None:
190+
with pytest.raises(ValueError, match="cookie name and value must not contain CR or LF"):
191+
Request(method="GET", url="/", cookies={"session": "abc\r\nSet-Cookie: evil"})
192+
193+
194+
def test_request_rejects_empty_cookie_value() -> None:
195+
with pytest.raises(ValueError, match="cookie name and value must be non-empty"):
196+
Request(method="GET", url="/", cookies={"session": ""})
197+
198+
199+
def test_with_header_rejects_crlf() -> None:
200+
r = Request(method="GET", url="/")
201+
with pytest.raises(ValueError, match="header name and value must not contain CR or LF"):
202+
r.with_header("X-Trace", "value\r\n")
203+
204+
205+
def test_with_cookie_rejects_crlf() -> None:
206+
r = Request(method="GET", url="/")
207+
with pytest.raises(ValueError, match="cookie name and value must not contain CR or LF"):
208+
r.with_cookie("session", "abc\r\n")
209+
210+
211+
@pytest.mark.parametrize("field_name", ["headers", "params", "cookies", "extensions"])
212+
def test_request_rejects_none_mapping_field(field_name: str) -> None:
213+
with pytest.raises(TypeError, match=f"{field_name} must be a Mapping"):
214+
Request(method="GET", url="/", **{field_name: None}) # ty: ignore[invalid-argument-type]
215+
216+
217+
@pytest.mark.parametrize("field_name", ["headers", "params", "cookies", "extensions"])
218+
def test_request_rejects_list_mapping_field(field_name: str) -> None:
219+
with pytest.raises(TypeError, match=f"{field_name} must be a Mapping"):
220+
Request(method="GET", url="/", **{field_name: []}) # ty: ignore[invalid-argument-type]
221+
222+
223+
def test_with_query_none_raises() -> None:
224+
r = Request(method="GET", url="/")
225+
with pytest.raises(TypeError, match="params must be a Mapping"):
226+
r.with_query(None) # ty: ignore[invalid-argument-type]

0 commit comments

Comments
 (0)