topcoat-router 0.8.0

A modular, batteries-included Rust web framework for server-rendered apps.
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
use std::ops::{Deref, DerefMut};

use ::serde::{Serialize, de::DeserializeOwned};
use http::{
    Method,
    header::{CONTENT_TYPE, HeaderValue},
};
use topcoat_core::{context::Cx, error::Result};

use crate::{
    Body,
    error::{bad_request, bad_request_at},
    request::{Bytes, FromRequest, OptionalFromRequest, content_type, method, uri},
    response::{IntoResponse, Response},
};

/// `application/x-www-form-urlencoded` request extractor and response wrapper.
///
/// As a [`FromRequest`] extractor, `Form<T>` deserializes URL-encoded form data
/// into `T`. For `GET` and `HEAD` requests it reads the URI query string; for
/// other methods it reads the request body and requires a
/// `Content-Type: application/x-www-form-urlencoded` header. As an
/// [`IntoResponse`] wrapper, it serializes `T` back to a URL-encoded body and
/// sets the response `Content-Type`.
///
/// Wrap it in [`Option`] to make the body optional. For `GET` and `HEAD`
/// requests the extractor yields [`None`] only when there is no query string;
/// for other methods it yields [`None`] when there is no `Content-Type` header.
///
/// # Examples
///
/// ```rust
/// use serde::{Deserialize, Serialize};
/// use topcoat::{
///     Result,
///     router::{
///         content::{Form, Json},
///         route,
///     },
/// };
///
/// #[derive(Deserialize, Serialize)]
/// struct Search {
///     query: String,
///     page: u32,
/// }
///
/// #[route(GET "/search")]
/// async fn search(Form(input): Form<Search>) -> Result<Json<Search>> {
///     Ok(Json(input))
/// }
/// ```
#[derive(Debug, Clone, Copy, Default)]
#[must_use]
pub struct Form<T>(pub T);

impl<T> From<T> for Form<T> {
    fn from(value: T) -> Self {
        Self(value)
    }
}

impl<T> Deref for Form<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Form<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> FromRequest for Form<T>
where
    T: DeserializeOwned,
{
    async fn from_request(cx: &Cx, body: Body) -> Result<Self> {
        let RawForm(bytes) = RawForm::from_request(cx, body).await?;
        Self::from_bytes(&bytes)
    }
}

impl<T> OptionalFromRequest for Form<T>
where
    T: DeserializeOwned,
{
    async fn from_request(cx: &Cx, body: Body) -> Result<Option<Self>> {
        if matches!(method(cx), &Method::GET | &Method::HEAD) {
            return match uri(cx).query() {
                Some(query) => Ok(Some(Self::from_bytes(query.as_bytes())?)),
                None => Ok(None),
            };
        }

        if content_type(cx).is_some() {
            Ok(Some(<Self as FromRequest>::from_request(cx, body).await?))
        } else {
            Ok(None)
        }
    }
}

impl<T> Form<T>
where
    T: DeserializeOwned,
{
    /// Deserializes URL-encoded form bytes into `Form<T>`.
    ///
    /// Unlike the [`FromRequest`] extractor, this does not inspect the request
    /// method or `Content-Type`; it parses `bytes` directly.
    ///
    /// # Errors
    ///
    /// Returns a bad-request error when `bytes` are not valid URL-encoded form
    /// data matching `T`. An empty value, as a browser sends for a blank input,
    /// deserializes to `None` for an `Option<T>` field.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let deserializer = crate::urlencoded::Deserializer::new(form_urlencoded::parse(bytes));
        let value = serde_path_to_error::deserialize(deserializer).map_err(|error| {
            bad_request_at(
                error.path(),
                format!("invalid form value: {}", error.inner()),
            )
        })?;

        Ok(Self(value))
    }
}

impl<T> IntoResponse for Form<T>
where
    T: Serialize,
{
    fn into_response(self, cx: &Cx) -> Result<Response> {
        (
            [(
                CONTENT_TYPE,
                HeaderValue::from_static("application/x-www-form-urlencoded"),
            )],
            serde_urlencoded::to_string(&self.0)?,
        )
            .into_response(cx)
    }
}

/// Extractor for the raw bytes of an `application/x-www-form-urlencoded`
/// request.
///
/// For `GET` and `HEAD` requests it yields the raw query string; for other
/// methods it yields the raw request body and requires a
/// `Content-Type: application/x-www-form-urlencoded` header. Unlike [`Form`],
/// the bytes are returned without deserialization.
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct RawForm(pub Bytes);

impl FromRequest for RawForm {
    async fn from_request(cx: &Cx, body: Body) -> Result<Self> {
        if matches!(method(cx), &Method::GET | &Method::HEAD) {
            let query = uri(cx).query().unwrap_or_default();
            return Ok(Self(Bytes::copy_from_slice(query.as_bytes())));
        }

        if !form_content_type(content_type(cx)) {
            return Err(bad_request(
                "expected request with `Content-Type: application/x-www-form-urlencoded`",
            )
            .into());
        }

        let bytes = Bytes::from_request(cx, body).await?;
        Ok(Self(bytes))
    }
}

