Skip to main content

glacier/
context.rs

1//! The per-request `Context` handed to every handler and middleware.
2
3use std::any::type_name;
4use std::str::FromStr;
5use std::sync::Arc;
6
7use bytes::Bytes;
8use http::request::Parts;
9use http::{Extensions, HeaderMap, Method, Uri};
10use serde::de::DeserializeOwned;
11
12use crate::cookies::Cookies;
13use crate::error::{Error, Result};
14use crate::session::Session;
15
16/// Request parameters as text, from `ctx.params()`. Keys repeat-free; the
17/// last value for a key wins (so a hidden `false` before a checkbox works).
18#[derive(Debug, Default, Clone, PartialEq)]
19pub struct Params(
20    std::collections::BTreeMap<String, String>,
21    /// The fields of a JSON request body, which `require` can wrap.
22    Vec<(String, String)>,
23    /// Every value of a repeated `name[]` param, in order.
24    Vec<(String, String)>,
25    /// The key a bare JSON body is wrapped under: the controller's name,
26    /// singular (`post` for `Posts`), as Rails' `wrap_parameters`.
27    Option<String>,
28    /// Whether the body was JSON, which the wrapper wraps even when empty.
29    bool,
30    /// The field names of the files uploaded with them (`post[photo]`),
31    /// which make `require("post")` find its key, as Rails' params hold
32    /// uploads.
33    Vec<String>,
34);
35
36/// `params["post_id"]` (in `.glacier`, `params[:post_id]`): a param as
37/// text, or `""` when it's missing, as Rails' `params[:post_id]` is `nil`.
38impl std::ops::Index<&str> for Params {
39    type Output = str;
40
41    fn index(&self, name: &str) -> &str {
42        self.get(name).unwrap_or("")
43    }
44}
45
46/// Each model's attributes by its wrapper key (`evidence_item`), which
47/// `glacier::app!()` registers: a bare JSON body is wrapped with only
48/// these, as Rails' `wrap_parameters` wraps a model's attribute names.
49static WRAPPED: std::sync::RwLock<std::collections::BTreeMap<String, &'static [&'static str]>> =
50    std::sync::RwLock::new(std::collections::BTreeMap::new());
51
52/// Registers a model's attributes for params wrapping, under its name in
53/// snake_case: what `glacier::app!()` does for every model.
54pub fn wrap_parameters<M: crate::model::Model>() {
55    let name = std::any::type_name::<M>()
56        .rsplit("::")
57        .next()
58        .unwrap_or_default();
59    let key = glacier_inflect::snake_case(name);
60    WRAPPED
61        .write()
62        .unwrap_or_else(|e| e.into_inner())
63        .insert(key, M::ATTRIBUTES);
64}
65
66/// The attributes a bare JSON body wraps under `key`, if a model has it.
67fn wrapped_attributes(key: &str) -> Option<&'static [&'static str]> {
68    WRAPPED
69        .read()
70        .unwrap_or_else(|e| e.into_inner())
71        .get(key)
72        .copied()
73}
74
75/// The id `IdPrefix` took off the front of the path.
76#[derive(Debug, Clone)]
77struct PathPrefix(String);
78
79/// The controller's wrapper key for the request's params, set when a
80/// controller action's route matches.
81#[derive(Debug, Clone)]
82pub(crate) struct ParamsWrapper(pub(crate) String);
83
84impl Params {
85    /// The params nested under `key`, as Rails' `params.require(:post)`: a
86    /// JSON object (`{"post": {"title": "…"}}`) or form fields named
87    /// `post[title]`. Missing or empty is a `400 Bad Request`.
88    ///
89    /// As Rails' default `wrap_parameters`, in a controller's action a JSON
90    /// body without the controller's own key (`post` for `Posts`) is read as
91    /// though nested under it: `{"title": "…"}` works too. When a model has
92    /// that name, only its attributes are (`{"foo": 1}` is then missing).
93    pub fn require(&self, key: &str) -> Result<Params> {
94        let nested = self.under(key);
95        let prefix = format!("{key}[");
96        let has_files = self.5.iter().any(|name| name.starts_with(&prefix));
97        if nested.0.is_empty() && !has_files {
98            return Err(Error::bad_request(format!(
99                "param is missing or the value is empty: {key}"
100            )));
101        }
102        Ok(nested)
103    }
104
105    /// The params nested under `key`, as Rails' `params.fetch(:answer)`:
106    /// like [`require`](Self::require), but present and empty is fine (an
107    /// action that only looks for an optional upload, say). Only a missing
108    /// key is a `400 Bad Request`; in a controller's action, a JSON body is
109    /// always wrapped under its key, so there it's never missing.
110    pub fn fetch(&self, key: &str) -> Result<Params> {
111        let prefix = format!("{key}[");
112        let present = self.contains(key)
113            || self.iter().any(|(name, _)| name.starts_with(&prefix))
114            || self.5.iter().any(|name| name.starts_with(&prefix))
115            || (self.4 && self.3.as_deref() == Some(key));
116        if !present {
117            return Err(Error::bad_request(format!(
118                "param is missing or the value is empty: {key}"
119            )));
120        }
121        Ok(self.under(key))
122    }
123
124    /// The params under `key`: nested JSON, `key[field]` form fields, or a
125    /// bare JSON body the controller's wrapper key names.
126    fn under(&self, key: &str) -> Params {
127        let mut nested = Params::default();
128        if let Some(text) = self.get(key)
129            && let Ok(serde_json::Value::Object(map)) = serde_json::from_str(text)
130        {
131            for (name, value) in map {
132                nested.insert(name, json_text(value));
133            }
134        }
135        let prefix = format!("{key}[");
136        for (name, value) in self.iter() {
137            if let Some(field) = name.strip_prefix(&prefix).and_then(|n| n.strip_suffix(']')) {
138                nested.insert(field, value);
139            }
140        }
141        if nested.0.is_empty() && !self.contains(key) && self.3.as_deref() == Some(key) {
142            // Only the model's attributes, when the key names a model.
143            let attributes = wrapped_attributes(key);
144            for (name, value) in &self.1 {
145                if attributes.is_none_or(|names| names.contains(&name.as_str())) {
146                    nested.insert(name.clone(), value.clone());
147                }
148            }
149        }
150        nested
151    }
152
153    pub fn get(&self, name: &str) -> Option<&str> {
154        self.0.get(name).map(String::as_str)
155    }
156
157    /// A param as text, `""` when it's missing: `params[:post_id]` in
158    /// `.glacier`, as Rails' `params[:post_id]`.
159    pub fn value(&self, name: &str) -> &str {
160        self.get(name).unwrap_or("")
161    }
162
163    pub fn contains(&self, name: &str) -> bool {
164        self.0.contains_key(name)
165    }
166
167    pub fn insert(&mut self, name: impl Into<String>, value: impl Into<String>) {
168        let (name, value) = (name.into(), value.into());
169        if name.ends_with("[]") {
170            self.2.push((name.clone(), value.clone()));
171        }
172        self.0.insert(name, value);
173    }
174
175    /// A list param, as Rails reads `params[:ids]`: every `ids[]=1&ids[]=2`
176    /// value, a JSON array's elements (`{"ids": [1, 2]}`), or a single
177    /// `ids=1`. Empty when it's missing.
178    pub fn list(&self, name: &str) -> Vec<String> {
179        let repeated = format!("{name}[]");
180        let values: Vec<String> = self
181            .2
182            .iter()
183            .filter(|(key, _)| *key == repeated)
184            .map(|(_, value)| value.clone())
185            .collect();
186        if !values.is_empty() {
187            return values;
188        }
189        match self.get(name) {
190            None => Vec::new(),
191            Some(text) => match serde_json::from_str(text) {
192                Ok(serde_json::Value::Array(items)) => items.into_iter().map(json_text).collect(),
193                _ => vec![text.to_owned()],
194            },
195        }
196    }
197
198    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
199        self.0.iter().map(|(k, v)| (k.as_str(), v.as_str()))
200    }
201
202    /// Nested attributes as Rails takes them, one `Params` per record: a
203    /// JSON list (`"answers_attributes": [{…}]`), a JSON object keyed by
204    /// index (`{"0": {…}}`), or form fields
205    /// (`answers_attributes[0][note]`). Empty when there are none.
206    pub fn nested(&self, key: &str) -> Vec<Params> {
207        if let Some(text) = self.get(key)
208            && let Ok(value) = serde_json::from_str::<serde_json::Value>(text)
209        {
210            let items: Vec<serde_json::Value> = match value {
211                serde_json::Value::Array(items) => items,
212                serde_json::Value::Object(by_index) => {
213                    by_index.into_iter().map(|(_, v)| v).collect()
214                }
215                _ => Vec::new(),
216            };
217            return items
218                .into_iter()
219                .filter_map(|item| match item {
220                    serde_json::Value::Object(map) => {
221                        Some(map.into_iter().map(|(k, v)| (k, json_text(v))).collect())
222                    }
223                    _ => None,
224                })
225                .collect();
226        }
227        // Form fields: `key[0][note]`, or `key][0][note` inside a
228        // `require`d record (`post[key][0][note]`).
229        let mut by_index: Vec<(String, Params)> = Vec::new();
230        for (name, value) in self.iter() {
231            let Some(rest) = name
232                .strip_prefix(key)
233                .and_then(|r| r.strip_prefix("][").or_else(|| r.strip_prefix('[')))
234            else {
235                continue;
236            };
237            let Some((index, field)) = rest.split_once(']') else {
238                continue;
239            };
240            let field = field.trim_start_matches('[').trim_end_matches(']');
241            let field = field.replacen("][", "[", 1);
242            if field.is_empty() {
243                continue;
244            }
245            match by_index.iter_mut().find(|(i, _)| i == index) {
246                Some((_, params)) => params.insert(field, value),
247                None => {
248                    let mut params = Params::default();
249                    params.insert(field, value);
250                    by_index.push((index.to_owned(), params));
251                }
252            }
253        }
254        by_index.sort_by(
255            |(a, _), (b, _)| match (a.parse::<u64>(), b.parse::<u64>()) {
256                (Ok(a), Ok(b)) => a.cmp(&b),
257                _ => a.cmp(b),
258            },
259        );
260        by_index.into_iter().map(|(_, params)| params).collect()
261    }
262
263    /// These params without `name`.
264    #[must_use]
265    pub fn without(mut self, name: &str) -> Self {
266        self.0.remove(name);
267        self
268    }
269}
270
271impl AsRef<Params> for Params {
272    fn as_ref(&self) -> &Params {
273        self
274    }
275}
276
277impl From<&Params> for Params {
278    fn from(params: &Params) -> Self {
279        params.clone()
280    }
281}
282
283impl<K: Into<String>, V: Into<String>> FromIterator<(K, V)> for Params {
284    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
285        let mut params = Params::default();
286        for (k, v) in iter {
287            params.insert(k, v);
288        }
289        params
290    }
291}
292
293/// A JSON value as param text: strings as they are, `null` as empty, and
294/// anything else (numbers, booleans, objects) as JSON.
295fn json_text(value: serde_json::Value) -> String {
296    match value {
297        serde_json::Value::String(s) => s,
298        serde_json::Value::Null => String::new(),
299        other => other.to_string(),
300    }
301}
302
303/// The address a request's connection came from, recorded by the server.
304#[derive(Debug, Clone, Copy)]
305pub struct RemoteAddr(pub std::net::SocketAddr);
306
307/// Proxies a request may pass through on its way in, as Rails trusts them:
308/// loopback and private addresses, and the config's `trusted_proxies`.
309fn trusted_proxy(ip: &std::net::IpAddr) -> bool {
310    let default = match ip {
311        std::net::IpAddr::V4(v4) => v4.is_loopback() || v4.is_private(),
312        std::net::IpAddr::V6(v6) => v6.is_loopback() || (v6.segments()[0] & 0xfe00) == 0xfc00,
313    };
314    default
315        || TRUSTED_PROXIES
316            .read()
317            .unwrap_or_else(|e| e.into_inner())
318            .iter()
319            .any(|range| range.contains(ip))
320}
321
322/// More proxies to trust, from the config's `trusted_proxies`.
323static TRUSTED_PROXIES: std::sync::RwLock<Vec<IpRange>> = std::sync::RwLock::new(Vec::new());
324
325/// Trusts these proxies too, besides loopback and private addresses: a
326/// load balancer's or CDN's public addresses, each an address or a CIDR
327/// range (`"203.0.113.0/24"`, `"2001:db8::/32"`). `App::config` reads them
328/// from `trusted_proxies`.
329///
330/// # Errors
331///
332/// For text that isn't an address or a range.
333pub fn trust_proxies<S: AsRef<str>>(ranges: &[S]) -> crate::Result<()> {
334    let parsed = ranges
335        .iter()
336        .map(|r| IpRange::parse(r.as_ref()))
337        .collect::<crate::Result<Vec<_>>>()?;
338    *TRUSTED_PROXIES.write().unwrap_or_else(|e| e.into_inner()) = parsed;
339    Ok(())
340}
341
342pub(crate) fn configure_proxies(config: &crate::Config) -> crate::Result<()> {
343    if let Some(ranges) = config.get_opt::<Vec<String>>("trusted_proxies")? {
344        trust_proxies(&ranges)?;
345    }
346    Ok(())
347}
348
349/// An address and how many of its leading bits a match shares.
350#[derive(Debug, Clone, Copy)]
351struct IpRange {
352    base: std::net::IpAddr,
353    bits: u32,
354}
355
356impl IpRange {
357    fn parse(text: &str) -> crate::Result<Self> {
358        let bad = || {
359            crate::Error::internal(format!(
360                "trusted_proxies: {text:?} isn't an address or a range"
361            ))
362        };
363        let (address, bits) = match text.trim().split_once('/') {
364            Some((address, bits)) => (address, Some(bits.parse::<u32>().map_err(|_| bad())?)),
365            None => (text.trim(), None),
366        };
367        let base: std::net::IpAddr = address.parse().map_err(|_| bad())?;
368        let max = if base.is_ipv4() { 32 } else { 128 };
369        let bits = bits.unwrap_or(max);
370        if bits > max {
371            return Err(bad());
372        }
373        Ok(Self { base, bits })
374    }
375
376    fn contains(&self, ip: &std::net::IpAddr) -> bool {
377        let (a, b, width) = match (self.base, ip) {
378            (std::net::IpAddr::V4(a), std::net::IpAddr::V4(b)) => {
379                (u128::from(u32::from(a)), u128::from(u32::from(*b)), 32)
380            }
381            (std::net::IpAddr::V6(a), std::net::IpAddr::V6(b)) => {
382                (u128::from(a), u128::from(*b), 128)
383            }
384            _ => return false,
385        };
386        if self.bits == 0 {
387            return true;
388        }
389        let shift = width - self.bits;
390        (a >> shift) == (b >> shift)
391    }
392}
393
394/// Path parameters captured by the router, e.g. `id` in `/posts/:id`.
395#[derive(Debug, Default, Clone)]
396pub struct PathParams(Vec<(String, String)>);
397
398impl PathParams {
399    pub fn get(&self, name: &str) -> Option<&str> {
400        self.0
401            .iter()
402            .find(|(key, _)| key == name)
403            .map(|(_, value)| value.as_str())
404    }
405
406    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
407        self.0.iter().map(|(k, v)| (k.as_str(), v.as_str()))
408    }
409
410    pub(crate) fn push(&mut self, name: &str, value: String) {
411        self.0.push((name.to_owned(), value));
412    }
413}
414
415/// Everything known about the current request.
416///
417/// The body is fully buffered before the handler runs (bounded by
418/// `App::max_body_size`), so the parsing helpers are synchronous.
419pub struct Context {
420    parts: Parts,
421    body: Bytes,
422    params: PathParams,
423    state: Arc<Extensions>,
424    cookies: Cookies,
425    session: Session,
426}
427
428impl Context {
429    pub(crate) fn new(
430        parts: Parts,
431        body: Bytes,
432        state: Arc<Extensions>,
433        cookies: Cookies,
434        session: Session,
435    ) -> Self {
436        Self {
437            parts,
438            body,
439            params: PathParams::default(),
440            state,
441            cookies,
442            session,
443        }
444    }
445
446    /// Replaces the request's path, keeping its query: what
447    /// [`IdPrefix`](crate::middleware::IdPrefix) routes once it has taken
448    /// the id off.
449    pub(crate) fn set_path(&mut self, path: &str) {
450        let uri = match self.parts.uri.query() {
451            Some(query) => format!("{path}?{query}"),
452            None => path.to_owned(),
453        };
454        if let Ok(uri) = uri.parse() {
455            self.parts.uri = uri;
456        }
457    }
458
459    pub(crate) fn set_path_prefix(&mut self, id: String) {
460        self.parts.extensions.insert(PathPrefix(id));
461    }
462
463    /// The id at the front of the request's path (`42` in `/42/projects`),
464    /// when [`IdPrefix`](crate::middleware::IdPrefix) took one off.
465    pub fn path_prefix(&self) -> Option<&str> {
466        self.parts
467            .extensions
468            .get::<PathPrefix>()
469            .map(|prefix| prefix.0.as_str())
470    }
471
472    pub(crate) fn set_method(&mut self, method: Method) {
473        self.parts.method = method;
474    }
475
476    pub(crate) fn set_params(&mut self, params: PathParams) {
477        self.params = params;
478    }
479
480    /// Notes the controller handling the request (from its route label,
481    /// `Posts#create`), so its params can be wrapped as Rails does.
482    pub(crate) fn set_controller(&mut self, label: &str) {
483        let Some((controller, _)) = label.split_once('#') else {
484            return;
485        };
486        let key = glacier_inflect::singularize(&glacier_inflect::snake_case(controller));
487        self.parts.extensions.insert(ParamsWrapper(key));
488    }
489
490    pub fn method(&self) -> &Method {
491        &self.parts.method
492    }
493
494    pub fn uri(&self) -> &Uri {
495        &self.parts.uri
496    }
497
498    pub fn path(&self) -> &str {
499        self.parts.uri.path()
500    }
501
502    pub fn headers(&self) -> &HeaderMap {
503        &self.parts.headers
504    }
505
506    pub fn header(&self, name: impl http::header::AsHeaderName) -> Option<&str> {
507        self.parts.headers.get(name).and_then(|v| v.to_str().ok())
508    }
509
510    /// The client's IP address, as Rails' `request.remote_ip`: the
511    /// connection's, unless it came through trusted proxies (loopback and
512    /// private addresses, and the config's `trusted_proxies`), in which case the nearest untrusted address in
513    /// `X-Forwarded-For`. `None` when there was no connection (in tests).
514    pub fn remote_ip(&self) -> Option<String> {
515        let peer = self.parts.extensions.get::<RemoteAddr>()?.0.ip();
516        if !trusted_proxy(&peer) {
517            return Some(peer.to_string());
518        }
519        let forwarded: Vec<std::net::IpAddr> = self
520            .header("x-forwarded-for")
521            .unwrap_or("")
522            .split(',')
523            .filter_map(|ip| ip.trim().parse().ok())
524            .collect();
525        let ip = forwarded
526            .iter()
527            .rev()
528            .find(|ip| !trusted_proxy(ip))
529            .or(forwarded.first())
530            .unwrap_or(&peer);
531        Some(ip.to_string())
532    }
533
534    /// Parameters captured by the route pattern, e.g. `id` in `/posts/:id`.
535    pub fn path_params(&self) -> &PathParams {
536        &self.params
537    }
538
539    /// Sets who the request is for, from middleware (who's signed in, and
540    /// in which org): what `access` is in an action, and what
541    /// `Post::for(access)` limits queries to.
542    pub fn set_access(&mut self, access: impl crate::access::Access) {
543        let access = crate::access::RequestAccess(std::sync::Arc::new(access));
544        // Who it's for, in the request's trace and logs: `org:42`.
545        tracing::Span::current().record("glacier.access", access.describe());
546        // For the rest of the request too: jobs it queues carry it.
547        crate::current::set(access.clone());
548        self.parts.extensions.insert(access);
549    }
550
551    /// Who the request is for, as its middleware set it: `access` in a
552    /// `.glacier` action. `401 Unauthorized` when nothing set one (no one
553    /// is signed in).
554    ///
555    /// # Errors
556    ///
557    /// `401 Unauthorized` without an access.
558    pub fn access(&self) -> Result<crate::access::RequestAccess> {
559        self.parts
560            .extensions
561            .get::<crate::access::RequestAccess>()
562            .cloned()
563            .ok_or_else(|| Error::new(http::StatusCode::UNAUTHORIZED, "sign in first"))
564    }
565
566    /// All request parameters as text: path params, the query string and
567    /// the body (form-encoded or a JSON object), later sources winning, as
568    /// in Rails' `params`. Pass them to `Post::create(..)` or
569    /// `post.update(..)`, which cast them into typed fields.
570    pub fn params(&self) -> Params {
571        let wrapper = self
572            .parts
573            .extensions
574            .get::<ParamsWrapper>()
575            .map(|wrapper| wrapper.0.clone());
576        let mut params = Params(
577            Default::default(),
578            Vec::new(),
579            Vec::new(),
580            wrapper,
581            false,
582            Vec::new(),
583        );
584        let query = self.uri().query().unwrap_or("");
585        for (key, value) in
586            serde_urlencoded::from_str::<Vec<(String, String)>>(query).unwrap_or_default()
587        {
588            params.insert(key, value);
589        }
590        let content_type = self.header(http::header::CONTENT_TYPE).unwrap_or("");
591        if content_type.starts_with("application/x-www-form-urlencoded") {
592            for (key, value) in form_urlencoded_pairs(&self.body) {
593                params.insert(key, value);
594            }
595        } else if let Some(boundary) = crate::upload::boundary(content_type) {
596            for part in crate::upload::parse(&self.body, &boundary) {
597                match part {
598                    crate::upload::Part::Field(key, value) => params.insert(key, value),
599                    crate::upload::Part::File(key, _) => params.5.push(key),
600                }
601            }
602        } else if content_type.starts_with("application/json")
603            && let Ok(serde_json::Value::Object(map)) = serde_json::from_slice(&self.body)
604        {
605            params.4 = true;
606            for (key, value) in map {
607                let value = json_text(value);
608                params.1.push((key.clone(), value.clone()));
609                params.insert(key, value);
610            }
611        }
612        for (key, value) in self.params.iter() {
613            params.insert(key.to_owned(), value.to_owned());
614        }
615        params
616    }
617
618    pub fn param(&self, name: &str) -> Option<&str> {
619        self.params.get(name)
620    }
621
622    /// The `:id` path parameter as an `i64`. A missing or malformed id is a
623    /// `404 Not Found`, as no record could have it.
624    pub fn id(&self) -> Result<i64> {
625        self.param("id")
626            .and_then(|id| id.parse().ok())
627            .ok_or_else(Error::not_found)
628    }
629
630    /// Parses a path parameter, responding `400 Bad Request` if it is
631    /// missing or malformed.
632    pub fn param_as<T: FromStr>(&self, name: &str) -> Result<T> {
633        let raw = self
634            .param(name)
635            .ok_or_else(|| Error::bad_request(format!("missing parameter `{name}`")))?;
636        raw.parse()
637            .map_err(|_| Error::bad_request(format!("invalid parameter `{name}`")))
638    }
639
640    /// Deserializes the query string.
641    pub fn query<T: DeserializeOwned>(&self) -> Result<T> {
642        serde_urlencoded::from_str(self.uri().query().unwrap_or(""))
643            .map_err(|e| Error::bad_request(format!("invalid query string: {e}")))
644    }
645
646    /// Deserializes a JSON request body.
647    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
648        serde_json::from_slice(&self.body)
649            .map_err(|e| Error::bad_request(format!("invalid JSON body: {e}")))
650    }
651
652    /// Deserializes a `application/x-www-form-urlencoded` request body.
653    pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
654        serde_urlencoded::from_bytes(&self.body)
655            .map_err(|e| Error::bad_request(format!("invalid form body: {e}")))
656    }
657
658    /// The files of a `multipart/form-data` request, by field name, in
659    /// the order sent.
660    pub fn files(&self) -> Vec<(String, crate::upload::Upload)> {
661        let content_type = self.header(http::header::CONTENT_TYPE).unwrap_or("");
662        let Some(boundary) = crate::upload::boundary(content_type) else {
663            return Vec::new();
664        };
665        crate::upload::parse(&self.body, &boundary)
666            .into_iter()
667            .filter_map(|part| match part {
668                crate::upload::Part::File(name, upload) => Some((name, upload)),
669                crate::upload::Part::Field(..) => None,
670            })
671            .collect()
672    }
673
674    /// The file uploaded as `name` (`comment[note_image]`), as Rails'
675    /// `params[:comment][:note_image]`.
676    pub fn file(&self, name: &str) -> Option<crate::upload::Upload> {
677        self.files()
678            .into_iter()
679            .find(|(field, _)| field == name)
680            .map(|(_, upload)| upload)
681    }
682
683    /// A single text field from a form's body, URL-encoded or
684    /// `multipart/form-data` (a form with a file input), without
685    /// deserializing the whole thing: the CSRF token and `_method` are read
686    /// this way, so upload forms pass them too.
687    pub fn form_field(&self, name: &str) -> Option<String> {
688        let content_type = self.header(http::header::CONTENT_TYPE).unwrap_or("");
689        if content_type.starts_with("application/x-www-form-urlencoded") {
690            return form_urlencoded_pairs(&self.body)
691                .into_iter()
692                .find(|(key, _)| key == name)
693                .map(|(_, value)| value);
694        }
695        let boundary = crate::upload::boundary(content_type)?;
696        crate::upload::parse(&self.body, &boundary)
697            .into_iter()
698            .find_map(|part| match part {
699                crate::upload::Part::Field(field, value) if field == name => Some(value),
700                _ => None,
701            })
702    }
703
704    pub fn body(&self) -> &Bytes {
705        &self.body
706    }
707
708    /// Application-wide state registered with `App::state`.
709    pub fn state<T: Send + Sync + 'static>(&self) -> Result<&T> {
710        self.state.get::<T>().ok_or_else(|| {
711            Error::internal(format!(
712                "no app state of type `{}` registered",
713                type_name::<T>()
714            ))
715        })
716    }
717
718    pub fn cookies(&self) -> &Cookies {
719        &self.cookies
720    }
721
722    pub fn session(&self) -> &Session {
723        &self.session
724    }
725
726    /// A flash message set by an earlier request (e.g. `"notice"`), or by
727    /// `flash_now`. Reading the flash spends it.
728    pub fn flash(&self, kind: &str) -> Option<String> {
729        self.session.flash(kind)
730    }
731
732    /// A flash message for the page this request renders, as Rails'
733    /// `flash.now[:alert] = …`.
734    pub fn flash_now(&self, kind: &str, message: impl Into<String>) {
735        self.session.flash_now(kind, message);
736    }
737
738    /// Sets a flash message for the next request.
739    pub fn put_flash(&self, kind: &str, message: impl Into<String>) {
740        self.session.put_flash(kind, message);
741    }
742
743    /// The URL the request came to, without its path: `https://example.com`,
744    /// from `X-Forwarded-Proto` and `Host` behind a proxy.
745    pub fn base_url(&self) -> String {
746        crate::request::base_url_of(&self.parts)
747    }
748
749    /// The CSRF token for this session, for embedding in forms.
750    pub fn csrf_token(&self) -> String {
751        crate::csrf::token_for(&self.session)
752    }
753
754    /// Per-request data, e.g. a current user set by an auth middleware.
755    pub fn extensions(&self) -> &Extensions {
756        &self.parts.extensions
757    }
758
759    pub fn extensions_mut(&mut self) -> &mut Extensions {
760        &mut self.parts.extensions
761    }
762}
763
764fn form_urlencoded_pairs(body: &[u8]) -> Vec<(String, String)> {
765    serde_urlencoded::from_bytes(body).unwrap_or_default()
766}
767
768#[cfg(test)]
769mod tests {
770    use super::*;
771
772    fn ctx(peer: &str, forwarded: Option<&str>) -> Context {
773        let mut req = http::Request::builder().uri("/");
774        if let Some(forwarded) = forwarded {
775            req = req.header("x-forwarded-for", forwarded);
776        }
777        let (mut parts, ()) = req.body(()).unwrap().into_parts();
778        parts.extensions.insert(RemoteAddr(peer.parse().unwrap()));
779        let cookies = Cookies::from_headers(&HeaderMap::new(), Arc::new(cookie::Key::generate()));
780        let session = Session::new(cookies.clone(), false);
781        Context::new(parts, Bytes::new(), Arc::default(), cookies, session)
782    }
783
784    #[test]
785    fn finds_the_client_ip_as_rails_does() {
786        assert_eq!(
787            ctx("203.0.113.9:5000", None).remote_ip().as_deref(),
788            Some("203.0.113.9")
789        );
790        assert_eq!(ctx("[::1]:5000", None).remote_ip().as_deref(), Some("::1"));
791        // Behind a local proxy: the nearest address that isn't a proxy.
792        assert_eq!(
793            ctx("127.0.0.1:5000", Some("198.51.100.7, 10.0.0.2"))
794                .remote_ip()
795                .as_deref(),
796            Some("198.51.100.7")
797        );
798        // A client can't pretend to be someone else from outside.
799        assert_eq!(
800            ctx("203.0.113.9:5000", Some("198.51.100.7"))
801                .remote_ip()
802                .as_deref(),
803            Some("203.0.113.9")
804        );
805    }
806
807    #[test]
808    fn trusts_configured_proxies_too() {
809        // A load balancer with a public address (TEST-NET-1 here).
810        trust_proxies(&["192.0.2.0/24", "2001:db8::1"]).unwrap();
811        assert_eq!(
812            ctx("192.0.2.40:5000", Some("198.51.100.7"))
813                .remote_ip()
814                .as_deref(),
815            Some("198.51.100.7")
816        );
817        assert_eq!(
818            ctx("192.0.3.40:5000", Some("198.51.100.7"))
819                .remote_ip()
820                .as_deref(),
821            Some("192.0.3.40")
822        );
823        assert_eq!(
824            ctx("[2001:db8::1]:5000", Some("198.51.100.7"))
825                .remote_ip()
826                .as_deref(),
827            Some("198.51.100.7")
828        );
829        assert!(trust_proxies(&["not an address"]).is_err());
830        assert!(trust_proxies(&["10.0.0.0/33"]).is_err());
831        let range = IpRange::parse("0.0.0.0/0").unwrap();
832        assert!(range.contains(&"8.8.8.8".parse().unwrap()));
833        assert!(!range.contains(&"::1".parse().unwrap()));
834    }
835}