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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
//! [![Build Status](https://travis-ci.org/lawliet89/rocket_cors.svg)](https://travis-ci.org/lawliet89/rocket_cors)
//! [![Dependency Status](https://dependencyci.com/github/lawliet89/rocket_cors/badge)](https://dependencyci.com/github/lawliet89/rocket_cors)
//! [![Repository](https://img.shields.io/github/tag/lawliet89/rocket_cors.svg)](https://github.com/lawliet89/rocket_cors)
//! [![Crates.io](https://img.shields.io/crates/v/rocket_cors.svg)](https://crates.io/crates/rocket_cors)
//!
//! - Documentation: [master branch](https://lawliet89.github.io/rocket_cors) | [stable](https://docs.rs/rocket_cors)
//!
//! Cross-origin resource sharing (CORS) for [Rocket](https://rocket.rs/) applications
//!
//! ## Requirements
//!
//! - Nightly Rust
//! - Rocket >= 0.4
//!
//! If you are using Rocket 0.3, use the `0.3.0` version of this crate.
//!
//! ### Nightly Rust
//!
//! Rocket requires nightly Rust. You should probably install Rust with
//! [rustup](https://www.rustup.rs/), then override the code directory to use nightly instead of
//! stable. See
//! [installation instructions](https://rocket.rs/guide/getting-started/#installing-rust).
//!
//! In particular, `rocket_cors` is currently targetted for the latest `nightly`. Older nightlies
//! might work, but they are subject to the minimum that Rocket sets.
//!
//! ## Installation
//!
//! Add the following to Cargo.toml:
//!
//! ```toml
//! rocket_cors = "0.4.0-rc.2"
//! ```
//!
//! To use the latest `master` branch, for example:
//!
//! ```toml
//! rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
//! ```
//!
//! ## Features
//!
//! By default, a `serialization` feature is enabled in this crate that allows you to (de)serialize
//! the `Cors` struct that is described below. If you would like to disable this, simply change
//! your `Cargo.toml` to:
//!
//! ```toml
//! rocket_cors = { version = "0.4.0-rc.2", default-features = false }
//! ```
//!
//! ## Usage
//!
//! Before you can add CORS responses to your application, you need to create a `Cors` struct that
//! will hold the settings.
//!
//! Each of the examples can be run off the repository via `cargo run --example xxx` where `xxx` is
//!
//! - `fairing`
//! - `guard`
//! - `manual`
//!
//! ### `Cors` Struct
//!
//! The [`Cors` struct](Cors) contains the settings for CORS requests to be validated
//! and for responses to be generated. Defaults are defined for every field in the struct, and
//! are documented on the [`Cors` struct](Cors) page. You can also deserialize
//! the struct from some format like JSON, YAML or TOML when the default `serialization` feature
//! is enabled.
//!
//! ### Three modes of operation
//!
//! You can add CORS to your routes via one of three ways, in descending order of ease and in
//! ascending order of flexibility.
//!
//! - Fairing (should only used exclusively)
//! - Request Guard
//! - Truly Manual
//!
//! Unfortunately, you cannot mix and match Fairing with any other of the methods, due to the
//! limitation of Rocket's fairing API. That is, the checks for Fairing will always happen first,
//! and if they fail, the route is never executed and so your guard or manual checks will never
//! get executed.
//!
//! You can, however, mix and match guards and manual checks.
//!
//! In summary:
//!
//! |                                         | Fairing | Request Guard | Manual |
//! |:---------------------------------------:|:-------:|:-------------:|:------:|
//! |         Must apply to all routes        |    ✔    |       ✗       |    ✗   |
//! | Different settings for different routes |    ✗    |       ✗       |    ✔   |
//! |     May define custom OPTIONS routes    |    ✗    |       ✔       |    ✔   |
//!
//! ### Fairing
//!
//! Fairing is the easiest to use and also the most inflexible. You don't have to define `OPTIONS`
//! routes for your application, and the checks are done transparently.
//!
//! However, you can only have one set of settings that must apply to all routes. You cannot opt
//! any route out of CORS checks.
//!
//! To use this, simply create a [`Cors` struct](Cors) and then
//! [`attach`](https://api.rocket.rs/rocket/struct.Rocket.html#method.attach) it to Rocket.
//!
//! ```rust,no_run
//! #![feature(proc_macro_hygiene, decl_macro)]
//! extern crate rocket;
//! extern crate rocket_cors;
//!
//! use rocket::{get, routes};
//! use rocket::http::Method;
//! use rocket_cors::{AllowedOrigins, AllowedHeaders};
//!
//! #[get("/")]
//! fn cors<'a>() -> &'a str {
//!     "Hello CORS"
//! }
//!
//! fn main() {
//!     let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
//!     assert!(failed_origins.is_empty());
//!
//!     // You can also deserialize this
//!     let options = rocket_cors::Cors {
//!         allowed_origins: allowed_origins,
//!         allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
//!         allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
//!         allow_credentials: true,
//!         ..Default::default()
//!     };
//!
//!     rocket::ignite()
//!         .mount("/", routes![cors])
//!         .attach(options)
//!         .launch();
//! }
//!
//! ```
//! #### Injected Route
//!
//! The fairing implementation will inject a route during attachment to Rocket. This route is used
//! to handle errors during CORS validation.
//!
//! This is due to the limitation in Rocket's Fairing
//! [lifecycle](https://rocket.rs/guide/fairings/). Ideally, we want to validate the CORS request
//! during `on_request`, and if the validation fails, we want to stop the route from even executing
//! to
//!
//! 1) prevent side effects
//! 1) prevent resource usage from unnecessary computation
//!
//! The only way to do this is to hijack the request and route it to our own injected route to
//! handle errors. Rocket does not allow Fairings to stop the processing of a route.
//!
//! You can configure the behaviour of the injected route through a couple of fields in the
//! [`Cors` struct](Cors).
//!
//! ### Request Guard
//!
//! Using request guard requires you to sacrifice the convenience of Fairings for being able to
//! opt some routes out of CORS checks and enforcement. _BUT_ you are still restricted to only
//! one set of CORS settings and you have to mount additional routes to catch and process OPTIONS
//! requests. The `OPTIONS` routes are used for CORS preflight checks.
//!
//! You will have to do the following:
//!
//! - Create a [`Cors` struct](Cors) and during Rocket's ignite, add the struct to
//! Rocket's [managed state](https://rocket.rs/guide/state/#managed-state).
//! - For all the routes that you want to enforce CORS on, you can mount either some
//! [catch all route](catch_all_options_routes) or define your own route for the OPTIONS
//! verb.
//! - Then in all the routes you want to enforce CORS on, add a
//! [Request Guard](https://rocket.rs/guide/requests/#request-guards) for the
//! [`Guard`](Guard) struct in the route arguments. You should not wrap this in an
//! `Option` or `Result` because the guard will let non-CORS requests through and will take over
//! error handling in case of errors.
//! - In your routes, to add CORS headers to your responses, use the appropriate functions on the
//! [`Guard`](Guard) for a `Response` or a `Responder`.
//!
//! ```rust,no_run
//! #![feature(proc_macro_hygiene, decl_macro)]
//! extern crate rocket;
//! extern crate rocket_cors;
//!
//! use std::io::Cursor;
//!
//! use rocket::{Response, get, options, routes};
//! use rocket::http::Method;
//! use rocket_cors::{Guard, AllowedOrigins, AllowedHeaders, Responder};
//!
//! /// Using a `Responder` -- the usual way you would use this
//! #[get("/")]
//! fn responder(cors: Guard) -> Responder<&str> {
//!     cors.responder("Hello CORS!")
//! }
//!
//! /// Using a `Response` instead of a `Responder`. You generally won't have to do this.
//! #[get("/response")]
//! fn response(cors: Guard) -> Response {
//!     let mut response = Response::new();
//!     response.set_sized_body(Cursor::new("Hello CORS!"));
//!     cors.response(response)
//! }
//!
//! /// Manually mount an OPTIONS route for your own handling
//! #[options("/manual")]
//! fn manual_options(cors: Guard) -> Responder<&str> {
//!     cors.responder("Manual OPTIONS preflight handling")
//! }
//!
//! /// Manually mount an OPTIONS route for your own handling
//! #[get("/manual")]
//! fn manual(cors: Guard) -> Responder<&str> {
//!     cors.responder("Manual OPTIONS preflight handling")
//! }
//!
//! fn main() {
//!     let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
//!     assert!(failed_origins.is_empty());
//!
//!     // You can also deserialize this
//!     let options = rocket_cors::Cors {
//!         allowed_origins: allowed_origins,
//!         allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
//!         allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
//!         allow_credentials: true,
//!         ..Default::default()
//!     };
//!
//!     rocket::ignite()
//!         .mount(
//!             "/",
//!             routes![responder, response],
//!         )
//!         // Mount the routes to catch all the OPTIONS pre-flight requests
//!         .mount("/", rocket_cors::catch_all_options_routes())
//!         // You can also manually mount an OPTIONS route that will be used instead
//!         .mount("/", routes![manual, manual_options])
//!         .manage(options)
//!         .launch();
//! }
//! ```
//!
//! ## Truly Manual
//!
//! This mode is the most difficult to use but offers the most amount of flexibility.
//! You might have to understand how the library works internally to know how to use this mode.
//! In exchange, you can selectively choose which routes to offer CORS protection to, and you
//! can mix and match CORS settings for the routes. You can combine usage of this mode with
//! "guard" to offer a mix of ease of use and flexibility.
//!
//! You really do not need to use this unless you have a truly ad-hoc need to respond to CORS
//! differently in a route. For example, you have a `ping` endpoint that allows all origins but
//! the rest of your routes do not.
//!
//! ### Handler
//!
//! This mode requires that you pass in a closure that will be lazily evaluated once a CORS request
//! has been validated. If validation fails, the closure will not be run. You should put any code
//! that has any side effects or with an appreciable computation cost inside this handler.
//!
//! ### Steps to perform:
//! - You will first need to have a `Cors` struct ready. This struct can be borrowed with a lifetime
//! at least as long as `'r` which is the lifetime of a Rocket request. `'static` works too.
//! In this case, you might as well use the `Guard` method above and place the `Cors` struct in
//! Rocket's [state](https://rocket.rs/guide/state/).
//! Alternatively, you can create a `Cors` struct directly in the route.
//! - Your routes _might_ need to have a `'r` lifetime and return `impl Responder<'r>`. See below.
//! - Using the `Cors` struct, use either the
//! [`respond_owned`](Cors#method.respond_owned) or
//! [`respond_borrowed`](Cors#method.respond_borrowed) function and pass in a handler
//! that will be executed once CORS validation is successful.
//! - Your handler will be passed a [`Guard`](Guard) which you will have to use to
//! add CORS headers into your own response.
//! - You will have to manually define your own `OPTIONS` routes.
//!
//! ### Notes about route lifetime
//! You might have to specify a `'r` lifetime in your routes and then return `impl Responder<'r>`.
//! If you are not sure what to do, you can try to leave the lifetime out and then add it in
//! when the compiler complains.
//!
//! Generally, you will need to manually annotate the lifetime for the following cases where
//! the compiler is unable to [elide](https://doc.rust-lang.org/beta/nomicon/lifetime-elision.html)
//! the lifetime:
//!
//! - Your function arguments do not borrow anything.
//! - Your function arguments borrow from more than one lifetime.
//! - Your function arguments borrow from a lifetime that is shorter than the `'r` lifetime
//! required.
//!
//! You can see examples when the lifetime annotation is required (or not) in `examples/manual.rs`.
//!
//! ### Owned example
//! This is the most likely scenario when you want to have manual CORS validation. You can use this
//! when the settings you want to use for a route is not the same as the rest of the application
//! (which you might have put in Rocket's state).
//!
//! ```rust,no_run
//! #![feature(proc_macro_hygiene, decl_macro)]
//! extern crate rocket;
//! extern crate rocket_cors;
//!
//! use rocket::{get, options, routes};
//! use rocket::http::Method;
//! use rocket::response::Responder;
//! use rocket_cors::{Cors, AllowedOrigins, AllowedHeaders};
//!
//! /// Create and use an ad-hoc Cors
//! #[get("/owned")]
//! fn owned<'r>() -> impl Responder<'r> {
//!     let options = cors_options();
//!     options.respond_owned(|guard| guard.responder("Hello CORS"))
//! }
//!
//! /// You need to define an OPTIONS route for preflight checks.
//! /// These routes can just return the unit type `()`
//! #[options("/owned")]
//! fn owned_options<'r>() -> impl Responder<'r> {
//!     let options = cors_options();
//!     options.respond_owned(|guard| guard.responder(()))
//! }
//!
//! fn cors_options() -> Cors {
//!     let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
//!     assert!(failed_origins.is_empty());
//!
//!     // You can also deserialize this
//!     rocket_cors::Cors {
//!         allowed_origins: allowed_origins,
//!         allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
//!         allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
//!         allow_credentials: true,
//!         ..Default::default()
//!     }
//! }
//!
//! fn main() {
//!     rocket::ignite()
//!         .mount(
//!             "/",
//!             routes![
//!                 owned,
//!                 owned_options,
//!             ],
//!         )
//!         .manage(cors_options())
//!         .launch();
//! }
//! ```
//!
//! ### Borrowed Example
//! You might want to borrow the `Cors` struct from Rocket's state, for example. Unless you have
//! special handling, you might want to use the Guard method instead which has less hassle.
//!
//! ```rust,no_run
//! #![feature(proc_macro_hygiene, decl_macro)]
//! extern crate rocket;
//! extern crate rocket_cors;
//!
//! use std::io::Cursor;
//!
//! use rocket::{State, Response, get, routes};
//! use rocket::http::Method;
//! use rocket::response::Responder;
//! use rocket_cors::{Cors, AllowedOrigins, AllowedHeaders};
//!
//! /// Using a borrowed Cors
//! #[get("/")]
//! fn borrowed(options: State<Cors>) -> impl Responder {
//!     options.inner().respond_borrowed(
//!         |guard| guard.responder("Hello CORS"),
//!     )
//! }
//!
//! /// Using a `Response` instead of a `Responder`. You generally won't have to do this.
//! #[get("/response")]
//! fn response(options: State<Cors>) -> impl Responder {
//!     let mut response = Response::new();
//!     response.set_sized_body(Cursor::new("Hello CORS!"));
//!
//!     options.inner().respond_borrowed(
//!         move |guard| guard.response(response),
//!     )
//! }
//!
//! fn cors_options() -> Cors {
//!     let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
//!     assert!(failed_origins.is_empty());
//!
//!     // You can also deserialize this
//!     rocket_cors::Cors {
//!         allowed_origins: allowed_origins,
//!         allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
//!         allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
//!         allow_credentials: true,
//!         ..Default::default()
//!     }
//! }
//!
//! fn main() {
//!     rocket::ignite()
//!         .mount(
//!             "/",
//!             routes![
//!                 borrowed,
//!                 response,
//!             ],
//!         )
//!         .mount("/", rocket_cors::catch_all_options_routes()) // mount the catch all routes
//!         .manage(cors_options())
//!         .launch();
//! }
//! ```
//!
//! ## Mixing Guard and Manual
//!
//! You can mix `Guard` and `Truly Manual` modes together for your application. For example, your
//! application might restrict the Origins that can access it, except for one `ping` route that
//! allows all access.
//!
//! You can run the example code below with `cargo run --example mix`.
//!
//! ```rust,no_run
//! #![feature(proc_macro_hygiene, decl_macro)]
//! extern crate rocket;
//! extern crate rocket_cors;
//!
//! use rocket::{get, options, routes};
//! use rocket::http::Method;
//! use rocket::response::Responder;
//! use rocket_cors::{Cors, Guard, AllowedOrigins, AllowedHeaders};
//!
//! /// The "usual" app route
//! #[get("/")]
//! fn app(cors: Guard) -> rocket_cors::Responder<&str> {
//!     cors.responder("Hello CORS!")
//! }
//!
//! /// The special "ping" route
//! #[get("/ping")]
//! fn ping<'r>() -> impl Responder<'r> {
//!     let options = cors_options_all();
//!     options.respond_owned(|guard| guard.responder("Pong!"))
//! }
//!
//! /// You need to define an OPTIONS route for preflight checks if you want to use `Cors` struct
//! /// that is not in Rocket's managed state.
//! /// These routes can just return the unit type `()`
//! #[options("/ping")]
//! fn ping_options<'r>() -> impl Responder<'r> {
//!     let options = cors_options_all();
//!     options.respond_owned(|guard| guard.responder(()))
//! }
//!
//! /// Returns the "application wide" Cors struct
//! fn cors_options() -> Cors {
//!     let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
//!     assert!(failed_origins.is_empty());
//!
//!     // You can also deserialize this
//!     rocket_cors::Cors {
//!         allowed_origins: allowed_origins,
//!         allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
//!         allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
//!         allow_credentials: true,
//!         ..Default::default()
//!     }
//! }
//!
//! /// A special struct that allows all origins
//! ///
//! /// Note: In your real application, you might want to use something like `lazy_static` to
//! /// generate a `&'static` reference to this instead of creating a new struct on every request.
//! fn cors_options_all() -> Cors {
//!     // You can also deserialize this
//!     rocket_cors::Cors {
//!         allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
//!         ..Default::default()
//!     }
//! }
//!
//! fn main() {
//!     rocket::ignite()
//!         .mount(
//!             "/",
//!             routes![
//!                 app,
//!                 ping,
//!                 ping_options,
//!             ],
//!         )
//!         .mount("/", rocket_cors::catch_all_options_routes()) // mount the catch all routes
//!         .manage(cors_options())
//!         .launch();
//! }
//!
//! ```
//!
//! ## Reference
//! - [Fetch CORS Specification](https://fetch.spec.whatwg.org/#cors-protocol)
//! - [Supplanted W3C CORS Specification](https://www.w3.org/TR/cors/)
//! - [Resource Advice](https://w3c.github.io/webappsec-cors-for-developers/#resources)

