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
use std::{collections::HashSet, convert::TryFrom};

use crate::{
    body::Body,
    endpoint::Endpoint,
    http::{
        header,
        header::{HeaderName, HeaderValue},
        Method, StatusCode,
    },
    middleware::Middleware,
    request::Request,
    response::Response,
    Error, IntoResponse, Result,
};

#[derive(Debug, Default, Clone)]
struct Config {
    allow_credentials: bool,
    allow_headers: HashSet<HeaderName>,
    allow_methods: HashSet<Method>,
    allow_origins: HashSet<HeaderValue>,
    expose_headers: HashSet<HeaderName>,
    max_age: i32,
}

/// Middleware for CORS
///
/// # Example
///
/// ```
/// use poem::{http::Method, middleware::Cors};
///
/// let cors = Cors::new()
///     .allow_method(Method::GET)
///     .allow_method(Method::POST)
///     .allow_credentials(false);
/// ```
#[derive(Default)]
pub struct Cors {
    config: Config,
}

impl Cors {
    /// Creates a new `CORS` middleware.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: Config {
                max_age: 86400,
                ..Default::default()
            },
        }
    }

    /// Set allow credentials.
    #[must_use]
    pub fn allow_credentials(mut self, allow_credentials: bool) -> Self {
        self.config.allow_credentials = allow_credentials;
        self
    }

    /// Add an allow header.
    #[must_use]
    pub fn allow_header<T>(mut self, header: T) -> Self
    where
        HeaderName: TryFrom<T>,
    {
        let header = match <HeaderName as TryFrom<T>>::try_from(header) {
            Ok(header) => header,
            Err(_) => panic!("illegal header"),
        };
        self.config.allow_headers.insert(header);
        self
    }

    /// Add an allow method.
    #[must_use]
    pub fn allow_method<T>(mut self, method: T) -> Self
    where
        Method: TryFrom<T>,
    {
        let method = match <Method as TryFrom<T>>::try_from(method) {
            Ok(method) => method,
            Err(_) => panic!("illegal method"),
        };
        self.config.allow_methods.insert(method);
        self
    }

    /// Add an allow origin.
    #[must_use]
    pub fn allow_origin<T>(mut self, origin: T) -> Self
    where
        HeaderValue: TryFrom<T>,
    {
        let origin = match <HeaderValue as TryFrom<T>>::try_from(origin) {
            Ok(origin) => origin,
            Err(_) => panic!("illegal origin"),
        };
        self.config.allow_origins.insert(origin);
        self
    }

    /// Add an expose method.
    #[must_use]
    pub fn expose_header<T>(mut self, header: T) -> Self
    where
        HeaderName: TryFrom<T>,
    {
        let header = match <HeaderName as TryFrom<T>>::try_from(header) {
            Ok(header) => header,
            Err(_) => panic!("illegal header"),
        };
        self.config.expose_headers.insert(header);
        self
    }

    /// Set max age.
    #[must_use]
    pub fn max_age(mut self, max_age: i32) -> Self {
        self.config.max_age = max_age;
        self
    }
}

impl<E: Endpoint> Middleware<E> for Cors {
    type Output = CorsEndpoint<E>;

    fn transform(&self, ep: E) -> Self::Output {
        CorsEndpoint {
            inner: ep,
            config: self.config.clone(),
        }
    }
}

/// Endpoint for Cors middleware.
pub struct CorsEndpoint<E> {
    inner: E,
    config: Config,
}

impl<E> CorsEndpoint<E> {
    fn is_valid_origin(&self, origin: &str) -> bool {
        if self.config.allow_origins.is_empty() {
            true
        } else {
            self.config.allow_origins.iter().any(|x| {
                if x == "*" {
                    return true;
                }
                x == origin
            })
        }
    }

    fn build_preflight_response(&self) -> Response {
        let mut builder = Response::builder();

        if !self.config.allow_origins.is_empty() {
            for origin in &self.config.allow_origins {
                builder = builder.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin.clone());
            }
        } else {
            builder = builder.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        }

