Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ fn oxyroute_debug() -> bool {
.unwrap_or(false)
}

fn contains_crlf(s: &str) -> bool {
s.contains('\r') || s.contains('\n')
}

fn is_unsafe_cookie_line(s: &str) -> bool {
s.chars().any(|c| c == '\r' || c == '\n' || c.is_control())
}

/// Map Python `PyErr` to HTTP 500 with a JSON body (no exception text unless `OXYROUTE_DEBUG=1`).
async fn send_internal_error(
protocol: &Py<PyAny>,
Expand Down Expand Up @@ -98,6 +106,9 @@ async fn try_http_exception(protocol: &Py<PyAny>, err: &PyErr) -> PyResult<Optio
let pair = item.downcast::<PyTuple>()?;
let k: String = pair.get_item(0)?.extract()?;
let v: String = pair.get_item(1)?.extract()?;
if contains_crlf(&k) || contains_crlf(&v) {
return Ok(None);
}
headers.push((k, v));
}
Ok(Some((status, body, headers)))
Expand Down Expand Up @@ -994,6 +1005,11 @@ fn structured_from_status_body(
for (k, v) in d.iter() {
let key: String = k.extract()?;
let val: String = v.extract()?;
if contains_crlf(&key) || contains_crlf(&val) {
return Err(pyo3::exceptions::PyValueError::new_err(
"unsafe response header contains CR or LF",
));
}
if key.eq_ignore_ascii_case("content-type") {
has_ct = true;
}
Expand All @@ -1008,6 +1024,11 @@ fn structured_from_status_body(
if !c.is_none() {
for item in c.downcast::<PyList>()?.iter() {
let s: String = item.extract()?;
if is_unsafe_cookie_line(&s) {
return Err(pyo3::exceptions::PyValueError::new_err(
"unsafe set-cookie value contains control characters",
));
}
pairs.push(("set-cookie".to_string(), s));
}
}
Expand Down
61 changes: 61 additions & 0 deletions tests/test_header_sanitization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Issue #72: reject unsafe CR/LF control chars in response headers/cookies."""

from __future__ import annotations

import asyncio

import httpx
from oxyroute import App, HTTPException, Response


def test_response_header_crlf_is_rejected_with_500() -> None:
app = App()

@app.get("/h")
def h() -> Response:
return Response(status=200, body="ok", headers={"X-Bad\r\nInjected": "1"})

async def _run() -> None:
tr = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=tr, base_url="http://test") as c:
r = await c.get("/h")
assert r.status_code == 500
assert r.headers.get("x-bad") is None
assert r.json().get("error") == "internal server error"

asyncio.run(_run())


def test_response_cookie_control_chars_is_rejected_with_500() -> None:
app = App()

@app.get("/c")
def c() -> Response:
return Response(status=200, body="ok", cookies=["a=1\r\nX: y"])

async def _run() -> None:
tr = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=tr, base_url="http://test") as c:
r = await c.get("/c")
assert r.status_code == 500
assert r.json().get("error") == "internal server error"

asyncio.run(_run())


def test_http_exception_header_crlf_is_safely_downgraded_to_500() -> None:
app = App()

@app.get("/e")
def e() -> str:
raise HTTPException(400, "bad", headers={"X-Err\nInject": "1"})

async def _run() -> None:
tr = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=tr, base_url="http://test") as c:
r = await c.get("/e")
assert r.status_code == 500
assert r.headers.get("x-err") is None
assert r.json().get("error") == "internal server error"

asyncio.run(_run())
Loading