1use std::net::{IpAddr, SocketAddr};
4
5use bytes::Bytes;
6use http::request::Parts;
7use http::{HeaderMap, Method, Uri};
8use http_body_util::combinators::UnsyncBoxBody;
9use http_body_util::{BodyExt, Empty, Full};
10use next_rust_router::Params;
11use serde::de::DeserializeOwned;
12
13use crate::cookies::Cookies;
14use crate::error::{Error, Result};
15
16pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
17pub type RequestBody = UnsyncBoxBody<Bytes, BoxError>;
19
20pub struct Request {
22 parts: Parts,
23 body: std::sync::Mutex<Option<RequestBody>>,
26 buffered: Option<Bytes>,
27 params: Params,
28 cookies: Cookies,
29 remote_addr: Option<SocketAddr>,
30 body_limit: usize,
31}
32
33impl std::fmt::Debug for Request {
34 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 f.debug_struct("Request").field("method", &self.parts.method).field("uri", &self.parts.uri).finish()
36 }
37}
38
39impl Request {
40 pub fn from_parts(
41 parts: Parts,
42 body: RequestBody,
43 remote_addr: Option<SocketAddr>,
44 body_limit: usize,
45 secure_cookies: bool,
46 ) -> Self {
47 let cookies = Cookies::from_headers(&parts.headers, secure_cookies);
48 Request {
49 parts,
50 body: std::sync::Mutex::new(Some(body)),
51 buffered: None,
52 params: Params::new(),
53 cookies,
54 remote_addr,
55 body_limit,
56 }
57 }
58
59 pub fn from_http(req: http::Request<Bytes>) -> Self {
62 let (parts, body) = req.into_parts();
63 let body = Full::new(body).map_err(|never| match never {}).boxed_unsync();
64 Request::from_parts(parts, body, None, usize::MAX, false)
65 }
66
67 pub fn get(uri: &str) -> Self {
69 let req = http::Request::get(uri).body(Bytes::new()).expect("valid uri");
70 Request::from_http(req)
71 }
72
73 pub fn method(&self) -> &Method {
74 &self.parts.method
75 }
76
77 pub fn uri(&self) -> &Uri {
78 &self.parts.uri
79 }
80
81 pub fn path(&self) -> &str {
82 self.parts.uri.path()
83 }
84
85 pub fn query_string(&self) -> &str {
86 self.parts.uri.query().unwrap_or("")
87 }
88
89 pub fn query<T: DeserializeOwned>(&self) -> Result<T> {
91 serde_urlencoded::from_str(self.query_string())
92 .map_err(|e| Error::http(400, format!("invalid query string: {e}")))
93 }
94
95 pub fn query_param(&self, name: &str) -> Option<String> {
97 serde_urlencoded::from_str::<Vec<(String, String)>>(self.query_string())
98 .ok()?
99 .into_iter()
100 .find(|(k, _)| k == name)
101 .map(|(_, v)| v)
102 }
103
104 pub fn headers(&self) -> &HeaderMap {
105 &self.parts.headers
106 }
107
108 pub fn headers_mut(&mut self) -> &mut HeaderMap {
109 &mut self.parts.headers
110 }
111
112 pub fn header(&self, name: &str) -> Option<&str> {
114 self.parts.headers.get(name).and_then(|v| v.to_str().ok())
115 }
116
117 pub fn params(&self) -> &Params {
118 &self.params
119 }
120
121 pub fn param(&self, name: &str) -> Option<&str> {
122 self.params.get(name)
123 }
124
125 pub(crate) fn set_params(&mut self, params: Params) {
126 self.params = params;
127 }
128
129 pub fn cookies(&self) -> &Cookies {
130 &self.cookies
131 }
132
133 pub fn remote_addr(&self) -> Option<SocketAddr> {
134 self.remote_addr
135 }
136
137 pub fn client_ip(&self) -> Option<IpAddr> {
142 client_ip_from(self.headers(), self.remote_addr, crate::trust_proxy())
143 }
144
145 pub fn extensions(&self) -> &http::Extensions {
146 &self.parts.extensions
147 }
148
149 pub fn extensions_mut(&mut self) -> &mut http::Extensions {
150 &mut self.parts.extensions
151 }
152
153 pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
155 self.parts.extensions.get::<T>()
156 }
157
158 pub fn insert_extension<T: Clone + Send + Sync + 'static>(&mut self, value: T) {
159 self.parts.extensions.insert(value);
160 }
161
162 pub fn set_path(&mut self, path_and_query: &str) -> Result<()> {
164 let uri: Uri = path_and_query.parse().map_err(|_| Error::http(400, "invalid rewrite target"))?;
165 self.parts.uri = uri;
166 Ok(())
167 }
168
169 pub(crate) fn limit_body(&mut self, limit: usize) {
171 self.body_limit = self.body_limit.min(limit);
172 }
173
174 pub fn set_body_limit(&mut self, limit: usize) {
176 self.body_limit = limit;
177 }
178
179 pub fn is_websocket_upgrade(&self) -> bool {
180 self.header("upgrade").is_some_and(|u| u.eq_ignore_ascii_case("websocket"))
181 }
182
183 pub fn same_origin(&self) -> bool {
201 let allowed = self
202 .extension::<std::sync::Arc<next_rust_core::Config>>()
203 .map(|c| c.security.allowed_origins.as_slice())
204 .unwrap_or(&[]);
205 crate::actions::same_origin(self, allowed)
206 }
207
208 pub fn is_secure(&self) -> bool {
210 self.parts.uri.scheme_str() == Some("https") || self.header("x-forwarded-proto") == Some("https")
211 }
212
213 pub async fn bytes(&mut self) -> Result<Bytes> {
216 if let Some(b) = &self.buffered {
217 return Ok(b.clone());
218 }
219 if let Some(len) = self.header("content-length").and_then(|l| l.parse::<usize>().ok())
220 && len > self.body_limit
221 {
222 return Err(Error::http(413, "request body too large"));
223 }
224 let limit = self.body_limit;
225 let mut body = self
226 .body
227 .get_mut()
228 .unwrap_or_else(|e| e.into_inner())
229 .take()
230 .unwrap_or_else(|| Empty::new().map_err(|never| match never {}).boxed_unsync());
231 let mut buf: Vec<u8> = Vec::new();
232 while let Some(frame) = body.frame().await {
233 let frame = match frame {
234 Ok(f) => f,
235 Err(e) => return Err(read_error(&*e)),
236 };
237 if let Ok(data) = frame.into_data() {
238 if buf.len() + data.len() > limit {
239 return Err(Error::http(413, "request body too large"));
240 }
241 buf.extend_from_slice(&data);
242 }
243 }
244 let bytes = Bytes::from(buf);
245 self.buffered = Some(bytes.clone());
246 Ok(bytes)
247 }
248
249 pub async fn raw_body(&mut self) -> Result<Bytes> {
251 self.bytes().await
252 }
253
254 pub async fn text(&mut self) -> Result<String> {
255 let b = self.bytes().await?;
256 String::from_utf8(b.to_vec()).map_err(|_| Error::http(400, "request body is not valid UTF-8"))
257 }
258
259 pub async fn json<T: DeserializeOwned>(&mut self) -> Result<T> {
260 let b = self.bytes().await?;
261 serde_json::from_slice(&b).map_err(|e| Error::http(400, format!("invalid JSON body: {e}")))
262 }
263
264 pub async fn form<T: DeserializeOwned>(&mut self) -> Result<T> {
266 let b = self.bytes().await?;
267 serde_urlencoded::from_bytes(&b).map_err(|e| Error::http(400, format!("invalid form body: {e}")))
268 }
269
270 pub fn take_body(&mut self) -> Option<RequestBody> {
273 if let Some(b) = self.buffered.clone() {
274 return Some(Full::new(b).map_err(|never| match never {}).boxed_unsync());
275 }
276 self.body.get_mut().unwrap_or_else(|e| e.into_inner()).take()
277 }
278
279 pub fn parts(&self) -> &Parts {
280 &self.parts
281 }
282
283 #[cfg_attr(not(feature = "websocket"), allow(dead_code))]
284 pub(crate) fn parts_mut(&mut self) -> &mut Parts {
285 &mut self.parts
286 }
287}
288
289fn read_error(e: &(dyn std::error::Error + Send + Sync)) -> Error {
290 Error::http(400, format!("failed to read request body: {e}"))
291}
292
293pub(crate) fn client_ip_from(headers: &HeaderMap, peer: Option<SocketAddr>, trust: bool) -> Option<IpAddr> {
295 if trust
296 && let Some(first) =
297 headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()).and_then(|v| v.split(',').next())
298 && let Some(ip) = parse_ip(first.trim())
299 {
300 return Some(ip);
301 }
302 peer.map(|a| a.ip())
303}
304
305fn parse_ip(s: &str) -> Option<IpAddr> {
308 s.parse::<IpAddr>()
309 .ok()
310 .or_else(|| s.parse::<SocketAddr>().ok().map(|a| a.ip()))
311 .or_else(|| s.strip_prefix('[')?.strip_suffix(']')?.parse().ok())
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 fn with_headers(headers: &[(&str, &str)]) -> Request {
319 let mut b = http::Request::post("/api/x");
320 for (k, v) in headers {
321 b = b.header(*k, *v);
322 }
323 Request::from_http(b.body(Bytes::new()).unwrap())
324 }
325
326 #[test]
327 fn same_origin_reads_fetch_metadata_then_origin() {
328 assert!(with_headers(&[("host", "app.example"), ("sec-fetch-site", "same-origin")]).same_origin());
329 assert!(with_headers(&[("host", "app.example"), ("sec-fetch-site", "none")]).same_origin());
330 assert!(!with_headers(&[("host", "app.example"), ("sec-fetch-site", "cross-site")]).same_origin());
331 assert!(with_headers(&[("host", "app.example"), ("origin", "https://app.example")]).same_origin());
332 assert!(!with_headers(&[("host", "app.example"), ("origin", "https://evil.example")]).same_origin());
333 assert!(with_headers(&[("host", "app.example")]).same_origin());
335 let mut req = with_headers(&[("host", "app.example"), ("origin", "https://admin.example")]);
337 assert!(!req.same_origin());
338 let mut config = next_rust_core::Config::default();
339 config.security.allowed_origins = vec!["https://admin.example".into()];
340 req.insert_extension(std::sync::Arc::new(config));
341 assert!(req.same_origin());
342 }
343
344 #[test]
345 fn client_ip_honours_trust_proxy() {
346 use std::net::{Ipv4Addr, Ipv6Addr};
347 let peer: SocketAddr = "10.0.0.1:443".parse().unwrap();
348 let mut h = HeaderMap::new();
349 h.insert("x-forwarded-for", "203.0.113.7, 10.0.0.1".parse().unwrap());
350 assert_eq!(client_ip_from(&h, Some(peer), false), Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))), "untrusted");
351 assert_eq!(client_ip_from(&h, Some(peer), true), Some(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7))));
352 for (value, want) in [
353 ("198.51.100.2:5678", IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2))),
354 ("[2001:db8::1]:5678", IpAddr::V6("2001:db8::1".parse::<Ipv6Addr>().unwrap())),
355 ("[2001:db8::1]", IpAddr::V6("2001:db8::1".parse::<Ipv6Addr>().unwrap())),
356 ] {
357 h.insert("x-forwarded-for", value.parse().unwrap());
358 assert_eq!(client_ip_from(&h, Some(peer), true), Some(want), "{value}");
359 }
360 h.insert("x-forwarded-for", "not-an-ip".parse().unwrap());
362 assert_eq!(client_ip_from(&h, Some(peer), true), Some(peer.ip()));
363 assert_eq!(client_ip_from(&HeaderMap::new(), None, true), None);
364 }
365}