glacier-web 0.1.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
//! 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>,
);

/// 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.
    pub fn require(&self, key: &str) -> Result<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) {
            for (name, value) in &self.1 {
                nested.insert(name.clone(), value.clone());
            }
        }
        if nested.0.is_empty() {
            return Err(Error::bad_request(format!(
                "param is missing or the value is empty: {key}"
            )));
        }
        Ok(nested)
    }

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

    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.
fn trusted_proxy(ip: &std::net::IpAddr) -> bool {
    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,
    }
}

/// 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,
        }
    }

    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), 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
    }

    /// 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);
        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) {
                if let crate::upload::Part::Field(key, value) = part {
                    params.insert(key, value);
                }
            }
        } else if content_type.starts_with("application/json")
            && let Ok(serde_json::Value::Object(map)) = serde_json::from_slice(&self.body)
        {
            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 the previous request (e.g. `"notice"`).
    pub fn flash(&self, kind: &str) -> Option<String> {
        self.session.flash(kind)
    }

    /// 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 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")
        );
    }
}