glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! The per-request `Context` handed to every handler and middleware.

use std::any::type_name;
use std::str::FromStr;
use std::sync::Arc;

use bytes::Bytes;
use http::request::Parts;
use http::{Extensions, HeaderMap, Method, Uri};
use serde::de::DeserializeOwned;

use crate::cookies::Cookies;
use crate::error::{Error, Result};
use crate::session::Session;

/// Request parameters as text, from `ctx.params()`. Keys repeat-free; the
/// last value for a key wins (so a hidden `false` before a checkbox works).
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Params(
    std::collections::BTreeMap<String, String>,
    /// The fields of a JSON request body, which `require` can wrap.
    Vec<(String, String)>,
    /// Every value of a repeated `name[]` param, in order.
    Vec<(String, String)>,
    /// The key a bare JSON body is wrapped under: the controller's name,
    /// singular (`post` for `Posts`), as Rails' `wrap_parameters`.
    Option<String>,
    /// Whether the body was JSON, which the wrapper wraps even when empty.
    bool,
    /// The field names of the files uploaded with them (`post[photo]`),
    /// which make `require("post")` find its key, as Rails' params hold
    /// uploads.
    Vec<String>,
);

/// `params["post_id"]` (in `.glacier`, `params[:post_id]`): a param as
/// text, or `""` when it's missing, as Rails' `params[:post_id]` is `nil`.
impl std::ops::Index<&str> for Params {
    type Output = str;

    fn index(&self, name: &str) -> &str {
        self.get(name).unwrap_or("")
    }
}

/// Each model's attributes by its wrapper key (`evidence_item`), which
/// `glacier::app!()` registers: a bare JSON body is wrapped with only
/// these, as Rails' `wrap_parameters` wraps a model's attribute names.
static WRAPPED: std::sync::RwLock<std::collections::BTreeMap<String, &'static [&'static str]>> =
    std::sync::RwLock::new(std::collections::BTreeMap::new());

/// Registers a model's attributes for params wrapping, under its name in
/// snake_case: what `glacier::app!()` does for every model.
pub fn wrap_parameters<M: crate::model::Model>() {
    let name = std::any::type_name::<M>()
        .rsplit("::")
        .next()
        .unwrap_or_default();
    let key = glacier_inflect::snake_case(name);
    WRAPPED
        .write()
        .unwrap_or_else(|e| e.into_inner())
        .insert(key, M::ATTRIBUTES);
}

/// The attributes a bare JSON body wraps under `key`, if a model has it.
fn wrapped_attributes(key: &str) -> Option<&'static [&'static str]> {
    WRAPPED
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .get(key)
        .copied()
}

/// The id `IdPrefix` took off the front of the path.
#[derive(Debug, Clone)]
struct PathPrefix(String);

/// The controller's wrapper key for the request's params, set when a
/// controller action's route matches.
#[derive(Debug, Clone)]
pub(crate) struct ParamsWrapper(pub(crate) String);

impl Params {
    /// The params nested under `key`, as Rails' `params.require(:post)`: a
    /// JSON object (`{"post": {"title": "…"}}`) or form fields named
    /// `post[title]`. Missing or empty is a `400 Bad Request`.
    ///
    /// As Rails' default `wrap_parameters`, in a controller's action a JSON
    /// body without the controller's own key (`post` for `Posts`) is read as
    /// though nested under it: `{"title": "…"}` works too. When a model has
    /// that name, only its attributes are (`{"foo": 1}` is then missing).
    pub fn require(&self, key: &str) -> Result<Params> {
        let nested = self.under(key);
        let prefix = format!("{key}[");
        let has_files = self.5.iter().any(|name| name.starts_with(&prefix));
        if nested.0.is_empty() && !has_files {
            return Err(Error::bad_request(format!(
                "param is missing or the value is empty: {key}"
            )));
        }
        Ok(nested)
    }