#![deny(
    const_err,
    dead_code,
    deprecated,
    exceeding_bitshifts,
    improper_ctypes,
    missing_docs,
    mutable_transmutes,
    no_mangle_const_items,
    non_camel_case_types,
    non_shorthand_field_patterns,
    non_upper_case_globals,
    overflowing_literals,
    path_statements,
    plugin_as_library,
    stable_features,
    trivial_casts,
    trivial_numeric_casts,
    unconditional_recursion,
    unknown_crate_types,
    unreachable_code,
    unused_allocation,
    unused_assignments,
    unused_attributes,
    unused_comparisons,
    unused_extern_crates,
    unused_features,
    unused_imports,
    unused_import_braces,
    unused_qualifications,
    unused_must_use,
    unused_mut,
    unused_parens,
    unused_results,
    unused_unsafe,
    variant_size_differences,
    warnings,
    while_true
)]
#![allow(
    legacy_directory_ownership,
    missing_copy_implementations,
    missing_debug_implementations,
    unknown_lints,
    unsafe_code,
    intra_doc_link_resolution_failure
)]
#![doc(test(attr(allow(unused_variables), deny(warnings))))]

#[cfg(test)]
#[macro_use]
mod test_macros;
mod fairing;

pub mod headers;

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::error;
use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;
use std::str::FromStr;

use ::log::{error, info, log};
use rocket::http::{self, Status};
use rocket::request::{FromRequest, Request};
use rocket::response;
use rocket::{error_, info_, log_, Outcome, State};
#[cfg(feature = "serialization")]
use serde_derive::{Deserialize, Serialize};

use crate::headers::{
    AccessControlRequestHeaders, AccessControlRequestMethod, HeaderFieldName, HeaderFieldNamesSet,
    Origin, Url,
};

