axol 0.2.0

Axol Web Framework
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
//! Middleware which adds headers for [CORS][mdn].
//!
//! # Example
//!
//! [`Cors`] is a [`Plugin`], so it is installed on a path prefix of a [`Router`]
//! and applies to that whole subtree.
//!
//! ```
//! use axol::Router;
//! use axol::cors::Cors;
//! use axol::http::Method;
//!
//! async fn handler() -> &'static str {
//!     "hello"
//! }
//!
//! let cors = Cors::new()
//!     // allow `GET` and `POST` when accessing the resource
//!     .allow_methods([Method::Get, Method::Post])
//!     // allow requests from any origin
//!     .allow_origin("*");
//!
//! let router = Router::new()
//!     .plugin("/", cors)
//!     .get("/", handler);
//! # let _ = router;
//! ```
//!
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

#![allow(clippy::enum_variant_names)]
use axol_http::{
    Method,
    header::HeaderMap,
    request::{RequestParts, RequestPartsRef},
    response::Response,
};

mod allow_credentials;
mod allow_headers;
mod allow_methods;
mod allow_origin;
mod allow_private_network;
mod expose_headers;
mod max_age;
mod vary;

use crate::{Error, Extension, FromRequestParts, Plugin, Result, Router};

/// A caller-supplied decision over a single header value plus the request it arrived on.
///
/// `T` is `bool` for the allow/deny knobs and `Duration` for [`MaxAge`].
pub type CorsPredicate<T> =
    std::sync::Arc<dyn for<'a> Fn(&'a str, RequestPartsRef<'a>) -> T + Send + Sync + 'static>;

pub use self::{
    allow_credentials::AllowCredentials, allow_headers::AllowHeaders, allow_methods::AllowMethods,
    allow_origin::AllowOrigin, allow_private_network::AllowPrivateNetwork,
    expose_headers::ExposeHeaders, max_age::MaxAge, vary::Vary,
};

/// Layer that applies the [`Cors`] middleware which adds headers for [CORS][mdn].
///
/// See the [module docs](crate::cors) for an example.
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
#[derive(Debug, Clone)]
#[must_use]
pub struct Cors {
    allow_credentials: AllowCredentials,
    allow_headers: AllowHeaders,
    allow_methods: AllowMethods,
    allow_origin: AllowOrigin,
    allow_private_network: AllowPrivateNetwork,
    expose_headers: ExposeHeaders,
    max_age: MaxAge,
    vary: Vary,
}

impl Cors {
    /// Create a new `Cors`.
    ///
    /// No headers are sent by default. Use the builder methods to customize
    /// the behavior.
    ///
    /// You need to set at least an allowed origin for browsers to make
    /// successful cross-origin requests to your service.
    pub fn new() -> Self {
        Self {
            allow_credentials: Default::default(),
            allow_headers: Default::default(),
            allow_methods: Default::default(),
            allow_origin: Default::default(),
            allow_private_network: Default::default(),
            expose_headers: Default::default(),
            max_age: Default::default(),
            vary: Default::default(),
        }
    }

    /// A permissive configuration:
    ///
    /// - All request headers allowed.
    /// - All methods allowed.
    /// - All origins allowed.
    /// - All headers exposed.
    pub fn permissive() -> Self {
        Self::new()
            .allow_headers(Any)
            .allow_methods(Any)
            .allow_origin(Any)
            .expose_headers(Any)
    }

    /// A very permissive configuration:
    ///
    /// - **Credentials allowed.**
    /// - The method received in `Access-Control-Request-Method` is sent back
    ///   as an allowed method.
    /// - The origin of the preflight request is sent back as an allowed origin.
    /// - The header names received in `Access-Control-Request-Headers` are sent
    ///   back as allowed headers.
    /// - No headers are currently exposed, but this may change in the future.
    pub fn very_permissive() -> Self {
        Self::new()
            .allow_credentials(true)
            .allow_headers(AllowHeaders::mirror_request())
            .allow_methods(AllowMethods::mirror_request())
            .allow_origin(AllowOrigin::mirror_request())
    }

    /// Set the [`Access-Control-Allow-Credentials`][mdn] header.
    ///
    /// ```
    /// use axol::cors::Cors;
    ///
    /// let cors = Cors::new().allow_credentials(true);
    /// ```
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
    pub fn allow_credentials<T>(mut self, allow_credentials: T) -> Self
    where
        T: Into<AllowCredentials>,
    {
        self.allow_credentials = allow_credentials.into();
        self
    }

    /// Set the value of the [`Access-Control-Allow-Headers`][mdn] header.
    ///
    /// ```
    /// use axol::cors::Cors;
    ///
    /// let cors = Cors::new().allow_headers(["authorization", "accept"]);
    /// ```
    ///
    /// All headers can be allowed with
    ///
    /// ```
    /// use axol::cors::{Any, Cors};
    ///
    /// let cors = Cors::new().allow_headers(Any);
    /// ```
    ///
    /// Note that multiple calls to this method will override any previous
    /// calls.
    ///
    /// Also note that `Access-Control-Allow-Headers` is required for requests that have
    /// `Access-Control-Request-Headers`.
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
    pub fn allow_headers<T>(mut self, headers: T) -> Self
    where
        T: Into<AllowHeaders>,
    {
        self.allow_headers = headers.into();
        self
    }