    /// The params nested under `key`, as Rails' `params.fetch(:answer)`:
    /// like [`require`](Self::require), but present and empty is fine (an
    /// action that only looks for an optional upload, say). Only a missing
    /// key is a `400 Bad Request`; in a controller's action, a JSON body is
    /// always wrapped under its key, so there it's never missing.
    pub fn fetch(&self, key: &str) -> Result<Params> {
        let prefix = format!("{key}[");
        let present = self.contains(key)
            || self.iter().any(|(name, _)| name.starts_with(&prefix))
            || self.5.iter().any(|name| name.starts_with(&prefix))
            || (self.4 && self.3.as_deref() == Some(key));
        if !present {
            return Err(Error::bad_request(format!(
                "param is missing or the value is empty: {key}"
            )));
        }
        Ok(self.under(key))
    }

    /// The params under `key`: nested JSON, `key[field]` form fields, or a
    /// bare JSON body the controller's wrapper key names.
    fn under(&self, key: &str) -> Params {
        let mut nested = Params::default();
        if let Some(text) = self.get(key)
            && let Ok(serde_json::Value::Object(map)) = serde_json::from_str(text)
        {
            for (name, value) in map {
                nested.insert(name, json_text(value));
            }
        }
        let prefix = format!("{key}[");
        for (name, value) in self.iter() {
            if let Some(field) = name.strip_prefix(&prefix).and_then(|n| n.strip_suffix(']')) {
                nested.insert(field, value);
            }
        }
        if nested.0.is_empty() && !self.contains(key) && self.3.as_deref() == Some(key) {
            // Only the model's attributes, when the key names a model.
            let attributes = wrapped_attributes(key);
            for (name, value) in &self.1 {
                if attributes.is_none_or(|names| names.contains(&name.as_str())) {
                    nested.insert(name.clone(), value.clone());
                }
            }
        }
        nested
    }

    pub fn get(&self, name: &str) -> Option<&str> {
        self.0.get(name).map(String::as_str)
    }

    /// A param as text, `""` when it's missing: `params[:post_id]` in
    /// `.glacier`, as Rails' `params[:post_id]`.
    pub fn value(&self, name: &str) -> &str {
        self.get(name).unwrap_or("")
    }

    pub fn contains(&self, name: &str) -> bool {
        self.0.contains_key(name)
    }

    pub fn insert(&mut self, name: impl Into<String>, value: impl Into<String>) {
        let (name, value) = (name.into(), value.into());
        if name.ends_with("[]") {
            self.2.push((name.clone(), value.clone()));
        }
        self.0.insert(name, value);
    }