/// Errors during operations
///
/// This enum implements `rocket::response::Responder` which will return an appropriate status code
/// while printing out the error in the console.
/// Because these errors are usually the result of an error while trying to respond to a CORS
/// request, CORS headers cannot be added to the response and your applications requesting CORS
/// will not be able to see the status code.
#[derive(Debug)]
pub enum Error {
    /// The HTTP request header `Origin` is required but was not provided
    MissingOrigin,
    /// The HTTP request header `Origin` could not be parsed correctly.
    BadOrigin(url::ParseError),
    /// The request header `Access-Control-Request-Method` is required but is missing
    MissingRequestMethod,
    /// The request header `Access-Control-Request-Method` has an invalid value
    BadRequestMethod,
    /// The request header `Access-Control-Request-Headers`  is required but is missing.
    MissingRequestHeaders,
    /// Origin is not allowed to make this request
    OriginNotAllowed,
    /// Requested method is not allowed
    MethodNotAllowed,
    /// One or more headers requested are not allowed
    HeadersNotAllowed,
    /// Credentials are allowed, but the Origin is set to "*". This is not allowed by W3C
    ///
    /// This is a misconfiguration. Check the docuemntation for `Cors`.
    CredentialsWithWildcardOrigin,
    /// A CORS Request Guard was used, but no CORS Options was available in Rocket's state
    ///
    /// This is a misconfiguration. Use `Rocket::manage` to add a CORS options to managed state.
    MissingCorsInRocketState,
    /// The `on_response` handler of Fairing could not find the injected header from the Request.
    /// Either some other fairing has removed it, or this is a bug.
    MissingInjectedHeader,
}

impl Error {
    fn status(&self) -> Status {
        match *self {
            Error::MissingOrigin
            | Error::OriginNotAllowed
            | Error::MethodNotAllowed
            | Error::HeadersNotAllowed => Status::Forbidden,
            Error::CredentialsWithWildcardOrigin
            | Error::MissingCorsInRocketState
            | Error::MissingInjectedHeader => Status::InternalServerError,
            _ => Status::BadRequest,
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::MissingOrigin => "The request header `Origin` is required but is missing",
            Error::BadOrigin(_) => "The request header `Origin` contains an invalid URL",
            Error::MissingRequestMethod => {
                "The request header `Access-Control-Request-Method` \
                 is required but is missing"
            }
            Error::BadRequestMethod => {
                "The request header `Access-Control-Request-Method` has an invalid value"
            }
            Error::MissingRequestHeaders => {
                "The request header `Access-Control-Request-Headers` \
                 is required but is missing"
            }
            Error::OriginNotAllowed => "Origin is not allowed to request",
            Error::MethodNotAllowed => "Method is not allowed",
            Error::HeadersNotAllowed => "Headers are not allowed",
            Error::CredentialsWithWildcardOrigin => {
                "Credentials are allowed, but the Origin is set to \"*\". \
                 This is not allowed by W3C"
            }
            Error::MissingCorsInRocketState => {
                "A CORS Request Guard was used, but no CORS Options was available in Rocket's state"
            }
            Error::MissingInjectedHeader => {
                "The `on_response` handler of Fairing could not find the injected header from the \
                 Request. Either some other fairing has removed it, or this is a bug."
            }
        }
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        match *self {
            Error::BadOrigin(ref e) => Some(e),
            _ => Some(self),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Error::BadOrigin(ref e) => fmt::Display::fmt(e, f),
            _ => write!(f, "{}", error::Error::description(self)),
        }
    }
}

impl<'r> response::Responder<'r> for Error {
    fn respond_to(self, _: &Request<'_>) -> Result<response::Response<'r>, Status> {
        error_!("CORS Error: {}", self);
        Err(self.status())
    }
}

/// An enum signifying that some of type T is allowed, or `All` (everything is allowed).
///
/// `Default` is implemented for this enum and is `All`.
///
/// This enum is serialized and deserialized
/// ["Externally tagged"](https://serde.rs/enum-representations.html)
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub enum AllOrSome<T> {
    /// Everything is allowed. Usually equivalent to the "*" value.
    All,
    /// Only some of `T` is allowed
    Some(T),
}

impl<T> Default for AllOrSome<T> {
    fn default() -> Self {
        AllOrSome::All
    }
}

impl<T> AllOrSome<T> {
    /// Returns whether this is an `All` variant
    pub fn is_all(&self) -> bool {
        match *self {
            AllOrSome::All => true,
            AllOrSome::Some(_) => false,
        }
    }

    /// Returns whether this is a `Some` variant
    pub fn is_some(&self) -> bool {
        !self.is_all()
    }
}

impl AllOrSome<HashSet<Url>> {
    #[deprecated(since = "0.1.3", note = "please use `AllowedOrigins::Some` instead")]
    /// New `AllOrSome` from a list of URL strings.
    /// Returns a tuple where the first element is the struct `AllOrSome`,
    /// and the second element
    /// is a map of strings which failed to parse into URLs and their associated parse errors.
    pub fn new_from_str_list(urls: &[&str]) -> (Self, HashMap<String, url::ParseError>) {
        AllowedOrigins::some(urls)
    }
}

/// A wrapper type around `rocket::http::Method` to support serialization and deserialization
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Method(http::Method);

impl FromStr for Method {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let method = http::Method::from_str(s)?;
        Ok(Method(method))
    }
}

impl Deref for Method {
    type Target = http::Method;

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

impl From<http::Method> for Method {
    fn from(method: http::Method) -> Self {
        Method(method)
    }
}

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

#[cfg(feature = "serialization")]
mod method_serde {
    use std::fmt;
    use std::str::FromStr;

    use serde::{self, Deserialize, Serialize};

    use crate::Method;

    impl Serialize for Method {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            serializer.serialize_str(self.as_str())
        }
    }

    impl<'de> Deserialize<'de> for Method {
        fn deserialize<D>(deserializer: D) -> Result<Method, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            use serde::de::{self, Visitor};

            struct MethodVisitor;
            impl<'de> Visitor<'de> for MethodVisitor {
                type Value = Method;

                fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                    formatter.write_str("a string containing a HTTP Verb")
                }

                fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
                where
                    E: de::Error,
                {
                    match Self::Value::from_str(s) {
                        Ok(value) => Ok(value),
                        Err(e) => Err(de::Error::custom(format!("{:?}", e))),
                    }
                }
            }

            deserializer.deserialize_string(MethodVisitor)
        }
    }
}

/// A list of allowed origins. Either Some origins are allowed, or all origins are allowed.
///
/// # Examples
/// ```rust
/// use rocket_cors::AllowedOrigins;
///
/// let all_origins = AllowedOrigins::all();
/// let (some_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
/// assert!(failed_origins.is_empty());
/// ```
pub type AllowedOrigins = AllOrSome<HashSet<Url>>;

impl AllowedOrigins {
    /// Allows some origins
    ///
    /// Returns a tuple where the first element is the struct `AllowedOrigins`,
    /// and the second element
    /// is a map of strings which failed to parse into URLs and their associated parse errors.
    pub fn some(urls: &[&str]) -> (Self, HashMap<String, url::ParseError>) {
        let (ok_set, error_map): (Vec<_>, Vec<_>) = urls
            .iter()
            .map(|s| (s.to_string(), Url::from_str(s)))
            .partition(|&(_, ref r)| r.is_ok());

        let error_map = error_map
            .into_iter()
            .map(|(s, r)| (s.to_string(), r.unwrap_err()))
            .collect();

        let ok_set = ok_set.into_iter().map(|(_, r)| r.unwrap()).collect();

        (AllOrSome::Some(ok_set), error_map)
    }

    /// Allows all origins
    pub fn all() -> Self {
        AllOrSome::All
    }
}

/// A list of allowed methods
///
/// The [list](https://api.rocket.rs/rocket/http/enum.Method.html)
/// of methods is whatever is supported by Rocket.
///
/// # Example
/// ```rust
/// use std::str::FromStr;
/// use rocket_cors::AllowedMethods;
///
/// let allowed_methods: AllowedMethods = ["Get", "Post", "Delete"]
///    .iter()
///    .map(|s| FromStr::from_str(s).unwrap())
///    .collect();
/// ```
pub type AllowedMethods = HashSet<Method>;

/// A list of allowed headers
///
/// # Examples
/// ```rust
/// use rocket_cors::AllowedHeaders;
///
/// let all_headers = AllowedHeaders::all();
/// let some_headers = AllowedHeaders::some(&["Authorization", "Accept"]);
/// ```
pub type AllowedHeaders = AllOrSome<HashSet<HeaderFieldName>>;

impl AllowedHeaders {
    /// Allow some headers
    pub fn some(headers: &[&str]) -> Self {
        AllOrSome::Some(headers.iter().map(|s| s.to_string().into()).collect())
    }

    /// Allows all headers
    pub fn all() -> Self {
        AllOrSome::All
    }
}

