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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Module containing the core functionality for CSRF protection.

use std::collections::HashSet;
use std::fmt::{self, Debug, Display};
use std::str;

use cookie::Cookie;
use csrf::{CsrfError, CsrfProtection, CsrfToken};
use data_encoding::{BASE64, BASE64URL};
use iron::error::HttpError;
use iron::headers::{Cookie as IronCookie, Header, HeaderFormat, SetCookie};
use iron::method;
use iron::middleware::{AroundMiddleware, Handler};
use iron::prelude::*;
use iron::status;
use time::Duration;
use urlencoded::{UrlEncodedBody, UrlEncodedQuery};

/// The name of the cookie for the CSRF validation data and signature.
pub const CSRF_COOKIE_NAME: &'static str = "csrf";

/// The name of the form field for the CSRF token.
pub const CSRF_FORM_FIELD: &'static str = "csrf-token";

/// The name of the HTTP header for the CSRF token.
pub const CSRF_HEADER: &'static str = "X-CSRF-Token";

/// The name of the query parameter for the CSRF token.
pub const CSRF_QUERY_STRING: &'static str = "csrf-token";

fn iron_error(err: CsrfError) -> IronError {
    IronError {
        response: Response::with((status::Forbidden, format!("{}", err))),
        error: Box::new(err),
    }
}

#[derive(Clone, PartialEq)]
struct XCsrfToken(CsrfToken);

impl Header for XCsrfToken {
    fn header_name() -> &'static str {
        CSRF_HEADER
    }

    fn parse_header(raw: &[Vec<u8>]) -> Result<Self, HttpError> {
        if raw.len() != 1 {
            // if there is more than one header, something is wrong. bail.
            return Err(HttpError::Header);
        }

        match BASE64.decode(&raw[0]) {
            Ok(v) => Ok(Self(CsrfToken::new(v))),
            Err(_) => Err(HttpError::Header),
        }
    }
}

impl HeaderFormat for XCsrfToken {
    fn fmt_header(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        Display::fmt(&self, f)
    }
}

impl Display for XCsrfToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.b64_string())
    }
}

impl Debug for XCsrfToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self, f)
    }
}

/// Error type for configuration related errors.
pub enum CsrfConfigError {
    /// The TTL was not valid.
    InvalidTtl,
    /// CSRF protection was not enabled for any HTTP methods.
    NoProtectedMethods,
}

/// The configuation used to initialize `CsrfProtectionMiddleware`.
pub struct CsrfConfig {
    // TODO make this an Option
    ttl_seconds: i64,
    protected_methods: HashSet<method::Method>,
    secure_cookie: bool,
}

impl CsrfConfig {
    /// Create a new builder that is initialized with the default configuration.
    pub fn build() -> CsrfConfigBuilder {
        CsrfConfigBuilder {
            config: CsrfConfig::default(),
        }
    }
}

impl Default for CsrfConfig {
    fn default() -> Self {
        let protected_methods: HashSet<method::Method> =
            vec![method::Post, method::Put, method::Patch, method::Delete]
                .iter()
                .cloned()
                .collect();
        CsrfConfig {
            ttl_seconds: 3600,
            protected_methods: protected_methods,
            secure_cookie: false,
        }
    }
}

/// A utility to help build a `CsrfConfig` in an API backwards compatible way.
pub struct CsrfConfigBuilder {
    config: CsrfConfig,
}

impl CsrfConfigBuilder {
    /// Set the TTL in seconds for CSRF cookies and tokens.
    ///
    /// Default: `3600`
    pub fn ttl_seconds(mut self, ttl_seconds: i64) -> Self {
        self.config.ttl_seconds = ttl_seconds;
        self
    }

    /// Set the HTTP methods that are require CSRF protection.
    ///
    /// Default: `POST`, `PUT`, `PATCH`, `DELETE`
    pub fn protected_methods(mut self, protected_methods: HashSet<method::Method>) -> Self {
        self.config.protected_methods = protected_methods;
        self
    }

