Skip to main content

ullun/
request.rs

1//! Request types and extractors
2
3use crate::cookies::Cookies;
4use crate::error::{Error, Result};
5use serde::de::DeserializeOwned;
6use std::collections::HashMap;
7use std::sync::{Arc, OnceLock};
8
9/// Path parameters extracted from route
10#[derive(Debug, Clone)]
11pub struct Params {
12    inner: HashMap<String, String>,
13}
14
15impl Params {
16    pub fn new() -> Self {
17        Self {
18            inner: HashMap::new(),
19        }
20    }
21
22    pub fn insert(&mut self, key: String, value: String) {
23        self.inner.insert(key, value);
24    }
25
26    pub fn get(&self, key: &str) -> Result<&str> {
27        self.inner
28            .get(key)
29            .map(|s| s.as_str())
30            .ok_or_else(|| Error::bad_request(format!("Missing param: {}", key)))
31    }
32
33    pub fn get_opt(&self, key: &str) -> Option<&str> {
34        self.inner.get(key).map(|s| s.as_str())
35    }
36
37    /// Parse a path parameter into any `FromStr` type, e.g. `params.parse::<u64>("id")?`
38    ///
39    /// Answers `400` naming the parameter when it does not parse.
40    pub fn parse<T: std::str::FromStr>(&self, key: &str) -> Result<T> {
41        self.get(key)?
42            .parse()
43            .map_err(|_| Error::bad_request(format!("Invalid path parameter '{}'", key)))
44    }
45}
46
47impl Default for Params {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53/// Query parameters from URL (also used for `application/x-www-form-urlencoded` bodies)
54#[derive(Debug, Clone)]
55pub struct Query {
56    inner: HashMap<String, String>,
57    raw: String,
58}
59
60impl Query {
61    pub fn new() -> Self {
62        Self {
63            inner: HashMap::new(),
64            raw: String::new(),
65        }
66    }
67
68    /// Parse `a=1&b=two`. Keys and values are percent-decoded and `+` is a
69    /// space. Pairs without `=` are kept with an empty value; if a key repeats,
70    /// the last value wins.
71    pub fn parse_query_string(query: &str) -> Self {
72        let mut q = Query {
73            inner: HashMap::new(),
74            raw: query.to_string(),
75        };
76        for pair in query.split('&').filter(|p| !p.is_empty()) {
77            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
78            q.inner
79                .insert(decode_component(key), decode_component(value));
80        }
81        q
82    }
83
84    pub fn get(&self, key: &str) -> Option<&str> {
85        self.inner.get(key).map(|s| s.as_str())
86    }
87
88    pub fn contains(&self, key: &str) -> bool {
89        self.inner.contains_key(key)
90    }
91
92    pub fn is_empty(&self) -> bool {
93        self.inner.is_empty()
94    }
95
96    /// Deserialize into a struct; numbers, booleans and `Option` are converted
97    /// from their string form.
98    pub fn parse<T: DeserializeOwned>(&self) -> Result<T> {
99        serde_urlencoded::from_str(&self.raw)
100            .map_err(|e| Error::bad_request(format!("Invalid query params: {}", e)))
101    }
102}
103
104fn decode_component(s: &str) -> String {
105    let s = s.replace('+', " ");
106    urlencoding::decode(&s).map(|c| c.into_owned()).unwrap_or(s)
107}
108
109impl Default for Query {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115/// The verified client certificate of a TLS connection (DER)
116#[derive(Debug, Clone)]
117pub struct ClientCertificate(pub Vec<u8>);
118
119/// Type-keyed storage for shared application state
120#[derive(Default)]
121pub(crate) struct StateMap {
122    values: HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>,
123}
124
125impl StateMap {
126    pub(crate) fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
127        self.values
128            .insert(std::any::TypeId::of::<T>(), Arc::new(value));
129    }
130
131    pub(crate) fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
132        self.values
133            .get(&std::any::TypeId::of::<T>())
134            .and_then(|v| v.downcast_ref::<T>())
135    }
136
137    pub(crate) fn get_arc<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
138        self.values
139            .get(&std::any::TypeId::of::<T>())
140            .and_then(|v| v.clone().downcast::<T>().ok())
141    }
142}
143
144/// HTTP Request wrapper
145pub struct Request {
146    pub method: http::Method,
147    pub uri: http::Uri,
148    pub headers: http::HeaderMap,
149    pub body: bytes::Bytes,
150    pub params: Params,
151    pub query: Query,
152    /// Typed per-request data; middleware can attach values for handlers
153    /// (authenticated user, request id, ...).
154    pub extensions: http::Extensions,
155    /// Address of the connected peer (the proxy when behind one)
156    pub remote_addr: Option<std::net::SocketAddr>,
157    /// The route pattern that matched, e.g. `/users/{id}`; `None` when no route
158    /// matched. Use it, not the raw path, as a metrics label or log field: it
159    /// stays the same for every id.
160    pub matched_path: Option<std::sync::Arc<str>>,
161    /// The request arrived over TLS (`App::tls`). Behind a TLS-terminating
162    /// proxy this is `false`; see `secure::RequireHttps::trust_forwarded_proto`.
163    pub secure: bool,
164    pub(crate) state: Option<std::sync::Arc<StateMap>>,
165    pub(crate) shutdown: Option<crate::shutdown::Shutdown>,
166    cookies: OnceLock<Cookies>,
167}
168
169impl Request {
170    pub fn new(
171        method: http::Method,
172        uri: http::Uri,
173        headers: http::HeaderMap,
174        body: bytes::Bytes,
175    ) -> Self {
176        let query = uri
177            .query()
178            .map(Query::parse_query_string)
179            .unwrap_or_default();
180
181        Self {
182            method,
183            uri,
184            headers,
185            body,
186            params: Params::new(),
187            query,
188            extensions: http::Extensions::new(),
189            remote_addr: None,
190            matched_path: None,
191            secure: false,
192            state: None,
193            shutdown: None,
194            cookies: OnceLock::new(),
195        }
196    }
197
198    /// Which of `offered` media types the client prefers according to `Accept`
199    /// (`None` when it accepts none of them), see [`crate::negotiate`]
200    pub fn accepts<'a>(&self, offered: &[&'a str]) -> Option<&'a str> {
201        let header = self
202            .headers
203            .get(http::header::ACCEPT)
204            .and_then(|v| v.to_str().ok())
205            .unwrap_or("");
206        crate::negotiate::best(header, offered)
207    }
208
209    /// Which of `offered` languages the client prefers according to `Accept-Language`
210    pub fn accepts_language<'a>(&self, offered: &[&'a str]) -> Option<&'a str> {
211        let header = self
212            .headers
213            .get(http::header::ACCEPT_LANGUAGE)
214            .and_then(|v| v.to_str().ok())
215            .unwrap_or("");
216        crate::negotiate::best_language(header, offered)
217    }
218
219    /// A copy for work that outlives the request (background refreshes)
220    pub(crate) fn duplicate(&self) -> Request {
221        let mut copy = Request::new(
222            self.method.clone(),
223            self.uri.clone(),
224            self.headers.clone(),
225            self.body.clone(),
226        );
227        copy.params = self.params.clone();
228        copy.extensions = self.extensions.clone();
229        copy.remote_addr = self.remote_addr;
230        copy.matched_path = self.matched_path.clone();
231        copy.secure = self.secure;
232        copy.state = self.state.clone();
233        copy.shutdown = self.shutdown.clone();
234        copy
235    }
236
237    /// True when the request came in over TLS
238    pub fn is_secure(&self) -> bool {
239        self.secure
240    }
241
242    /// Nonce for inline scripts and styles, when the
243    /// [`SecurityHeaders`](crate::security_headers::SecurityHeaders) policy uses the
244    /// `{nonce}` placeholder
245    pub fn csp_nonce(&self) -> Option<&str> {
246        self.extensions
247            .get::<crate::security_headers::CspNonce>()
248            .map(|n| n.0.as_str())
249    }
250
251    /// DER of the leaf certificate the client presented during the TLS
252    /// handshake (mutual TLS, feature `tls`); `None` for anonymous clients and
253    /// plain HTTP. The certificate has already been verified against the CAs
254    /// given to `TlsConfig::client_auth`; check *which* verified client it is
255    /// (fingerprint or subject) before authorizing anything.
256    pub fn client_certificate(&self) -> Option<&[u8]> {
257        self.extensions
258            .get::<ClientCertificate>()
259            .map(|c| c.0.as_slice())
260    }
261
262    /// Shared application state registered with `App::state`
263    ///
264    /// Answers `500` when no value of type `T` was registered: that is a
265    /// programming error, not something the client can fix.
266    pub fn state<T: Send + Sync + 'static>(&self) -> Result<&T> {
267        self.try_state().ok_or_else(|| {
268            Error::internal(format!(
269                "State of type {} is not registered",
270                std::any::type_name::<T>()
271            ))
272        })
273    }
274
275    /// Signal that fires when the server begins shutting down
276    ///
277    /// Long-lived handlers (SSE streams, polling loops) select on it to end
278    /// promptly: `tokio::select! { _ = req.shutdown_signal().wait() => break, ... }`.
279    pub fn shutdown_signal(&self) -> crate::shutdown::Shutdown {
280        self.shutdown
281            .clone()
282            .unwrap_or_else(crate::shutdown::Shutdown::never)
283    }
284
285    /// An owned handle to the same state, for when the value must outlive a
286    /// borrow of the request (it is moved into middleware `next.run(req)`, a
287    /// spawned task, ...)
288    pub fn state_arc<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
289        self.state
290            .as_ref()
291            .and_then(|s| s.get_arc::<T>())
292            .ok_or_else(|| {
293                Error::internal(format!(
294                    "State of type {} is not registered",
295                    std::any::type_name::<T>()
296                ))
297            })
298    }
299
300    /// Like [`Request::state`], `None` when the type is not registered
301    pub fn try_state<T: Send + Sync + 'static>(&self) -> Option<&T> {
302        self.state.as_ref()?.get::<T>()
303    }
304
305    /// Get cookies from the request
306    pub fn cookies(&self) -> &Cookies {
307        self.cookies.get_or_init(|| {
308            if let Some(cookie_header) = self.headers.get("cookie") {
309                if let Ok(cookie_str) = cookie_header.to_str() {
310                    Cookies::parse(cookie_str)
311                } else {
312                    Cookies::new()
313                }
314            } else {
315                Cookies::new()
316            }
317        })
318    }
319
320    /// Parse an `application/x-www-form-urlencoded` body into a struct
321    ///
322    /// Answers `415` for other content types and `400` for values that do not
323    /// fit the target type.
324    pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
325        self.require_form_content_type()?;
326        serde_urlencoded::from_bytes(&self.body)
327            .map_err(|e| Error::bad_request(format!("Invalid form data: {}", e)))
328    }
329
330    /// The same body as decoded key/value access (`+` and `%XX` decoded)
331    pub fn form_data(&self) -> Result<Query> {
332        self.require_form_content_type()?;
333        let text = std::str::from_utf8(&self.body)
334            .map_err(|_| Error::bad_request("Form data is not valid UTF-8"))?;
335        Ok(Query::parse_query_string(text))
336    }
337
338    fn require_form_content_type(&self) -> Result<()> {
339        let is_form = self
340            .headers
341            .get(http::header::CONTENT_TYPE)
342            .and_then(|v| v.to_str().ok())
343            .map(|v| {
344                v.split(';')
345                    .next()
346                    .unwrap_or("")
347                    .trim()
348                    .eq_ignore_ascii_case("application/x-www-form-urlencoded")
349            })
350            .unwrap_or(false);
351        if is_form {
352            Ok(())
353        } else {
354            Err(Error::custom(
355                415,
356                "Expected content-type application/x-www-form-urlencoded",
357            ))
358        }
359    }
360
361    /// Parse JSON body
362    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
363        serde_json::from_slice(&self.body)
364            .map_err(|e| Error::bad_request(format!("Invalid JSON: {}", e)))
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    fn form_request(content_type: Option<&str>, body: &'static str) -> Request {
373        let mut headers = http::HeaderMap::new();
374        if let Some(ct) = content_type {
375            headers.insert(http::header::CONTENT_TYPE, ct.parse().unwrap());
376        }
377        Request::new(
378            http::Method::POST,
379            "/".parse().unwrap(),
380            headers,
381            bytes::Bytes::from_static(body.as_bytes()),
382        )
383    }
384
385    #[derive(Debug, serde::Deserialize, PartialEq)]
386    struct Signup {
387        name: String,
388        age: u8,
389        newsletter: Option<bool>,
390    }
391
392    #[test]
393    fn params_parse_typed_values() {
394        let mut p = Params::new();
395        p.insert("id".into(), "42".into());
396        p.insert("name".into(), "x".into());
397        assert_eq!(p.parse::<u64>("id").unwrap(), 42);
398        assert_eq!(p.parse::<String>("name").unwrap(), "x");
399        let bad = p.parse::<u64>("name").unwrap_err();
400        assert_eq!(bad.status_code(), 400);
401        assert_eq!(bad.message(), "Invalid path parameter 'name'");
402        assert_eq!(p.parse::<u64>("missing").unwrap_err().status_code(), 400);
403        assert!(p.parse::<u8>("id").is_ok());
404        p.insert("big".into(), "300".into());
405        assert!(p.parse::<u8>("big").is_err());
406    }
407
408    #[test]
409    fn query_decodes_keys_values_and_plus() {
410        let q = Query::parse_query_string("q=rust+web&na%20me=a%26b&flag&&x=1");
411        assert_eq!(q.get("q"), Some("rust web"));
412        assert_eq!(q.get("na me"), Some("a&b"));
413        assert_eq!(q.get("flag"), Some(""));
414        assert!(q.contains("x") && !q.is_empty());
415    }
416
417    #[test]
418    fn query_parse_converts_types() {
419        let q = Query::parse_query_string("name=Ann&age=31&newsletter=true");
420        assert_eq!(
421            q.parse::<Signup>().unwrap(),
422            Signup {
423                name: "Ann".into(),
424                age: 31,
425                newsletter: Some(true)
426            }
427        );
428        let bad = Query::parse_query_string("name=Ann&age=old");
429        assert_eq!(bad.parse::<Signup>().unwrap_err().status_code(), 400);
430    }
431
432    #[test]
433    fn form_typed_and_untyped() {
434        let req = form_request(
435            Some("application/x-www-form-urlencoded; charset=UTF-8"),
436            "name=Ann+Lee&age=31",
437        );
438        let signup: Signup = req.form().unwrap();
439        assert_eq!(
440            signup,
441            Signup {
442                name: "Ann Lee".into(),
443                age: 31,
444                newsletter: None
445            }
446        );
447        assert_eq!(req.form_data().unwrap().get("name"), Some("Ann Lee"));
448    }
449
450    #[test]
451    fn form_rejects_wrong_content_type_and_bad_values() {
452        let json = form_request(Some("application/json"), "name=Ann&age=1");
453        assert_eq!(json.form::<Signup>().unwrap_err().status_code(), 415);
454        let none = form_request(None, "name=Ann&age=1");
455        assert_eq!(none.form_data().unwrap_err().status_code(), 415);
456
457        let bad = form_request(
458            Some("application/x-www-form-urlencoded"),
459            "name=Ann&age=300",
460        );
461        assert_eq!(bad.form::<Signup>().unwrap_err().status_code(), 400);
462    }
463}