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    /// True when the request came in over TLS
199    pub fn is_secure(&self) -> bool {
200        self.secure
201    }
202
203    /// Nonce for inline scripts and styles, when the
204    /// [`SecurityHeaders`](crate::security_headers::SecurityHeaders) policy uses the
205    /// `{nonce}` placeholder
206    pub fn csp_nonce(&self) -> Option<&str> {
207        self.extensions
208            .get::<crate::security_headers::CspNonce>()
209            .map(|n| n.0.as_str())
210    }
211
212    /// DER of the leaf certificate the client presented during the TLS
213    /// handshake (mutual TLS, feature `tls`); `None` for anonymous clients and
214    /// plain HTTP. The certificate has already been verified against the CAs
215    /// given to `TlsConfig::client_auth`; check *which* verified client it is
216    /// (fingerprint or subject) before authorizing anything.
217    pub fn client_certificate(&self) -> Option<&[u8]> {
218        self.extensions
219            .get::<ClientCertificate>()
220            .map(|c| c.0.as_slice())
221    }
222
223    /// Shared application state registered with `App::state`
224    ///
225    /// Answers `500` when no value of type `T` was registered: that is a
226    /// programming error, not something the client can fix.
227    pub fn state<T: Send + Sync + 'static>(&self) -> Result<&T> {
228        self.try_state().ok_or_else(|| {
229            Error::internal(format!(
230                "State of type {} is not registered",
231                std::any::type_name::<T>()
232            ))
233        })
234    }
235
236    /// Signal that fires when the server begins shutting down
237    ///
238    /// Long-lived handlers (SSE streams, polling loops) select on it to end
239    /// promptly: `tokio::select! { _ = req.shutdown_signal().wait() => break, ... }`.
240    pub fn shutdown_signal(&self) -> crate::shutdown::Shutdown {
241        self.shutdown
242            .clone()
243            .unwrap_or_else(crate::shutdown::Shutdown::never)
244    }
245
246    /// An owned handle to the same state, for when the value must outlive a
247    /// borrow of the request (it is moved into middleware `next.run(req)`, a
248    /// spawned task, ...)
249    pub fn state_arc<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
250        self.state
251            .as_ref()
252            .and_then(|s| s.get_arc::<T>())
253            .ok_or_else(|| {
254                Error::internal(format!(
255                    "State of type {} is not registered",
256                    std::any::type_name::<T>()
257                ))
258            })
259    }
260
261    /// Like [`Request::state`], `None` when the type is not registered
262    pub fn try_state<T: Send + Sync + 'static>(&self) -> Option<&T> {
263        self.state.as_ref()?.get::<T>()
264    }
265
266    /// Get cookies from the request
267    pub fn cookies(&self) -> &Cookies {
268        self.cookies.get_or_init(|| {
269            if let Some(cookie_header) = self.headers.get("cookie") {
270                if let Ok(cookie_str) = cookie_header.to_str() {
271                    Cookies::parse(cookie_str)
272                } else {
273                    Cookies::new()
274                }
275            } else {
276                Cookies::new()
277            }
278        })
279    }
280
281    /// Parse an `application/x-www-form-urlencoded` body into a struct
282    ///
283    /// Answers `415` for other content types and `400` for values that do not
284    /// fit the target type.
285    pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
286        self.require_form_content_type()?;
287        serde_urlencoded::from_bytes(&self.body)
288            .map_err(|e| Error::bad_request(format!("Invalid form data: {}", e)))
289    }
290
291    /// The same body as decoded key/value access (`+` and `%XX` decoded)
292    pub fn form_data(&self) -> Result<Query> {
293        self.require_form_content_type()?;
294        let text = std::str::from_utf8(&self.body)
295            .map_err(|_| Error::bad_request("Form data is not valid UTF-8"))?;
296        Ok(Query::parse_query_string(text))
297    }
298
299    fn require_form_content_type(&self) -> Result<()> {
300        let is_form = self
301            .headers
302            .get(http::header::CONTENT_TYPE)
303            .and_then(|v| v.to_str().ok())
304            .map(|v| {
305                v.split(';')
306                    .next()
307                    .unwrap_or("")
308                    .trim()
309                    .eq_ignore_ascii_case("application/x-www-form-urlencoded")
310            })
311            .unwrap_or(false);
312        if is_form {
313            Ok(())
314        } else {
315            Err(Error::custom(
316                415,
317                "Expected content-type application/x-www-form-urlencoded",
318            ))
319        }
320    }
321
322    /// Parse JSON body
323    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
324        serde_json::from_slice(&self.body)
325            .map_err(|e| Error::bad_request(format!("Invalid JSON: {}", e)))
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    fn form_request(content_type: Option<&str>, body: &'static str) -> Request {
334        let mut headers = http::HeaderMap::new();
335        if let Some(ct) = content_type {
336            headers.insert(http::header::CONTENT_TYPE, ct.parse().unwrap());
337        }
338        Request::new(
339            http::Method::POST,
340            "/".parse().unwrap(),
341            headers,
342            bytes::Bytes::from_static(body.as_bytes()),
343        )
344    }
345
346    #[derive(Debug, serde::Deserialize, PartialEq)]
347    struct Signup {
348        name: String,
349        age: u8,
350        newsletter: Option<bool>,
351    }
352
353    #[test]
354    fn params_parse_typed_values() {
355        let mut p = Params::new();
356        p.insert("id".into(), "42".into());
357        p.insert("name".into(), "x".into());
358        assert_eq!(p.parse::<u64>("id").unwrap(), 42);
359        assert_eq!(p.parse::<String>("name").unwrap(), "x");
360        let bad = p.parse::<u64>("name").unwrap_err();
361        assert_eq!(bad.status_code(), 400);
362        assert_eq!(bad.message(), "Invalid path parameter 'name'");
363        assert_eq!(p.parse::<u64>("missing").unwrap_err().status_code(), 400);
364        assert!(p.parse::<u8>("id").is_ok());
365        p.insert("big".into(), "300".into());
366        assert!(p.parse::<u8>("big").is_err());
367    }
368
369    #[test]
370    fn query_decodes_keys_values_and_plus() {
371        let q = Query::parse_query_string("q=rust+web&na%20me=a%26b&flag&&x=1");
372        assert_eq!(q.get("q"), Some("rust web"));
373        assert_eq!(q.get("na me"), Some("a&b"));
374        assert_eq!(q.get("flag"), Some(""));
375        assert!(q.contains("x") && !q.is_empty());
376    }
377
378    #[test]
379    fn query_parse_converts_types() {
380        let q = Query::parse_query_string("name=Ann&age=31&newsletter=true");
381        assert_eq!(
382            q.parse::<Signup>().unwrap(),
383            Signup {
384                name: "Ann".into(),
385                age: 31,
386                newsletter: Some(true)
387            }
388        );
389        let bad = Query::parse_query_string("name=Ann&age=old");
390        assert_eq!(bad.parse::<Signup>().unwrap_err().status_code(), 400);
391    }
392
393    #[test]
394    fn form_typed_and_untyped() {
395        let req = form_request(
396            Some("application/x-www-form-urlencoded; charset=UTF-8"),
397            "name=Ann+Lee&age=31",
398        );
399        let signup: Signup = req.form().unwrap();
400        assert_eq!(
401            signup,
402            Signup {
403                name: "Ann Lee".into(),
404                age: 31,
405                newsletter: None
406            }
407        );
408        assert_eq!(req.form_data().unwrap().get("name"), Some("Ann Lee"));
409    }
410
411    #[test]
412    fn form_rejects_wrong_content_type_and_bad_values() {
413        let json = form_request(Some("application/json"), "name=Ann&age=1");
414        assert_eq!(json.form::<Signup>().unwrap_err().status_code(), 415);
415        let none = form_request(None, "name=Ann&age=1");
416        assert_eq!(none.form_data().unwrap_err().status_code(), 415);
417
418        let bad = form_request(
419            Some("application/x-www-form-urlencoded"),
420            "name=Ann&age=300",
421        );
422        assert_eq!(bad.form::<Signup>().unwrap_err().status_code(), 400);
423    }
424}