        for method in &self.config.allow_methods {
            builder = builder.header(header::ACCESS_CONTROL_ALLOW_METHODS, method.as_str());
        }

        if !self.config.allow_headers.is_empty() {
            for header in &self.config.allow_headers {
                builder = builder.header(header::ACCESS_CONTROL_ALLOW_HEADERS, header.clone());
            }
        } else {
            builder = builder.header(header::ACCESS_CONTROL_ALLOW_HEADERS, "*");
        }

        builder = builder.header(header::ACCESS_CONTROL_MAX_AGE, self.config.max_age);

        if self.config.allow_credentials {
            builder = builder.header(header::ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        }

        for header in &self.config.expose_headers {
            builder = builder.header(header::ACCESS_CONTROL_EXPOSE_HEADERS, header.clone());
        }

        builder.body(Body::empty())
    }
}

#[async_trait::async_trait]
impl<E: Endpoint> Endpoint for CorsEndpoint<E> {
    type Output = Result<Response>;

    async fn call(&self, req: Request) -> Self::Output {
        let origin = match req.headers().get(header::ORIGIN) {
            Some(origin) => origin.to_str().map(ToString::to_string),
            None => {
                // This is not a CORS request if there is no Origin header
                return Ok(self.inner.call(req).await.into_response());
            }
        };
        let origin = origin.map_err(|_| Error::new(StatusCode::BAD_REQUEST))?;

        if !self.is_valid_origin(&origin) {
            return Err(Error::new(StatusCode::UNAUTHORIZED));
        }

        if req.method() == Method::OPTIONS {
            return Ok(self.build_preflight_response());
        }

        let mut resp = self.inner.call(req).await.into_response();

        if self.config.allow_origins.is_empty() {
            resp.headers_mut().insert(
                header::ACCESS_CONTROL_ALLOW_ORIGIN,
                HeaderValue::from_static("*"),
            );
        } else {
            resp.headers_mut().insert(
                header::ACCESS_CONTROL_ALLOW_ORIGIN,
                HeaderValue::from_str(&origin).unwrap(),
            );
        }

        if self.config.allow_credentials {
            resp.headers_mut().insert(
                header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
                HeaderValue::from_static("true"),
            );
        }

        resp.headers_mut().extend(
            self.config
                .expose_headers
                .iter()
                .map(|value| (header::ACCESS_CONTROL_EXPOSE_HEADERS, value.clone().into())),
        );

        Ok(resp)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{endpoint::make_sync, EndpointExt};

    const ALLOW_ORIGIN: &str = "example.com";
    const EXPOSE_HEADER: &str = "X-My-Custom-Header";

    fn request() -> Request {
        Request::builder()
            .method(Method::OPTIONS)
            .header(header::ORIGIN, ALLOW_ORIGIN)
            .finish()
    }

    fn get_request() -> Request {
        Request::builder()
            .method(Method::GET)
            .header(header::ORIGIN, ALLOW_ORIGIN)
            .finish()
    }

    #[tokio::test]
    async fn preflight_request() {
        let ep = make_sync(|_| "hello").with(
            Cors::new()
                .allow_origin(ALLOW_ORIGIN)
                .allow_method(Method::GET)
                .allow_method(Method::POST)
                .allow_method(Method::OPTIONS)
                .allow_method(Method::DELETE)
                .expose_header(EXPOSE_HEADER)
                .allow_credentials(true),
        );
        let resp = ep.map_to_response().call(request()).await;

        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
                .unwrap(),
            ALLOW_ORIGIN
        );
        let mut allow_methods = resp
            .headers()
            .get_all(header::ACCESS_CONTROL_ALLOW_METHODS)
            .into_iter()
            .collect::<Vec<_>>();
        allow_methods.sort();
        assert_eq!(
            allow_methods,
            vec![
                HeaderValue::from_static("DELETE"),
                HeaderValue::from_static("GET"),
                HeaderValue::from_static("OPTIONS"),
                HeaderValue::from_static("POST"),
            ],
        );
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
                .unwrap(),
            "*"
        );
        assert_eq!(
            resp.headers().get(header::ACCESS_CONTROL_MAX_AGE).unwrap(),
            "86400"
        );
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .unwrap(),
            "true"
        );
    }

    #[tokio::test]
    async fn default_cors_middleware() {
        let ep = make_sync(|_| "hello").with(Cors::new());
        let resp = ep.map_to_response().call(get_request()).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
                .unwrap(),
            "*"
        );
    }

    #[tokio::test]
    async fn custom_cors_middleware() {
        let ep = make_sync(|_| "hello").with(
            Cors::new()
                .allow_origin(ALLOW_ORIGIN)
                .allow_method(Method::GET)
                .allow_method(Method::POST)
                .allow_method(Method::OPTIONS)
                .allow_method(Method::DELETE)
                .expose_header(EXPOSE_HEADER)
                .allow_credentials(true),
        );
        let resp = ep.map_to_response().call(get_request()).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
                .unwrap(),
            ALLOW_ORIGIN
        );
    }

    #[tokio::test]
    async fn credentials_true() {
        let ep = make_sync(|_| "hello").with(Cors::new().allow_credentials(true));
        let resp = ep.map_to_response().call(get_request()).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
                .unwrap(),
            "true"
        );
    }

    #[tokio::test]
    async fn set_allow_origin_list() {
        let ep = make_sync(|_| "hello")
            .with(Cors::new().allow_origin("foo.com").allow_origin("bar.com"))
            .map_to_response();

        for origin in &["foo.com", "bar.com"] {
            let resp = ep
                .call(
                    Request::builder()
                        .method(Method::GET)
                        .header(header::ORIGIN, HeaderValue::from_str(origin).unwrap())
                        .finish(),
                )
                .await;

            assert_eq!(resp.status(), StatusCode::OK);
            assert_eq!(
                resp.headers()
                    .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
                    .unwrap(),
                origin
            );
        }
    }

    #[tokio::test]
    async fn unauthorized_origin() {
        let ep = make_sync(|_| "hello").with(Cors::new().allow_origin(ALLOW_ORIGIN));
        let resp = ep
            .map_to_response()
            .call(
                Request::builder()
                    .method(Method::GET)
                    .header(header::ORIGIN, "foo.com")
                    .finish(),
            )
            .await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[cfg(feature = "cookie")]
    #[tokio::test]
    async fn retain_cookies() {
        use crate::{
            handler,
            middleware::CookieJarManager,
            web::cookie::{Cookie, CookieJar},
        };
        #[handler(internal)]
        async fn index(cookie_jar: &CookieJar) {
            cookie_jar.add(Cookie::new_with_str("foo", "bar"));
        }

        let ep = index
            .with(CookieJarManager::new())
            .with(Cors::new().allow_origin(ALLOW_ORIGIN));
        let resp = ep.map_to_response().call(get_request()).await;

        assert_eq!(resp.headers().get(header::SET_COOKIE).unwrap(), "foo=bar");
    }

    #[tokio::test]
    async fn set_cors_headers_to_error_responses() {
        let ep = make_sync(|_| Err::<(), Error>(Error::new(StatusCode::BAD_REQUEST)))
            .with(Cors::new().allow_origin(ALLOW_ORIGIN));
        let resp = ep.map_to_response().call(get_request()).await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
                .unwrap(),
            ALLOW_ORIGIN
        );
    }

    #[tokio::test]
    async fn no_cors_requests() {
        let ep = make_sync(|_| "hello").with(Cors::new().allow_origin(ALLOW_ORIGIN));
        let resp = ep
            .map_to_response()
            .call(Request::builder().method(Method::GET).finish())
            .await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert!(resp
            .headers()
            .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
            .is_none());
    }
}