/// Returns whether `content_type` is `application/x-www-form-urlencoded`,
/// ignoring any media type parameters (such as `; charset=utf-8`) and case.
fn form_content_type(content_type: Option<&str>) -> bool {
    let Some(content_type) = content_type else {
        return false;
    };

    content_type
        .split(';')
        .next()
        .unwrap_or_default()
        .trim()
        .eq_ignore_ascii_case("application/x-www-form-urlencoded")
}

#[cfg(test)]
mod tests {
    use http::{Method, Request, header::CONTENT_TYPE};
    use topcoat_core::context::{Cx, CxTestBuilder};

    use super::*;
    use crate::{
        Body,
        error::BadRequestError,
        request::{FromRequest, OptionalFromRequest},
        to_bytes,
    };

    const FORM_CONTENT_TYPE: &str = "application/x-www-form-urlencoded";

    /// Builds a `Cx` carrying request `Parts` with the given method, URI, and
    /// optional `Content-Type` header.
    fn cx(method: Method, uri: &str, content_type: Option<&str>) -> Cx {
        let mut builder = Request::builder().method(method).uri(uri);
        if let Some(content_type) = content_type {
            builder = builder.header(CONTENT_TYPE, content_type);
        }

        let (parts, ()) = builder.body(()).expect("request should build").into_parts();

        CxTestBuilder::new().request_context(parts).build()
    }

    #[tokio::test]
    async fn from_request_reads_query_for_get() {
        let cx = cx(Method::GET, "/search?a=1&b=two", None);
        let Form(pairs) =
            <Form<Vec<(String, String)>> as FromRequest>::from_request(&cx, Body::empty())
                .await
                .expect("a valid query string");

        assert_eq!(
            pairs,
            vec![
                ("a".to_owned(), "1".to_owned()),
                ("b".to_owned(), "two".to_owned())
            ]
        );
    }

    #[tokio::test]
    async fn from_request_reads_body_for_post() {
        let cx = cx(Method::POST, "/search", Some(FORM_CONTENT_TYPE));
        let Form(pairs) = <Form<Vec<(String, String)>> as FromRequest>::from_request(
            &cx,
            Body::from("a=1&b=two"),
        )
        .await
        .expect("a valid form body");

        assert_eq!(
            pairs,
            vec![
                ("a".to_owned(), "1".to_owned()),
                ("b".to_owned(), "two".to_owned())
            ]
        );
    }

    #[tokio::test]
    async fn from_request_post_without_content_type_is_bad_request() {
        let cx = cx(Method::POST, "/search", None);
        let error =
            <Form<Vec<(String, String)>> as FromRequest>::from_request(&cx, Body::from("a=1"))
                .await
                .expect_err("a missing form content type is rejected");

        assert!(error.downcast_ref::<BadRequestError>().is_some());
    }

    #[tokio::test]
    async fn optional_from_request_get_without_query_is_none() {
        let cx = cx(Method::GET, "/search", None);
        let form =
            <Form<Vec<(String, String)>> as OptionalFromRequest>::from_request(&cx, Body::empty())
                .await
                .expect("an absent query string is not an error");

        assert!(form.is_none());
    }

    #[tokio::test]
    async fn optional_from_request_get_with_query_is_some() {
        let cx = cx(Method::GET, "/search?a=1", None);
        let form =
            <Form<Vec<(String, String)>> as OptionalFromRequest>::from_request(&cx, Body::empty())
                .await
                .expect("a valid query string is not an error");

        assert_eq!(
            form.expect("a form payload is present").0,
            vec![("a".to_owned(), "1".to_owned())]
        );
    }

    #[tokio::test]
    async fn optional_from_request_post_without_content_type_is_none() {
        let cx = cx(Method::POST, "/search", None);
        let form = <Form<Vec<(String, String)>> as OptionalFromRequest>::from_request(
            &cx,
            Body::from("a=1"),
        )
        .await
        .expect("an absent content type is not an error");

        assert!(form.is_none());
    }

    #[tokio::test]
    async fn optional_from_request_post_with_content_type_is_some() {
        let cx = cx(Method::POST, "/search", Some(FORM_CONTENT_TYPE));
        let form = <Form<Vec<(String, String)>> as OptionalFromRequest>::from_request(
            &cx,
            Body::from("a=1"),
        )
        .await
        .expect("a valid form body is not an error");

        assert_eq!(
            form.expect("a form payload is present").0,
            vec![("a".to_owned(), "1".to_owned())]
        );
    }

    #[test]
    fn from_bytes_deserializes_into_target_type() {
        let Form(pairs) =
            Form::<Vec<(String, u32)>>::from_bytes(b"a=1&b=2").expect("valid form data");
        assert_eq!(pairs, vec![("a".to_owned(), 1), ("b".to_owned(), 2)]);
    }

