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
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
/// Helmet is a collection of HTTP headers that help secure your app by setting various HTTP headers.
///
/// ntex-helmet is a middleware that automatically sets these headers.
///
/// It is based on the [Helmet](https://helmetjs.github.io/) library for Node.js and is highly configurable.
use core::fmt::Display;
use std::rc::Rc;

use ntex::{
    forward_poll_ready, forward_poll_shutdown,
    http::header::{HeaderName, HeaderValue},
    util::BoxFuture,
    web::{WebRequest, WebResponse},
    Middleware, Service, ServiceCtx,
};

/// Header trait
///
/// Allows custom headers to be added to the response
///
/// # Examples
///
/// ```
/// use ntex_helmet::Header;
///
/// struct MyHeader;
///
/// impl Header for MyHeader {
///    fn name(&self) -> &'static str {
///       "My-Header"
///   }
///
///   fn value(&self) -> String {
///      "my-value".to_string()
///  }
/// }
/// ```
pub trait Header {
    fn name(&self) -> &'static str;
    fn value(&self) -> String;
}

/// Manages `Cross-Origin-Embedder-Policy` header
///
/// The Cross-Origin-Embedder-Policy HTTP response header prevents a document from loading any cross-origin resources that do not explicitly grant the document permission (via CORS headers) to load them.
///
/// # Values
///
/// - unsafe-none: The document is not subject to any Cross-Origin-Embedder-Policy restrictions.
/// - require-corp: The document is subject to Cross-Origin-Embedder-Policy restrictions.
/// - credentialless: The document is subject to Cross-Origin-Embedder-Policy restrictions, and is not allowed to request credentials (e.g. cookies, certificates, HTTP authentication) from the user.
///
/// # Examples
///
/// ```
/// use ntex_helmet::CrossOriginEmbedderPolicy;
///
/// let cross_origin_embedder_policy = CrossOriginEmbedderPolicy::unsafe_none();
///
/// let cross_origin_embedder_policy = CrossOriginEmbedderPolicy::require_corp();
///
/// let cross_origin_embedder_policy = CrossOriginEmbedderPolicy::credentialless();
/// ```
#[derive(Clone)]
pub enum CrossOriginEmbedderPolicy {
    UnsafeNone,
    RequireCorp,
    Credentialless,
}

impl CrossOriginEmbedderPolicy {
    pub fn unsafe_none() -> Self {
        Self::UnsafeNone
    }

    pub fn require_corp() -> Self {
        Self::RequireCorp
    }

    pub fn credentialless() -> Self {
        Self::Credentialless
    }
}

impl Display for CrossOriginEmbedderPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CrossOriginEmbedderPolicy::UnsafeNone => write!(f, "unsafe-none"),
            CrossOriginEmbedderPolicy::RequireCorp => write!(f, "require-corp"),
            CrossOriginEmbedderPolicy::Credentialless => write!(f, "credentialless"),
        }
    }
}

impl Header for CrossOriginEmbedderPolicy {
    fn name(&self) -> &'static str {
        "Cross-Origin-Embedder-Policy"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `Cross-Origin-Opener-Policy` header
///
/// The Cross-Origin-Opener-Policy HTTP response header restricts how selected resources are allowed to interact with the document's browsing context in response to user navigation. Each resource can declare an opener policy which applies to the resource's corresponding browsing context.
///
/// # Values
///
/// - same-origin: The resource's browsing context is the same-origin as the document's browsing context.
/// - same-origin-allow-popups: The resource's browsing context is the same-origin as the document's browsing context, and the resource is allowed to open new browsing contexts.
/// - unsafe-none: The resource's browsing context is cross-origin with the document's browsing context.
///
/// # Examples
///
/// ```
/// use ntex_helmet::CrossOriginOpenerPolicy;
///
/// let cross_origin_opener_policy = CrossOriginOpenerPolicy::same_origin();
/// ```
#[derive(Clone)]
pub enum CrossOriginOpenerPolicy {
    SameOrigin,
    SameOriginAllowPopups,
    UnsafeNone,
}

impl CrossOriginOpenerPolicy {
    pub fn same_origin() -> Self {
        Self::SameOrigin
    }

    pub fn same_origin_allow_popups() -> Self {
        Self::SameOriginAllowPopups
    }

    pub fn unsafe_none() -> Self {
        Self::UnsafeNone
    }
}

impl Display for CrossOriginOpenerPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CrossOriginOpenerPolicy::SameOrigin => write!(f, "same-origin"),
            CrossOriginOpenerPolicy::SameOriginAllowPopups => write!(f, "same-origin-allow-popups"),
            CrossOriginOpenerPolicy::UnsafeNone => write!(f, "unsafe-none"),
        }
    }
}

impl Header for CrossOriginOpenerPolicy {
    fn name(&self) -> &'static str {
        "Cross-Origin-Opener-Policy"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `Cross-Origin-Resource-Policy` header
///
/// The Cross-Origin-Resource-Policy HTTP response header conveys a desire that the browser blocks no-cors cross-origin/cross-site requests to the given resource.
///
/// # Values
///
/// - same-origin: The resource is same-origin to the document.
/// - same-site: The resource is same-site to the document.
/// - cross-origin: The resource is cross-origin to the document.
///
/// # Examples
///
/// ```
/// use ntex_helmet::CrossOriginResourcePolicy;
///
/// let cross_origin_resource_policy = CrossOriginResourcePolicy::same_origin();
/// ```
#[derive(Clone)]
pub enum CrossOriginResourcePolicy {
    SameOrigin,
    SameSite,
    CrossOrigin,
}

impl CrossOriginResourcePolicy {
    pub fn same_origin() -> Self {
        Self::SameOrigin
    }

    pub fn same_site() -> Self {
        Self::SameSite
    }

    pub fn cross_origin() -> Self {
        Self::CrossOrigin
    }
}

impl Display for CrossOriginResourcePolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CrossOriginResourcePolicy::SameOrigin => write!(f, "same-origin"),
            CrossOriginResourcePolicy::SameSite => write!(f, "same-site"),
            CrossOriginResourcePolicy::CrossOrigin => write!(f, "cross-origin"),
        }
    }
}

impl Header for CrossOriginResourcePolicy {
    fn name(&self) -> &'static str {
        "Cross-Origin-Resource-Policy"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `Origin-Agent-Cluster` header
///
/// The Origin-Agent-Cluster HTTP request header indicates that the client prefers an "origin agent cluster" (OAC) for the origin of the resource being requested. An OAC is a cluster of servers that are controlled by the same entity as the origin server, and that are geographically close to the client. The OAC is used to provide the client with a better experience, for example by serving content from a server that is close to the client, or by serving content that is optimized for the client's device.
///
/// # Values
///
/// - 0: The client does not prefer an OAC.
/// - 1: The client prefers an OAC.
///
/// # Examples
///
/// ```
/// use ntex_helmet::OriginAgentCluster;
///
/// let origin_agent_cluster = OriginAgentCluster::new(true);
/// ```
#[derive(Clone)]
pub struct OriginAgentCluster(bool);

impl OriginAgentCluster {
    pub fn new(prefer_mobile_experience: bool) -> Self {
        Self(prefer_mobile_experience)
    }
}

impl Display for OriginAgentCluster {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.0 {
            write!(f, "?1")
        } else {
            write!(f, "?0")
        }
    }
}

