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
//! Library aimed at providing CORS functionality
//! for Gotham based servers.
//!
//! Currently a very basic implementation with
//! limited customisability.
#[macro_use]
extern crate gotham_derive;

extern crate futures;
extern crate gotham;
extern crate hyper;
extern crate unicase;

use futures::Future;
use gotham::handler::HandlerFuture;
use gotham::middleware::Middleware;
use gotham::state::{FromState, State};
use hyper::header::{
    AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowMethods,
    AccessControlAllowOrigin, AccessControlMaxAge, Headers, Origin,
};
use hyper::Method;
use std::option::Option;
use unicase::Ascii;

/// Struct to perform the necessary CORS
/// functionality needed. Allows some
/// customisation through use of the
/// new() function.
///
/// Example of use:
/// ```rust
/// extern crate gotham;
/// extern crate gotham_cors_middleware;
///
/// use gotham::pipeline::new_pipeline;
/// use gotham_cors_middleware::CORSMiddleware;
/// use gotham::pipeline::single::single_pipeline;
/// use gotham::router::builder::*;
/// use gotham::router::Router;
///
/// pub fn router() -> Router {
///     let (chain, pipeline) = single_pipeline(
///         new_pipeline()
///             .add(CORSMiddleware::default())
///             .build()
///     );
///
///     build_router(chain, pipeline, |route| {
///         // Routes
///     })
/// }
/// ```
#[derive(Clone, NewMiddleware, Debug, PartialEq)]
pub struct CORSMiddleware {
    methods: Vec<Method>,
    origin: Option<String>,
    max_age: u32,
}

impl CORSMiddleware {
    /// Create a new CORSMiddleware with custom methods,
    /// origin and max_age properties.
    ///
    /// Expects methods to be a Vec of hyper::Method enum
    /// values, origin to be an Option containing a String
    /// (so allows for None values - which defaults to
    /// returning the sender origin on request or returning
    /// a string of "*" - see the call function source) and
    /// max age to be a u32 value.
    ///
    /// Example of use:
    /// ```rust
    /// extern crate gotham;
    /// extern crate gotham_cors_middleware;
    /// extern crate hyper;
    ///
    /// use gotham::pipeline::new_pipeline;
    /// use gotham_cors_middleware::CORSMiddleware;
    /// use gotham::pipeline::single::single_pipeline;
    /// use gotham::router::builder::*;
    /// use gotham::router::Router;
    /// use hyper::Method;
    ///
    /// fn create_custom_middleware() -> CORSMiddleware {
    ///     let methods = vec![Method::Delete, Method::Get, Method::Head, Method::Options];
    ///
    ///     let max_age = 1000;
    ///
    ///     let origin = Some("http://www.example.com".to_string());
    ///
    ///     CORSMiddleware::new(methods, origin, max_age)
    /// }
    ///
    /// pub fn router() -> Router {
    ///     let (chain, pipeline) = single_pipeline(
    ///         new_pipeline()
    ///             .add(create_custom_middleware())
    ///             .build()
    ///     );
    ///
    ///     build_router(chain, pipeline, |route| {
    ///         // Routes
    ///     })
    /// }
    /// ```
    pub fn new(methods: Vec<Method>, origin: Option<String>, max_age: u32) -> CORSMiddleware {
        CORSMiddleware {
            methods,
            origin,
            max_age,
        }
    }

    /// Creates a new CORSMiddleware with what is currently
    /// the "default" values for methods/origin/max_age.
    ///
    /// This is based off the values that were used previously
    /// before they were customisable. If you need different
    /// values, use the new() function.
    pub fn default() -> CORSMiddleware {
        let methods = vec![
            Method::Delete,
            Method::Get,
            Method::Head,
            Method::Options,
            Method::Patch,
            Method::Post,
            Method::Put,
        ];

        let origin = None;
        let max_age = 86400;

        CORSMiddleware::new(methods, origin, max_age)
    }
}