/// Response generator and [Fairing](https://rocket.rs/guide/fairings/) for CORS
///
/// This struct can be as Fairing or in an ad-hoc manner to generate CORS response. See the
/// documentation at the [crate root](index.html) for usage information.
///
/// You create a new copy of this struct by defining the configurations in the fields below.
/// This struct can also be deserialized by serde with the `serialization` feature which is
/// enabled by default.
///
/// [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) is implemented for this
/// struct. The default for each field is described in the docuementation for the field.
///
/// # Examples
///
/// You can run an example from the repository to demonstrate the JSON serialization with
/// `cargo run --example json`.
///
/// ## Pure default
/// ```rust
/// let default = rocket_cors::Cors::default();
/// ```
///
/// ## JSON Examples
/// ### Default
///
/// ```json
/// {
///   "allowed_origins": "All",
///   "allowed_methods": [
///     "POST",
///     "PATCH",
///     "PUT",
///     "DELETE",
///     "HEAD",
///     "OPTIONS",
///     "GET"
///   ],
///   "allowed_headers": "All",
///   "allow_credentials": false,
///   "expose_headers": [],
///   "max_age": null,
///   "send_wildcard": false,
///   "fairing_route_base": "/cors",
///   "fairing_route_rank": 0
/// }
/// ```
/// ### Defined
/// ```json
/// {
///   "allowed_origins": {
///     "Some": [
///       "https://www.acme.com/"
///     ]
///   },
///   "allowed_methods": [
///     "POST",
///     "DELETE",
///     "GET"
///   ],
///   "allowed_headers": {
///     "Some": [
///       "Accept",
///       "Authorization"
///     ]
///   },
///   "allow_credentials": true,
///   "expose_headers": [
///     "Content-Type",
///     "X-Custom"
///   ],
///   "max_age": 42,
///   "send_wildcard": false,
///   "fairing_route_base": "/mycors"
/// }
///
/// ```
#[derive(Eq, PartialEq, Clone, Debug)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct Cors {
    /// Origins that are allowed to make requests.
    /// Will be verified against the `Origin` request header.
    ///
    /// When `All` is set, and `send_wildcard` is set, "*" will be sent in
    /// the `Access-Control-Allow-Origin` response header. Otherwise, the client's `Origin` request
    /// header will be echoed back in the `Access-Control-Allow-Origin` response header.
    ///
    /// When `Some` is set, the client's `Origin` request header will be checked in a
    /// case-sensitive manner.
    ///
    /// This is the `list of origins` in the
    /// [Resource Processing Model](https://www.w3.org/TR/cors/#resource-processing-model).
    ///
    /// Defaults to `All`.
    ///
    #[cfg_attr(feature = "serialization", serde(default))]
    pub allowed_origins: AllowedOrigins,
    /// The list of methods which the allowed origins are allowed to access for
    /// non-simple requests.
    ///
    /// This is the `list of methods` in the
    /// [Resource Processing Model](https://www.w3.org/TR/cors/#resource-processing-model).
    ///
    /// Defaults to `[GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]`
    #[cfg_attr(
        feature = "serialization",
        serde(default = "Cors::default_allowed_methods")
    )]
    pub allowed_methods: AllowedMethods,
    /// The list of header field names which can be used when this resource is accessed by allowed
    /// origins.
    ///
    /// If `All` is set, whatever is requested by the client in `Access-Control-Request-Headers`
    /// will be echoed back in the `Access-Control-Allow-Headers` header.
    ///
    /// This is the `list of headers` in the
    /// [Resource Processing Model](https://www.w3.org/TR/cors/#resource-processing-model).
    ///
    /// Defaults to `All`.
    #[cfg_attr(feature = "serialization", serde(default))]
    pub allowed_headers: AllOrSome<HashSet<HeaderFieldName>>,
    /// Allows users to make authenticated requests.
    /// If true, injects the `Access-Control-Allow-Credentials` header in responses.
    /// This allows cookies and credentials to be submitted across domains.
    ///
    /// This **CANNOT** be used in conjunction with `allowed_origins` set to `All` and
    /// `send_wildcard` set to `true`. Depending on the mode of usage, this will either result
    /// in an `Error::CredentialsWithWildcardOrigin` error during Rocket launch or runtime.
    ///
    /// Defaults to `false`.
    #[cfg_attr(feature = "serialization", serde(default))]
    pub allow_credentials: bool,
    /// The list of headers which are safe to expose to the API of a CORS API specification.
    /// This corresponds to the `Access-Control-Expose-Headers` responde header.
    ///
    /// This is the `list of exposed headers` in the
    /// [Resource Processing Model](https://www.w3.org/TR/cors/#resource-processing-model).
    ///
    /// This defaults to an empty set.
    #[cfg_attr(feature = "serialization", serde(default))]
    pub expose_headers: HashSet<String>,
    /// The maximum time for which this CORS request maybe cached. This value is set as the
    /// `Access-Control-Max-Age` header.
    ///
    /// This defaults to `None` (unset).
    #[cfg_attr(feature = "serialization", serde(default))]
    pub max_age: Option<usize>,
    /// If true, and the `allowed_origins` parameter is `All`, a wildcard
    /// `Access-Control-Allow-Origin` response header is sent, rather than the request’s
    /// `Origin` header.
    ///
    /// This is the `supports credentials flag` in the
    /// [Resource Processing Model](https://www.w3.org/TR/cors/#resource-processing-model).
    ///
    /// This **CANNOT** be used in conjunction with `allowed_origins` set to `All` and
    /// `allow_credentials` set to `true`. Depending on the mode of usage, this will either result
    /// in an `Error::CredentialsWithWildcardOrigin` error during Rocket launch or runtime.
    ///
    /// Defaults to `false`.
    #[cfg_attr(feature = "serialization", serde(default))]
    pub send_wildcard: bool,
    /// When used as Fairing, Cors will need to redirect failed CORS checks to a custom route
    /// mounted by the fairing. Specify the base of the route so that it doesn't clash with any
    /// of your existing routes.
    ///
    /// Defaults to "/cors"
    #[cfg_attr(
        feature = "serialization",
        serde(default = "Cors::default_fairing_route_base")
    )]
    pub fairing_route_base: String,
    /// When used as Fairing, Cors will need to redirect failed CORS checks to a custom route
    /// mounted by the fairing. Specify the rank of the route so that it doesn't clash with any
    /// of your existing routes. Remember that a higher ranked route has lower priority.
    ///
    /// Defaults to 0
    #[cfg_attr(
        feature = "serialization",
        serde(default = "Cors::default_fairing_route_rank")
    )]
    pub fairing_route_rank: isize,
}

impl Default for Cors {
    fn default() -> Self {
        Self {
            allowed_origins: Default::default(),
            allowed_methods: Self::default_allowed_methods(),
            allowed_headers: Default::default(),
            allow_credentials: Default::default(),
            expose_headers: Default::default(),
            max_age: Default::default(),
            send_wildcard: Default::default(),
            fairing_route_base: Self::default_fairing_route_base(),
            fairing_route_rank: Self::default_fairing_route_rank(),
        }
    }
}

impl Cors {
    fn default_allowed_methods() -> HashSet<Method> {
        use rocket::http::Method;

        vec![
            Method::Get,
            Method::Head,
            Method::Post,
            Method::Options,
            Method::Put,
            Method::Patch,
            Method::Delete,
        ]
        .into_iter()
        .map(From::from)
        .collect()
    }

    fn default_fairing_route_base() -> String {
        "/cors".to_string()
    }

    fn default_fairing_route_rank() -> isize {
        0
    }

    /// Validates if any of the settings are disallowed or incorrect
    ///
    /// This is run during initial Fairing attachment
    pub fn validate(&self) -> Result<(), Error> {
        if self.allowed_origins.is_all() && self.send_wildcard && self.allow_credentials {
            Err(Error::CredentialsWithWildcardOrigin)?;
        }

        Ok(())
    }

    /// Manually respond to a request with CORS checks and headers using an Owned `Cors`.
    ///
    /// Use this variant when your `Cors` struct will not live at least as long as the whole `'r`
    /// lifetime of the request.
    ///
    /// After the CORS checks are done, the passed in handler closure will be run to generate a
    /// final response. You will have to merge your response with the `Guard` that you have been
    /// passed in to include the CORS headers.
    ///
    /// See the documentation at the [crate root](index.html) for usage information.
    pub fn respond_owned<'r, F, R>(self, handler: F) -> Result<ManualResponder<'r, F, R>, Error>
    where
        F: FnOnce(Guard<'r>) -> R + 'r,
        R: response::Responder<'r>,
    {
        self.validate()?;
        Ok(ManualResponder::new(Cow::Owned(self), handler))
    }

    /// Manually respond to a request with CORS checks and headers using a borrowed `Cors`.
    ///
    /// Use this variant when your `Cors` struct will live at least as long as the whole `'r`
    /// lifetime of the request. If you are getting your `Cors` from Rocket's state, you will have
    /// to use the [`inner` function](https://api.rocket.rs/rocket/struct.State.html#method.inner)
    /// to get a longer borrowed lifetime.
    ///
    /// After the CORS checks are done, the passed in handler closure will be run to generate a
    /// final response. You will have to merge your response with the `Guard` that you have been
    /// passed in to include the CORS headers.
    ///
    /// See the documentation at the [crate root](index.html) for usage information.
    pub fn respond_borrowed<'r, F, R>(
        &'r self,
        handler: F,
    ) -> Result<ManualResponder<'r, F, R>, Error>
    where
        F: FnOnce(Guard<'r>) -> R + 'r,
        R: response::Responder<'r>,
    {
        self.validate()?;
        Ok(ManualResponder::new(Cow::Borrowed(self), handler))
    }
}

/// A CORS Response which provides the following CORS headers:
///
/// - `Access-Control-Allow-Origin`
/// - `Access-Control-Expose-Headers`
/// - `Access-Control-Max-Age`
/// - `Access-Control-Allow-Credentials`
/// - `Access-Control-Allow-Methods`
/// - `Access-Control-Allow-Headers`
///
/// The following headers will be merged:
/// - `Vary`
///
/// You can get this struct by using `Cors::validate_request` in an ad-hoc manner.
#[derive(Eq, PartialEq, Debug)]
pub(crate) struct Response {
    allow_origin: Option<AllOrSome<Url>>,
    allow_methods: HashSet<Method>,
    allow_headers: HeaderFieldNamesSet,
    allow_credentials: bool,
    expose_headers: HeaderFieldNamesSet,
    max_age: Option<usize>,
    vary_origin: bool,
}

impl Response {
    /// Create an empty `Response`
    fn new() -> Self {
        Self {
            allow_origin: None,
            allow_headers: HashSet::new(),
            allow_methods: HashSet::new(),
            allow_credentials: false,
            expose_headers: HashSet::new(),
            max_age: None,
            vary_origin: false,
        }
    }

    /// Consumes the `Response` and return an altered response with origin and `vary_origin` set
    fn origin(mut self, origin: &Url, vary_origin: bool) -> Self {
        self.allow_origin = Some(AllOrSome::Some(origin.clone()));
        self.vary_origin = vary_origin;
        self
    }