impl Header for OriginAgentCluster {
    fn name(&self) -> &'static str {
        "Origin-Agent-Cluster"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `Referrer-Policy` header
///
/// The Referrer-Policy HTTP response header controls how much referrer information (sent via the Referer header) should be included with requests.
///
/// # Values
///
/// - no-referrer: The Referer header will be omitted entirely. No referrer information is sent along with requests.
/// - no-referrer-when-downgrade: The Referer header will be omitted entirely. However, if the protected resource URL scheme is HTTPS, then the full path will still be sent as a referrer.
/// - origin: Only send the origin of the document as the referrer in all cases. The document https://example.com/page.html will send the referrer https://example.com/.
/// - origin-when-cross-origin: Send a full URL when performing a same-origin request, but only send the origin of the document for other cases.
/// - same-origin: A referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information.
/// - strict-origin: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
/// - strict-origin-when-cross-origin: Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
/// - unsafe-url: Send a full URL (stripped from parameters) when performing a same-origin or cross-origin request. This policy will leak origins and paths from TLS-protected resources to insecure origins. Carefully consider the impact of this setting.
///
/// # Examples
///
/// ```
/// use ntex_helmet::ReferrerPolicy;
///
/// let referrer_policy = ReferrerPolicy::no_referrer();
/// ```
#[derive(Clone)]
pub enum ReferrerPolicy {
    NoReferrer,
    NoReferrerWhenDowngrade,
    Origin,
    OriginWhenCrossOrigin,
    SameOrigin,
    StrictOrigin,
    StrictOriginWhenCrossOrigin,
    UnsafeUrl,
}

impl ReferrerPolicy {
    pub fn no_referrer() -> Self {
        Self::NoReferrer
    }

    pub fn no_referrer_when_downgrade() -> Self {
        Self::NoReferrerWhenDowngrade
    }

    pub fn origin() -> Self {
        Self::Origin
    }

    pub fn origin_when_cross_origin() -> Self {
        Self::OriginWhenCrossOrigin
    }

    pub fn same_origin() -> Self {
        Self::SameOrigin
    }

    pub fn strict_origin() -> Self {
        Self::StrictOrigin
    }

    pub fn strict_origin_when_cross_origin() -> Self {
        Self::StrictOriginWhenCrossOrigin
    }

    pub fn unsafe_url() -> Self {
        Self::UnsafeUrl
    }
}

impl Display for ReferrerPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReferrerPolicy::NoReferrer => write!(f, "no-referrer"),
            ReferrerPolicy::NoReferrerWhenDowngrade => write!(f, "no-referrer-when-downgrade"),
            ReferrerPolicy::Origin => write!(f, "origin"),
            ReferrerPolicy::OriginWhenCrossOrigin => write!(f, "origin-when-cross-origin"),
            ReferrerPolicy::SameOrigin => write!(f, "same-origin"),
            ReferrerPolicy::StrictOrigin => write!(f, "strict-origin"),
            ReferrerPolicy::StrictOriginWhenCrossOrigin => {
                write!(f, "strict-origin-when-cross-origin")
            }
            ReferrerPolicy::UnsafeUrl => write!(f, "unsafe-url"),
        }
    }
}

impl Header for ReferrerPolicy {
    fn name(&self) -> &'static str {
        "Referrer-Policy"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `Strict-Transport-Security` header
///
/// The Strict-Transport-Security HTTP response header (often abbreviated as HSTS) lets a web site tell browsers that it should only be accessed using HTTPS, instead of using HTTP.
///
/// # Values
///
/// - max-age: The time, in seconds, that the browser should remember that a site is only to be accessed using HTTPS.
/// - includeSubDomains: If this optional parameter is specified, this rule applies to all of the site's subdomains as well.
/// - preload: If this optional parameter is specified, this rule applies to all of the site's subdomains as well.
///
/// # Examples
///
/// ```
/// use ntex_helmet::StrictTransportSecurity;
///
/// let strict_transport_security = StrictTransportSecurity::default();
///
/// let custom_strict_transport_security = StrictTransportSecurity::default()
///    .max_age(31536000)
///    .include_sub_domains()
///    .preload();
/// ```
#[derive(Clone)]
pub struct StrictTransportSecurity {
    max_age: u32,
    include_sub_domains: bool,
    preload: bool,
}

impl StrictTransportSecurity {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn max_age(mut self, max_age: u32) -> Self {
        self.max_age = max_age;
        self
    }

    pub fn include_sub_domains(mut self) -> Self {
        self.include_sub_domains = true;
        self
    }

    pub fn preload(mut self) -> Self {
        self.preload = true;
        self
    }
}

impl Default for StrictTransportSecurity {
    fn default() -> Self {
        Self {
            max_age: 31536000,
            include_sub_domains: false,
            preload: false,
        }
    }
}

impl Display for StrictTransportSecurity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "max-age={}", self.max_age)?;
        if self.include_sub_domains {
            write!(f, "; includeSubDomains")?;
        }
        if self.preload {
            write!(f, "; preload")?;
        }
        Ok(())
    }
}

impl Header for StrictTransportSecurity {
    fn name(&self) -> &'static str {
        "Strict-Transport-Security"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `X-Content-Type-Options` header
///
/// The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and be followed. This allows to opt-out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.
///
/// # Values
///
/// - nosniff: Prevents the browser from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions.
///
/// # Examples
///
/// ```
/// use ntex_helmet::XContentTypeOptions;
///
/// let x_content_type_options = XContentTypeOptions::nosniff();
/// ```
#[derive(Clone)]
pub enum XContentTypeOptions {
    NoSniff,
}

impl XContentTypeOptions {
    pub fn nosniff() -> Self {
        Self::NoSniff
    }
}

impl Display for XContentTypeOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XContentTypeOptions::NoSniff => write!(f, "nosniff"),
        }
    }
}

impl Header for XContentTypeOptions {
    fn name(&self) -> &'static str {
        "X-Content-Type-Options"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `X-DNS-Prefetch-Control` header
///
/// The X-DNS-Prefetch-Control HTTP response header controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth.
///
/// # Values
///
/// - off: Disable DNS prefetching.
/// - on: Enable DNS prefetching, allowing the browser to proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth.
///
/// # Examples
///
/// ```
/// use ntex_helmet::XDNSPrefetchControl;
///
/// let x_dns_prefetch_control = XDNSPrefetchControl::off();
/// ```
#[derive(Clone)]
pub enum XDNSPrefetchControl {
    Off,
    On,
}

impl XDNSPrefetchControl {
    pub fn off() -> Self {
        Self::Off
    }

    pub fn on() -> Self {
        Self::On
    }
}

impl Display for XDNSPrefetchControl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XDNSPrefetchControl::Off => write!(f, "off"),
            XDNSPrefetchControl::On => write!(f, "on"),
        }
    }
}

impl Header for XDNSPrefetchControl {
    fn name(&self) -> &'static str {
        "X-DNS-Prefetch-Control"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `X-Download-Options` header
///
/// The X-Download-Options HTTP response header indicates that the browser (Internet Explorer) should not display the option to "Open" a file that has been downloaded from an application, to prevent phishing attacks that could trick users into opening potentially malicious content that could infect their computer.
///
/// # Values
///
/// - noopen: Prevents Internet Explorer from executing downloads in your site’s context.
///
/// # Examples
///
/// ```
/// use ntex_helmet::XDownloadOptions;
///
/// let x_download_options = XDownloadOptions::noopen();
/// ```
#[derive(Clone)]
pub enum XDownloadOptions {
    NoOpen,
}

impl XDownloadOptions {
    pub fn noopen() -> Self {
        Self::NoOpen
    }
}

impl Display for XDownloadOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XDownloadOptions::NoOpen => write!(f, "noopen"),
        }
    }
}