impl Middleware for CORSMiddleware {
    fn call<Chain>(self, state: State, chain: Chain) -> Box<HandlerFuture>
    where
        Chain: FnOnce(State) -> Box<HandlerFuture>,
    {
        let settings = self.clone();
        let f = chain(state).map(|(state, response)| {
            let origin: String;
            if settings.origin.is_none() {
                let origin_raw = Headers::borrow_from(&state).get::<Origin>().clone();
                let ori = match origin_raw {
                    Some(o) => o.to_string(),
                    None => "*".to_string(),
                };

                origin = ori;
            } else {
                origin = settings.origin.unwrap();
            };

            let mut headers = Headers::new();

            headers.set(AccessControlAllowCredentials);
            headers.set(AccessControlAllowHeaders(vec![
                Ascii::new("Authorization".to_string()),
                Ascii::new("Content-Type".to_string()),
            ]));
            headers.set(AccessControlAllowOrigin::Value(origin));
            headers.set(AccessControlAllowMethods(settings.methods));
            headers.set(AccessControlMaxAge(settings.max_age));

            let res = response.with_headers(headers);

            (state, res)
        });

        Box::new(f)
    }
}

#[cfg(test)]
mod tests {
    extern crate mime;

    use super::*;

    use futures::future;
    use gotham::http::response::create_response;
    use gotham::pipeline::new_pipeline;
    use gotham::pipeline::single::single_pipeline;
    use gotham::router::builder::*;
    use gotham::router::Router;
    use gotham::test::TestServer;
    use hyper::Method::Options;
    use hyper::StatusCode;
    use hyper::{Get, Head};

    // Since we cannot construct 'State' ourselves, we need to test via an 'actual' app
    fn handler(state: State) -> Box<HandlerFuture> {
        let body = "Hello World".to_string();

        let response = create_response(
            &state,
            StatusCode::Ok,
            Some((body.into_bytes(), mime::TEXT_PLAIN)),
        );

        Box::new(future::ok((state, response)))
    }

    fn default_router() -> Router {
        let (chain, pipeline) =
            single_pipeline(new_pipeline().add(CORSMiddleware::default()).build());

        build_router(chain, pipeline, |route| {
            route.request(vec![Get, Head, Options], "/").to(handler);
        })
    }

    fn custom_router() -> Router {
        let methods = vec![Method::Delete, Method::Get, Method::Head, Method::Options];

        let max_age = 1000;

        let origin = Some("http://www.example.com".to_string());

        let (chain, pipeline) = single_pipeline(
            new_pipeline()
                .add(CORSMiddleware::new(methods, origin, max_age))
                .build(),
        );

        build_router(chain, pipeline, |route| {
            route.request(vec![Get, Head, Options], "/").to(handler);
        })
    }

    #[test]
    fn test_headers_set() {
        let test_server = TestServer::new(default_router()).unwrap();

        let response = test_server
            .client()
            .get("https://example.com/")
            .perform()
            .unwrap();

        assert_eq!(response.status(), StatusCode::Ok);
        let headers = response.headers();
        assert_eq!(
            headers
                .get::<AccessControlAllowOrigin>()
                .unwrap()
                .to_string(),
            "*".to_string()
        );
        assert_eq!(
            headers.get::<AccessControlMaxAge>().unwrap().to_string(),
            "86400".to_string()
        );
    }

    #[test]
    fn test_custom_headers_set() {
        let test_server = TestServer::new(custom_router()).unwrap();

        let response = test_server
            .client()
            .get("https://example.com/")
            .perform()
            .unwrap();

        assert_eq!(response.status(), StatusCode::Ok);
        let headers = response.headers();
        assert_eq!(
            headers
                .get::<AccessControlAllowOrigin>()
                .unwrap()
                .to_string(),
            "http://www.example.com".to_string()
        );
        assert_eq!(
            headers.get::<AccessControlMaxAge>().unwrap().to_string(),
            "1000".to_string()
        );
    }

    #[test]
    fn test_new_cors_middleware() {
        let methods = vec![Method::Delete, Method::Get, Method::Head, Method::Options];

        let max_age = 1000;

        let origin = Some("http://www.example.com".to_string());

        let test = CORSMiddleware::new(methods.clone(), origin.clone(), max_age.clone());

        let default = CORSMiddleware::default();

        assert_ne!(test, default);

        assert_eq!(test.origin, origin);
        assert_eq!(test.max_age, max_age);
        assert_eq!(test.methods, methods);
    }

    #[test]
    fn test_default_cors_middleware() {
        let test = CORSMiddleware::default();
        let methods = vec![
            Method::Delete,
            Method::Get,
            Method::Head,
            Method::Options,
            Method::Patch,
            Method::Post,
            Method::Put,
        ];

        assert_eq!(test.methods, methods);

        assert_eq!(test.max_age, 86400);

        assert_eq!(test.origin, None);
    }
}