1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//! Python headers wrapper around `http::HeaderMap`.
use pyo3::prelude::*;
use pyo3::types::{PyList, PyString, PyTuple};
/// A case-insensitive HTTP headers container exposed to Python.
#[pyclass(name = "Headers", from_py_object)]
#[derive(Clone)]
pub struct PyHeaders {
inner: http::HeaderMap,
}
// Manual `Debug` that redacts credential-carrying headers: the derived
// `HeaderMap` debug would dump `authorization`/`cookie` values in clear
// (panic captures, logs), while `__repr__` redacts them.
impl std::fmt::Debug for PyHeaders {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let pairs: Vec<(String, String)> = self
.inner
.iter()
.map(|(k, v)| {
let name = k.as_str();
let val = if matches!(
name,
"authorization" | "proxy-authorization" | "cookie" | "set-cookie"
) {
"<redacted>"
} else {
v.to_str().unwrap_or("<binary>")
};
(name.to_owned(), val.to_owned())
})
.collect();
f.debug_struct("PyHeaders").field("inner", &pairs).finish()
}
}
impl PyHeaders {
/// Create a `PyHeaders` from an `http::HeaderMap`.
pub fn from_header_map(inner: http::HeaderMap) -> Self {
Self { inner }
}
/// Get a reference to the inner `HeaderMap`.
pub fn inner_ref(&self) -> &http::HeaderMap {
&self.inner
}
}
#[pymethods]
impl PyHeaders {
/// Get a header value by name (case-insensitive).
///
/// Returns the value as a string, or `default` if not present.
#[pyo3(signature = (name, default=None))]
fn get<'py>(
&self,
py: Python<'py>,
name: &str,
default: Option<&Bound<'py, PyAny>>,
) -> Bound<'py, PyAny> {
match self.inner.get(name).and_then(|v| v.to_str().ok()) {
Some(s) => PyString::new(py, s).into_any(),
None => match default {
Some(d) => d.clone(),
None => py.None().into_bound(py),
},
}
}
/// Check if a header name is present (case-insensitive).
fn __contains__(&self, name: &str) -> bool {
self.inner.contains_key(name)
}
/// Get a header value by name (case-insensitive), raising `KeyError` if absent.
fn __getitem__(&self, name: &str) -> PyResult<String> {
self.inner
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
.ok_or_else(|| {
PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!("header '{name}' not found"))
})
}
/// Returns the number of headers.
fn __len__(&self) -> usize {
self.inner.len()
}
/// Iterate over header names (one entry per (name, value) pair, so
/// duplicate headers like `Set-Cookie` appear multiple times; matches
/// `__len__` and HTTPX per-pair semantics).
fn __iter__(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
let names: Vec<String> = self
.inner
.iter()
.map(|(k, _)| k.as_str().to_owned())
.collect();
Ok(PyList::new(py, names)?.into())
}
/// Returns a list of header names (one entry per pair, duplicates included).
fn keys(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
let names: Vec<String> = self
.inner
.iter()
.map(|(k, _)| k.as_str().to_owned())
.collect();
Ok(PyList::new(py, names)?.into())
}
/// Returns a list of header values.
fn values(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
let vals: Vec<String> = self
.inner
.values()
.filter_map(|v| v.to_str().ok())
.map(str::to_string)
.collect();
Ok(PyList::new(py, vals)?.into())
}
/// Returns a list of (name, value) tuples.
fn items(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
let mut result: Vec<Bound<'_, PyTuple>> = Vec::new();
for (k, v) in &self.inner {
let name = k.as_str();
if let Ok(val) = v.to_str() {
result.push(PyTuple::new(py, [name, val])?);
}
}
Ok(PyList::new(py, result)?.into())
}
/// Get all values for a header name (case-insensitive).
///
/// Returns a list of strings, one per occurrence of the header.
/// Raises `ValueError` if the header name is invalid.
fn get_list(&self, name: &str) -> PyResult<Vec<String>> {
let header_name = http::header::HeaderName::from_bytes(name.as_bytes()).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Invalid header name: {e}"))
})?;
let values: Vec<String> = self
.inner
.get_all(&header_name)
.iter()
.map(|v| String::from_utf8_lossy(v.as_bytes()).to_string())
.collect();
Ok(values)
}
/// String representation for debugging.
fn __repr__(&self) -> String {
let pairs: Vec<String> = self
.inner
.iter()
.map(|(k, v)| {
let name = k.as_str();
let val = if matches!(
name,
"authorization" | "proxy-authorization" | "cookie" | "set-cookie"
) {
"<redacted>"
} else {
v.to_str().unwrap_or("<binary>")
};
format!("{name}: {val}")
})
.collect();
format!("Headers({{{}}})", pairs.join(", "))
}
}