    /// Set the `Secure` flag on the CSRF cookie. If this is set to true, then user agents will
    /// only send the cookie over HTTPS.
    ///
    /// Default: false/absent.
    pub fn secure_cookie(mut self, secure_cookie: bool) -> Self {
        self.config.secure_cookie = secure_cookie;
        self
    }

    /// Validate and build the `CsrfConfig`.
    pub fn finish(self) -> Result<CsrfConfig, CsrfConfigError> {
        let config = self.config;
        if config.ttl_seconds < 0 {
            return Err(CsrfConfigError::InvalidTtl);
        }

        if config.protected_methods.is_empty() {
            return Err(CsrfConfigError::NoProtectedMethods);
        }
        Ok(config)
    }
}

struct CsrfHandler<P: CsrfProtection, H: Handler> {
    protect: P,
    config: CsrfConfig,
    handler: H,
}

impl<P: CsrfProtection, H: Handler> CsrfHandler<P, H> {
    fn new(protect: P, config: CsrfConfig, handler: H) -> Self {
        CsrfHandler {
            protect: protect,
            config: config,
            handler: handler,
        }
    }

    // TODO have this return an &str
    fn extract_csrf_cookie(&self, request: &Request) -> Option<Vec<u8>> {
        request.headers.get::<IronCookie>().and_then(|raw_cookie| {
            raw_cookie
                .0
                .iter()
                .filter_map(|c| {
                    Cookie::parse_encoded(c.clone())
                        .ok()
                        .and_then(|cookie| match cookie.name_value() {
                            (CSRF_COOKIE_NAME, value) => Some(value.to_string()),
                            _ => None,
                        })
                        .and_then(|c| BASE64.decode(c.as_bytes()).ok())
                })
                .collect::<Vec<Vec<u8>>>()
                .first()
                .map(|c| c.clone())
        })
    }

    // TODO have this return an &str
    fn extract_csrf_token(&self, mut request: &mut Request) -> Option<Vec<u8>> {
        let f_token = self.extract_csrf_token_from_form_url_encoded(&mut request);
        let q_token = self.extract_csrf_token_from_query(&mut request);
        let h_token = self.extract_csrf_token_from_headers(&mut request);

        debug!(
            "CSRF token found in Form: {}, Query: {}, Header: {}",
            f_token.is_some(),
            q_token.is_some(),
            h_token.is_some()
        );

        f_token.or(q_token).or(h_token)
    }

    // TODO have this return an &str
    fn extract_csrf_token_from_form_url_encoded(&self, request: &mut Request) -> Option<Vec<u8>> {
        request
            .get_ref::<UrlEncodedBody>()
            .ok()
            .and_then(|form| form.get(CSRF_FORM_FIELD))
            .and_then(|vs| {
                vs.iter()
                    .filter_map(|v| BASE64URL.decode(v.as_bytes()).ok())
                    .next()
            })
            .map(|t| t.clone())
    }

    // TODO have this return an &str
    fn extract_csrf_token_from_query(&self, request: &mut Request) -> Option<Vec<u8>> {
        request
            .get_ref::<UrlEncodedQuery>()
            .ok()
            .and_then(|query| query.get(CSRF_QUERY_STRING))
            .and_then(|vs| {
                vs.iter()
                    .filter_map(|v| BASE64URL.decode(v.as_bytes()).ok())
                    .next()
            })
            .map(|t| t.clone())
    }

    // TODO have this return an &str
    fn extract_csrf_token_from_headers(&self, request: &mut Request) -> Option<Vec<u8>> {
        let token = request
            .headers
            .get::<XCsrfToken>()
            .map(|t| t.to_string())
            .and_then(|s| BASE64.decode(s.as_bytes()).ok());
        let _ = request.headers.remove::<XCsrfToken>();
        token
    }
}