    /// A list param, as Rails reads `params[:ids]`: every `ids[]=1&ids[]=2`
    /// value, a JSON array's elements (`{"ids": [1, 2]}`), or a single
    /// `ids=1`. Empty when it's missing.
    pub fn list(&self, name: &str) -> Vec<String> {
        let repeated = format!("{name}[]");
        let values: Vec<String> = self
            .2
            .iter()
            .filter(|(key, _)| *key == repeated)
            .map(|(_, value)| value.clone())
            .collect();
        if !values.is_empty() {
            return values;
        }
        match self.get(name) {
            None => Vec::new(),
            Some(text) => match serde_json::from_str(text) {
                Ok(serde_json::Value::Array(items)) => items.into_iter().map(json_text).collect(),
                _ => vec![text.to_owned()],
            },
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.0.iter().map(|(k, v)| (k.as_str(), v.as_str()))
    }

    /// Nested attributes as Rails takes them, one `Params` per record: a
    /// JSON list (`"answers_attributes": [{…}]`), a JSON object keyed by
    /// index (`{"0": {…}}`), or form fields
    /// (`answers_attributes[0][note]`). Empty when there are none.
    pub fn nested(&self, key: &str) -> Vec<Params> {
        if let Some(text) = self.get(key)
            && let Ok(value) = serde_json::from_str::<serde_json::Value>(text)
        {
            let items: Vec<serde_json::Value> = match value {
                serde_json::Value::Array(items) => items,
                serde_json::Value::Object(by_index) => {
                    by_index.into_iter().map(|(_, v)| v).collect()
                }
                _ => Vec::new(),
            };
            return items
                .into_iter()
                .filter_map(|item| match item {
                    serde_json::Value::Object(map) => {
                        Some(map.into_iter().map(|(k, v)| (k, json_text(v))).collect())
                    }
                    _ => None,
                })
                .collect();
        }
        // Form fields: `key[0][note]`, or `key][0][note` inside a
        // `require`d record (`post[key][0][note]`).
        let mut by_index: Vec<(String, Params)> = Vec::new();
        for (name, value) in self.iter() {
            let Some(rest) = name
                .strip_prefix(key)
                .and_then(|r| r.strip_prefix("][").or_else(|| r.strip_prefix('[')))
            else {
                continue;
            };
            let Some((index, field)) = rest.split_once(']') else {
                continue;
            };
            let field = field.trim_start_matches('[').trim_end_matches(']');
            let field = field.replacen("][", "[", 1);
            if field.is_empty() {
                continue;
            }
            match by_index.iter_mut().find(|(i, _)| i == index) {
                Some((_, params)) => params.insert(field, value),
                None => {
                    let mut params = Params::default();
                    params.insert(field, value);
                    by_index.push((index.to_owned(), params));
                }
            }
        }
        by_index.sort_by(
            |(a, _), (b, _)| match (a.parse::<u64>(), b.parse::<u64>()) {
                (Ok(a), Ok(b)) => a.cmp(&b),
                _ => a.cmp(b),
            },
        );
        by_index.into_iter().map(|(_, params)| params).collect()
    }

    /// These params without `name`.
    #[must_use]
    pub fn without(mut self, name: &str) -> Self {
        self.0.remove(name);
        self
    }
}

impl AsRef<Params> for Params {
    fn as_ref(&self) -> &Params {
        self
    }
}

impl From<&Params> for Params {
    fn from(params: &Params) -> Self {
        params.clone()
    }
}

impl<K: Into<String>, V: Into<String>> FromIterator<(K, V)> for Params {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let mut params = Params::default();
        for (k, v) in iter {
            params.insert(k, v);
        }
        params
    }
}

/// A JSON value as param text: strings as they are, `null` as empty, and
/// anything else (numbers, booleans, objects) as JSON.
fn json_text(value: serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s,
        serde_json::Value::Null => String::new(),
        other => other.to_string(),
    }
}

/// The address a request's connection came from, recorded by the server.
#[derive(Debug, Clone, Copy)]
pub struct RemoteAddr(pub std::net::SocketAddr);

/// Proxies a request may pass through on its way in, as Rails trusts them:
/// loopback and private addresses, and the config's `trusted_proxies`.
fn trusted_proxy(ip: &std::net::IpAddr) -> bool {
    let default = match ip {
        std::net::IpAddr::V4(v4) => v4.is_loopback() || v4.is_private(),
        std::net::IpAddr::V6(v6) => v6.is_loopback() || (v6.segments()[0] & 0xfe00) == 0xfc00,
    };
    default
        || TRUSTED_PROXIES
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .any(|range| range.contains(ip))
}

/// More proxies to trust, from the config's `trusted_proxies`.
static TRUSTED_PROXIES: std::sync::RwLock<Vec<IpRange>> = std::sync::RwLock::new(Vec::new());

/// Trusts these proxies too, besides loopback and private addresses: a
/// load balancer's or CDN's public addresses, each an address or a CIDR
/// range (`"203.0.113.0/24"`, `"2001:db8::/32"`). `App::config` reads them
/// from `trusted_proxies`.
///
/// # Errors
///
/// For text that isn't an address or a range.
pub fn trust_proxies<S: AsRef<str>>(ranges: &[S]) -> crate::Result<()> {
    let parsed = ranges
        .iter()
        .map(|r| IpRange::parse(r.as_ref()))
        .collect::<crate::Result<Vec<_>>>()?;
    *TRUSTED_PROXIES.write().unwrap_or_else(|e| e.into_inner()) = parsed;
    Ok(())
}

pub(crate) fn configure_proxies(config: &crate::Config) -> crate::Result<()> {
    if let Some(ranges) = config.get_opt::<Vec<String>>("trusted_proxies")? {
        trust_proxies(&ranges)?;
    }
    Ok(())
}