    #[test]
    fn from_bytes_rejects_values_that_do_not_match_the_target() {
        let error = Form::<Vec<(String, u32)>>::from_bytes(b"a=not-a-number")
            .expect_err("a type mismatch is rejected");

        assert!(error.downcast_ref::<BadRequestError>().is_some());
    }

    #[tokio::test]
    async fn into_response_serializes_form_with_content_type() {
        let response = Form(vec![
            ("a".to_owned(), "1".to_owned()),
            ("b".to_owned(), "two".to_owned()),
        ])
        .into_response(&Cx::default())
        .expect("serialization succeeds");

        assert_eq!(
            response
                .headers()
                .get(CONTENT_TYPE)
                .map(http::HeaderValue::as_bytes),
            Some(FORM_CONTENT_TYPE.as_bytes())
        );

        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("reading the response body");
        assert_eq!(&body[..], b"a=1&b=two");
    }

    #[tokio::test]
    async fn raw_form_get_yields_query_bytes() {
        let cx = cx(Method::GET, "/search?a=1&b=two", None);
        let RawForm(bytes) = RawForm::from_request(&cx, Body::empty())
            .await
            .expect("a query string");

        assert_eq!(&bytes[..], b"a=1&b=two");
    }

    #[tokio::test]
    async fn raw_form_post_yields_body_bytes() {
        let cx = cx(Method::POST, "/search", Some(FORM_CONTENT_TYPE));
        let RawForm(bytes) = RawForm::from_request(&cx, Body::from("a=1&b=two"))
            .await
            .expect("a form body");

        assert_eq!(&bytes[..], b"a=1&b=two");
    }

    #[tokio::test]
    async fn raw_form_post_without_content_type_is_bad_request() {
        let cx = cx(Method::POST, "/search", None);
        let error = RawForm::from_request(&cx, Body::from("a=1"))
            .await
            .expect_err("a missing form content type is rejected");

        assert!(error.downcast_ref::<BadRequestError>().is_some());
    }

    #[test]
    fn form_content_type_recognizes_urlencoded_media_types() {
        assert!(form_content_type(Some(FORM_CONTENT_TYPE)));
        assert!(form_content_type(Some(
            "application/x-www-form-urlencoded; charset=utf-8"
        )));
        assert!(form_content_type(Some("APPLICATION/X-WWW-FORM-URLENCODED")));

        assert!(!form_content_type(None));
        assert!(!form_content_type(Some("application/json")));
        assert!(!form_content_type(Some("text/plain")));
    }

    #[derive(Debug, serde::Deserialize)]
    struct Deadline {
        due: Option<f64>,
    }

    #[test]
    fn from_bytes_reads_empty_optional_value_as_none() {
        let Form(deadline) =
            Form::<Deadline>::from_bytes(b"due=").expect("an empty optional value");

        assert_eq!(deadline.due, None);
    }

    #[test]
    fn from_bytes_reads_present_optional_value() {
        let Form(deadline) =
            Form::<Deadline>::from_bytes(b"due=1.5").expect("a valid optional value");

        assert_eq!(deadline.due, Some(1.5));
    }

    #[test]
    fn from_bytes_reads_missing_optional_key_as_none() {
        let Form(deadline) = Form::<Deadline>::from_bytes(b"").expect("no keys at all");

        assert_eq!(deadline.due, None);
    }

    #[test]
    fn from_bytes_keeps_empty_required_string() {
        #[derive(Debug, serde::Deserialize)]
        struct Named {
            name: String,
        }

        let Form(named) = Form::<Named>::from_bytes(b"name=").expect("an empty string value");

        assert_eq!(named.name, "");
    }

    #[test]
    fn from_bytes_reads_empty_optional_string_as_none() {
        #[derive(Debug, serde::Deserialize)]
        struct Nickname {
            nick: Option<String>,
        }

        let Form(nickname) =
            Form::<Nickname>::from_bytes(b"nick=").expect("an empty optional string");

        assert_eq!(nickname.nick, None);
    }

    #[test]
    fn from_bytes_rejects_empty_required_number() {
        #[derive(Debug, serde::Deserialize)]
        struct Count {
            #[allow(dead_code)]
            n: f64,
        }

        let error = Form::<Count>::from_bytes(b"n=").expect_err("an empty required number");

        assert!(error.to_string().contains("invalid form value"), "{error}");
    }

    #[derive(Debug, PartialEq, serde::Deserialize)]
    enum Priority {
        High,
    }

    #[derive(Debug, serde::Deserialize)]
    struct Task {
        priority: Option<Priority>,
    }

    #[test]
    fn from_bytes_reads_empty_optional_enum_as_none() {
        let Form(task) = Form::<Task>::from_bytes(b"priority=").expect("an empty optional enum");

        assert_eq!(task.priority, None);
    }

    #[test]
    fn from_bytes_reads_present_optional_enum() {
        let Form(task) = Form::<Task>::from_bytes(b"priority=High").expect("a valid optional enum");

        assert_eq!(task.priority, Some(Priority::High));
    }
}