impl<P: CsrfProtection + 'static, H: Handler> Handler for CsrfHandler<P, H> {
    fn handle(&self, mut request: &mut Request) -> IronResult<Response> {
        // before
        let token_opt = self
            .extract_csrf_token(&mut request)
            .and_then(|t| self.protect.parse_token(&t).ok());
        let cookie_opt = self
            .extract_csrf_cookie(&request)
            .and_then(|c| self.protect.parse_cookie(&c).ok());

        if self.config.protected_methods.contains(&request.method) {
            debug!(
                "CSRF elements present. token: {}, cookie: {}",
                token_opt.is_some(),
                cookie_opt.is_some()
            );

            match (token_opt.as_ref(), cookie_opt.as_ref()) {
                (Some(token), Some(cookie)) => {
                    let verified = self.protect.verify_token_pair(&token, &cookie);
                    if !verified {
                        // TODO differentiate between server error and validation error
                        return Ok(Response::with((status::Forbidden, "CSRF Error")));
                    }
                }
                _ => return Ok(Response::with((status::Forbidden, "CSRF Error"))),
            }
        }

        let (token, csrf_cookie) = self
            .protect
            .generate_token_pair(
                cookie_opt
                    .and_then(|c| {
                        let c = c.value();
                        if c.len() < 64 {
                            None
                        } else {
                            let mut buf = [0; 64];
                            buf.copy_from_slice(&c);
                            Some(buf)
                        }
                    })
                    .as_ref(),
                self.config.ttl_seconds,
            )
            .map_err(iron_error)?;
        let _ = request.extensions.insert::<CsrfToken>(token);

        // main
        let mut response = self.handler.handle(&mut request)?;

        // after
        let cookie = Cookie::build(CSRF_COOKIE_NAME, csrf_cookie.b64_string())
            // TODO config for path
            .path("/")
            .http_only(true)
            .secure(self.config.secure_cookie)
            // TODO config flag for SameSite
            .max_age(Duration::seconds(self.config.ttl_seconds))
            .finish();
        let mut cookies = vec![format!("{}", cookie.encoded())]; // TODO is this formatting dumb?

        {
            if let Some(set_cookie) = response.headers.get::<SetCookie>() {
                cookies.extend(set_cookie.0.clone())
            }
        }
        response.headers.set(SetCookie(cookies));

        Ok(response)
    }
}

/// An implementation of `iron::AroundMiddleware` that provides transparent wrapping of an
/// application with CSRF protection.
// TODO example
pub struct CsrfProtectionMiddleware<P: CsrfProtection> {
    protect: P,
    config: CsrfConfig,
}

impl<P: CsrfProtection> CsrfProtectionMiddleware<P> {
    /// Create a new instance of `CsrfProtectionMiddleware` from a `CsrfProtection` and
    /// `CsrfConfig`.
    pub fn new(protect: P, config: CsrfConfig) -> Self {
        CsrfProtectionMiddleware {
            protect: protect,
            config: config,
        }
    }
}