/// An address and how many of its leading bits a match shares.
#[derive(Debug, Clone, Copy)]
struct IpRange {
    base: std::net::IpAddr,
    bits: u32,
}

impl IpRange {
    fn parse(text: &str) -> crate::Result<Self> {
        let bad = || {
            crate::Error::internal(format!(
                "trusted_proxies: {text:?} isn't an address or a range"
            ))
        };
        let (address, bits) = match text.trim().split_once('/') {
            Some((address, bits)) => (address, Some(bits.parse::<u32>().map_err(|_| bad())?)),
            None => (text.trim(), None),
        };
        let base: std::net::IpAddr = address.parse().map_err(|_| bad())?;
        let max = if base.is_ipv4() { 32 } else { 128 };
        let bits = bits.unwrap_or(max);
        if bits > max {
            return Err(bad());
        }
        Ok(Self { base, bits })
    }

    fn contains(&self, ip: &std::net::IpAddr) -> bool {
        let (a, b, width) = match (self.base, ip) {
            (std::net::IpAddr::V4(a), std::net::IpAddr::V4(b)) => {
                (u128::from(u32::from(a)), u128::from(u32::from(*b)), 32)
            }
            (std::net::IpAddr::V6(a), std::net::IpAddr::V6(b)) => {
                (u128::from(a), u128::from(*b), 128)
            }
            _ => return false,
        };
        if self.bits == 0 {
            return true;
        }
        let shift = width - self.bits;
        (a >> shift) == (b >> shift)
    }
}

/// Path parameters captured by the router, e.g. `id` in `/posts/:id`.
#[derive(Debug, Default, Clone)]
pub struct PathParams(Vec<(String, String)>);

impl PathParams {
    pub fn get(&self, name: &str) -> Option<&str> {
        self.0
            .iter()
            .find(|(key, _)| key == name)
            .map(|(_, value)| value.as_str())
    }

    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.0.iter().map(|(k, v)| (k.as_str(), v.as_str()))
    }

    pub(crate) fn push(&mut self, name: &str, value: String) {
        self.0.push((name.to_owned(), value));
    }
}

/// Everything known about the current request.
///
/// The body is fully buffered before the handler runs (bounded by
/// `App::max_body_size`), so the parsing helpers are synchronous.
pub struct Context {
    parts: Parts,
    body: Bytes,
    params: PathParams,
    state: Arc<Extensions>,
    cookies: Cookies,
    session: Session,
}

impl Context {
    pub(crate) fn new(
        parts: Parts,
        body: Bytes,
        state: Arc<Extensions>,
        cookies: Cookies,
        session: Session,
    ) -> Self {
        Self {
            parts,
            body,
            params: PathParams::default(),
            state,
            cookies,
            session,
        }
    }

    /// Replaces the request's path, keeping its query: what
    /// [`IdPrefix`](crate::middleware::IdPrefix) routes once it has taken
    /// the id off.
    pub(crate) fn set_path(&mut self, path: &str) {
        let uri = match self.parts.uri.query() {
            Some(query) => format!("{path}?{query}"),
            None => path.to_owned(),
        };
        if let Ok(uri) = uri.parse() {
            self.parts.uri = uri;
        }
    }

    pub(crate) fn set_path_prefix(&mut self, id: String) {
        self.parts.extensions.insert(PathPrefix(id));
    }

    /// The id at the front of the request's path (`42` in `/42/projects`),
    /// when [`IdPrefix`](crate::middleware::IdPrefix) took one off.
    pub fn path_prefix(&self) -> Option<&str> {
        self.parts
            .extensions
            .get::<PathPrefix>()
            .map(|prefix| prefix.0.as_str())
    }

    pub(crate) fn set_method(&mut self, method: Method) {
        self.parts.method = method;
    }

    pub(crate) fn set_params(&mut self, params: PathParams) {
        self.params = params;
    }