    /// Consumes the `Response` and return an altered response with origin set to "*"
    fn any(mut self) -> Self {
        self.allow_origin = Some(AllOrSome::All);
        self
    }

    /// Consumes the Response and set credentials
    fn credentials(mut self, value: bool) -> Self {
        self.allow_credentials = value;
        self
    }

    /// Consumes the CORS, set expose_headers to
    /// passed headers and returns changed CORS
    fn exposed_headers(mut self, headers: &[&str]) -> Self {
        self.expose_headers = headers.into_iter().map(|s| s.to_string().into()).collect();
        self
    }

    /// Consumes the CORS, set max_age to
    /// passed value and returns changed CORS
    fn max_age(mut self, value: Option<usize>) -> Self {
        self.max_age = value;
        self
    }

    /// Consumes the CORS, set allow_methods to
    /// passed methods and returns changed CORS
    fn methods(mut self, methods: &HashSet<Method>) -> Self {
        self.allow_methods = methods.clone();
        self
    }

    /// Consumes the CORS, set allow_headers to
    /// passed headers and returns changed CORS
    fn headers(mut self, headers: &[&str]) -> Self {
        self.allow_headers = headers.into_iter().map(|s| s.to_string().into()).collect();
        self
    }

    /// Consumes the `Response` and return  a `Responder` that wraps a
    /// provided `rocket:response::Responder` with CORS headers
    pub fn responder<'r, R: response::Responder<'r>>(self, responder: R) -> Responder<'r, R> {
        Responder::new(responder, self)
    }

    /// Merge a `rocket::Response` with this CORS response. This is usually used in the final step
    /// of a route to return a value for the route.
    ///
    /// This will overwrite any existing CORS headers
    pub fn response<'r>(&self, base: response::Response<'r>) -> response::Response<'r> {
        let mut response = response::Response::build_from(base).finalize();
        self.merge(&mut response);
        response
    }

    /// Merge CORS headers with an existing `rocket::Response`.
    ///
    /// This will overwrite any existing CORS headers
    fn merge(&self, response: &mut response::Response<'_>) {
        // TODO: We should be able to remove this
        let origin = match self.allow_origin {
            None => {
                // This is not a CORS response
                return;
            }
            Some(ref origin) => origin,
        };

        // Origin should be ASCII serialized
        // c.f. https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin
        let origin = match *origin {
            AllOrSome::All => "*".to_string(),
            AllOrSome::Some(ref origin) => origin.origin().ascii_serialization(),
        };

        let _ = response.set_raw_header("Access-Control-Allow-Origin", origin);

        if self.allow_credentials {
            let _ = response.set_raw_header("Access-Control-Allow-Credentials", "true");
        } else {
            response.remove_header("Access-Control-Allow-Credentials");
        }

        if !self.expose_headers.is_empty() {
            let headers: Vec<String> = self
                .expose_headers
                .iter()
                .map(|s| s.deref().to_string())
                .collect();
            let headers = headers.join(", ");

            let _ = response.set_raw_header("Access-Control-Expose-Headers", headers);
        } else {
            response.remove_header("Access-Control-Expose-Headers");
        }

        if !self.allow_headers.is_empty() {
            let headers: Vec<String> = self
                .allow_headers
                .iter()
                .map(|s| s.deref().to_string())
                .collect();
            let headers = headers.join(", ");

            let _ = response.set_raw_header("Access-Control-Allow-Headers", headers);
        } else {
            response.remove_header("Access-Control-Allow-Headers");
        }

        if !self.allow_methods.is_empty() {
            let methods: Vec<_> = self.allow_methods.iter().map(|m| m.as_str()).collect();
            let methods = methods.join(", ");

            let _ = response.set_raw_header("Access-Control-Allow-Methods", methods);
        } else {
            response.remove_header("Access-Control-Allow-Methods");
        }

        if self.max_age.is_some() {
            let max_age = self.max_age.unwrap();
            let _ = response.set_raw_header("Access-Control-Max-Age", max_age.to_string());
        } else {
            response.remove_header("Access-Control-Max-Age");
        }

        if self.vary_origin {
            response.adjoin_raw_header("Vary", "Origin");
        }
    }

    /// Validate and create a new CORS Response from a request and settings
    pub fn validate_and_build<'a, 'r>(
        options: &'a Cors,
        request: &'a Request<'r>,
    ) -> Result<Self, Error> {
        validate_and_build(options, request)
    }
}

/// A [request guard](https://rocket.rs/guide/requests/#request-guards) to check CORS headers
/// before a route is run. Will not execute the route if checks fail.
///
/// See the documentation at the [crate root](index.html) for usage information.
///
/// You should not wrap this in an
/// `Option` or `Result` because the guard will let non-CORS requests through and will take over
/// error handling in case of errors.
/// In essence, this is just a wrapper around `Response` with a `'r` borrowed lifetime so users
/// don't have to keep specifying the lifetimes in their routes
pub struct Guard<'r> {
    response: Response,
    marker: PhantomData<&'r Response>,
}

impl<'r> Guard<'r> {
    fn new(response: Response) -> Self {
        Self {
            response,
            marker: PhantomData,
        }
    }

    /// Consumes the Guard and return  a `Responder` that wraps a
    /// provided `rocket:response::Responder` with CORS headers
    pub fn responder<R: response::Responder<'r>>(self, responder: R) -> Responder<'r, R> {
        self.response.responder(responder)
    }

    /// Merge a `rocket::Response` with this CORS Guard. This is usually used in the final step
    /// of a route to return a value for the route.
    ///
    /// This will overwrite any existing CORS headers
    pub fn response(&self, base: response::Response<'r>) -> response::Response<'r> {
        self.response.response(base)
    }
}

impl<'a, 'r> FromRequest<'a, 'r> for Guard<'r> {
    type Error = Error;

    fn from_request(request: &'a Request<'r>) -> rocket::request::Outcome<Self, Self::Error> {
        let options = match request.guard::<State<'_, Cors>>() {
            Outcome::Success(options) => options,
            _ => {
                let error = Error::MissingCorsInRocketState;
                return Outcome::Failure((error.status(), error));
            }
        };

        match Response::validate_and_build(&options, request) {
            Ok(response) => Outcome::Success(Self::new(response)),
            Err(error) => Outcome::Failure((error.status(), error)),
        }
    }
}

/// A [`Responder`](https://rocket.rs/guide/responses/#responder) which will simply wraps another
/// `Responder` with CORS headers.
///
/// The following CORS headers will be overwritten:
///
/// - `Access-Control-Allow-Origin`
/// - `Access-Control-Expose-Headers`
/// - `Access-Control-Max-Age`
/// - `Access-Control-Allow-Credentials`
/// - `Access-Control-Allow-Methods`
/// - `Access-Control-Allow-Headers`
///
/// The following headers will be merged:
/// - `Vary`
///
/// See the documentation at the [crate root](index.html) for usage information.
#[derive(Debug)]
pub struct Responder<'r, R> {
    responder: R,
    cors_response: Response,
    marker: PhantomData<dyn response::Responder<'r>>,
}

impl<'r, R: response::Responder<'r>> Responder<'r, R> {
    fn new(responder: R, cors_response: Response) -> Self {
        Self {
            responder,
            cors_response,
            marker: PhantomData,
        }
    }

    /// Respond to a request
    fn respond(self, request: &Request<'_>) -> response::Result<'r> {
        let mut response = self.responder.respond_to(request)?; // handle status errors?
        self.cors_response.merge(&mut response);
        Ok(response)
    }
}

impl<'r, R: response::Responder<'r>> response::Responder<'r> for Responder<'r, R> {
    fn respond_to(self, request: &Request<'_>) -> response::Result<'r> {
        self.respond(request)
    }
}

/// A Manual Responder used in the "truly manual" mode of operation.
///
/// See the documentation at the [crate root](index.html) for usage information.
pub struct ManualResponder<'r, F, R> {
    options: Cow<'r, Cors>,
    handler: F,
    marker: PhantomData<R>,
}