impl Header for XDownloadOptions {
    fn name(&self) -> &'static str {
        "X-Download-Options"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `X-Frame-Options` header
///
/// The X-Frame-Options HTTP response header can be used to to avoid click-jacking attacks by preventing the content to be included in other websites.
///
/// # Values
///
/// - deny: The page cannot be displayed in a frame, regardless of the site attempting to do so.
/// - sameorigin: The page can only be displayed in a frame on the same origin as the page itself.
/// - allow-from: The page can only be displayed in a frame on the specified origin. Requires a URI as an argument.
///
/// # Examples
///
/// ```
/// use ntex_helmet::XFrameOptions;
///
/// let x_frame_options = XFrameOptions::deny();
///
/// let x_frame_options = XFrameOptions::same_origin();
///
/// let x_frame_options = XFrameOptions::allow_from("https://example.com");
/// ```
#[derive(Clone)]
pub enum XFrameOptions {
    Deny,
    SameOrigin,
    // deprecated - use Content-Security-Policy instead see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options#allow-from_origin
    AllowFrom(String),
}

impl XFrameOptions {
    pub fn deny() -> Self {
        Self::Deny
    }

    pub fn same_origin() -> Self {
        Self::SameOrigin
    }

    pub fn allow_from(uri: &str) -> Self {
        Self::AllowFrom(uri.to_string())
    }
}

impl Display for XFrameOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XFrameOptions::Deny => write!(f, "DENY"),
            XFrameOptions::SameOrigin => write!(f, "SAMEORIGIN"),
            XFrameOptions::AllowFrom(uri) => write!(f, "ALLOW-FROM {}", uri),
        }
    }
}

impl Header for XFrameOptions {
    fn name(&self) -> &'static str {
        "X-Frame-Options"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `X-Permitted-Cross-Domain-Policies` header
///
/// The X-Permitted-Cross-Domain-Policies HTTP response header determines whether cross-domain policy files (crossdomain.xml and clientaccesspolicy.xml) will be ignored by Flash and Adobe Acrobat in subsequent requests.
///
/// # Values
///
/// - none: No policy file is allowed.
/// - master-only: Only a master policy file, but no other policy files, is allowed.
/// - by-content-type: A policy file is allowed if its MIME type matches the Content-Type of the requested resource.
/// - by-ftp-filename: A policy file is allowed if its URL matches the URL of the requested resource.
/// - all: Any policy file is allowed.
///
/// # Examples
///
/// ```
/// use ntex_helmet::XPermittedCrossDomainPolicies;
///
/// let x_permitted_cross_domain_policies = XPermittedCrossDomainPolicies::none();
///
/// let x_permitted_cross_domain_policies = XPermittedCrossDomainPolicies::master_only();
///
/// let x_permitted_cross_domain_policies = XPermittedCrossDomainPolicies::by_content_type();
///
/// let x_permitted_cross_domain_policies = XPermittedCrossDomainPolicies::by_ftp_filename();
///
/// let x_permitted_cross_domain_policies = XPermittedCrossDomainPolicies::all();
/// ```
#[derive(Clone)]
pub enum XPermittedCrossDomainPolicies {
    None,
    MasterOnly,
    ByContentType,
    ByFtpFilename,
    All,
}

impl XPermittedCrossDomainPolicies {
    pub fn none() -> Self {
        Self::None
    }

    pub fn master_only() -> Self {
        Self::MasterOnly
    }

    pub fn by_content_type() -> Self {
        Self::ByContentType
    }

    pub fn by_ftp_filename() -> Self {
        Self::ByFtpFilename
    }

    pub fn all() -> Self {
        Self::All
    }
}

impl Display for XPermittedCrossDomainPolicies {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XPermittedCrossDomainPolicies::None => write!(f, "none"),
            XPermittedCrossDomainPolicies::MasterOnly => write!(f, "master-only"),
            XPermittedCrossDomainPolicies::ByContentType => write!(f, "by-content-type"),
            XPermittedCrossDomainPolicies::ByFtpFilename => write!(f, "by-ftp-filename"),
            XPermittedCrossDomainPolicies::All => write!(f, "all"),
        }
    }
}

impl Header for XPermittedCrossDomainPolicies {
    fn name(&self) -> &'static str {
        "X-Permitted-Cross-Domain-Policies"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `X-XSS-Protection` header
///
/// The HTTP X-XSS-Protection response header is a feature of Internet Explorer, Chrome and Safari that stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. Although these protections are largely unnecessary in modern browsers when sites implement a strong Content-Security-Policy that disables the use of inline JavaScript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support CSP.
///
/// # Values
///
/// - 0: Disables XSS filtering.
/// - 1: Enables XSS filtering (usually default in browsers).
/// - 1; mode=block: Enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.
/// - 1; report=<reporting-URI>: Enables XSS filtering. If a cross-site scripting attack is detected, the browser will sanitize the page and report the violation. This uses the functionality of the CSP report-uri directive to send a report.
///
/// # Examples
///
/// ```
/// use ntex_helmet::XXSSProtection;
///
/// let x_xss_protection = XXSSProtection::on();
///
/// let x_xss_protection = XXSSProtection::off();
///
/// let x_xss_protection = XXSSProtection::on().mode_block();
///
/// let x_xss_protection = XXSSProtection::on().report("https://example.com");
///
/// let x_xss_protection = XXSSProtection::on().mode_block().report("https://example.com");
/// ```
#[derive(Clone)]
pub struct XXSSProtection {
    on: bool,
    mode_block: bool,
    report: Option<String>,
}

impl XXSSProtection {
    /// Disables XSS filtering.
    pub fn off() -> Self {
        Self {
            on: false,
            mode_block: false,
            report: None,
        }
    }

    /// Enables XSS filtering (usually default in browsers).
    pub fn on() -> Self {
        Self {
            on: true,
            mode_block: false,
            report: None,
        }
    }

    /// Enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.
    pub fn mode_block(mut self) -> Self {
        self.mode_block = true;
        self
    }

    /// Enables XSS filtering. If a cross-site scripting attack is detected, the browser will sanitize the page and report the violation. This uses the functionality of the CSP report-uri directive to send a report.
    pub fn report(mut self, report: &str) -> Self {
        self.report = Some(report.to_string());
        self
    }
}

impl Display for XXSSProtection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.on {
            write!(f, "1")?;
            if self.mode_block {
                write!(f, "; mode=block")?;
            }
            if let Some(report) = &self.report {
                write!(f, "; report={}", report)?;
            }
        } else {
            write!(f, "0")?;
        }
        Ok(())
    }
}

impl Header for XXSSProtection {
    fn name(&self) -> &'static str {
        "X-XSS-Protection"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `X-Powered-By` header
///
/// ntex does not set `X-Powered-By` header by default.
/// Instead of silencing the header, Helmet allows you to set it to a custom value.
/// This can be useful against primitive fingerprinting.
///
/// # Examples
///
/// ```
/// use ntex_helmet::XPoweredBy;
///
/// let x_powered_by = XPoweredBy::new("PHP 4.2.0");
/// ```
#[derive(Clone)]
pub struct XPoweredBy(String);

impl XPoweredBy {
    /// Set the `X-Powered-By` header to a custom value.
    pub fn new(comment: &str) -> Self {
        Self(comment.to_string())
    }
}

impl Display for XPoweredBy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)?;
        Ok(())
    }
}