    /// Notes the controller handling the request (from its route label,
    /// `Posts#create`), so its params can be wrapped as Rails does.
    pub(crate) fn set_controller(&mut self, label: &str) {
        let Some((controller, _)) = label.split_once('#') else {
            return;
        };
        let key = glacier_inflect::singularize(&glacier_inflect::snake_case(controller));
        self.parts.extensions.insert(ParamsWrapper(key));
    }

    pub fn method(&self) -> &Method {
        &self.parts.method
    }

    pub fn uri(&self) -> &Uri {
        &self.parts.uri
    }

    pub fn path(&self) -> &str {
        self.parts.uri.path()
    }

    pub fn headers(&self) -> &HeaderMap {
        &self.parts.headers
    }

    pub fn header(&self, name: impl http::header::AsHeaderName) -> Option<&str> {
        self.parts.headers.get(name).and_then(|v| v.to_str().ok())
    }

    /// The client's IP address, as Rails' `request.remote_ip`: the
    /// connection's, unless it came through trusted proxies (loopback and
    /// private addresses, and the config's `trusted_proxies`), in which case the nearest untrusted address in
    /// `X-Forwarded-For`. `None` when there was no connection (in tests).
    pub fn remote_ip(&self) -> Option<String> {
        let peer = self.parts.extensions.get::<RemoteAddr>()?.0.ip();
        if !trusted_proxy(&peer) {
            return Some(peer.to_string());
        }
        let forwarded: Vec<std::net::IpAddr> = self
            .header("x-forwarded-for")
            .unwrap_or("")
            .split(',')
            .filter_map(|ip| ip.trim().parse().ok())
            .collect();
        let ip = forwarded
            .iter()
            .rev()
            .find(|ip| !trusted_proxy(ip))
            .or(forwarded.first())
            .unwrap_or(&peer);
        Some(ip.to_string())
    }

    /// Parameters captured by the route pattern, e.g. `id` in `/posts/:id`.
    pub fn path_params(&self) -> &PathParams {
        &self.params
    }

    /// Sets who the request is for, from middleware (who's signed in, and
    /// in which org): what `access` is in an action, and what
    /// `Post::for(access)` limits queries to.
    pub fn set_access(&mut self, access: impl crate::access::Access) {
        let access = crate::access::RequestAccess(std::sync::Arc::new(access));
        // Who it's for, in the request's trace and logs: `org:42`.
        tracing::Span::current().record("glacier.access", access.describe());
        // For the rest of the request too: jobs it queues carry it.
        crate::current::set(access.clone());
        self.parts.extensions.insert(access);
    }

    /// Who the request is for, as its middleware set it: `access` in a
    /// `.glacier` action. `401 Unauthorized` when nothing set one (no one
    /// is signed in).
    ///
    /// # Errors
    ///
    /// `401 Unauthorized` without an access.
    pub fn access(&self) -> Result<crate::access::RequestAccess> {
        self.parts
            .extensions
            .get::<crate::access::RequestAccess>()
            .cloned()
            .ok_or_else(|| Error::new(http::StatusCode::UNAUTHORIZED, "sign in first"))
    }

    /// All request parameters as text: path params, the query string and
    /// the body (form-encoded or a JSON object), later sources winning, as
    /// in Rails' `params`. Pass them to `Post::create(..)` or
    /// `post.update(..)`, which cast them into typed fields.
    pub fn params(&self) -> Params {
        let wrapper = self
            .parts
            .extensions
            .get::<ParamsWrapper>()
            .map(|wrapper| wrapper.0.clone());
        let mut params = Params(
            Default::default(),
            Vec::new(),
            Vec::new(),
            wrapper,
            false,
            Vec::new(),
        );
        let query = self.uri().query().unwrap_or("");
        for (key, value) in
            serde_urlencoded::from_str::<Vec<(String, String)>>(query).unwrap_or_default()
        {
            params.insert(key, value);
        }
        let content_type = self.header(http::header::CONTENT_TYPE).unwrap_or("");
        if content_type.starts_with("application/x-www-form-urlencoded") {
            for (key, value) in form_urlencoded_pairs(&self.body) {
                params.insert(key, value);
            }
        } else if let Some(boundary) = crate::upload::boundary(content_type) {
            for part in crate::upload::parse(&self.body, &boundary) {
                match part {
                    crate::upload::Part::Field(key, value) => params.insert(key, value),
                    crate::upload::Part::File(key, _) => params.5.push(key),
                }
            }
        } else if content_type.starts_with("application/json")
            && let Ok(serde_json::Value::Object(map)) = serde_json::from_slice(&self.body)
        {
            params.4 = true;
            for (key, value) in map {
                let value = json_text(value);
                params.1.push((key.clone(), value.clone()));
                params.insert(key, value);
            }
        }
        for (key, value) in self.params.iter() {
            params.insert(key.to_owned(), value.to_owned());
        }
        params
    }