impl<'r, F, R> ManualResponder<'r, F, R>
where
    F: FnOnce(Guard<'r>) -> R + 'r,
    R: response::Responder<'r>,
{
    /// Create a new manual responder by passing in either a borrowed or owned `Cors` option.
    ///
    /// A borrowed `Cors` option must live for the entirety of the `'r` lifetime which is the
    /// lifetime of the entire Rocket request.
    fn new(options: Cow<'r, Cors>, handler: F) -> Self {
        let marker = PhantomData;
        Self {
            options,
            handler,
            marker,
        }
    }

    fn build_guard(&self, request: &Request<'_>) -> Result<Guard<'r>, Error> {
        let response = Response::validate_and_build(&self.options, request)?;
        Ok(Guard::new(response))
    }
}

impl<'r, F, R> response::Responder<'r> for ManualResponder<'r, F, R>
where
    F: FnOnce(Guard<'r>) -> R + 'r,
    R: response::Responder<'r>,
{
    fn respond_to(self, request: &Request<'_>) -> response::Result<'r> {
        let guard = match self.build_guard(request) {
            Ok(guard) => guard,
            Err(err) => {
                error_!("CORS error: {}", err);
                return Err(err.status());
            }
        };
        (self.handler)(guard).respond_to(request)
    }
}

/// Result of CORS validation.
///
/// The variants hold enough information to build a response to the validation result
#[derive(Debug, Eq, PartialEq)]
enum ValidationResult {
    /// Not a CORS request
    None,
    /// Successful preflight request
    Preflight {
        origin: Origin,
        headers: Option<AccessControlRequestHeaders>,
    },
    /// Successful actual request
    Request { origin: Origin },
}

/// Validates a request for CORS and returns a CORS Response
fn validate_and_build(options: &Cors, request: &Request<'_>) -> Result<Response, Error> {
    let result = validate(options, request)?;

    Ok(match result {
        ValidationResult::None => Response::new(),
        ValidationResult::Preflight { origin, headers } => {
            preflight_response(options, &origin, headers.as_ref())
        }
        ValidationResult::Request { origin } => actual_request_response(options, &origin),
    })
}

/// Validate a CORS request
fn validate(options: &Cors, request: &Request<'_>) -> Result<ValidationResult, Error> {
    // 1. If the Origin header is not present terminate this set of steps.
    // The request is outside the scope of this specification.
    let origin = origin(request)?;
    let origin = match origin {
        None => {
            // Not a CORS request
            return Ok(ValidationResult::None);
        }
        Some(origin) => origin,
    };

    // Check if the request verb is an OPTION or something else
    match request.method() {
        http::Method::Options => {
            let method = request_method(request)?;
            let headers = request_headers(request)?;
            preflight_validate(options, &origin, &method, &headers)?;
            Ok(ValidationResult::Preflight { origin, headers })
        }
        _ => {
            actual_request_validate(options, &origin)?;
            Ok(ValidationResult::Request { origin })
        }
    }
}

/// Consumes the responder and based on the provided list of allowed origins,
/// check if the requested origin is allowed.
/// Useful for pre-flight and during requests
fn validate_origin(
    origin: &Origin,
    allowed_origins: &AllOrSome<HashSet<Url>>,
) -> Result<(), Error> {
    match *allowed_origins {
        // Always matching is acceptable since the list of origins can be unbounded.
        AllOrSome::All => Ok(()),
        AllOrSome::Some(ref allowed_origins) => allowed_origins
            .get(origin)
            .and_then(|_| Some(()))
            .ok_or_else(|| Error::OriginNotAllowed),
    }
}

/// Validate allowed methods
fn validate_allowed_method(
    method: &AccessControlRequestMethod,
    allowed_methods: &HashSet<Method>,
) -> Result<(), Error> {
    let &AccessControlRequestMethod(ref request_method) = method;
    if !allowed_methods.iter().any(|m| m == request_method) {
        Err(Error::MethodNotAllowed)?
    }

    // TODO: Subset to route? Or just the method requested for?
    Ok(())
}

/// Validate allowed headers
fn validate_allowed_headers(
    headers: &AccessControlRequestHeaders,
    allowed_headers: &AllOrSome<HashSet<HeaderFieldName>>,
) -> Result<(), Error> {
    let &AccessControlRequestHeaders(ref headers) = headers;

    match *allowed_headers {
        AllOrSome::All => Ok(()),
        AllOrSome::Some(ref allowed_headers) => {
            if !headers.is_empty() && !headers.is_subset(allowed_headers) {
                Err(Error::HeadersNotAllowed)?
            }
            Ok(())
        }
    }
}

/// Gets the `Origin` request header from the request
fn origin(request: &Request<'_>) -> Result<Option<Origin>, Error> {
    match Origin::from_request(request) {
        Outcome::Forward(()) => Ok(None),
        Outcome::Success(origin) => Ok(Some(origin)),
        Outcome::Failure((_, err)) => Err(err),
    }
}

/// Gets the `Access-Control-Request-Method` request header from the request
fn request_method(request: &Request<'_>) -> Result<Option<AccessControlRequestMethod>, Error> {
    match AccessControlRequestMethod::from_request(request) {
        Outcome::Forward(()) => Ok(None),
        Outcome::Success(method) => Ok(Some(method)),
        Outcome::Failure((_, err)) => Err(err),
    }
}

/// Gets the `Access-Control-Request-Headers` request header from the request
fn request_headers(request: &Request<'_>) -> Result<Option<AccessControlRequestHeaders>, Error> {
    match AccessControlRequestHeaders::from_request(request) {
        Outcome::Forward(()) => Ok(None),
        Outcome::Success(geaders) => Ok(Some(geaders)),
        Outcome::Failure((_, err)) => Err(err),
    }
}

/// Do pre-flight validation checks
///
/// This implementation references the
/// [W3C recommendation](https://www.w3.org/TR/cors/#resource-preflight-requests)
/// and [Fetch specification](https://fetch.spec.whatwg.org/#cors-preflight-fetch)
fn preflight_validate(
    options: &Cors,
    origin: &Origin,
    method: &Option<AccessControlRequestMethod>,
    headers: &Option<AccessControlRequestHeaders>,
) -> Result<(), Error> {
    options.validate()?; // Fast-forward check for #7

    // Note: All header parse failures are dealt with in the `FromRequest` trait implementation

    // 2. If the value of the Origin header is not a case-sensitive match for any of the values
    // in list of origins do not set any additional headers and terminate this set of steps.
    validate_origin(origin, &options.allowed_origins)?;

    // 3. Let `method` be the value as result of parsing the Access-Control-Request-Method
    // header.
    // If there is no Access-Control-Request-Method header or if parsing failed,
    // do not set any additional headers and terminate this set of steps.
    // The request is outside the scope of this specification.

    let method = method.as_ref().ok_or_else(|| Error::MissingRequestMethod)?;

    // 4. Let header field-names be the values as result of parsing the
    // Access-Control-Request-Headers headers.
    // If there are no Access-Control-Request-Headers headers
    // let header field-names be the empty list.
    // If parsing failed do not set any additional headers and terminate this set of steps.
    // The request is outside the scope of this specification.

    // 5. If method is not a case-sensitive match for any of the values in list of methods
    // do not set any additional headers and terminate this set of steps.

    validate_allowed_method(method, &options.allowed_methods)?;

    // 6. If any of the header field-names is not a ASCII case-insensitive match for any of the
    // values in list of headers do not set any additional headers and terminate this set of
    // steps.

    if let Some(ref headers) = *headers {
        validate_allowed_headers(headers, &options.allowed_headers)?;
    }

    Ok(())
}

/// Build a response for pre-flight checks
///
/// This implementation references the
/// [W3C recommendation](https://www.w3.org/TR/cors/#resource-preflight-requests)
/// and [Fetch specification](https://fetch.spec.whatwg.org/#cors-preflight-fetch).
fn preflight_response(
    options: &Cors,
    origin: &Origin,
    headers: Option<&AccessControlRequestHeaders>,
) -> Response {
    let response = Response::new();

    // 7. If the resource supports credentials add a single Access-Control-Allow-Origin header,
    // with the value of the Origin header as value, and add a
    // single Access-Control-Allow-Credentials header with the case-sensitive string "true" as
    // value.
    // Otherwise, add a single Access-Control-Allow-Origin header,
    // with either the value of the Origin header or the string "*" as value.
    // Note: The string "*" cannot be used for a resource that supports credentials.

    // Validation has been done in options.validate
    let response = match options.allowed_origins {
        AllOrSome::All => {
            if options.send_wildcard {
                response.any()
            } else {
                response.origin(origin, true)
            }
        }
        AllOrSome::Some(_) => response.origin(origin, false),
    };
    let response = response.credentials(options.allow_credentials);

    // 8. Optionally add a single Access-Control-Max-Age header
    // with as value the amount of seconds the user agent is allowed to cache the result of the
    // request.
    let response = response.max_age(options.max_age);

    // 9. If method is a simple method this step may be skipped.
    // Add one or more Access-Control-Allow-Methods headers consisting of
    // (a subset of) the list of methods.
    // If a method is a simple method it does not need to be listed, but this is not prohibited.
    // Since the list of methods can be unbounded,
    // simply returning the method indicated by Access-Control-Request-Method
    // (if supported) can be enough.

    let response = response.methods(&options.allowed_methods);

    // 10. If each of the header field-names is a simple header and none is Content-Type,
    // this step may be skipped.
    // Add one or more Access-Control-Allow-Headers headers consisting of (a subset of)
    // the list of headers.
    // If a header field name is a simple header and is not Content-Type,
    // it is not required to be listed. Content-Type is to be listed as only a
    // subset of its values makes it qualify as simple header.
    // Since the list of headers can be unbounded, simply returning supported headers
    // from Access-Control-Allow-Headers can be enough.

    // We do not do anything special with simple headers
    if let Some(headers) = headers {
        let &AccessControlRequestHeaders(ref headers) = headers;
        response.headers(
            headers
                .iter()
                .map(|s| &**s.deref())
                .collect::<Vec<&str>>()
                .as_slice(),
        )
    } else {
        response
    }
}

/// Do checks for an actual request
///
/// This implementation references the
/// [W3C recommendation](https://www.w3.org/TR/cors/#resource-requests)
/// and [Fetch specification](https://fetch.spec.whatwg.org/#cors-preflight-fetch).
fn actual_request_validate(options: &Cors, origin: &Origin) -> Result<(), Error> {
    options.validate()?;

    // Note: All header parse failures are dealt with in the `FromRequest` trait implementation

    // 2. If the value of the Origin header is not a case-sensitive match for any of the values
    // in list of origins, do not set any additional headers and terminate this set of steps.
    // Always matching is acceptable since the list of origins can be unbounded.

    validate_origin(origin, &options.allowed_origins)?;

    Ok(())
}

/// Build the response for an actual request
///
/// This implementation references the
/// [W3C recommendation](https://www.w3.org/TR/cors/#resource-requests)
/// and [Fetch specification](https://fetch.spec.whatwg.org/#cors-preflight-fetch)
fn actual_request_response(options: &Cors, origin: &Origin) -> Response {
    let response = Response::new();

    // 3. If the resource supports credentials add a single Access-Control-Allow-Origin header,
    // with the value of the Origin header as value, and add a
    // single Access-Control-Allow-Credentials header with the case-sensitive string "true" as
    // value.
    // Otherwise, add a single Access-Control-Allow-Origin header,
    // with either the value of the Origin header or the string "*" as value.
    // Note: The string "*" cannot be used for a resource that supports credentials.

    // Validation has been done in options.validate

    let response = match options.allowed_origins {
        AllOrSome::All => {
            if options.send_wildcard {
                response.any()
            } else {
                response.origin(origin, true)
            }
        }
        AllOrSome::Some(_) => response.origin(origin, false),
    };

    let response = response.credentials(options.allow_credentials);

    // 4. If the list of exposed headers is not empty add one or more
    // Access-Control-Expose-Headers headers, with as values the header field names given in
    // the list of exposed headers.
    // By not adding the appropriate headers resource can also clear the preflight result cache
    // of all entries where origin is a case-sensitive match for the value of the Origin header
    // and url is a case-sensitive match for the URL of the resource.

    response.exposed_headers(
        options
            .expose_headers
            .iter()
            .map(|s| &**s)
            .collect::<Vec<&str>>()
            .as_slice(),
    )
}

/// Returns "catch all" OPTIONS routes that you can mount to catch all OPTIONS request. Only works
/// if you have put a `Cors` struct into Rocket's managed state.
///
/// This route has very high rank (and therefore low priority) of
/// [max value](https://doc.rust-lang.org/nightly/std/primitive.isize.html#method.max_value)
/// so you can define your own to override this route's behaviour.
///
/// See the documentation at the [crate root](index.html) for usage information.
pub fn catch_all_options_routes() -> Vec<rocket::Route> {
    vec![
        rocket::Route::ranked(
            isize::max_value(),
            http::Method::Options,
            "/",
            catch_all_options_route_handler,
        ),
        rocket::Route::ranked(
            isize::max_value(),
            http::Method::Options,
            "/<catch_all_options_route..>",
            catch_all_options_route_handler,
        ),
    ]
}

/// Handler for the "catch all options route"
fn catch_all_options_route_handler<'r>(
    request: &'r Request<'_>,
    _: rocket::Data,
) -> rocket::handler::Outcome<'r> {
    let guard: Guard<'_> = match request.guard() {
        Outcome::Success(guard) => guard,
        Outcome::Failure((status, _)) => return rocket::handler::Outcome::failure(status),
        Outcome::Forward(()) => unreachable!("Should not be reachable"),
    };

    info_!(
        "\"Catch all\" handling of CORS `OPTIONS` preflight for request {}",
        request
    );

    rocket::handler::Outcome::from(request, guard.responder(()))
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use rocket::http::Header;
    use rocket::local::Client;
    #[cfg(feature = "serialization")]
    use serde_json;

    use super::*;
    use crate::http::Method;

    fn make_cors_options() -> Cors {
        let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
        assert!(failed_origins.is_empty());

        Cors {
            allowed_origins: allowed_origins,
            allowed_methods: vec![http::Method::Get]
                .into_iter()
                .map(From::from)
                .collect(),
            allowed_headers: AllowedHeaders::some(&[&"Authorization", "Accept"]),
            allow_credentials: true,
            expose_headers: ["Content-Type", "X-Custom"]
                .into_iter()
                .map(|s| s.to_string().into())
                .collect(),
            ..Default::default()
        }
    }

    fn make_invalid_options() -> Cors {
        let mut cors = make_cors_options();
        cors.allow_credentials = true;
        cors.allowed_origins = AllOrSome::All;
        cors.send_wildcard = true;
        cors
    }

    /// Make a client with no routes for unit testing
    fn make_client() -> Client {
        let rocket = rocket::ignite();
        Client::new(rocket).expect("valid rocket instance")
    }

    // CORS options test

    #[test]
    fn cors_is_validated() {
        assert!(make_cors_options().validate().is_ok())
    }

    #[test]
    #[should_panic(expected = "CredentialsWithWildcardOrigin")]
    fn cors_validates_illegal_allow_credentials() {
        let cors = make_invalid_options();

        cors.validate().unwrap();
    }

    /// Check that the the default deserialization matches the one returned by `Default::default`
    #[cfg(feature = "serialization")]
    #[test]
    fn cors_default_deserialization_is_correct() {
        let deserialized: Cors = serde_json::from_str("{}").expect("To not fail");
        assert_eq!(deserialized, Cors::default());
    }

    // The following tests check validation

    #[test]
    fn validate_origin_allows_all_origins() {
        let url = "https://www.example.com";
        let origin = Origin::from_str(url).unwrap();
        let allowed_origins = AllOrSome::All;

        not_err!(validate_origin(&origin, &allowed_origins));
    }

    #[test]
    fn validate_origin_allows_origin() {
        let url = "https://www.example.com";
        let origin = Origin::from_str(url).unwrap();
        let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.example.com"]);
        assert!(failed_origins.is_empty());

        not_err!(validate_origin(&origin, &allowed_origins));
    }

    #[test]
    #[should_panic(expected = "OriginNotAllowed")]
    fn validate_origin_rejects_invalid_origin() {
        let url = "https://www.acme.com";
        let origin = Origin::from_str(url).unwrap();
        let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.example.com"]);
        assert!(failed_origins.is_empty());

        validate_origin(&origin, &allowed_origins).unwrap();
    }

    #[test]
    fn response_sets_allow_origin_without_vary_correctly() {
        let response = Response::new();
        let response = response.origin(
            &FromStr::from_str("https://www.example.com").unwrap(),
            false,
        );

        // Build response and check built response header
        let expected_header = vec!["https://www.example.com"];
        let response = response.response(response::Response::new());
        let actual_header: Vec<_> = response
            .headers()
            .get("Access-Control-Allow-Origin")
            .collect();
        assert_eq!(expected_header, actual_header);

        assert!(response.headers().get("Vary").next().is_none());
    }

    #[test]
    fn response_sets_allow_origin_with_vary_correctly() {
        let response = Response::new();
        let response =
            response.origin(&FromStr::from_str("https://www.example.com").unwrap(), true);

        // Build response and check built response header
        let expected_header = vec!["https://www.example.com"];
        let response = response.response(response::Response::new());
        let actual_header: Vec<_> = response
            .headers()
            .get("Access-Control-Allow-Origin")
            .collect();
        assert_eq!(expected_header, actual_header);
    }

    #[test]
    fn response_sets_any_origin_correctly() {
        let response = Response::new();
        let response = response.any();

        // Build response and check built response header
        let expected_header = vec!["*"];
        let response = response.response(response::Response::new());
        let actual_header: Vec<_> = response
            .headers()
            .get("Access-Control-Allow-Origin")
            .collect();
        assert_eq!(expected_header, actual_header);
    }

    #[test]
    fn response_sets_allow_origin_with_ascii_serialization() {
        let response = Response::new();
        let response = response.origin(&FromStr::from_str("https://аpple.com").unwrap(), false);

        // Build response and check built response header
        let expected_header = vec!["https://xn--pple-43d.com"];
        let response = response.response(response::Response::new());
        let actual_header: Vec<_> = response
            .headers()
            .get("Access-Control-Allow-Origin")
            .collect();
        assert_eq!(expected_header, actual_header);
    }

    #[test]
    fn response_sets_exposed_headers_correctly() {
        let headers = vec!["Bar", "Baz", "Foo"];
        let response = Response::new();
        let response = response.origin(
            &FromStr::from_str("https://www.example.com").unwrap(),
            false,
        );
        let response = response.exposed_headers(&headers);

        // Build response and check built response header
        let response = response.response(response::Response::new());
        let actual_header: Vec<_> = response
            .headers()
            .get("Access-Control-Expose-Headers")
            .collect();

        assert_eq!(1, actual_header.len());
        let mut actual_headers: Vec<String> = actual_header[0]
            .split(',')
            .map(|header| header.trim().to_string())
            .collect();
        actual_headers.sort();
        assert_eq!(headers, actual_headers);
    }

    #[test]
    fn response_sets_max_age_correctly() {
        let response = Response::new();
        let response = response.origin(
            &FromStr::from_str("https://www.example.com").unwrap(),
            false,
        );

        let response = response.max_age(Some(42));

        // Build response and check built response header
        let expected_header = vec!["42"];
        let response = response.response(response::Response::new());
        let actual_header: Vec<_> = response.headers().get("Access-Control-Max-Age").collect();
        assert_eq!(expected_header, actual_header);
    }

    #[test]
    fn response_does_not_set_max_age_when_none() {
        let response = Response::new();
        let response = response.origin(
            &FromStr::from_str("https://www.example.com").unwrap(),
            false,
        );

        let response = response.max_age(None);

        // Build response and check built response header
        let response = response.response(response::Response::new());
        assert!(response
            .headers()
            .get("Access-Control-Max-Age")
            .next()
            .is_none())
    }

    #[test]
    fn allowed_methods_validated_correctly() {
        let allowed_methods = vec![Method::Get, Method::Head, Method::Post]
            .into_iter()
            .map(From::from)
            .collect();

        let method = "GET";

        not_err!(validate_allowed_method(
            &FromStr::from_str(method).expect("not to fail"),
            &allowed_methods,
        ));
    }

    #[test]
    #[should_panic(expected = "MethodNotAllowed")]
    fn allowed_methods_errors_on_disallowed_method() {
        let allowed_methods = vec![Method::Get, Method::Head, Method::Post]
            .into_iter()
            .map(From::from)
            .collect();

        let method = "DELETE";

        validate_allowed_method(
            &FromStr::from_str(method).expect("not to fail"),
            &allowed_methods,
        )
        .unwrap()
    }

    #[test]
    fn all_allowed_headers_are_validated_correctly() {
        let allowed_headers = AllOrSome::All;
        let requested_headers = vec!["Bar", "Foo"];

        not_err!(validate_allowed_headers(
            &FromStr::from_str(&requested_headers.join(",")).unwrap(),
            &allowed_headers,
        ));
    }

    /// `Response::allowed_headers` should check that headers are allowed, and only
    /// echoes back the list that is actually requested for and not the whole list
    #[test]
    fn allowed_headers_are_validated_correctly() {
        let allowed_headers = vec!["Bar", "Baz", "Foo"];
        let requested_headers = vec!["Bar", "Foo"];

        not_err!(validate_allowed_headers(
            &FromStr::from_str(&requested_headers.join(",")).unwrap(),
            &AllOrSome::Some(
                allowed_headers
                    .iter()
                    .map(|s| FromStr::from_str(*s).unwrap())
                    .collect(),
            ),
        ));
    }

    #[test]
    #[should_panic(expected = "HeadersNotAllowed")]
    fn allowed_headers_errors_on_non_subset() {
        let allowed_headers = vec!["Bar", "Baz", "Foo"];
        let requested_headers = vec!["Bar", "Foo", "Unknown"];

        validate_allowed_headers(
            &FromStr::from_str(&requested_headers.join(",")).unwrap(),
            &AllOrSome::Some(
                allowed_headers
                    .iter()
                    .map(|s| FromStr::from_str(*s).unwrap())
                    .collect(),
            ),
        )
        .unwrap();
    }

    #[test]
    fn response_does_not_build_if_origin_is_not_set() {
        let response = Response::new();
        let response = response.response(response::Response::new());

        let headers: Vec<_> = response.headers().iter().collect();
        assert_eq!(headers.len(), 0);
    }

    #[test]
    fn response_build_removes_existing_cors_headers_and_keeps_others() {
        use std::io::Cursor;

        let original = response::Response::build()
            .status(Status::ImATeapot)
            .raw_header("X-Teapot-Make", "Rocket")
            .raw_header("Access-Control-Max-Age", "42")
            .sized_body(Cursor::new("Brewing the best coffee!"))
            .finalize();

        let response = Response::new();
        let response = response.origin(
            &FromStr::from_str("https://www.example.com").unwrap(),
            false,
        );
        let response = response.response(original);
        // Check CORS header
        let expected_header = vec!["https://www.example.com"];
        let actual_header: Vec<_> = response
            .headers()
            .get("Access-Control-Allow-Origin")
            .collect();
        assert_eq!(expected_header, actual_header);

        // Check other header
        let expected_header = vec!["Rocket"];
        let actual_header: Vec<_> = response.headers().get("X-Teapot-Make").collect();
        assert_eq!(expected_header, actual_header);

        // Check that `Access-Control-Max-Age` is removed
        assert!(response
            .headers()
            .get("Access-Control-Max-Age")
            .next()
            .is_none());
    }

    #[derive(Debug, PartialEq)]
    #[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
    struct MethodTest {
        method: crate::Method,
    }

    #[cfg(feature = "serialization")]
    #[test]
    fn method_serde_roundtrip() {
        use serde_test::{assert_tokens, Token};

        let test = MethodTest {
            method: From::from(http::Method::Get),
        };

        assert_tokens(
            &test,
            &[
                Token::Struct {
                    name: "MethodTest",
                    len: 1,
                },
                Token::Str("method"),
                Token::Str("GET"),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn preflight_validated_correctly() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let result = validate(&options, request.inner()).expect("to not fail");
        let expected_result = ValidationResult::Preflight {
            origin: FromStr::from_str("https://www.acme.com").unwrap(),
            // Checks that only a subset of allowed headers are returned
            // -- i.e. whatever is requested for
            headers: Some(FromStr::from_str("Authorization").unwrap()),
        };

        assert_eq!(expected_result, result);
    }

    #[test]
    #[should_panic(expected = "CredentialsWithWildcardOrigin")]
    fn preflight_validation_errors_on_invalid_options() {
        let options = make_invalid_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let _ = validate(&options, request.inner()).unwrap();
    }

    #[test]
    fn preflight_validation_allows_all_origin() {
        let mut options = make_cors_options();
        options.allowed_origins = AllOrSome::All;
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.example.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let result = validate(&options, request.inner()).expect("to not fail");
        let expected_result = ValidationResult::Preflight {
            origin: FromStr::from_str("https://www.example.com").unwrap(),
            headers: Some(FromStr::from_str("Authorization").unwrap()),
        };

        assert_eq!(expected_result, result);
    }

    #[test]
    #[should_panic(expected = "OriginNotAllowed")]
    fn preflight_validation_errors_on_invalid_origin() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.example.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let _ = validate(&options, request.inner()).unwrap();
    }

    #[test]
    #[should_panic(expected = "MissingRequestMethod")]
    fn preflight_validation_errors_on_missing_request_method() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(request_headers);

        let _ = validate(&options, request.inner()).unwrap();
    }

    #[test]
    #[should_panic(expected = "MethodNotAllowed")]
    fn preflight_validation_errors_on_disallowed_method() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Post,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let _ = validate(&options, request.inner()).unwrap();
    }

    #[test]
    #[should_panic(expected = "HeadersNotAllowed")]
    fn preflight_validation_errors_on_disallowed_headers() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers = hyper::header::AccessControlRequestHeaders(vec![
            FromStr::from_str("Authorization").unwrap(),
            FromStr::from_str("X-NOT-ALLOWED").unwrap(),
        ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let _ = validate(&options, request.inner()).unwrap();
    }

    #[test]
    fn actual_request_validated_correctly() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let request = client.get("/").header(origin_header);

        let result = validate(&options, request.inner()).expect("to not fail");
        let expected_result = ValidationResult::Request {
            origin: FromStr::from_str("https://www.acme.com").unwrap(),
        };

        assert_eq!(expected_result, result);
    }

    #[test]
    #[should_panic(expected = "CredentialsWithWildcardOrigin")]
    fn actual_request_validation_errors_on_invalid_options() {
        let options = make_invalid_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let request = client.get("/").header(origin_header);

        let _ = validate(&options, request.inner()).unwrap();
    }

    #[test]
    fn actual_request_validation_allows_all_origin() {
        let mut options = make_cors_options();
        options.allowed_origins = AllOrSome::All;
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.example.com").unwrap());
        let request = client.get("/").header(origin_header);

        let result = validate(&options, request.inner()).expect("to not fail");
        let expected_result = ValidationResult::Request {
            origin: FromStr::from_str("https://www.example.com").unwrap(),
        };

        assert_eq!(expected_result, result);
    }

    #[test]
    #[should_panic(expected = "OriginNotAllowed")]
    fn actual_request_validation_errors_on_incorrect_origin() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.example.com").unwrap());
        let request = client.get("/").header(origin_header);

        let _ = validate(&options, request.inner()).unwrap();
    }

    #[test]
    fn non_cors_request_return_empty_response() {
        let options = make_cors_options();
        let client = make_client();

        let request = client.options("/");
        let response = validate_and_build(&options, request.inner()).expect("to not fail");
        let expected_response = Response::new();
        assert_eq!(expected_response, response);
    }

    #[test]
    fn preflight_validated_and_built_correctly() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let response = validate_and_build(&options, request.inner()).expect("to not fail");

        let expected_response = Response::new()
            .origin(&FromStr::from_str("https://www.acme.com/").unwrap(), false)
            .headers(&["Authorization"])
            .methods(&options.allowed_methods)
            .credentials(options.allow_credentials)
            .max_age(options.max_age);

        assert_eq!(expected_response, response);
    }

    /// Tests that when All origins are allowed and send_wildcard disabled, the vary header is set
    /// in the response and the requested origin is echoed
    #[test]
    fn preflight_all_origins_with_vary() {
        let mut options = make_cors_options();
        options.allowed_origins = AllOrSome::All;
        options.send_wildcard = false;

        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let response = validate_and_build(&options, request.inner()).expect("to not fail");

        let expected_response = Response::new()
            .origin(&FromStr::from_str("https://www.acme.com/").unwrap(), true)
            .headers(&["Authorization"])
            .methods(&options.allowed_methods)
            .credentials(options.allow_credentials)
            .max_age(options.max_age);

        assert_eq!(expected_response, response);
    }

    /// Tests that when All origins are allowed and send_wildcard enabled, the origin is set to "*"
    #[test]
    fn preflight_all_origins_with_wildcard() {
        let mut options = make_cors_options();
        options.allowed_origins = AllOrSome::All;
        options.send_wildcard = true;
        options.allow_credentials = false;

        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let method_header = Header::from(hyper::header::AccessControlRequestMethod(
            hyper::method::Method::Get,
        ));
        let request_headers =
            hyper::header::AccessControlRequestHeaders(vec![
                FromStr::from_str("Authorization").unwrap()
            ]);
        let request_headers = Header::from(request_headers);

        let request = client
            .options("/")
            .header(origin_header)
            .header(method_header)
            .header(request_headers);

        let response = validate_and_build(&options, request.inner()).expect("to not fail");

        let expected_response = Response::new()
            .any()
            .headers(&["Authorization"])
            .methods(&options.allowed_methods)
            .credentials(options.allow_credentials)
            .max_age(options.max_age);

        assert_eq!(expected_response, response);
    }

    #[test]
    fn actual_request_validated_and_built_correctly() {
        let options = make_cors_options();
        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let request = client.get("/").header(origin_header);

        let response = validate_and_build(&options, request.inner()).expect("to not fail");
        let expected_response = Response::new()
            .origin(&FromStr::from_str("https://www.acme.com/").unwrap(), false)
            .credentials(options.allow_credentials)
            .exposed_headers(&["Content-Type", "X-Custom"]);

        assert_eq!(expected_response, response);
    }

    #[test]
    fn actual_request_all_origins_with_vary() {
        let mut options = make_cors_options();
        options.allowed_origins = AllOrSome::All;
        options.send_wildcard = false;
        options.allow_credentials = false;

        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let request = client.get("/").header(origin_header);

        let response = validate_and_build(&options, request.inner()).expect("to not fail");
        let expected_response = Response::new()
            .origin(&FromStr::from_str("https://www.acme.com/").unwrap(), true)
            .credentials(options.allow_credentials)
            .exposed_headers(&["Content-Type", "X-Custom"]);

        assert_eq!(expected_response, response);
    }

    #[test]
    fn actual_request_all_origins_with_wildcard() {
        let mut options = make_cors_options();
        options.allowed_origins = AllOrSome::All;
        options.send_wildcard = true;
        options.allow_credentials = false;

        let client = make_client();

        let origin_header =
            Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
        let request = client.get("/").header(origin_header);

        let response = validate_and_build(&options, request.inner()).expect("to not fail");
        let expected_response = Response::new()
            .any()
            .credentials(options.allow_credentials)
            .exposed_headers(&["Content-Type", "X-Custom"]);

        assert_eq!(expected_response, response);
    }
}