    /// Set the value of the [`Access-Control-Max-Age`][mdn] header.
    ///
    /// ```
    /// use std::time::Duration;
    /// use axol::cors::Cors;
    ///
    /// let cors = Cors::new().max_age(Duration::from_secs(60) * 10);
    /// ```
    ///
    /// By default the header will not be set which disables caching and will
    /// require a preflight call for all requests.
    ///
    /// Note that each browser has a maximum internal value that takes
    /// precedence when the Access-Control-Max-Age is greater. For more details
    /// see [mdn].
    ///
    /// If you need more flexibility, you can use supply a function which can
    /// dynamically decide the max-age based on the origin and other parts of
    /// each preflight request:
    ///
    /// ```
    /// # struct MyServerConfig { cors_max_age: Duration }
    /// use std::time::Duration;
    ///
    /// use axol::cors::{Cors, MaxAge};
    /// use axol::http::request::RequestPartsRef;
    ///
    /// let cors = Cors::new().max_age(MaxAge::dynamic(
    ///     |_origin: &str, parts: RequestPartsRef<'_>| -> Duration {
    ///         // Let's say you want to be able to reload your config at
    ///         // runtime and have another middleware that always inserts
    ///         // the current config into the request extensions
    ///         match parts.extensions.get::<MyServerConfig>() {
    ///             Some(config) => config.cors_max_age,
    ///             None => Duration::from_secs(60),
    ///         }
    ///     },
    /// ));
    /// ```
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
    pub fn max_age<T>(mut self, max_age: T) -> Self
    where
        T: Into<MaxAge>,
    {
        self.max_age = max_age.into();
        self
    }

    /// Set the value of the [`Access-Control-Allow-Methods`][mdn] header.
    ///
    /// ```
    /// use axol::cors::Cors;
    /// use axol::http::Method;
    ///
    /// let cors = Cors::new().allow_methods([Method::Get, Method::Post]);
    /// ```
    ///
    /// All methods can be allowed with
    ///
    /// ```
    /// use axol::cors::{Any, Cors};
    ///
    /// let cors = Cors::new().allow_methods(Any);
    /// ```
    ///
    /// Note that multiple calls to this method will override any previous
    /// calls.
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
    pub fn allow_methods<T>(mut self, methods: T) -> Self
    where
        T: Into<AllowMethods>,
    {
        self.allow_methods = methods.into();
        self
    }

    /// Set the value of the [`Access-Control-Allow-Origin`][mdn] header.
    ///
    /// ```
    /// use axol::cors::Cors;
    ///
    /// let cors = Cors::new().allow_origin("http://example.com");
    /// ```
    ///
    /// Multiple origins can be allowed with
    ///
    /// ```
    /// use axol::cors::Cors;
    ///
    /// let cors = Cors::new().allow_origin([
    ///     "http://example.com",
    ///     "http://api.example.com",
    /// ]);
    /// ```
    ///
    /// All origins can be allowed with
    ///
    /// ```
    /// use axol::cors::{Any, Cors};
    ///
    /// let cors = Cors::new().allow_origin(Any);
    /// ```
    ///
    /// You can also use a closure
    ///
    /// ```
    /// use axol::cors::{AllowOrigin, Cors};
    /// use axol::http::request::RequestPartsRef;
    ///
    /// let cors = Cors::new().allow_origin(AllowOrigin::predicate(
    ///     |origin: &str, _parts: RequestPartsRef<'_>| {
    ///         origin.ends_with(".rust-lang.org")
    ///     },
    /// ));
    /// ```
    ///
    /// Note that multiple calls to this method will override any previous
    /// calls.
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
    pub fn allow_origin<T>(mut self, origin: T) -> Self
    where
        T: Into<AllowOrigin>,
    {
        self.allow_origin = origin.into();
        self
    }

    /// Set the value of the [`Access-Control-Expose-Headers`][mdn] header.
    ///
    /// ```
    /// use axol::cors::Cors;
    ///
    /// let cors = Cors::new().expose_headers(["content-encoding"]);
    /// ```
    ///
    /// All headers can be allowed with
    ///
    /// ```
    /// use axol::cors::{Any, Cors};
    ///
    /// let cors = Cors::new().expose_headers(Any);
    /// ```
    ///
    /// Note that multiple calls to this method will override any previous
    /// calls.
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
    pub fn expose_headers<T>(mut self, headers: T) -> Self
    where
        T: Into<ExposeHeaders>,
    {
        self.expose_headers = headers.into();
        self
    }

    /// Set the value of the [`Access-Control-Allow-Private-Network`][wicg] header.
    ///
    /// ```
    /// use axol::cors::Cors;
    ///
    /// let cors = Cors::new().allow_private_network(true);
    /// ```
    ///
    /// [wicg]: https://wicg.github.io/private-network-access/
    pub fn allow_private_network<T>(mut self, allow_private_network: T) -> Self
    where
        T: Into<AllowPrivateNetwork>,
    {
        self.allow_private_network = allow_private_network.into();
        self
    }