    pub fn param(&self, name: &str) -> Option<&str> {
        self.params.get(name)
    }

    /// The `:id` path parameter as an `i64`. A missing or malformed id is a
    /// `404 Not Found`, as no record could have it.
    pub fn id(&self) -> Result<i64> {
        self.param("id")
            .and_then(|id| id.parse().ok())
            .ok_or_else(Error::not_found)
    }

    /// Parses a path parameter, responding `400 Bad Request` if it is
    /// missing or malformed.
    pub fn param_as<T: FromStr>(&self, name: &str) -> Result<T> {
        let raw = self
            .param(name)
            .ok_or_else(|| Error::bad_request(format!("missing parameter `{name}`")))?;
        raw.parse()
            .map_err(|_| Error::bad_request(format!("invalid parameter `{name}`")))
    }

    /// Deserializes the query string.
    pub fn query<T: DeserializeOwned>(&self) -> Result<T> {
        serde_urlencoded::from_str(self.uri().query().unwrap_or(""))
            .map_err(|e| Error::bad_request(format!("invalid query string: {e}")))
    }

    /// Deserializes a JSON request body.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_slice(&self.body)
            .map_err(|e| Error::bad_request(format!("invalid JSON body: {e}")))
    }

    /// Deserializes a `application/x-www-form-urlencoded` request body.
    pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
        serde_urlencoded::from_bytes(&self.body)
            .map_err(|e| Error::bad_request(format!("invalid form body: {e}")))
    }

    /// A single field from a form-encoded body, without deserializing the
    /// whole thing.
    /// The files of a `multipart/form-data` request, by field name, in
    /// the order sent.
    pub fn files(&self) -> Vec<(String, crate::upload::Upload)> {
        let content_type = self.header(http::header::CONTENT_TYPE).unwrap_or("");
        let Some(boundary) = crate::upload::boundary(content_type) else {
            return Vec::new();
        };
        crate::upload::parse(&self.body, &boundary)
            .into_iter()
            .filter_map(|part| match part {
                crate::upload::Part::File(name, upload) => Some((name, upload)),
                crate::upload::Part::Field(..) => None,
            })
            .collect()
    }

    /// The file uploaded as `name` (`comment[note_image]`), as Rails'
    /// `params[:comment][:note_image]`.
    pub fn file(&self, name: &str) -> Option<crate::upload::Upload> {
        self.files()
            .into_iter()
            .find(|(field, _)| field == name)
            .map(|(_, upload)| upload)
    }

    pub fn form_field(&self, name: &str) -> Option<String> {
        let is_form = self
            .header(http::header::CONTENT_TYPE)
            .is_some_and(|ct| ct.starts_with("application/x-www-form-urlencoded"));
        if !is_form {
            return None;
        }
        form_urlencoded_pairs(&self.body)
            .into_iter()
            .find(|(key, _)| key == name)
            .map(|(_, value)| value)
    }

    pub fn body(&self) -> &Bytes {
        &self.body
    }

    /// Application-wide state registered with `App::state`.
    pub fn state<T: Send + Sync + 'static>(&self) -> Result<&T> {
        self.state.get::<T>().ok_or_else(|| {
            Error::internal(format!(
                "no app state of type `{}` registered",
                type_name::<T>()
            ))
        })
    }

    pub fn cookies(&self) -> &Cookies {
        &self.cookies
    }

    pub fn session(&self) -> &Session {
        &self.session
    }

    /// A flash message set by an earlier request (e.g. `"notice"`), or by
    /// `flash_now`. Reading the flash spends it.
    pub fn flash(&self, kind: &str) -> Option<String> {
        self.session.flash(kind)
    }

    /// A flash message for the page this request renders, as Rails'
    /// `flash.now[:alert] = …`.
    pub fn flash_now(&self, kind: &str, message: impl Into<String>) {
        self.session.flash_now(kind, message);
    }

    /// Sets a flash message for the next request.
    pub fn put_flash(&self, kind: &str, message: impl Into<String>) {
        self.session.put_flash(kind, message);
    }

    /// The URL the request came to, without its path: `https://example.com`,
    /// from `X-Forwarded-Proto` and `Host` behind a proxy.
    pub fn base_url(&self) -> String {
        crate::request::base_url_of(&self.parts)
    }

    /// The CSRF token for this session, for embedding in forms.
    pub fn csrf_token(&self) -> String {
        crate::csrf::token_for(&self.session)
    }

    /// Per-request data, e.g. a current user set by an auth middleware.
    pub fn extensions(&self) -> &Extensions {
        &self.parts.extensions
    }

    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.parts.extensions
    }
}

