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