impl Header for XPoweredBy {
    fn name(&self) -> &'static str {
        "X-Powered-By"
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Manages `Content-Security-Policy` header
///
/// The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS).
///
/// # Directives
///
/// - child-src: Defines valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>.
/// - connect-src: Applies to XMLHttpRequest (AJAX), WebSocket or EventSource. If not allowed the browser emulates a 400 HTTP status code.
/// - default-src: The default-src is the default policy for loading content such as JavaScript, Images, CSS, Font's, AJAX requests, Frames, HTML5 Media. See the list of directives to see which values are allowed as default.
/// - font-src: Defines valid sources for fonts loaded using @font-face.
/// - frame-src: Defines valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>.
/// - img-src: Defines valid sources of images and favicons.
/// - manifest-src: Specifies which manifest can be applied to the resource.
/// - media-src: Defines valid sources for loading media using the <audio> and <video> elements.
/// - object-src: Defines valid sources for the <object>, <embed>, and <applet> elements.
/// - prefetch-src: Specifies which referrer to use when fetching the resource.
/// - script-src: Defines valid sources for JavaScript.
/// - script-src-elem: Defines valid sources for JavaScript inline event handlers.
/// - script-src-attr: Defines valid sources for JavaScript inline event handlers.
/// - style-src: Defines valid sources for stylesheets.
/// - style-src-elem: Defines valid sources for stylesheets inline event handlers.
/// - style-src-attr: Defines valid sources for stylesheets inline event handlers.
/// - worker-src: Defines valid sources for Worker, SharedWorker, or ServiceWorker scripts.
/// - base-uri: Restricts the URLs which can be used in a document's <base> element.
/// - sandbox: Enables a sandbox for the requested resource similar to the iframe sandbox attribute. The sandbox applies a same origin policy, prevents popups, plugins and script execution is blocked. You can keep the sandbox value empty to keep all restrictions in place, or add values: allow-forms allow-same-origin allow-scripts allow-popups, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-presentation, allow-popups-to-escape-sandbox, allow-top-navigation, allow-top-navigation-by-user-activation.
/// - form-action: Restricts the URLs which can be used as the target of a form submissions from a given context.
/// - frame-ancestors: Specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>.
/// - report-to: Enables reporting of violations.
/// - require-trusted-types-for: Specifies which trusted types are required by a resource.
/// - trusted-types: Specifies which trusted types are defined by a resource.
/// - upgrade-insecure-requests: Block HTTP requests on insecure elements.
///
/// # Examples
///
/// ```
/// use ntex_helmet::ContentSecurityPolicy;
///
/// let content_security_policy = ContentSecurityPolicy::default()
///    .child_src(vec!["'self'", "https://youtube.com"])
///    .connect_src(vec!["'self'", "https://youtube.com"])
///    .default_src(vec!["'self'", "https://youtube.com"])
///    .font_src(vec!["'self'", "https://youtube.com"]);
/// ```
#[derive(Clone)]
pub enum ContentSecurityPolicyDirective<'a> {
    /// Warning: Instead of child-src, if you want to regulate nested browsing contexts and workers, you should use the frame-src and worker-src directives, respectively.
    ChildSrc(Vec<&'a str>),
    /// Applies to XMLHttpRequest (AJAX), WebSocket or EventSource. If not allowed the browser emulates a 400 HTTP status code.
    ConnectSrc(Vec<&'a str>),
    /// The default-src is the default policy for loading content such as JavaScript, Images, CSS, Font's, AJAX requests, Frames, HTML5 Media. See the list of directives to see which values are allowed as default.
    DefaultSrc(Vec<&'a str>),
    /// Defines valid sources for fonts loaded using @font-face.
    FontSrc(Vec<&'a str>),
    /// Defines valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>.
    FrameSrc(Vec<&'a str>),
    /// Defines valid sources of images and favicons.
    ImgSrc(Vec<&'a str>),
    /// Specifies which manifest can be applied to the resource.
    ManifestSrc(Vec<&'a str>),
    /// Defines valid sources for loading media using the <audio> and <video> elements.
    MediaSrc(Vec<&'a str>),
    /// Defines valid sources for the <object>, <embed>, and <applet> elements.
    ObjectSrc(Vec<&'a str>),
    /// Specifies which referrer to use when fetching the resource.
    PrefetchSrc(Vec<&'a str>),
    /// Defines valid sources for JavaScript.
    ScriptSrc(Vec<&'a str>),
    /// Defines valid sources for JavaScript inline event handlers.
    ScriptSrcElem(Vec<&'a str>),
    /// Defines valid sources for JavaScript inline event handlers.
    ScriptSrcAttr(Vec<&'a str>),
    /// Defines valid sources for stylesheets.
    StyleSrc(Vec<&'a str>),
    /// Defines valid sources for stylesheets inline event handlers.
    StyleSrcElem(Vec<&'a str>),
    /// Defines valid sources for stylesheets inline event handlers.
    StyleSrcAttr(Vec<&'a str>),
    /// Defines valid sources for Worker, SharedWorker, or ServiceWorker scripts.
    WorkerSrc(Vec<&'a str>),
    // Document directives
    /// Restricts the URLs which can be used in a document's <base> element.
    BaseUri(Vec<&'a str>),
    /// Enables a sandbox for the requested resource similar to the iframe sandbox attribute. The sandbox applies a same origin policy, prevents popups, plugins and script execution is blocked. You can keep the sandbox value empty to keep all restrictions in place, or add values: allow-forms allow-same-origin allow-scripts allow-popups, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-presentation, allow-popups-to-escape-sandbox, allow-top-navigation, allow-top-navigation-by-user-activation.
    Sandbox(Vec<&'a str>),
    // Navigation directives
    /// Restricts the URLs which can be used as the target of a form submissions from a given context.
    FormAction(Vec<&'a str>),
    /// Specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>.
    FrameAncestors(Vec<&'a str>),
    // Reporting directives
    /// Enables reporting of violations.
    ///
    /// report-uri is deprecated, however, it is still supported by browsers that don't yet support report-to. ReportTo will apply both to report-uri and report-to with the same values, to support browsers that support both.
    ReportTo(Vec<&'a str>),
    // Other
    /// Specifies which trusted types are required by a resource.
    RequireTrustedTypesFor(Vec<&'a str>),
    /// Specifies which trusted types are defined by a resource.
    TrustedTypes(Vec<&'a str>),
    /// Block HTTP requests on insecure elements.
    UpgradeInsecureRequests,
}

impl<'a> ContentSecurityPolicyDirective<'a> {
    /// child-src: Defines valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>.
    pub fn child_src(values: Vec<&'a str>) -> Self {
        Self::ChildSrc(values)
    }

    /// connect-src: Applies to XMLHttpRequest (AJAX), WebSocket or EventSource. If not allowed the browser emulates a 400 HTTP status code.
    pub fn connect_src(values: Vec<&'a str>) -> Self {
        Self::ConnectSrc(values)
    }

    /// default-src: The default-src is the default policy for loading content such as JavaScript, Images, CSS, Font's, AJAX requests, Frames, HTML5 Media. See the list of directives to see which values are allowed as default.
    pub fn default_src(values: Vec<&'a str>) -> Self {
        Self::DefaultSrc(values)
    }

    /// font-src: Defines valid sources for fonts loaded using @font-face.
    pub fn font_src(values: Vec<&'a str>) -> Self {
        Self::FontSrc(values)
    }

    /// frame-src: Defines valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>.
    pub fn frame_src(values: Vec<&'a str>) -> Self {
        Self::FrameSrc(values)
    }

    /// img-src: Defines valid sources of images and favicons.
    pub fn img_src(values: Vec<&'a str>) -> Self {
        Self::ImgSrc(values)
    }

    /// manifest-src: Specifies which manifest can be applied to the resource.
    pub fn manifest_src(values: Vec<&'a str>) -> Self {
        Self::ManifestSrc(values)
    }

    /// media-src: Defines valid sources for loading media using the <audio> and <video> elements.
    pub fn media_src(values: Vec<&'a str>) -> Self {
        Self::MediaSrc(values)
    }

    /// object-src: Defines valid sources for the <object>, <embed>, and <applet> elements.
    pub fn object_src(values: Vec<&'a str>) -> Self {
        Self::ObjectSrc(values)
    }

    /// prefetch-src: Specifies which referrer to use when fetching the resource.
    pub fn prefetch_src(values: Vec<&'a str>) -> Self {
        Self::PrefetchSrc(values)
    }

    /// script-src: Defines valid sources for JavaScript.
    pub fn script_src(values: Vec<&'a str>) -> Self {
        Self::ScriptSrc(values)
    }

    /// script-src-elem: Defines valid sources for JavaScript inline event handlers.
    pub fn script_src_elem(values: Vec<&'a str>) -> Self {
        Self::ScriptSrcElem(values)
    }

    /// script-src-attr: Defines valid sources for JavaScript inline event handlers.
    pub fn script_src_attr(values: Vec<&'a str>) -> Self {
        Self::ScriptSrcAttr(values)
    }

    /// style-src: Defines valid sources for stylesheets.
    pub fn style_src(values: Vec<&'a str>) -> Self {
        Self::StyleSrc(values)
    }

    /// style-src-elem: Defines valid sources for stylesheets inline event handlers.
    pub fn style_src_elem(values: Vec<&'a str>) -> Self {
        Self::StyleSrcElem(values)
    }

    /// style-src-attr: Defines valid sources for stylesheets inline event handlers.
    pub fn style_src_attr(values: Vec<&'a str>) -> Self {
        Self::StyleSrcAttr(values)
    }

    /// worker-src: Defines valid sources for Worker, SharedWorker, or ServiceWorker scripts.
    pub fn worker_src(values: Vec<&'a str>) -> Self {
        Self::WorkerSrc(values)
    }

    /// base-uri: Restricts the URLs which can be used in a document's <base> element.
    pub fn base_uri(values: Vec<&'a str>) -> Self {
        Self::BaseUri(values)
    }

    /// sandbox: Enables a sandbox for the requested resource similar to the iframe sandbox attribute. The sandbox applies a same origin policy, prevents popups, plugins and script execution is blocked. You can keep the sandbox value empty to keep all restrictions in place, or add values: allow-forms allow-same-origin allow-scripts allow-popups, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-presentation, allow-popups-to-escape-sandbox, allow-top-navigation, allow-top-navigation-by-user-activation.
    pub fn sandbox(values: Vec<&'a str>) -> Self {
        Self::Sandbox(values)
    }

    /// form-action: Restricts the URLs which can be used as the target of a form submissions from a given context.
    pub fn form_action(values: Vec<&'a str>) -> Self {
        Self::FormAction(values)
    }

    /// frame-ancestors: Specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>.
    pub fn frame_ancestors(values: Vec<&'a str>) -> Self {
        Self::FrameAncestors(values)
    }

    /// report-to: Enables reporting of violations.
    pub fn report_to(values: Vec<&'a str>) -> Self {
        Self::ReportTo(values)
    }

    /// require-trusted-types-for: Specifies which trusted types are required by a resource.
    pub fn require_trusted_types_for(values: Vec<&'a str>) -> Self {
        Self::RequireTrustedTypesFor(values)
    }

    /// trusted-types: Specifies which trusted types are defined by a resource.
    pub fn trusted_types(values: Vec<&'a str>) -> Self {
        Self::TrustedTypes(values)
    }

    /// Block HTTP requests on insecure elements.
    pub fn upgrade_insecure_requests() -> Self {
        Self::UpgradeInsecureRequests
    }
}

impl Display for ContentSecurityPolicyDirective<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ContentSecurityPolicyDirective::ChildSrc(values) => {
                write!(f, "child-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ConnectSrc(values) => {
                write!(f, "connect-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::DefaultSrc(values) => {
                write!(f, "default-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::FontSrc(values) => {
                write!(f, "font-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::FrameSrc(values) => {
                write!(f, "frame-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ImgSrc(values) => {
                write!(f, "img-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ManifestSrc(values) => {
                write!(f, "manifest-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::MediaSrc(values) => {
                write!(f, "media-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ObjectSrc(values) => {
                write!(f, "object-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::PrefetchSrc(values) => {
                write!(f, "prefetch-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ScriptSrc(values) => {
                write!(f, "script-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ScriptSrcElem(values) => {
                write!(f, "script-src-elem {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ScriptSrcAttr(values) => {
                write!(f, "script-src-attr {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::StyleSrc(values) => {
                write!(f, "style-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::StyleSrcElem(values) => {
                write!(f, "style-src-elem {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::StyleSrcAttr(values) => {
                write!(f, "style-src-attr {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::WorkerSrc(values) => {
                write!(f, "worker-src {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::BaseUri(values) => {
                write!(f, "base-uri {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::Sandbox(values) => {
                write!(f, "sandbox {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::FormAction(values) => {
                write!(f, "form-action {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::FrameAncestors(values) => {
                write!(f, "frame-ancestors {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::ReportTo(values) => {
                let values = values.join(" ");
                write!(f, "report-to {}; report-uri {}", values, values)
            }
            ContentSecurityPolicyDirective::RequireTrustedTypesFor(values) => {
                write!(f, "require-trusted-types-for {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::TrustedTypes(values) => {
                write!(f, "trusted-types {}", values.join(" "))
            }
            ContentSecurityPolicyDirective::UpgradeInsecureRequests => {
                write!(f, "upgrade-insecure-requests")
            }
        }
    }
}

/// Manages `Content-Security-Policy` header
///
/// The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS).
///
/// # Examples
///
/// ```
/// use ntex_helmet::ContentSecurityPolicy;
///
/// let content_security_policy = ContentSecurityPolicy::default()
///    .child_src(vec!["'self'", "https://youtube.com"])
///    .connect_src(vec!["'self'", "https://youtube.com"])
///    .default_src(vec!["'self'", "https://youtube.com"])
///    .font_src(vec!["'self'", "https://youtube.com"]);
/// ```
///
/// ## Report only
///
/// In report only mode, the browser will not block the request, but will send a report to the specified URI.
///
/// Make sure to set the `report-to` directive.
///
/// ```
/// use ntex_helmet::ContentSecurityPolicy;
///
/// let content_security_policy = ContentSecurityPolicy::default()
///    .child_src(vec!["'self'", "https://youtube.com"])
///    .report_to(vec!["https://example.com/report"])
///    .report_only();
/// ```
#[derive(Clone)]
pub struct ContentSecurityPolicy<'a> {
    directives: Vec<ContentSecurityPolicyDirective<'a>>,
    report_only: bool,
}

impl<'a> ContentSecurityPolicy<'a> {
    pub fn new() -> Self {
        Self {
            directives: Vec::new(),
            report_only: false,
        }
    }

    fn directive(mut self, directive: ContentSecurityPolicyDirective<'a>) -> Self {
        self.directives.push(directive);
        self
    }

    /// child-src: Defines valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>.
    pub fn child_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::child_src(values))
    }

    /// connect-src: Applies to XMLHttpRequest (AJAX), WebSocket or EventSource. If not allowed the browser emulates a 400 HTTP status code.
    pub fn connect_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::connect_src(values))
    }

    /// default-src: The default-src is the default policy for loading content such as JavaScript, Images, CSS, Font's, AJAX requests, Frames, HTML5 Media. See the list of directives to see which values are allowed as default.
    pub fn default_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::default_src(values))
    }

    /// font-src: Defines valid sources for fonts loaded using @font-face.
    pub fn font_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::font_src(values))
    }

    /// frame-src: Defines valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>.
    pub fn frame_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::frame_src(values))
    }

    /// img-src: Defines valid sources of images and favicons.
    pub fn img_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::img_src(values))
    }

    /// manifest-src: Specifies which manifest can be applied to the resource.
    pub fn manifest_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::manifest_src(values))
    }

    /// media-src: Defines valid sources for loading media using the <audio> and <video> elements.
    pub fn media_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::media_src(values))
    }

    /// object-src: Defines valid sources for the <object>, <embed>, and <applet> elements.
    pub fn object_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::object_src(values))
    }

    /// prefetch-src: Specifies which referrer to use when fetching the resource.
    pub fn prefetch_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::prefetch_src(values))
    }

    /// script-src: Defines valid sources for JavaScript.
    pub fn script_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::script_src(values))
    }

    /// script-src-elem: Defines valid sources for JavaScript inline event handlers.
    pub fn script_src_elem(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::script_src_elem(values))
    }

    /// script-src-attr: Defines valid sources for JavaScript inline event handlers.
    pub fn script_src_attr(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::script_src_attr(values))
    }

    /// style-src: Defines valid sources for stylesheets.
    pub fn style_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::style_src(values))
    }

    /// style-src-elem: Defines valid sources for stylesheets inline event handlers.
    pub fn style_src_elem(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::style_src_elem(values))
    }

    /// style-src-attr: Defines valid sources for stylesheets inline event handlers.
    pub fn style_src_attr(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::style_src_attr(values))
    }

    /// worker-src: Defines valid sources for Worker, SharedWorker, or ServiceWorker scripts.
    pub fn worker_src(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::worker_src(values))
    }

    /// base-uri: Restricts the URLs which can be used in a document's <base> element.
    pub fn base_uri(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::base_uri(values))
    }

    /// sandbox: Enables a sandbox for the requested resource similar to the iframe sandbox attribute. The sandbox applies a same origin policy, prevents popups, plugins and script execution is blocked. You can keep the sandbox value empty to keep all restrictions in place, or add values: allow-forms allow-same-origin allow-scripts allow-popups, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-presentation, allow-popups-to-escape-sandbox, allow-top-navigation, allow-top-navigation-by-user-activation.
    pub fn sandbox(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::sandbox(values))
    }

    /// form-action: Restricts the URLs which can be used as the target of a form submissions from a given context.
    pub fn form_action(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::form_action(values))
    }

    /// frame-ancestors: Specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>.
    pub fn frame_ancestors(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::frame_ancestors(values))
    }

    /// report-to: Enables reporting of violations.
    pub fn report_to(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::report_to(values))
    }

    /// require-trusted-types-for: Specifies which trusted types are required by a resource.
    pub fn require_trusted_types_for(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::require_trusted_types_for(
            values,
        ))
    }

    /// trusted-types: Specifies which trusted types are defined by a resource.
    pub fn trusted_types(self, values: Vec<&'a str>) -> Self {
        self.directive(ContentSecurityPolicyDirective::trusted_types(values))
    }

    /// Block HTTP requests on insecure elements.
    pub fn upgrade_insecure_requests(self) -> Self {
        self.directive(ContentSecurityPolicyDirective::upgrade_insecure_requests())
    }

    /// Enable report only mode
    ///
    /// When set to true, the `Content-Security-Policy-Report-Only` header is set instead of `Content-Security-Policy`.
    ///
    /// Defaults to false.
    ///
    /// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
    pub fn report_only(mut self) -> Self {
        self.report_only = true;
        self
    }
}

impl<'a> Display for ContentSecurityPolicy<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let directives = self
            .directives
            .iter()
            .map(|d| d.to_string())
            .collect::<Vec<String>>()
            .join("; ");
        write!(f, "{}", directives)
    }
}

impl<'a> Default for ContentSecurityPolicy<'a> {
    /// Default policy for the Content-Security-Policy header.
    ///
    /// values:
    /// ```text
    /// default-src 'self';
    /// base-uri 'self';
    /// font-src 'self' https: data:;
    /// form-action 'self';
    /// frame-ancestors 'self';
    /// img-src 'self' data:;
    /// object-src 'none';
    /// script-src 'self';
    /// script-src-attr 'none';
    /// style-src 'self' https: 'unsafe-inline';
    /// upgrade-insecure-requests
    /// ```
    fn default() -> Self {
        Self::new()
            .default_src(vec!["'self'"])
            .base_uri(vec!["'self'"])
            .font_src(vec!["'self'", "https:", "data:"])
            .form_action(vec!["'self'"])
            .frame_ancestors(vec!["'self'"])
            .img_src(vec!["'self'", "data:"])
            .object_src(vec!["'none'"])
            .script_src(vec!["'self'"])
            .script_src_attr(vec!["'none'"])
            .style_src(vec!["'self'", "https:", "'unsafe-inline'"])
            .upgrade_insecure_requests()
    }
}

impl<'a> Header for ContentSecurityPolicy<'a> {
    fn name(&self) -> &'static str {
        if self.report_only {
            "Content-Security-Policy-Report-Only"
        } else {
            "Content-Security-Policy"
        }
    }

    fn value(&self) -> String {
        self.to_string()
    }
}

/// Helmet security headers middleware for ntex services
///
/// # Examples
///
/// ```
/// use ntex_helmet::Helmet;
///
/// let helmet = Helmet::default();
///
/// let app = ntex::web::App::new()
///    .wrap(helmet)
///    .service(ntex::web::resource("/").to(|| async { "Hello world!" }));
/// ```
///
/// ## Adding custom headers
///
/// ```
/// use ntex_helmet::{Helmet, StrictTransportSecurity};
///
/// let helmet = Helmet::new()
///    .add(StrictTransportSecurity::new().max_age(31536000).include_sub_domains());
///
/// let app = ntex::web::App::new()
///    .wrap(helmet)
///    .service(ntex::web::resource("/").to(|| async { "Hello world!" }));
/// ```
pub struct Helmet {
    inner: Rc<Inner>,
}

pub struct HelmetMiddleware<S> {
    service: S,
    inner: Rc<Inner>,
}

pub struct Inner {
    headers: Vec<Box<dyn Header>>,
}

impl Helmet {
    /// Create new `Helmet` instance without any headers applied
    pub fn new() -> Self {
        Self {
            inner: Rc::new(Inner {
                headers: Vec::new(),
            }),
        }
    }

    /// Add header to the middleware
    pub fn add(mut self, header: impl Header + 'static) -> Self {
        Rc::get_mut(&mut self.inner)
            .expect("Helmet is already in use")
            .headers
            .push(Box::new(header));
        self
    }
}

impl Default for Helmet {
    /// Default `Helmet` instance with all headers applied
    ///
    /// ```text
    /// Content-Security-Policy: default-src 'self'; base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests
    /// Cross-Origin-Opener-Policy: same-origin
    /// Cross-Origin-Resource-Policy: same-origin
    /// Origin-Agent-Cluster: ?1
    /// Referrer-Policy: no-referrer
    /// Strict-Transport-Security: max-age=15552000; includeSubDomains
    /// X-Content-Type-Options: nosniff
    /// X-DNS-Prefetch-Control: off
    /// X-Download-Options: noopen
    /// X-Frame-Options: sameorigin
    /// X-Permitted-Cross-Domain-Policies: none
    /// X-XSS-Protection: 0
    /// ```
    fn default() -> Self {
        Self::new()
            .add(ContentSecurityPolicy::default())
            .add(CrossOriginOpenerPolicy::same_origin())
            .add(CrossOriginResourcePolicy::same_origin())
            .add(OriginAgentCluster(true))
            .add(ReferrerPolicy::no_referrer())
            .add(
                StrictTransportSecurity::new()
                    .max_age(15552000)
                    .include_sub_domains(),
            )
            .add(XContentTypeOptions::nosniff())
            .add(XDNSPrefetchControl::off())
            .add(XDownloadOptions::noopen())
            .add(XFrameOptions::same_origin())
            .add(XPermittedCrossDomainPolicies::none())
            .add(XXSSProtection::off())
    }
}

impl<S, E> Service<WebRequest<E>> for HelmetMiddleware<S>
where
    S: Service<WebRequest<E>, Response = WebResponse>,
    E: 'static,
{
    type Response = WebResponse;
    type Error = S::Error;
    type Future<'f> =
        BoxFuture<'f, Result<Self::Response, Self::Error>> where S: 'f, E: 'f;

    forward_poll_ready!(service);
    forward_poll_shutdown!(service);

    fn call<'a>(&'a self, req: WebRequest<E>, ctx: ServiceCtx<'a, Self>) -> Self::Future<'a> {
        Box::pin(async move {
            let mut res = ctx.call(&self.service, req).await?;

            // set response headers
            for header in self.inner.headers.iter() {
                let name = HeaderName::try_from(header.name()).expect("invalid header name");
                let value = HeaderValue::from_str(&header.value()).expect("invalid header value");
                res.headers_mut().append(name, value);
            }

            Ok(res)
        })
    }
}

impl<S> Middleware<S> for Helmet {
    type Service = HelmetMiddleware<S>;

    fn create(&self, service: S) -> Self::Service {
        HelmetMiddleware {
            service,
            inner: self.inner.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use ntex::{
        web::test::{ok_service, TestRequest},
        Pipeline,
    };

    use super::*;

    #[ntex::test]
    async fn test_cross_origin_embedder_policy_unsafe_none() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginEmbedderPolicy::unsafe_none())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Embedder-Policy").unwrap(),
            "unsafe-none"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_embedder_policy_require_corp() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginEmbedderPolicy::require_corp())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Embedder-Policy").unwrap(),
            "require-corp"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_embedder_policy_credentialless() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginEmbedderPolicy::credentialless())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Embedder-Policy").unwrap(),
            "credentialless"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_opener_policy_same_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginOpenerPolicy::same_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Opener-Policy").unwrap(),
            "same-origin"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_opener_policy_same_origin_allow_popups() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginOpenerPolicy::same_origin_allow_popups())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Opener-Policy").unwrap(),
            "same-origin-allow-popups"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_opener_policy_unsafe_none() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginOpenerPolicy::unsafe_none())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Opener-Policy").unwrap(),
            "unsafe-none"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_resource_policy_same_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginResourcePolicy::same_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Resource-Policy").unwrap(),
            "same-origin"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_resource_policy_cross_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginResourcePolicy::cross_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Resource-Policy").unwrap(),
            "cross-origin"
        );
    }

    #[ntex::test]
    async fn test_cross_origin_resource_policy_same_site() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(CrossOriginResourcePolicy::same_site())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Cross-Origin-Resource-Policy").unwrap(),
            "same-site"
        );
    }

    #[ntex::test]
    async fn test_origin_agent_cluster_prefer_mobile() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(OriginAgentCluster::new(true))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("Origin-Agent-Cluster")
                .unwrap()
                .to_str()
                .unwrap(),
            "?1"
        );
    }

    #[ntex::test]
    async fn test_origin_agent_cluster_not_prefer_mobile() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(OriginAgentCluster::new(false))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("Origin-Agent-Cluster")
                .unwrap()
                .to_str()
                .unwrap(),
            "?0"
        );
    }

    #[ntex::test]
    async fn test_referrer_policy_no_referrer() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::no_referrer())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Referrer-Policy").unwrap(),
            "no-referrer"
        );
    }

    #[ntex::test]
    async fn test_referrer_policy_no_referrer_when_downgrade() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::no_referrer_when_downgrade())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Referrer-Policy").unwrap(),
            "no-referrer-when-downgrade"
        );
    }

    #[ntex::test]
    async fn test_referrer_policy_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::origin())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(resp.headers().get("Referrer-Policy").unwrap(), "origin");
    }

    #[ntex::test]
    async fn test_referrer_policy_origin_when_cross_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::origin_when_cross_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Referrer-Policy").unwrap(),
            "origin-when-cross-origin"
        );
    }

    #[ntex::test]
    async fn test_referrer_policy_same_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::same_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Referrer-Policy").unwrap(),
            "same-origin"
        );
    }

    #[ntex::test]
    async fn test_referrer_policy_strict_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::strict_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Referrer-Policy").unwrap(),
            "strict-origin"
        );
    }

    #[ntex::test]
    async fn test_referrer_policy_strict_origin_when_cross_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::strict_origin_when_cross_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Referrer-Policy").unwrap(),
            "strict-origin-when-cross-origin"
        );
    }

    #[ntex::test]
    async fn test_referrer_policy_unsafe_url() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ReferrerPolicy::unsafe_url())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(resp.headers().get("Referrer-Policy").unwrap(), "unsafe-url");
    }

    #[ntex::test]
    async fn test_strict_transport_security_max_age() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(StrictTransportSecurity::new().max_age(31536000))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Strict-Transport-Security")
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=31536000"
        );
    }

    #[ntex::test]
    async fn test_strict_transport_security_max_age_include_sub_domains() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    StrictTransportSecurity::new()
                        .max_age(31536000)
                        .include_sub_domains(),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Strict-Transport-Security")
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=31536000; includeSubDomains"
        );
    }

    #[ntex::test]
    async fn test_strict_transport_security_max_age_preload() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(StrictTransportSecurity::new().max_age(31536000).preload())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Strict-Transport-Security")
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=31536000; preload"
        );
    }

    #[ntex::test]
    async fn test_strict_transport_security_max_age_include_sub_domains_preload() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    StrictTransportSecurity::new()
                        .max_age(31536000)
                        .include_sub_domains()
                        .preload(),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Strict-Transport-Security")
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=31536000; includeSubDomains; preload"
        );
    }

    #[ntex::test]
    async fn test_x_content_type_options_nosniff() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XContentTypeOptions::nosniff())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-Content-Type-Options")
                .unwrap()
                .to_str()
                .unwrap(),
            "nosniff"
        );
    }

    #[ntex::test]
    async fn test_x_dns_prefetch_control_off() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XDNSPrefetchControl::off())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-DNS-Prefetch-Control")
                .unwrap()
                .to_str()
                .unwrap(),
            "off"
        );
    }

    #[ntex::test]
    async fn test_x_dns_prefetch_control_on() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XDNSPrefetchControl::on())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-DNS-Prefetch-Control")
                .unwrap()
                .to_str()
                .unwrap(),
            "on"
        );
    }

    #[ntex::test]
    async fn test_x_download_options_noopen() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XDownloadOptions::noopen())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-Download-Options")
                .unwrap()
                .to_str()
                .unwrap(),
            "noopen"
        );
    }

    #[ntex::test]
    async fn test_x_frame_options_deny() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XFrameOptions::deny())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-Frame-Options")
                .unwrap()
                .to_str()
                .unwrap(),
            "DENY"
        );
    }

    #[ntex::test]
    async fn test_x_frame_options_same_origin() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XFrameOptions::same_origin())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-Frame-Options")
                .unwrap()
                .to_str()
                .unwrap(),
            "SAMEORIGIN"
        );
    }

    #[ntex::test]
    async fn test_x_frame_options_allow_from() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XFrameOptions::allow_from("https://example.com"))
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-Frame-Options")
                .unwrap()
                .to_str()
                .unwrap(),
            "ALLOW-FROM https://example.com"
        );
    }

    #[ntex::test]
    async fn test_x_permitted_cross_domain_policies_none() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XPermittedCrossDomainPolicies::none())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("X-Permitted-Cross-Domain-Policies")
                .unwrap()
                .to_str()
                .unwrap(),
            "none"
        );
    }

    #[ntex::test]
    async fn test_x_permitted_cross_domain_policies_master_only() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XPermittedCrossDomainPolicies::master_only())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("X-Permitted-Cross-Domain-Policies")
                .unwrap()
                .to_str()
                .unwrap(),
            "master-only"
        );
    }

    #[ntex::test]
    async fn test_x_permitted_cross_domain_policies_by_content_type() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XPermittedCrossDomainPolicies::by_content_type())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("X-Permitted-Cross-Domain-Policies")
                .unwrap()
                .to_str()
                .unwrap(),
            "by-content-type"
        );
    }

    #[ntex::test]
    async fn test_x_permitted_cross_domain_policies_by_ftp_filename() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XPermittedCrossDomainPolicies::by_ftp_filename())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("X-Permitted-Cross-Domain-Policies")
                .unwrap()
                .to_str()
                .unwrap(),
            "by-ftp-filename"
        );
    }

    #[ntex::test]
    async fn test_x_permitted_cross_domain_policies_all() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XPermittedCrossDomainPolicies::all())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("X-Permitted-Cross-Domain-Policies")
                .unwrap()
                .to_str()
                .unwrap(),
            "all"
        );
    }

    #[ntex::test]
    async fn test_x_xss_protection_zero() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XXSSProtection::off())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(resp.headers().get("X-XSS-Protection").unwrap(), "0");
    }

    #[ntex::test]
    async fn test_x_xss_protection_one() {
        let mw = Pipeline::new(Helmet::new().add(XXSSProtection::on()).create(ok_service()));

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(resp.headers().get("X-XSS-Protection").unwrap(), "1");
    }

    #[ntex::test]
    async fn test_x_xss_protection_one_mode_block() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XXSSProtection::on().mode_block())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers().get("X-XSS-Protection").unwrap(),
            "1; mode=block"
        );
    }

    #[ntex::test]
    async fn test_x_xss_protection_one_mode_block_report() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    XXSSProtection::on()
                        .mode_block()
                        .report("https://example.com/report-xss-attack"),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("X-XSS-Protection")
                .unwrap()
                .to_str()
                .unwrap(),
            "1; mode=block; report=https://example.com/report-xss-attack"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_default() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::default())
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "default-src 'self'; base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests"
        );
    }

    #[ntex::test]
    async fn test_x_powered_by() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(XPoweredBy::new("PHP 4.2.0"))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(resp.headers().get("X-Powered-By").unwrap(), "PHP 4.2.0");
    }

    #[ntex::test]
    async fn test_content_security_policy_child_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().child_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "child-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_connect_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new().connect_src(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "connect-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_default_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new().default_src(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "default-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_font_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().font_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "font-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_frame_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().frame_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "frame-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_img_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().img_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "img-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_manifest_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .manifest_src(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "manifest-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_media_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().media_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "media-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_object_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().object_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "object-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_prefetch_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .prefetch_src(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "prefetch-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_script_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().script_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "script-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_script_src_elem() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .script_src_elem(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "script-src-elem 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_script_src_attr() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .script_src_attr(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "script-src-attr 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_style_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().style_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "style-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_style_src_attr() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .style_src_attr(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "style-src-attr 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_style_src_elem() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .style_src_elem(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "style-src-elem 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_worker_src() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().worker_src(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "worker-src 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_base_uri() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().base_uri(vec!["'self'", "https://youtube.com"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "base-uri 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_sandbox() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().sandbox(vec!["allow-forms", "allow-scripts"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "sandbox allow-forms allow-scripts"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_form_action() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new().form_action(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "form-action 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_frame_ancestors() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .frame_ancestors(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default()
            .header("Origin", "https://example.com")
            .to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "frame-ancestors 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_report_to() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().report_to(vec!["default", "endpoint", "group"]))
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "report-to default endpoint group; report-uri default endpoint group"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_trusted_types() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .trusted_types(vec!["'self'", "https://youtube.com"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "trusted-types 'self' https://youtube.com"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_require_trusted_types_for() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new().require_trusted_types_for(vec!["script", "style"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "require-trusted-types-for script style"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_upgrade_insecure_requests() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(ContentSecurityPolicy::new().upgrade_insecure_requests())
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();
        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "upgrade-insecure-requests"
        );
    }

    #[ntex::test]
    async fn test_helmet_default() {
        let mw = Pipeline::new(Helmet::default().create(ok_service()));

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert_eq!(
            resp.headers().get("Content-Security-Policy").unwrap(),
            "default-src 'self'; base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests"
        );
        assert_eq!(
            resp.headers().get("Cross-Origin-Opener-Policy").unwrap(),
            "same-origin"
        );
        assert_eq!(
            resp.headers().get("Cross-Origin-Resource-Policy").unwrap(),
            "same-origin"
        );
        assert_eq!(resp.headers().get("Origin-Agent-Cluster").unwrap(), "?1");
        assert_eq!(
            resp.headers().get("Referrer-Policy").unwrap(),
            "no-referrer"
        );
        assert_eq!(
            resp.headers().get("Strict-Transport-Security").unwrap(),
            "max-age=15552000; includeSubDomains"
        );
        assert_eq!(
            resp.headers().get("X-Content-Type-Options").unwrap(),
            "nosniff"
        );
        assert_eq!(resp.headers().get("X-DNS-Prefetch-Control").unwrap(), "off");
        assert_eq!(resp.headers().get("X-Download-Options").unwrap(), "noopen");
        assert_eq!(resp.headers().get("X-Frame-Options").unwrap(), "SAMEORIGIN");
        assert_eq!(
            resp.headers()
                .get("X-Permitted-Cross-Domain-Policies")
                .unwrap(),
            "none"
        );
    }

    #[ntex::test]
    async fn test_content_security_policy_report_only() {
        let mw = Pipeline::new(
            Helmet::new()
                .add(
                    ContentSecurityPolicy::new()
                        .report_only()
                        .base_uri(vec!["'self'"]),
                )
                .create(ok_service()),
        );

        let req = TestRequest::default().to_srv_request();
        let resp = mw.call(req).await.unwrap();

        assert!(resp.headers().get("Content-Security-Policy").is_none());

        assert_eq!(
            resp.headers()
                .get("Content-Security-Policy-Report-Only")
                .unwrap()
                .to_str()
                .unwrap(),
            "base-uri 'self'"
        );
    }
}