fn form_urlencoded_pairs(body: &[u8]) -> Vec<(String, String)> {
    serde_urlencoded::from_bytes(body).unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ctx(peer: &str, forwarded: Option<&str>) -> Context {
        let mut req = http::Request::builder().uri("/");
        if let Some(forwarded) = forwarded {
            req = req.header("x-forwarded-for", forwarded);
        }
        let (mut parts, ()) = req.body(()).unwrap().into_parts();
        parts.extensions.insert(RemoteAddr(peer.parse().unwrap()));
        let cookies = Cookies::from_headers(&HeaderMap::new(), Arc::new(cookie::Key::generate()));
        let session = Session::new(cookies.clone(), false);
        Context::new(parts, Bytes::new(), Arc::default(), cookies, session)
    }

    #[test]
    fn finds_the_client_ip_as_rails_does() {
        assert_eq!(
            ctx("203.0.113.9:5000", None).remote_ip().as_deref(),
            Some("203.0.113.9")
        );
        assert_eq!(ctx("[::1]:5000", None).remote_ip().as_deref(), Some("::1"));
        // Behind a local proxy: the nearest address that isn't a proxy.
        assert_eq!(
            ctx("127.0.0.1:5000", Some("198.51.100.7, 10.0.0.2"))
                .remote_ip()
                .as_deref(),
            Some("198.51.100.7")
        );
        // A client can't pretend to be someone else from outside.
        assert_eq!(
            ctx("203.0.113.9:5000", Some("198.51.100.7"))
                .remote_ip()
                .as_deref(),
            Some("203.0.113.9")
        );
    }

    #[test]
    fn trusts_configured_proxies_too() {
        // A load balancer with a public address (TEST-NET-1 here).
        trust_proxies(&["192.0.2.0/24", "2001:db8::1"]).unwrap();
        assert_eq!(
            ctx("192.0.2.40:5000", Some("198.51.100.7"))
                .remote_ip()
                .as_deref(),
            Some("198.51.100.7")
        );
        assert_eq!(
            ctx("192.0.3.40:5000", Some("198.51.100.7"))
                .remote_ip()
                .as_deref(),
            Some("192.0.3.40")
        );
        assert_eq!(
            ctx("[2001:db8::1]:5000", Some("198.51.100.7"))
                .remote_ip()
                .as_deref(),
            Some("198.51.100.7")
        );
        assert!(trust_proxies(&["not an address"]).is_err());
        assert!(trust_proxies(&["10.0.0.0/33"]).is_err());
        let range = IpRange::parse("0.0.0.0/0").unwrap();
        assert!(range.contains(&"8.8.8.8".parse().unwrap()));
        assert!(!range.contains(&"::1".parse().unwrap()));
    }
}