impl<P: CsrfProtection + 'static> AroundMiddleware for CsrfProtectionMiddleware<P> {
    fn around(self, handler: Box<dyn Handler>) -> Box<dyn Handler> {
        Box::new(CsrfHandler::new(self.protect, self.config, handler))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use csrf::{AesGcmCsrfProtection, ChaCha20Poly1305CsrfProtection, MultiCsrfProtection};
    use iron::headers::Headers;
    use iron_test::request as mock_request;
    use iron_test::response::extract_body_to_string;

    lazy_static! {
        static ref BODY_METHODS: Vec<method::Method> = vec![
            method::Post,
            method::Put,
            method::Patch,
            method::Connect,
            method::Extension("WAT".to_string())
        ];
    }

    lazy_static! {
        static ref ALL_METHODS: Vec<method::Method> = vec![
            method::Get,
            method::Post,
            method::Put,
            method::Patch,
            method::Delete,
            method::Options,
            method::Connect,
            method::Trace,
            method::Extension("WAT".to_string())
        ];
    }

    const TEST_QUERY_PARAM: &'static str = "test-param";
    const TEST_QUERY_VALUE: &'static str = "test-value";
    const TEST_COOKIE_NAME: &'static str = "some-cookie";
    const TEST_COOKIE_VALUE: &'static str = "some-value";

    const KEY_32: [u8; 32] = *b"01234567012345670123456701234567";

    // TODO write test that ensures encrypted messages don't contain the plaintext

    #[test]
    fn cookies_and_tokens_can_be_verfied() {
        let protect = AesGcmCsrfProtection::from_key(KEY_32);
        let (token, cookie) = protect
            .generate_token_pair(None, 300)
            .expect("couldn't generate token/cookie pair");
        let token = BASE64
            .decode(token.b64_string().as_bytes())
            .expect("token not base64");
        let token = protect.parse_token(&token).expect("token not parsed");
        let cookie = BASE64
            .decode(cookie.b64_string().as_bytes())
            .expect("cookie not base64");
        let cookie = protect.parse_cookie(&cookie).expect("cookie not parsed");
        assert!(
            protect.verify_token_pair(&token, &cookie),
            "could not verify token/cookie pair"
        );
    }

    #[test]
    fn config_properties() {
        // ttl of 0 is allowed
        assert!(CsrfConfig::build().ttl_seconds(0).finish().is_ok());

        // negative ttl is not allowed
        assert!(CsrfConfig::build().ttl_seconds(-1).finish().is_err());

        // empty set of protected methods is not allowed
        assert!(CsrfConfig::build()
            .protected_methods(HashSet::new())
            .finish()
            .is_err())
    }

    fn get_middleware() -> CsrfProtectionMiddleware<AesGcmCsrfProtection> {
        let protect = AesGcmCsrfProtection::from_key(KEY_32);
        CsrfProtectionMiddleware::new(protect, CsrfConfig::default())
    }

    #[test]
    fn middleware_validates_token() {
        let middleware = get_middleware();

        let (token, cookie) = middleware.protect.generate_token_pair(None, 300).unwrap();
        let token = BASE64
            .decode(token.b64_string().as_bytes())
            .expect("token not base64");
        let token = middleware
            .protect
            .parse_token(&token)
            .expect("token not parsed");
        let cookie = BASE64
            .decode(cookie.b64_string().as_bytes())
            .expect("cookie not base64");
        let cookie = middleware
            .protect
            .parse_cookie(&cookie)
            .expect("cookie not parsed");

        assert!(middleware.protect.verify_token_pair(&token, &cookie));
    }

    #[test]
    fn middleware_fails_modified_token() {
        let middleware = get_middleware();

        let (token, _) = middleware.protect.generate_token_pair(None, 300).unwrap();
        let mut token = BASE64
            .decode(token.b64_string().as_bytes())
            .expect("token not base64");

        // flip a bit in the padding
        token[0] = token[0] ^ 0x01;
        assert!(middleware.protect.parse_token(&token).is_err());
        token[0] = token[0] ^ 0x01; // flip the bit back

        // flip a bit in the token
        token[16] = token[16] ^ 0x01;
        assert!(middleware.protect.parse_token(&token).is_err());
        token[16] = token[16] ^ 0x01; // flip the bit back

        // flip a bit in the tag
        let len = token.len();
        token[len - 1] = token[len - 1] ^ 0x01;
        assert!(middleware.protect.parse_token(&token).is_err());
    }

    #[test]
    fn middleware_fails_modified_cookie() {
        let middleware = get_middleware();

        let (_, cookie) = middleware.protect.generate_token_pair(None, 300).unwrap();
        let mut cookie = BASE64
            .decode(cookie.b64_string().as_bytes())
            .expect("cookie not base64");

        // flip a bit in the padding
        cookie[0] = cookie[0] ^ 0x01;
        assert!(middleware.protect.parse_cookie(&cookie).is_err());
        cookie[0] = cookie[0] ^ 0x01; // flip the bit back

        // flip a bit in the expiry/token
        cookie[16] = cookie[16] ^ 0x01;
        assert!(middleware.protect.parse_cookie(&cookie).is_err());
        cookie[16] = cookie[16] ^ 0x01; // flip the bit back

        // flip a bit in the tag
        let len = cookie.len();
        cookie[len - 1] = cookie[len - 1] ^ 0x01;
        assert!(middleware.protect.parse_cookie(&cookie).is_err());
    }

    #[test]
    fn middleware_fails_expired_tokens() {
        let middleware = get_middleware();

        let (token, cookie) = middleware.protect.generate_token_pair(None, 0).unwrap();

        let token = BASE64
            .decode(token.b64_string().as_bytes())
            .expect("token not base64");
        let token = middleware
            .protect
            .parse_token(&token)
            .expect("token not parsed");

        let cookie = BASE64
            .decode(cookie.b64_string().as_bytes())
            .expect("cookie not base64");
        let cookie = middleware
            .protect
            .parse_cookie(&cookie)
            .expect("cookie not parsed");

        assert!(!middleware.protect.verify_token_pair(&token, &cookie));
    }

    #[test]
    fn middleware_fails_mismatched_tokens() {
        let middleware = get_middleware();

        let (token, _) = middleware.protect.generate_token_pair(None, 300).unwrap();
        let (_, cookie) = middleware.protect.generate_token_pair(None, 300).unwrap();

        let token = BASE64
            .decode(token.b64_string().as_bytes())
            .expect("token not base64");
        let token = middleware
            .protect
            .parse_token(&token)
            .expect("token not parsed");

        let cookie = BASE64
            .decode(cookie.b64_string().as_bytes())
            .expect("cookie not base64");
        let cookie = middleware
            .protect
            .parse_cookie(&cookie)
            .expect("cookie not parsed");

        assert!(!middleware.protect.verify_token_pair(&token, &cookie));
    }

    // TODO set ttl = 1, sleep 2, check validation fails
    // TODO check token is same when passed old token

    fn mock_header_handler(request: &mut Request) -> IronResult<Response> {
        assert_eq!(request.headers.get::<XCsrfToken>(), None);

        let token = request
            .extensions
            .get::<CsrfToken>()
            .map(|t| t.b64_string())
            .unwrap_or("<no token>".to_string());

        Ok(Response::with((status::Ok, token)))
    }

    fn mock_handler(request: &mut Request) -> IronResult<Response> {
        let token = request
            .extensions
            .get::<CsrfToken>()
            .map(|t| t.b64_string())
            .unwrap_or("<no token>".to_string());

        Ok(Response::with((status::Ok, token)))
    }

    fn mock_query_handler(request: &mut Request) -> IronResult<Response> {
        let token = request
            .extensions
            .get::<CsrfToken>()
            .map(|t| t.b64_string())
            .unwrap_or("<no token>".to_string());

        if BODY_METHODS.contains(&request.method) {
            let form_data = request
                .get_ref::<UrlEncodedQuery>()
                .expect("no url encoded query");

            assert_eq!(
                form_data.get(TEST_QUERY_PARAM),
                Some(&vec![TEST_QUERY_VALUE.to_string()])
            );
            // TODO assert_eq!(form_data.get(CSRF_QUERY_STRING), None);
        }

        Ok(Response::with((status::Ok, token)))
    }

    fn mock_url_form_handler(request: &mut Request) -> IronResult<Response> {
        let token = request
            .extensions
            .get::<CsrfToken>()
            .map(|t| t.b64_string())
            .unwrap_or("<no token>".to_string());

        if BODY_METHODS.contains(&request.method) {
            let form_data = request
                .get_ref::<UrlEncodedBody>()
                .expect("not url form encoded");

            assert_eq!(
                form_data.get(TEST_QUERY_PARAM),
                Some(&vec![TEST_QUERY_VALUE.to_string()])
            );
            // TODO assert_eq!(form_data.get(CSRF_QUERY_STRING), None);
        }

        Ok(Response::with((status::Ok, token)))
    }

    fn mock_cookie_handler(_: &mut Request) -> IronResult<Response> {
        let cookie = Cookie::new(TEST_COOKIE_NAME, TEST_COOKIE_VALUE);
        let mut response = Response::with((status::Ok, ""));
        response.headers.set(SetCookie(vec![format!["{}", cookie]]));
        Ok(response)
    }

    fn get_handler_token_cookie<H: Handler>(handler: H) -> (Box<dyn Handler>, CsrfToken, String) {
        let middleware = get_middleware();
        let handler = middleware.around(Box::new(handler));

        // do one GET to get the token
        let response = mock_request::get("http://localhost/", Headers::new(), &handler).unwrap();
        assert_eq!(response.status, Some(status::Ok));

        let (csrf_token, csrf_cookie) = extract_token_cookie(response);

        (handler, csrf_token, csrf_cookie)
    }

    fn extract_token_cookie(resp: Response) -> (CsrfToken, String) {
        let headers = resp.headers.clone();
        let set_cookie = headers.get::<SetCookie>().unwrap();
        let cookie = Cookie::parse(set_cookie.0[0].clone()).unwrap();
        (
            CsrfToken::new(
                BASE64
                    .decode(extract_body_to_string(resp).as_bytes())
                    .unwrap(),
            ),
            format!("{}", cookie),
        )
    }

    #[test]
    fn methods_without_token() {
        let (handler, _, csrf_cookie) = get_handler_token_cookie(mock_handler);
        let path = "http://localhost/";
        let mut headers = Headers::new();
        headers.set(IronCookie(vec![csrf_cookie.clone()]));
        let body = "";

        let response = mock_request::get(path, headers.clone(), &handler).unwrap();
        assert_eq!(response.status, Some(status::Ok));

        let response = mock_request::head(path, headers.clone(), &handler).unwrap();
        assert_eq!(response.status, Some(status::Ok));

        let response = mock_request::head(path, headers.clone(), &handler).unwrap();
        assert_eq!(response.status, Some(status::Ok));

        let response =
            mock_request::request(method::Trace, path, body, headers.clone(), &handler).unwrap();
        assert_eq!(response.status, Some(status::Ok));

        let response =
            mock_request::request(method::Connect, path, body, headers.clone(), &handler).unwrap();
        assert_eq!(response.status, Some(status::Ok));

        let response = mock_request::request(
            method::Extension("WAT".to_string()),
            path,
            body,
            headers.clone(),
            &handler,
        )
        .unwrap();
        assert_eq!(response.status, Some(status::Ok));

        let response = mock_request::post(path, headers.clone(), body, &handler).unwrap();
        assert_eq!(response.status, Some(status::Forbidden));

        let response = mock_request::put(path, headers.clone(), body, &handler).unwrap();
        assert_eq!(response.status, Some(status::Forbidden));

        let response = mock_request::put(path, headers.clone(), body, &handler).unwrap();
        assert_eq!(response.status, Some(status::Forbidden));

        let response = mock_request::patch(path, headers.clone(), body, &handler).unwrap();
        assert_eq!(response.status, Some(status::Forbidden));
    }

    #[test]
    fn methods_with_csrf_header() {
        let (handler, csrf_token, csrf_cookie) = get_handler_token_cookie(mock_header_handler);

        let path = "http://localhost/";
        let mut headers = Headers::new();
        headers.set(IronCookie(vec![csrf_cookie.clone()]));
        headers.set(XCsrfToken(csrf_token));
        let body = "";

        for verb in ALL_METHODS.iter().cloned() {
            let response =
                mock_request::request(verb, path, body, headers.clone(), &handler).unwrap();
            assert_eq!(response.status, Some(status::Ok));
        }
    }

    #[test]
    fn methods_with_csrf_url() {
        let (handler, csrf_token, csrf_cookie) = get_handler_token_cookie(mock_query_handler);
        let path = format!(
            "http://localhost/?{}={}&{}={}",
            CSRF_QUERY_STRING,
            csrf_token.b64_url_string(),
            TEST_QUERY_PARAM,
            TEST_QUERY_VALUE
        );
        let path = path.as_str();
        let mut headers = Headers::new();
        headers.set(IronCookie(vec![csrf_cookie.clone()]));
        let body = "";

        for verb in ALL_METHODS.iter().cloned() {
            let response =
                mock_request::request(verb, path, body, headers.clone(), &handler).unwrap();
            assert_eq!(response.status, Some(status::Ok));
        }
    }

    #[test]
    fn methods_with_csrf_url_form() {
        let (handler, csrf_token, csrf_cookie) = get_handler_token_cookie(mock_url_form_handler);
        let path = "http://localhost/";
        let mut headers = Headers::new();
        headers.set(IronCookie(vec![csrf_cookie.clone()]));
        headers.set_raw(
            "content-type",
            vec![b"application/x-www-form-urlencoded".to_vec()],
        );
        let body = format!(
            "{}={}&{}={}",
            CSRF_QUERY_STRING,
            csrf_token.b64_url_string(),
            TEST_QUERY_PARAM,
            TEST_QUERY_VALUE
        );
        let body = body.as_str();

        for verb in BODY_METHODS.iter().cloned() {
            let response =
                mock_request::request(verb, path, body, headers.clone(), &handler).unwrap();
            assert_eq!(response.status, Some(status::Ok));
        }
    }

    #[test]
    fn cookies_not_overwritten() {
        let middleware = get_middleware();
        let handler = middleware.around(Box::new(mock_cookie_handler));

        let response = mock_request::get("http://localhost/", Headers::new(), &handler).unwrap();
        let set_cookie = response
            .headers
            .get::<SetCookie>()
            .expect("SetCookie header not set");

        assert!(set_cookie.0.len() == 2);
        assert!(set_cookie
            .0
            .iter()
            .find(|c| { c.contains(TEST_COOKIE_NAME) && c.contains(TEST_COOKIE_VALUE) })
            .is_some())
    }

    #[test]
    fn multiprotect_and_rotation() {
        let protect_1 = AesGcmCsrfProtection::from_key(KEY_32);
        let protect_1_clone = AesGcmCsrfProtection::from_key(KEY_32);
        let middle_1 = CsrfProtectionMiddleware::new(protect_1, CsrfConfig::default());
        let handler_1 = middle_1.around(Box::new(mock_handler));

        let protect_2 = ChaCha20Poly1305CsrfProtection::from_key(KEY_32);
        let protect_2_clone = ChaCha20Poly1305CsrfProtection::from_key(KEY_32);
        let middle_2 = CsrfProtectionMiddleware::new(protect_2, CsrfConfig::default());
        let handler_2 = middle_2.around(Box::new(mock_handler));

        let multi_protect =
            MultiCsrfProtection::new(Box::new(protect_2_clone), vec![Box::new(protect_1_clone)]);
        let multi_middle = CsrfProtectionMiddleware::new(multi_protect, CsrfConfig::default());
        let multi_handler = multi_middle.around(Box::new(mock_handler));

        // make one request to the first CSRF protected handler
        let resp = mock_request::get("http://localhost/", Headers::new(), &handler_1).unwrap();
        let (token, cookie) = extract_token_cookie(resp);

        // test that the cookie is valid
        let path = format!(
            "http://localhost/?{}={}&{}={}",
            CSRF_QUERY_STRING,
            token.b64_url_string(),
            TEST_QUERY_PARAM,
            TEST_QUERY_VALUE
        );
        let path = path.as_str();
        let mut headers = Headers::new();
        headers.set(IronCookie(vec![cookie]));
        let body = "";
        let resp =
            mock_request::request(method::Post, path, body, headers.clone(), &handler_1).unwrap();
        assert_eq!(resp.status, Some(status::Ok));

        // test the cookie/token against the multi handler
        let resp = mock_request::request(method::Post, path, body, headers.clone(), &multi_handler)
            .unwrap();
        assert_eq!(resp.status, Some(status::Ok));

        // extract the new cookie/token from the response
        let (token, cookie) = extract_token_cookie(resp);

        // test the rotated cookie/token against the new handler
        let path = format!(
            "http://localhost/?{}={}&{}={}",
            CSRF_QUERY_STRING,
            token.b64_url_string(),
            TEST_QUERY_PARAM,
            TEST_QUERY_VALUE
        );
        let path = path.as_str();
        let mut headers = Headers::new();
        headers.set(IronCookie(vec![cookie]));
        let body = "";
        let resp =
            mock_request::request(method::Post, path, body, headers.clone(), &handler_2).unwrap();
        assert_eq!(resp.status, Some(status::Ok));
    }

    // TODO test that verifies protected_method feature/configuration
}