    /// Set the value(s) of the [`Vary`][mdn] header.
    ///
    /// In contrast to the other headers, this one has a non-empty default of
    /// [`preflight_request_headers()`].
    ///
    /// You only need to set this is you want to remove some of these defaults,
    /// or if you use a closure for one of the other headers and want to add a
    /// vary header accordingly.
    ///
    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
    pub fn vary<T>(mut self, headers: T) -> Self
    where
        T: Into<Vary>,
    {
        self.vary = headers.into();
        self
    }
}

/// Represents a wildcard value (`*`) used with some CORS headers such as
/// [`Cors::allow_methods`].
#[derive(Debug, Clone, Copy)]
#[must_use]
pub struct Any;

impl Default for Cors {
    fn default() -> Self {
        Self::new()
    }
}

struct OptionsFilter;

#[async_trait::async_trait]
impl<'a> FromRequestParts<'a> for OptionsFilter {
    async fn from_request_parts(request: RequestPartsRef<'a>) -> Result<Self> {
        if request.method != Method::Options {
            return Err(Error::SkipMiddleware);
        }
        Ok(Self)
    }
}

struct NotOptionsFilter;

#[async_trait::async_trait]
impl<'a> FromRequestParts<'a> for NotOptionsFilter {
    async fn from_request_parts(request: RequestPartsRef<'a>) -> Result<Self> {
        if request.method == Method::Options {
            return Err(Error::SkipMiddleware);
        }
        Ok(Self)
    }
}

impl Cors {
    async fn options_intercept(
        _: OptionsFilter,
        Extension(cors): Extension<Cors>,
        parts: RequestParts,
    ) -> Result<Option<HeaderMap>> {
        let origin = parts.headers.get("origin");
        let mut headers = HeaderMap::new();
        if let Some(header) = cors.allow_origin.to_header(origin, parts.as_ref()) {
            headers.append_typed(&header);
        }
        if let Some(header) = cors.allow_credentials.to_header(origin, parts.as_ref()) {
            headers.append_typed(&header);
        }
        if let Some((name, value)) = cors.allow_private_network.to_header(origin, parts.as_ref()) {
            headers.append(name, value);
        }
        for value in cors.vary.values() {
            headers.append("vary", value);
        }
        if let Some(header) = cors.allow_methods.to_header(parts.as_ref()) {
            headers.append_typed(&header);
        }
        if let Some(header) = cors.allow_headers.to_header(parts.as_ref()) {
            headers.append_typed(&header);
        }
        if let Some(header) = cors.max_age.to_header(origin, parts.as_ref()) {
            headers.append_typed(&header);
        }

        Ok(Some(headers))
    }

    async fn response_augment(
        _: NotOptionsFilter,
        Extension(cors): Extension<Cors>,
        parts: RequestParts,
        mut response: Response,
    ) -> Response {
        let origin = parts.headers.get("origin");

        if let Some(header) = cors.allow_origin.to_header(origin, parts.as_ref()) {
            response.headers.append_typed(&header);
        }
        if let Some(header) = cors.allow_credentials.to_header(origin, parts.as_ref()) {
            response.headers.append_typed(&header);
        }
        if let Some((name, value)) = cors.allow_private_network.to_header(origin, parts.as_ref()) {
            response.headers.append(name, value);
        }
        for value in cors.vary.values() {
            response.headers.append("vary", value);
        }
        if let Some(header) = cors.expose_headers.to_header(parts.as_ref()) {
            response.headers.append_typed(&header);
        }

        response
    }
}

impl Plugin for Cors {
    fn apply(self, router: Router, path: &str) -> Router {
        ensure_usable_cors_rules(&self);
        router
            .extension(path, self)
            .request_hook(path, Cors::options_intercept)
            .late_response_hook(path, Cors::response_augment)
    }
}

fn ensure_usable_cors_rules(layer: &Cors) {
    if layer.allow_credentials.is_true() {
        assert!(
            !layer.allow_headers.is_wildcard(),
            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
             with `Access-Control-Allow-Headers: *`"
        );

        assert!(
            !layer.allow_methods.is_wildcard(),
            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
             with `Access-Control-Allow-Methods: *`"
        );

        assert!(
            !layer.allow_origin.is_wildcard(),
            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
             with `Access-Control-Allow-Origin: *`"
        );

        assert!(
            !layer.expose_headers.is_wildcard(),
            "Invalid CORS configuration: Cannot combine `Access-Control-Allow-Credentials: true` \
             with `Access-Control-Expose-Headers: *`"
        );
    }
}

/// Returns an iterator over the three request headers that may be involved in a CORS preflight request.
///
/// This is the default set of header names returned in the `vary` header
pub fn preflight_request_headers() -> impl Iterator<Item = &'static str> {
    [
        "origin",
        "access-control-request-method",
        "access-control-request-headers",
    ]
    .into_iter()
}