auditmysite 1.7.2

Resource-efficient WCAG 2.2 AA Accessibility Checker in Rust
Documentation
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
//! Security headers analysis module
//!
//! Analyzes HTTP security headers and SSL/TLS configuration.

pub mod module;
mod sourcemap;
pub use module::SecurityModule;
pub use sourcemap::{audit_source_maps, SourceMapLeak, SourceMapLeakAudit};

use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use tracing::info;

use crate::error::{AuditError, Result};
use crate::taxonomy::Severity;

/// A CDN, WAF, or hosting service detected from response headers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedProtection {
    pub name: String,
    /// Human-readable category, e.g. "CDN + WAF"
    pub kind: String,
    pub is_waf: bool,
    pub is_cdn: bool,
}

/// CDN/WAF protection fingerprinted from response headers
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProtectionDetection {
    pub services: Vec<DetectedProtection>,
    pub has_waf: bool,
    pub has_cdn: bool,
}

/// Security analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityAnalysis {
    /// Overall security score (0-100)
    pub score: u32,
    /// Security grade (A+ to F)
    pub grade: String,
    /// Security headers present
    pub headers: SecurityHeaders,
    /// SSL/TLS information
    pub ssl: SslInfo,
    /// Issues found
    pub issues: Vec<SecurityIssue>,
    /// Recommendations
    pub recommendations: Vec<String>,
    /// Detected CDN/WAF/hosting protection
    pub protection: ProtectionDetection,
    /// Publicly reachable source maps for loaded scripts/stylesheets (#538)
    #[serde(default)]
    pub sourcemap_leaks: SourceMapLeakAudit,
}

/// Security headers status
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SecurityHeaders {
    /// Content-Security-Policy
    pub content_security_policy: Option<String>,
    /// X-Content-Type-Options
    pub x_content_type_options: Option<String>,
    /// X-Frame-Options
    pub x_frame_options: Option<String>,
    /// Referrer-Policy
    pub referrer_policy: Option<String>,
    /// Permissions-Policy
    pub permissions_policy: Option<String>,
    /// Strict-Transport-Security (HSTS)
    pub strict_transport_security: Option<String>,
    /// Cross-Origin-Opener-Policy
    pub cross_origin_opener_policy: Option<String>,
    /// Cross-Origin-Resource-Policy
    pub cross_origin_resource_policy: Option<String>,
    /// Access-Control-Allow-Origin
    pub access_control_allow_origin: Option<String>,
    /// Access-Control-Allow-Credentials
    pub access_control_allow_credentials: Option<String>,
}

impl SecurityHeaders {
    /// Count how many security headers are present
    pub fn count(&self) -> usize {
        [
            self.content_security_policy.is_some(),
            self.x_content_type_options.is_some(),
            self.x_frame_options.is_some(),
            self.referrer_policy.is_some(),
            self.permissions_policy.is_some(),
            self.strict_transport_security.is_some(),
            self.cross_origin_opener_policy.is_some(),
            self.cross_origin_resource_policy.is_some(),
            self.access_control_allow_origin.is_some(),
            self.access_control_allow_credentials.is_some(),
        ]
        .iter()
        .filter(|&&x| x)
        .count()
    }
}

/// SSL/TLS information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SslInfo {
    /// Uses HTTPS
    pub https: bool,
    /// Has valid certificate (basic check)
    pub valid_certificate: bool,
    /// Has HSTS
    pub has_hsts: bool,
    /// HSTS max-age value
    pub hsts_max_age: Option<u64>,
    /// HSTS includes subdomains
    pub hsts_include_subdomains: bool,
    /// HSTS preload
    pub hsts_preload: bool,
    /// TLS protocol reported by the browser (e.g. "TLS 1.3").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
    /// TLS cipher reported by the browser.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cipher: Option<String>,
    /// Certificate subject name reported by the browser.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_subject: Option<String>,
    /// Certificate issuer reported by the browser.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_issuer: Option<String>,
    /// Certificate expiration timestamp (seconds since Unix epoch).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_valid_to: Option<i64>,
    /// Days until certificate expiration, based on collection time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_expires_in_days: Option<i64>,
    /// Number of certificates in the chain exposed by CDP.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_chain_length: Option<usize>,
    /// Browser-reported certificate network error, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_error: Option<String>,
    /// Whether the browser reported weak certificate signatures.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_has_weak_signature: Option<bool>,
    /// Whether the browser reported SHA-1 signatures in the chain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub certificate_has_sha1_signature: Option<bool>,
}

/// Browser-observed certificate details from the CDP Security domain.
#[derive(Debug, Clone, Default)]
pub struct BrowserCertificateDetails {
    pub protocol: Option<String>,
    pub cipher: Option<String>,
    pub subject: Option<String>,
    pub issuer: Option<String>,
    pub valid_to: Option<i64>,
    pub expires_in_days: Option<i64>,
    pub chain_length: Option<usize>,
    pub error: Option<String>,
    pub has_weak_signature: Option<bool>,
    pub has_sha1_signature: Option<bool>,
}

impl SslInfo {
    pub fn apply_certificate_details(&mut self, details: BrowserCertificateDetails) {
        self.protocol = details.protocol;
        self.cipher = details.cipher;
        self.certificate_subject = details.subject;
        self.certificate_issuer = details.issuer;
        self.certificate_valid_to = details.valid_to;
        self.certificate_expires_in_days = details.expires_in_days;
        self.certificate_chain_length = details.chain_length;
        self.certificate_error = details.error;
        self.certificate_has_weak_signature = details.has_weak_signature;
        self.certificate_has_sha1_signature = details.has_sha1_signature;
        if self.certificate_error.is_some() {
            self.valid_certificate = false;
        }
    }
}

/// Classification tier for a security header (#578).
///
/// A raw "N headers missing" count treats every header as equally urgent,
/// which isn't true: some are baseline hygiene for virtually every site,
/// some only matter for a specific architecture, some depend on a
/// deployment context this tool cannot observe from a single automated page
/// fetch, and some can't be meaningfully judged as present/absent at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HeaderTier {
    /// Applies to virtually every site; missing it is a real gap regardless
    /// of architecture (CSP, HSTS, X-Content-Type-Options, X-Frame-Options,
    /// HTTPS itself).
    Baseline,
    /// Good practice, but whether it's expected depends on the site's
    /// architecture (Referrer-Policy, Permissions-Policy).
    ArchitectureDependent,
    /// Relevance depends on a deployment context (e.g. SharedArrayBuffer
    /// usage, cross-origin isolation) that can't be determined from a
    /// single automated page fetch (Cross-Origin-Opener/Resource-Policy).
    ContextDependent,
    /// Presence or absence alone isn't a meaningful signal — a static crawl
    /// can't tell whether cross-origin sharing is intentional (CORS
    /// headers).
    NotAssessable,
}

/// Classifies a security header by how universally applicable it is (#578).
/// Falls back to `Baseline` for anything outside the fixed table, which
/// covers confirmed misconfigurations (e.g. CSP quality issues, public
/// source maps) — those are never ambiguous by nature, so they read as
/// baseline findings rather than context-dependent ones.
pub fn header_tier(header: &str) -> HeaderTier {
    match header {
        "Content-Security-Policy"
        | "Strict-Transport-Security"
        | "X-Content-Type-Options"
        | "X-Frame-Options"
        | "HTTPS" => HeaderTier::Baseline,
        "Referrer-Policy" | "Permissions-Policy" => HeaderTier::ArchitectureDependent,
        "Cross-Origin-Opener-Policy" | "Cross-Origin-Resource-Policy" => {
            HeaderTier::ContextDependent
        }
        "Access-Control-Allow-Origin" | "Access-Control-Allow-Credentials" => {
            HeaderTier::NotAssessable
        }
        _ => HeaderTier::Baseline,
    }
}

/// Security issue
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityIssue {
    pub header: String,
    pub issue_type: String,
    /// Canonical English, produced by [`security_issue_text`] (#406). The PDF
    /// re-derives the localized wording from `kind()` plus `values`; this field
    /// keeps the stored JSON language-neutral.
    pub message: String,
    pub severity: Severity,
    /// Classification tier for the underlying header (#578) — lets report
    /// consumers distinguish baseline hygiene from context-dependent
    /// findings without re-deriving it from `header`.
    pub tier: HeaderTier,
    /// Raw values interpolated into the message, so the presentation layer can
    /// rebuild the sentence in another language instead of parsing `message`.
    #[serde(default, skip_serializing_if = "SecurityIssueValues::is_empty")]
    pub values: SecurityIssueValues,
}

/// The canonical identity of a security finding — the single key
/// [`security_issue_text`] renders from.
///
/// Derived from the already-stored `header`/`issue_type` pair rather than
/// stored as a fourth field, so reports written by older builds (and cached
/// artifacts) keep working unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecurityIssueKind {
    MissingHttps,
    MissingCsp,
    MissingXContentTypeOptions,
    MissingXFrameOptions,
    MissingHsts,
    MissingReferrerPolicy,
    MissingPermissionsPolicy,
    MissingCoop,
    MissingCorp,
    CorsWildcardCredentials,
    HstsPreloadIneligible,
    PermissionsPolicyPermissive,
    PublicSourceMap,
    CspUnsafeInlineScript,
    CspUnsafeEvalScript,
    CspWildcardScriptSource,
    CspUnsafeInlineStyle,
    CspWildcardSource,
    /// `object-src`, `base-uri`, `frame-ancestors` — the directive name lives
    /// in [`SecurityIssueValues::csp_directive`].
    CspMissingDirective,
}

/// The CSP directives [`SecurityIssueKind::CspMissingDirective`] is raised for.
pub const CSP_REQUIRED_DIRECTIVES: [&str; 3] = ["object-src", "base-uri", "frame-ancestors"];

impl SecurityIssueKind {
    /// Every kind this build can emit. Add new variants here — the
    /// localization guard and the check inventory both iterate it.
    pub const ALL: [SecurityIssueKind; 19] = [
        SecurityIssueKind::MissingHttps,
        SecurityIssueKind::MissingCsp,
        SecurityIssueKind::MissingXContentTypeOptions,
        SecurityIssueKind::MissingXFrameOptions,
        SecurityIssueKind::MissingHsts,
        SecurityIssueKind::MissingReferrerPolicy,
        SecurityIssueKind::MissingPermissionsPolicy,
        SecurityIssueKind::MissingCoop,
        SecurityIssueKind::MissingCorp,
        SecurityIssueKind::CorsWildcardCredentials,
        SecurityIssueKind::HstsPreloadIneligible,
        SecurityIssueKind::PermissionsPolicyPermissive,
        SecurityIssueKind::PublicSourceMap,
        SecurityIssueKind::CspUnsafeInlineScript,
        SecurityIssueKind::CspUnsafeEvalScript,
        SecurityIssueKind::CspWildcardScriptSource,
        SecurityIssueKind::CspUnsafeInlineStyle,
        SecurityIssueKind::CspWildcardSource,
        SecurityIssueKind::CspMissingDirective,
    ];

    /// The response header a kind is reported against.
    pub fn header(self) -> &'static str {
        use SecurityIssueKind::*;
        match self {
            MissingHttps => "HTTPS",
            MissingCsp
            | CspUnsafeInlineScript
            | CspUnsafeEvalScript
            | CspWildcardScriptSource
            | CspUnsafeInlineStyle
            | CspWildcardSource
            | CspMissingDirective => "Content-Security-Policy",
            MissingXContentTypeOptions => "X-Content-Type-Options",
            MissingXFrameOptions => "X-Frame-Options",
            MissingHsts | HstsPreloadIneligible => "Strict-Transport-Security",
            MissingReferrerPolicy => "Referrer-Policy",
            MissingPermissionsPolicy | PermissionsPolicyPermissive => "Permissions-Policy",
            MissingCoop => "Cross-Origin-Opener-Policy",
            MissingCorp => "Cross-Origin-Resource-Policy",
            CorsWildcardCredentials => "Access-Control-Allow-Origin",
            PublicSourceMap => "Source Map",
        }
    }
}

/// Every `"{header}:{issue_type}"` id this build can emit — the canonical
/// inventory the non-WCAG detection corpus is checked against (#558).
///
/// Derived from [`SecurityIssueKind::ALL`], so it cannot drift from the code
/// the way the previous string-literal scan of this file could.
pub fn all_security_check_ids() -> Vec<String> {
    let mut ids = Vec::new();
    for kind in SecurityIssueKind::ALL {
        if kind == SecurityIssueKind::CspMissingDirective {
            for directive in CSP_REQUIRED_DIRECTIVES {
                let values = SecurityIssueValues {
                    csp_directive: Some(directive.to_string()),
                    ..Default::default()
                };
                ids.push(format!(
                    "{}:{}",
                    kind.header(),
                    issue_type_for(kind, &values)
                ));
            }
        } else {
            ids.push(format!(
                "{}:{}",
                kind.header(),
                issue_type_for(kind, &SecurityIssueValues::default())
            ));
        }
    }
    ids.sort();
    ids.dedup();
    ids
}

/// Values interpolated into a security message. Empty for the many findings
/// whose sentence carries no numbers.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecurityIssueValues {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hsts_max_age: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hsts_include_subdomains: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_map_count: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_map_example: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub csp_directive: Option<String>,
}

impl SecurityIssueValues {
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }
}

impl SecurityIssue {
    /// `None` for an `(header, issue_type)` pair this build does not know —
    /// callers then fall back to the stored canonical-English `message`.
    pub fn kind(&self) -> Option<SecurityIssueKind> {
        use SecurityIssueKind::*;
        let kind = match self.issue_type.as_str() {
            "missing_https" => MissingHttps,
            "missing_header" => match self.header.as_str() {
                "Content-Security-Policy" => MissingCsp,
                "X-Content-Type-Options" => MissingXContentTypeOptions,
                "X-Frame-Options" => MissingXFrameOptions,
                "Strict-Transport-Security" => MissingHsts,
                "Referrer-Policy" => MissingReferrerPolicy,
                "Permissions-Policy" => MissingPermissionsPolicy,
                "Cross-Origin-Opener-Policy" => MissingCoop,
                "Cross-Origin-Resource-Policy" => MissingCorp,
                _ => return None,
            },
            "cors_wildcard_credentials" => CorsWildcardCredentials,
            "hsts_preload_ineligible" => HstsPreloadIneligible,
            "permissions_policy_permissive" => PermissionsPolicyPermissive,
            "public_source_map" => PublicSourceMap,
            "unsafe_inline_script" => CspUnsafeInlineScript,
            "unsafe_eval_script" => CspUnsafeEvalScript,
            "wildcard_script_source" => CspWildcardScriptSource,
            "unsafe_inline_style" => CspUnsafeInlineStyle,
            "wildcard_source" => CspWildcardSource,
            other if other.starts_with("missing_") => CspMissingDirective,
            _ => return None,
        };
        Some(kind)
    }

    /// The finding's message in `locale`'s language. Falls back to the stored
    /// canonical English for kinds this build does not recognize.
    pub fn localized_message(&self, en: bool) -> String {
        match self.kind() {
            Some(kind) => security_issue_text(kind, &self.values, en),
            None => self.message.clone(),
        }
    }
}

/// The only source of security-finding wording (#406). The analysis layer calls
/// it with `en = true` to bake canonical English into the stored struct; the
/// PDF calls it with the run language.
pub fn security_issue_text(
    kind: SecurityIssueKind,
    values: &SecurityIssueValues,
    en: bool,
) -> String {
    use SecurityIssueKind::*;
    match kind {
        MissingHttps => if en {
            "Site is not served over HTTPS"
        } else {
            "Seite wird nicht über HTTPS ausgeliefert"
        }
        .to_string(),
        MissingCsp => if en {
            "Missing Content-Security-Policy header"
        } else {
            "Content-Security-Policy-Header fehlt"
        }
        .to_string(),
        MissingXContentTypeOptions => if en {
            "Missing X-Content-Type-Options header"
        } else {
            "X-Content-Type-Options-Header fehlt"
        }
        .to_string(),
        MissingXFrameOptions => if en {
            "Missing X-Frame-Options header (clickjacking protection)"
        } else {
            "X-Frame-Options-Header fehlt (Clickjacking-Schutz)"
        }
        .to_string(),
        MissingHsts => if en {
            "Missing HSTS header"
        } else {
            "HSTS-Header fehlt"
        }
        .to_string(),
        MissingReferrerPolicy => if en {
            "Missing Referrer-Policy header"
        } else {
            "Referrer-Policy-Header fehlt"
        }
        .to_string(),
        MissingPermissionsPolicy => if en {
            "Missing Permissions-Policy header"
        } else {
            "Permissions-Policy-Header fehlt"
        }
        .to_string(),
        MissingCoop => if en {
            "Cross-Origin-Opener-Policy is not set. This header only matters if the page uses \
             SharedArrayBuffer, high-resolution timers, or needs to isolate itself from \
             cross-origin popups — if none of that applies, no action is needed here. If it \
             does apply, set it to same-origin and verify popup/window interactions still work \
             as expected."
        } else {
            "Cross-Origin-Opener-Policy ist nicht gesetzt. Dieser Header ist nur relevant, wenn \
             die Seite SharedArrayBuffer, hochauflösende Timer verwendet oder sich von \
             Cross-Origin-Popups isolieren muss — trifft das nicht zu, ist hier keine Maßnahme \
             nötig. Trifft es zu: auf same-origin setzen und prüfen, ob Popup-/Fenster-\
             Interaktionen weiterhin wie erwartet funktionieren."
        }
        .to_string(),
        MissingCorp => if en {
            "Cross-Origin-Resource-Policy is not set. This header only matters if the page \
             serves fonts, scripts, or media that other origins should be prevented from \
             loading — if the site's resources are intentionally public, no action is needed \
             here. If cross-origin loading should be restricted, set it to same-origin or \
             same-site."
        } else {
            "Cross-Origin-Resource-Policy ist nicht gesetzt. Dieser Header ist nur relevant, \
             wenn die Seite Schriften, Skripte oder Medien ausliefert, die andere Origins nicht \
             laden können sollen — sind die Ressourcen bewusst öffentlich, ist hier keine \
             Maßnahme nötig. Soll Cross-Origin-Laden eingeschränkt werden: auf same-origin oder \
             same-site setzen."
        }
        .to_string(),
        CorsWildcardCredentials => if en {
            "CORS allows any origin while also allowing credentials"
        } else {
            "CORS erlaubt jede Origin und gleichzeitig Credentials"
        }
        .to_string(),
        HstsPreloadIneligible => {
            let max_age = values.hsts_max_age.as_deref().unwrap_or("unset");
            let subdomains = values.hsts_include_subdomains.unwrap_or(false);
            if en {
                format!(
                    "HSTS preload directive is set but requirements aren't met (max-age={max_age}, includeSubDomains={subdomains}) — the site won't qualify for the HSTS preload list"
                )
            } else {
                format!(
                    "HSTS-preload-Direktive ist gesetzt, die Voraussetzungen sind aber nicht erfüllt (max-age={max_age}, includeSubDomains={subdomains}) — die Seite wird nicht in die HSTS-Preload-Liste aufgenommen"
                )
            }
        }
        PermissionsPolicyPermissive => if en {
            "Permissions-Policy header is present but doesn't restrict any feature (empty or wildcard-only)"
        } else {
            "Permissions-Policy-Header ist vorhanden, schränkt aber kein Feature ein (leer oder nur Wildcards)"
        }
        .to_string(),
        PublicSourceMap => {
            let count = values.source_map_count.unwrap_or(1);
            let example = values
                .source_map_example
                .as_deref()
                .map(|url| format!(" (e.g. {url})"))
                .unwrap_or_default();
            if en {
                format!(
                    "{count} publicly reachable source map{} found{example} — exposes original source, comments, and internal file paths",
                    if count == 1 { "" } else { "s" }
                )
            } else {
                let example = example.replace(" (e.g. ", " (z. B. ");
                format!(
                    "{count} öffentlich erreichbare Source-Map{} gefunden{example} — legt Originalquellcode, Kommentare und interne Dateipfade offen",
                    if count == 1 { "" } else { "s" }
                )
            }
        }
        CspUnsafeInlineScript => if en {
            "CSP allows unsafe-inline scripts without nonce/hash protection"
        } else {
            "CSP erlaubt unsafe-inline-Skripte ohne Nonce-/Hash-Absicherung"
        }
        .to_string(),
        CspUnsafeEvalScript => if en {
            "CSP allows unsafe-eval in script sources"
        } else {
            "CSP erlaubt unsafe-eval in den Skript-Quellen"
        }
        .to_string(),
        CspWildcardScriptSource => if en {
            "CSP allows wildcard script sources"
        } else {
            "CSP erlaubt Wildcard-Skriptquellen"
        }
        .to_string(),
        CspUnsafeInlineStyle => if en {
            "CSP allows unsafe-inline styles without nonce/hash protection"
        } else {
            "CSP erlaubt unsafe-inline-Styles ohne Nonce-/Hash-Absicherung"
        }
        .to_string(),
        CspWildcardSource => if en {
            "CSP contains wildcard source expressions"
        } else {
            "CSP enthält Wildcard-Quellausdrücke"
        }
        .to_string(),
        CspMissingDirective => {
            let directive = values.csp_directive.as_deref().unwrap_or("object-src");
            if en {
                format!("CSP missing {directive} directive")
            } else {
                format!("CSP fehlt die {directive}-Direktive")
            }
        }
    }
}

/// The stored `issue_type` string for a kind. Kept as an explicit mapping so
/// the JSON contract stays byte-identical to what earlier builds wrote — see
/// `security_issue_types_match_the_stored_contract`.
fn issue_type_for(kind: SecurityIssueKind, values: &SecurityIssueValues) -> String {
    use SecurityIssueKind::*;
    match kind {
        MissingHttps => "missing_https".to_string(),
        MissingCsp
        | MissingXContentTypeOptions
        | MissingXFrameOptions
        | MissingHsts
        | MissingReferrerPolicy
        | MissingPermissionsPolicy
        | MissingCoop
        | MissingCorp => "missing_header".to_string(),
        CorsWildcardCredentials => "cors_wildcard_credentials".to_string(),
        HstsPreloadIneligible => "hsts_preload_ineligible".to_string(),
        PermissionsPolicyPermissive => "permissions_policy_permissive".to_string(),
        PublicSourceMap => "public_source_map".to_string(),
        CspUnsafeInlineScript => "unsafe_inline_script".to_string(),
        CspUnsafeEvalScript => "unsafe_eval_script".to_string(),
        CspWildcardScriptSource => "wildcard_script_source".to_string(),
        CspUnsafeInlineStyle => "unsafe_inline_style".to_string(),
        CspWildcardSource => "wildcard_source".to_string(),
        CspMissingDirective => format!(
            "missing_{}",
            values.csp_directive.as_deref().unwrap_or("object-src")
        ),
    }
}

/// Build a finding with its canonical-English message derived from `kind` —
/// the message is never written by hand at a call site (#406).
fn security_issue(
    header: &str,
    kind: SecurityIssueKind,
    values: SecurityIssueValues,
    severity: Severity,
    tier: HeaderTier,
) -> SecurityIssue {
    SecurityIssue {
        header: header.to_string(),
        issue_type: issue_type_for(kind, &values),
        message: security_issue_text(kind, &values, true),
        severity,
        tier,
        values,
    }
}

/// Analyze security headers of a URL
pub async fn analyze_security(url: &str) -> Result<SecurityAnalysis> {
    info!("Analyzing security headers for {}...", url);

    let https = url.starts_with("https://");

    let client = reqwest::Client::builder()
        .danger_accept_invalid_certs(false)
        .build()
        .map_err(AuditError::HttpError)?;

    let response = match client.head(url).send().await {
        Ok(response) => Ok(response),
        Err(_) => client.get(url).send().await,
    };

    let (headers, protection) = match response {
        Ok(response) => {
            let raw = response.headers();
            let h = extract_security_headers(raw);
            let p = detect_protection(raw);
            (h, p)
        }
        Err(err) => {
            info!(
                "Security header request failed for {}; continuing with URL-only security analysis: {}",
                url, err
            );
            (SecurityHeaders::default(), ProtectionDetection::default())
        }
    };

    // Analyze SSL
    let ssl = analyze_ssl(https, &headers);

    // Generate issues
    let mut issues = generate_security_issues(&headers, https);

    // HSTS preload eligibility + Permissions-Policy quality (#535)
    if hsts_preload_ineligible(&ssl) {
        issues.push(security_issue(
            "Strict-Transport-Security",
            SecurityIssueKind::HstsPreloadIneligible,
            SecurityIssueValues {
                hsts_max_age: Some(
                    ssl.hsts_max_age
                        .map(|v| v.to_string())
                        .unwrap_or_else(|| "unset".to_string()),
                ),
                hsts_include_subdomains: Some(ssl.hsts_include_subdomains),
                ..Default::default()
            },
            Severity::Low,
            HeaderTier::Baseline,
        ));
    }
    if permissions_policy_is_permissive(&headers) {
        issues.push(security_issue(
            "Permissions-Policy",
            SecurityIssueKind::PermissionsPolicyPermissive,
            SecurityIssueValues::default(),
            Severity::Low,
            HeaderTier::ArchitectureDependent,
        ));
    }

    // Public source-map leak check (#538)
    let sourcemap_leaks = audit_source_maps(url).await;
    if !sourcemap_leaks.leaks.is_empty() {
        issues.push(security_issue(
            "Source Map",
            SecurityIssueKind::PublicSourceMap,
            SecurityIssueValues {
                source_map_count: Some(sourcemap_leaks.leaks.len()),
                source_map_example: Some(sourcemap_leaks.leaks[0].map_url.clone()),
                ..Default::default()
            },
            Severity::High,
            HeaderTier::Baseline,
        ));
    }

    // Generate recommendations
    let recommendations = generate_recommendations(&headers, https);

    // Calculate score
    let score = calculate_security_score(&headers, &ssl, &issues);
    let grade = calculate_grade(score);

    info!(
        "Security analysis: score={}, grade={}, headers={}, protection={:?}",
        score,
        grade,
        headers.count(),
        protection
            .services
            .iter()
            .map(|s| s.name.as_str())
            .collect::<Vec<_>>(),
    );

    Ok(SecurityAnalysis {
        score,
        grade,
        headers,
        ssl,
        issues,
        recommendations,
        protection,
        sourcemap_leaks,
    })
}

fn detect_protection(headers: &HeaderMap) -> ProtectionDetection {
    let hdr = |name: &str| {
        headers
            .get(name)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_lowercase()
    };
    let has = |name: &str| headers.contains_key(name);

    let mut services: Vec<DetectedProtection> = Vec::new();

    macro_rules! push {
        ($name:expr, $kind:expr, $waf:expr, $cdn:expr) => {
            services.push(DetectedProtection {
                name: $name.to_string(),
                kind: $kind.to_string(),
                is_waf: $waf,
                is_cdn: $cdn,
            });
        };
    }

    if has("cf-ray") || hdr("server").contains("cloudflare") {
        push!("Cloudflare", "CDN + WAF", true, true);
    }
    if has("x-amz-cf-id") || hdr("via").contains("cloudfront") {
        push!("AWS CloudFront", "CDN", false, true);
    }
    if has("x-akamai-request-id")
        || has("x-check-cacheable")
        || has("akamai-origin-hop")
        || hdr("server").contains("akamaighost")
    {
        push!("Akamai", "CDN + WAF", true, true);
    }
    if has("x-fastly-request-id") || has("fastly-restarts") || hdr("x-served-by").contains("cache-")
    {
        push!("Fastly", "CDN", false, true);
    }
    if has("x-sucuri-id") || has("x-sucuri-cache") || hdr("server").contains("sucuri") {
        push!("Sucuri", "WAF + CDN", true, true);
    }
    if has("x-iinfo") || hdr("x-cdn").contains("imperva") || hdr("x-cdn").contains("incapsula") {
        push!("Imperva", "WAF + CDN", true, true);
    }
    if has("x-vercel-id") {
        push!("Vercel", "Hosting + CDN", false, true);
    }
    if has("x-nf-request-id") || hdr("server").contains("netlify") {
        push!("Netlify", "Hosting + CDN", false, true);
    }
    if has("cdn-pullzone") || has("bunny-request-id") || has("cdn-requestid") {
        push!("BunnyCDN", "CDN", false, true);
    }
    if hdr("server").contains("keycdn-engine") || (has("x-edge-location") && !has("x-amz-cf-id")) {
        push!("KeyCDN", "CDN", false, true);
    }
    if has("x-varnish") || hdr("via").contains("varnish") {
        push!("Varnish", "Cache", false, true);
    }

    let has_waf = services.iter().any(|s| s.is_waf);
    let has_cdn = services.iter().any(|s| s.is_cdn);

    ProtectionDetection {
        services,
        has_waf,
        has_cdn,
    }
}

fn extract_security_headers(headers: &HeaderMap) -> SecurityHeaders {
    SecurityHeaders {
        content_security_policy: headers
            .get("content-security-policy")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        x_content_type_options: headers
            .get("x-content-type-options")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        x_frame_options: headers
            .get("x-frame-options")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        referrer_policy: headers
            .get("referrer-policy")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        permissions_policy: headers
            .get("permissions-policy")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        strict_transport_security: headers
            .get("strict-transport-security")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        cross_origin_opener_policy: headers
            .get("cross-origin-opener-policy")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        cross_origin_resource_policy: headers
            .get("cross-origin-resource-policy")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        access_control_allow_origin: headers
            .get("access-control-allow-origin")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
        access_control_allow_credentials: headers
            .get("access-control-allow-credentials")
            .and_then(|v| v.to_str().ok())
            .map(String::from),
    }
}

fn analyze_ssl(https: bool, headers: &SecurityHeaders) -> SslInfo {
    let hsts = headers.strict_transport_security.as_ref();

    let (hsts_max_age, hsts_include_subdomains, hsts_preload) = if let Some(hsts_value) = hsts {
        let max_age = hsts_value
            .split(';')
            .find(|s| s.trim().starts_with("max-age"))
            .and_then(|s| s.split('=').nth(1))
            .and_then(|s| s.trim().parse().ok());

        let include_subdomains = hsts_value.to_lowercase().contains("includesubdomains");
        let preload = hsts_value.to_lowercase().contains("preload");

        (max_age, include_subdomains, preload)
    } else {
        (None, false, false)
    };

    SslInfo {
        https,
        valid_certificate: https, // Basic assumption
        has_hsts: hsts.is_some(),
        hsts_max_age,
        hsts_include_subdomains,
        hsts_preload,
        ..Default::default()
    }
}

pub(crate) fn generate_security_issues(
    headers: &SecurityHeaders,
    https: bool,
) -> Vec<SecurityIssue> {
    let mut issues = Vec::new();

    if !https {
        issues.push(security_issue(
            "HTTPS",
            SecurityIssueKind::MissingHttps,
            SecurityIssueValues::default(),
            Severity::Critical,
            HeaderTier::Baseline,
        ));
    }

    if headers.content_security_policy.is_none() {
        issues.push(security_issue(
            "Content-Security-Policy",
            SecurityIssueKind::MissingCsp,
            SecurityIssueValues::default(),
            Severity::High,
            HeaderTier::Baseline,
        ));
    } else if let Some(ref csp) = headers.content_security_policy {
        issues.extend(collect_csp_quality_issues(csp));
    }

    if headers.x_content_type_options.is_none() {
        issues.push(security_issue(
            "X-Content-Type-Options",
            SecurityIssueKind::MissingXContentTypeOptions,
            SecurityIssueValues::default(),
            Severity::Medium,
            HeaderTier::Baseline,
        ));
    }

    if headers.x_frame_options.is_none() {
        issues.push(security_issue(
            "X-Frame-Options",
            SecurityIssueKind::MissingXFrameOptions,
            SecurityIssueValues::default(),
            Severity::Medium,
            HeaderTier::Baseline,
        ));
    }

    if https && headers.strict_transport_security.is_none() {
        issues.push(security_issue(
            "Strict-Transport-Security",
            SecurityIssueKind::MissingHsts,
            SecurityIssueValues::default(),
            Severity::High,
            HeaderTier::Baseline,
        ));
    }

    if headers.referrer_policy.is_none() {
        issues.push(security_issue(
            "Referrer-Policy",
            SecurityIssueKind::MissingReferrerPolicy,
            SecurityIssueValues::default(),
            Severity::Low,
            HeaderTier::ArchitectureDependent,
        ));
    }

    if headers.permissions_policy.is_none() {
        issues.push(security_issue(
            "Permissions-Policy",
            SecurityIssueKind::MissingPermissionsPolicy,
            SecurityIssueValues::default(),
            Severity::Low,
            HeaderTier::ArchitectureDependent,
        ));
    }

    // COOP/CORP relevance depends on deployment context this tool cannot
    // observe from a single unauthenticated fetch — a marketing page almost
    // never needs them, but an authenticated app page using SharedArrayBuffer
    // or a cross-origin OAuth popup flow genuinely might. A static crawl has
    // no way to tell those two cases apart, so the message below asks the
    // verification question instead of asserting either "add this" or
    // "ignore this" (#578).
    if headers.cross_origin_opener_policy.is_none() {
        issues.push(security_issue(
            "Cross-Origin-Opener-Policy",
            SecurityIssueKind::MissingCoop,
            SecurityIssueValues::default(),
            Severity::Low,
            HeaderTier::ContextDependent,
        ));
    }

    if headers.cross_origin_resource_policy.is_none() {
        issues.push(security_issue(
            "Cross-Origin-Resource-Policy",
            SecurityIssueKind::MissingCorp,
            SecurityIssueValues::default(),
            Severity::Low,
            HeaderTier::ContextDependent,
        ));
    }

    if cors_allows_wildcard_credentials(headers) {
        issues.push(security_issue(
            "Access-Control-Allow-Origin",
            SecurityIssueKind::CorsWildcardCredentials,
            SecurityIssueValues::default(),
            Severity::High,
            HeaderTier::Baseline,
        ));
    }

    issues
}

fn cors_allows_wildcard_credentials(headers: &SecurityHeaders) -> bool {
    headers
        .access_control_allow_origin
        .as_deref()
        .is_some_and(|origin| origin.trim() == "*")
        && headers
            .access_control_allow_credentials
            .as_deref()
            .is_some_and(|credentials| credentials.trim().eq_ignore_ascii_case("true"))
}

/// True when the HSTS header's `preload` directive is present but the site
/// doesn't actually meet the HSTS preload list requirements (max-age of at
/// least one year AND `includeSubDomains`) — claiming preload readiness
/// without meeting it is a misleading/incomplete configuration (#535).
fn hsts_preload_ineligible(ssl: &SslInfo) -> bool {
    const ONE_YEAR_SECONDS: u64 = 31_536_000;
    ssl.hsts_preload
        && (ssl.hsts_max_age.unwrap_or(0) < ONE_YEAR_SECONDS || !ssl.hsts_include_subdomains)
}

/// True when Permissions-Policy is present but restricts nothing: an empty
/// value, or every listed feature left wide open with `*` (#535).
fn permissions_policy_is_permissive(headers: &SecurityHeaders) -> bool {
    let Some(value) = headers.permissions_policy.as_deref() else {
        return false;
    };
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return true;
    }
    trimmed.split(',').all(|directive| {
        directive
            .split('=')
            .nth(1)
            .map(|allowlist| allowlist.trim() == "*")
            .unwrap_or(false)
    })
}

fn collect_csp_quality_issues(policy: &str) -> Vec<SecurityIssue> {
    let directives = parse_csp_directives(policy);
    let mut issues = Vec::new();

    let effective_script = directive_values(&directives, "script-src")
        .or_else(|| directive_values(&directives, "default-src"))
        .unwrap_or_default();
    if effective_script.contains(&"'unsafe-inline'") && !has_nonce_or_hash(effective_script) {
        issues.push(csp_issue(
            SecurityIssueKind::CspUnsafeInlineScript,
            SecurityIssueValues::default(),
            Severity::High,
        ));
    }
    if effective_script.contains(&"'unsafe-eval'") {
        issues.push(csp_issue(
            SecurityIssueKind::CspUnsafeEvalScript,
            SecurityIssueValues::default(),
            Severity::High,
        ));
    }
    if has_wildcard_source(effective_script) {
        issues.push(csp_issue(
            SecurityIssueKind::CspWildcardScriptSource,
            SecurityIssueValues::default(),
            Severity::High,
        ));
    }

    let effective_style = directive_values(&directives, "style-src")
        .or_else(|| directive_values(&directives, "default-src"))
        .unwrap_or_default();
    if effective_style.contains(&"'unsafe-inline'") && !has_nonce_or_hash(effective_style) {
        issues.push(csp_issue(
            SecurityIssueKind::CspUnsafeInlineStyle,
            SecurityIssueValues::default(),
            Severity::Medium,
        ));
    }

    if has_wildcard_source(
        directives
            .values()
            .flatten()
            .copied()
            .collect::<Vec<_>>()
            .as_slice(),
    ) {
        issues.push(csp_issue(
            SecurityIssueKind::CspWildcardSource,
            SecurityIssueValues::default(),
            Severity::Medium,
        ));
    }

    for directive in CSP_REQUIRED_DIRECTIVES {
        let severity = Severity::Medium;
        if !directives.contains_key(directive) {
            issues.push(csp_issue(
                SecurityIssueKind::CspMissingDirective,
                SecurityIssueValues {
                    csp_directive: Some(directive.to_string()),
                    ..Default::default()
                },
                severity,
            ));
        }
    }

    issues
}

fn generate_csp_recommendations(policy: &str) -> Vec<String> {
    let issue_types: std::collections::BTreeSet<_> = collect_csp_quality_issues(policy)
        .into_iter()
        .map(|issue| issue.issue_type)
        .collect();
    let mut recommendations = Vec::new();

    if issue_types.contains("unsafe_inline_script") || issue_types.contains("unsafe_inline_style") {
        recommendations.push(
            "Remove unsafe-inline from CSP or replace it with nonces/hashes for approved inline code"
                .to_string(),
        );
    }
    if issue_types.contains("unsafe_eval_script") {
        recommendations.push(
            "Remove unsafe-eval from script-src; avoid runtime string evaluation in production"
                .to_string(),
        );
    }
    if issue_types.contains("wildcard_script_source") || issue_types.contains("wildcard_source") {
        recommendations
            .push("Replace wildcard CSP sources with explicit trusted origins".to_string());
    }
    if issue_types
        .iter()
        .any(|issue| issue.starts_with("missing_"))
    {
        recommendations.push(
            "Harden CSP with object-src 'none', base-uri 'self', and frame-ancestors 'none' or a trusted origin"
                .to_string(),
        );
    }

    recommendations
}

fn csp_issue(
    kind: SecurityIssueKind,
    values: SecurityIssueValues,
    severity: Severity,
) -> SecurityIssue {
    security_issue(
        "Content-Security-Policy",
        kind,
        values,
        severity,
        HeaderTier::Baseline,
    )
}

fn parse_csp_directives(policy: &str) -> BTreeMap<String, Vec<&str>> {
    let mut directives = BTreeMap::new();
    for directive in policy.split(';') {
        let mut parts = directive.split_whitespace();
        let Some(name) = parts.next() else {
            continue;
        };
        directives.insert(name.to_ascii_lowercase(), parts.collect());
    }
    directives
}

fn directive_values<'a>(
    directives: &'a BTreeMap<String, Vec<&'a str>>,
    name: &str,
) -> Option<&'a [&'a str]> {
    directives.get(name).map(Vec::as_slice)
}

fn has_nonce_or_hash(values: &[&str]) -> bool {
    values.iter().any(|value| {
        value.starts_with("'nonce-")
            || value.starts_with("'sha256-")
            || value.starts_with("'sha384-")
            || value.starts_with("'sha512-")
    })
}

fn has_wildcard_source(values: &[&str]) -> bool {
    values.iter().any(|value| {
        *value == "*"
            || value.starts_with("*.")
            || value.starts_with("https://*")
            || value.starts_with("http://*")
    })
}

fn generate_recommendations(headers: &SecurityHeaders, https: bool) -> Vec<String> {
    let mut recommendations = Vec::new();

    if !https {
        recommendations.push("Enable HTTPS with a valid SSL certificate".to_string());
    }

    if headers.content_security_policy.is_none() {
        recommendations.push(
            "Add Content-Security-Policy header to prevent XSS and data injection".to_string(),
        );
    } else if let Some(ref csp) = headers.content_security_policy {
        recommendations.extend(generate_csp_recommendations(csp));
    }

    if headers.x_content_type_options.is_none() {
        recommendations
            .push("Add X-Content-Type-Options: nosniff to prevent MIME-type sniffing".to_string());
    }

    if headers.x_frame_options.is_none() {
        recommendations
            .push("Add X-Frame-Options: DENY or SAMEORIGIN to prevent clickjacking".to_string());
    }

    if https && headers.strict_transport_security.is_none() {
        recommendations.push(
            "Add Strict-Transport-Security header with max-age of at least 1 year".to_string(),
        );
    }

    if headers.permissions_policy.is_none() {
        recommendations
            .push("Add Permissions-Policy header to control browser features".to_string());
    }

    if headers.cross_origin_opener_policy.is_none() {
        recommendations.push(
            "Consider Cross-Origin-Opener-Policy (same-origin) if the site uses SharedArrayBuffer, \
             high-resolution timers, or cross-origin popups — not required for standard sites."
                .to_string(),
        );
    }

    if headers.cross_origin_resource_policy.is_none() {
        recommendations.push(
            "Consider Cross-Origin-Resource-Policy if the site serves fonts, scripts, or media \
             that other origins should not be able to load — not required if resources are intentionally public."
                .to_string(),
        );
    }

    if cors_allows_wildcard_credentials(headers) {
        recommendations.push(
            "Do not combine Access-Control-Allow-Origin: * with credentialed CORS; allowlist trusted origins instead."
                .to_string(),
        );
    }

    recommendations
}

pub(crate) fn calculate_security_score(
    _headers: &SecurityHeaders,
    ssl: &SslInfo,
    issues: &[SecurityIssue],
) -> u32 {
    let mut score = 100u32;

    // A *present* CSP (even a permissive one) provides partial protection, so its
    // cumulative quality penalty must never exceed the penalty for a *missing*
    // CSP — otherwise a site with an imperfect CSP scores worse than one with no
    // CSP at all, which is backwards. We therefore bucket CSP-quality issues and
    // cap their combined deduction at the missing-CSP penalty (High = 15).
    const MISSING_CSP_PENALTY: u32 = 15;
    let deduction = |sev: &Severity| match sev {
        Severity::Critical => 25,
        Severity::High => 15,
        Severity::Medium => 10,
        Severity::Low => 5,
    };
    let mut csp_quality_penalty = 0u32;
    for issue in issues {
        let is_csp_quality =
            issue.header == "Content-Security-Policy" && issue.issue_type != "missing_header";
        if is_csp_quality {
            csp_quality_penalty += deduction(&issue.severity);
        } else {
            // Deduct for issues (includes missing HTTPS as a critical issue)
            score = score.saturating_sub(deduction(&issue.severity));
        }
    }
    score = score.saturating_sub(csp_quality_penalty.min(MISSING_CSP_PENALTY));

    // Bonus for HSTS
    if ssl.has_hsts {
        score = score.saturating_add(5).min(100);
        if ssl.hsts_include_subdomains {
            score = score.saturating_add(3).min(100);
        }
        if ssl.hsts_preload {
            score = score.saturating_add(2).min(100);
        }
    }

    score
}

/// Coarse security sub-category (plan/5-module-accessibility-security-
/// driver-detail.md): Security has no per-check taxonomy registry like
/// WCAG's `taxonomy::Subcategory`, so this groups `SecurityIssue.header`
/// values into the handful of categories a non-technical reader would
/// recognize, mirroring the review's own example wording ("fehlende
/// Security-Header, unsichere externe Ressourcen, Cookie-/Transport-
/// Konfiguration").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SecurityCategory {
    /// CSP, X-Content-Type-Options, X-Frame-Options — baseline response
    /// headers that harden the page itself.
    #[default]
    ResponseHeaders,
    /// HTTPS/TLS transport security (HSTS).
    TransportSecurity,
    /// Cross-origin/embedding access policies (Referrer-Policy,
    /// Permissions-Policy, Cross-Origin-Opener/Resource-Policy, CORS).
    AccessPolicies,
    /// Publicly reachable source maps and other third-party/asset exposure.
    ThirdPartyExposure,
}

impl SecurityCategory {
    pub fn label(&self, en: bool) -> &'static str {
        if en {
            match self {
                Self::ResponseHeaders => "Response headers",
                Self::TransportSecurity => "Transport security",
                Self::AccessPolicies => "Access policies",
                Self::ThirdPartyExposure => "Third-party exposure",
            }
        } else {
            match self {
                Self::ResponseHeaders => "Response-Header",
                Self::TransportSecurity => "Transportsicherheit",
                Self::AccessPolicies => "Zugriffs-Richtlinien",
                Self::ThirdPartyExposure => "Drittanbieter-Exposition",
            }
        }
    }

    /// All categories, in a fixed display order.
    pub fn all() -> [SecurityCategory; 4] {
        [
            Self::ResponseHeaders,
            Self::TransportSecurity,
            Self::AccessPolicies,
            Self::ThirdPartyExposure,
        ]
    }

    fn for_header(header: &str) -> SecurityCategory {
        match header {
            "HTTPS" | "Strict-Transport-Security" => Self::TransportSecurity,
            "Content-Security-Policy" | "X-Content-Type-Options" | "X-Frame-Options" => {
                Self::ResponseHeaders
            }
            "Referrer-Policy"
            | "Permissions-Policy"
            | "Cross-Origin-Opener-Policy"
            | "Cross-Origin-Resource-Policy"
            | "Access-Control-Allow-Origin" => Self::AccessPolicies,
            "Source Map" => Self::ThirdPartyExposure,
            // Unrecognized/future header names default to the general
            // response-headers bucket rather than being silently dropped.
            _ => Self::ResponseHeaders,
        }
    }
}

/// Per-category security score (0-100), reusing the exact severity→penalty
/// mapping `calculate_security_score` uses for the overall score, just
/// scoped to the issues in each category — so a category with e.g. one
/// missing baseline header scores the same way that single issue would
/// deduct from the overall score, not a newly invented scale. A category
/// with no issues scores 100 (plan/5-module-accessibility-security-driver-
/// detail.md).
pub fn calculate_security_category_scores(
    issues: &[SecurityIssue],
) -> Vec<(SecurityCategory, u32)> {
    let deduction = |sev: &Severity| match sev {
        Severity::Critical => 25,
        Severity::High => 15,
        Severity::Medium => 10,
        Severity::Low => 5,
    };
    SecurityCategory::all()
        .into_iter()
        .map(|category| {
            let mut score = 100u32;
            for issue in issues {
                if SecurityCategory::for_header(&issue.header) == category {
                    score = score.saturating_sub(deduction(&issue.severity));
                }
            }
            (category, score)
        })
        .collect()
}

fn calculate_grade(score: u32) -> String {
    crate::registry::SECURITY_GRADE
        .label(score as f32, false)
        .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every kind this build knows must render differently in the two
    /// languages, and the English side must stay free of German characters —
    /// the #406 guard every localized module carries.
    #[test]
    fn every_security_message_is_localized_and_english_stays_english() {
        let values = SecurityIssueValues {
            hsts_max_age: Some("100".to_string()),
            hsts_include_subdomains: Some(false),
            source_map_count: Some(3),
            source_map_example: Some("https://example.com/app.js.map".to_string()),
            csp_directive: Some("object-src".to_string()),
        };
        for kind in SecurityIssueKind::ALL {
            let en = security_issue_text(kind, &values, true);
            let de = security_issue_text(kind, &values, false);
            assert!(!en.is_empty(), "{kind:?}: empty English text");
            assert_ne!(en, de, "{kind:?}: German text must differ from English");
            assert!(
                !en.chars().any(|c| "äöüÄÖÜß".contains(c)),
                "{kind:?} English text leaks German: {en}"
            );
        }
    }

    /// The generated `issue_type` strings are part of the JSON contract and
    /// must not drift when the kind enum is refactored.
    #[test]
    fn security_issue_types_match_the_stored_contract() {
        use SecurityIssueKind::*;
        let empty = SecurityIssueValues::default();
        for (kind, expected) in [
            (MissingHttps, "missing_https"),
            (MissingCsp, "missing_header"),
            (MissingCoop, "missing_header"),
            (CorsWildcardCredentials, "cors_wildcard_credentials"),
            (HstsPreloadIneligible, "hsts_preload_ineligible"),
            (PermissionsPolicyPermissive, "permissions_policy_permissive"),
            (PublicSourceMap, "public_source_map"),
            (CspUnsafeInlineScript, "unsafe_inline_script"),
            (CspUnsafeEvalScript, "unsafe_eval_script"),
            (CspWildcardScriptSource, "wildcard_script_source"),
            (CspUnsafeInlineStyle, "unsafe_inline_style"),
            (CspWildcardSource, "wildcard_source"),
        ] {
            assert_eq!(issue_type_for(kind, &empty), expected, "{kind:?}");
        }
        assert_eq!(
            issue_type_for(
                CspMissingDirective,
                &SecurityIssueValues {
                    csp_directive: Some("frame-ancestors".to_string()),
                    ..Default::default()
                }
            ),
            "missing_frame-ancestors"
        );
    }

    /// `kind()` is derived from the stored `header`/`issue_type` pair, so a
    /// report written by an older build still localizes.
    #[test]
    fn kind_round_trips_through_the_stored_fields() {
        let issue = security_issue(
            "Cross-Origin-Opener-Policy",
            SecurityIssueKind::MissingCoop,
            SecurityIssueValues::default(),
            Severity::Low,
            HeaderTier::ContextDependent,
        );
        assert_eq!(issue.kind(), Some(SecurityIssueKind::MissingCoop));
        assert_eq!(issue.message, issue.localized_message(true));
        assert_ne!(issue.message, issue.localized_message(false));
    }

    /// An issue_type this build does not know falls back to the stored
    /// canonical-English message instead of inventing a sentence.
    #[test]
    fn unknown_issue_type_falls_back_to_the_stored_message() {
        let issue = SecurityIssue {
            header: "X-Frame-Options".to_string(),
            issue_type: "something_this_build_does_not_know".to_string(),
            message: "stored message".to_string(),
            severity: Severity::Low,
            tier: HeaderTier::Baseline,
            values: SecurityIssueValues::default(),
        };
        assert_eq!(issue.kind(), None);
        assert_eq!(issue.localized_message(false), "stored message");
    }

    #[test]
    fn test_security_headers_count() {
        let headers = SecurityHeaders {
            content_security_policy: Some(strong_csp()),
            x_content_type_options: Some("nosniff".to_string()),
            x_frame_options: Some("DENY".to_string()),
            ..Default::default()
        };

        assert_eq!(headers.count(), 3);
    }

    #[test]
    fn test_generate_recommendations_coop_corp_generate_low_issues() {
        let headers = SecurityHeaders {
            content_security_policy: Some("default-src 'self'".to_string()),
            x_content_type_options: Some("nosniff".to_string()),
            x_frame_options: Some("DENY".to_string()),
            strict_transport_security: Some("max-age=31536000".to_string()),
            referrer_policy: Some("strict-origin".to_string()),
            permissions_policy: Some("camera=()".to_string()),
            ..Default::default()
        };
        let recs = generate_recommendations(&headers, true);
        // COOP and CORP absent → informational recommendations are still generated
        assert!(recs
            .iter()
            .any(|r| r.contains("Cross-Origin-Opener-Policy")));
        assert!(recs
            .iter()
            .any(|r| r.contains("Cross-Origin-Resource-Policy")));
        // COOP and CORP now generate Low-severity issues, tagged context-dependent
        let issues = generate_security_issues(&headers, true);
        assert!(issues.iter().any(|i| i.header.contains("Cross-Origin")
            && i.severity == Severity::Low
            && i.tier == HeaderTier::ContextDependent));
    }

    /// Header classification table (#578): Baseline headers apply to
    /// virtually every site, architecture-dependent ones are good practice
    /// but not universal, context-dependent relevance can't be determined
    /// from a single automated fetch, and CORS presence/absence alone isn't
    /// assessable at all.
    #[test]
    fn test_header_tier_classification() {
        assert_eq!(header_tier("Content-Security-Policy"), HeaderTier::Baseline);
        assert_eq!(
            header_tier("Strict-Transport-Security"),
            HeaderTier::Baseline
        );
        assert_eq!(header_tier("X-Content-Type-Options"), HeaderTier::Baseline);
        assert_eq!(header_tier("X-Frame-Options"), HeaderTier::Baseline);
        assert_eq!(header_tier("HTTPS"), HeaderTier::Baseline);

        assert_eq!(
            header_tier("Referrer-Policy"),
            HeaderTier::ArchitectureDependent
        );
        assert_eq!(
            header_tier("Permissions-Policy"),
            HeaderTier::ArchitectureDependent
        );

        assert_eq!(
            header_tier("Cross-Origin-Opener-Policy"),
            HeaderTier::ContextDependent
        );
        assert_eq!(
            header_tier("Cross-Origin-Resource-Policy"),
            HeaderTier::ContextDependent
        );

        assert_eq!(
            header_tier("Access-Control-Allow-Origin"),
            HeaderTier::NotAssessable
        );
        assert_eq!(
            header_tier("Access-Control-Allow-Credentials"),
            HeaderTier::NotAssessable
        );
    }

    /// "Standardmarketingseite" scenario (#578 acceptance criteria): a page
    /// with only baseline headers set and COOP/CORP missing should read as a
    /// verification question, not an unconditional "add this header"
    /// instruction — the tool cannot know whether this deployment needs
    /// cross-origin isolation at all.
    #[test]
    fn test_coop_missing_message_is_a_verification_question_not_a_flat_instruction() {
        let headers = SecurityHeaders::default();
        let issues = generate_security_issues(&headers, true);
        let coop = issues
            .iter()
            .find(|i| i.header == "Cross-Origin-Opener-Policy")
            .expect("COOP issue expected when header is absent");

        assert_eq!(coop.severity, Severity::Low);
        assert_eq!(coop.tier, HeaderTier::ContextDependent);
        assert!(
            coop.message.contains("SharedArrayBuffer"),
            "message should name the concrete scenario that makes COOP relevant: {}",
            coop.message
        );
        assert!(
            coop.message.contains("no action is needed"),
            "message should tell the reader when COOP does NOT apply: {}",
            coop.message
        );
        assert!(
            !coop.message.starts_with("Missing"),
            "message should not read as a flat missing-header instruction: {}",
            coop.message
        );
    }

    /// "Cross-Origin-Ressourcen-Szenario" (#578 acceptance criteria): CORP's
    /// guidance must name the concrete scenario (other origins loading
    /// fonts/scripts/media) rather than a blanket "add this header" line.
    #[test]
    fn test_corp_missing_message_covers_cross_origin_resource_scenario() {
        let headers = SecurityHeaders::default();
        let issues = generate_security_issues(&headers, true);
        let corp = issues
            .iter()
            .find(|i| i.header == "Cross-Origin-Resource-Policy")
            .expect("CORP issue expected when header is absent");

        assert_eq!(corp.severity, Severity::Low);
        assert_eq!(corp.tier, HeaderTier::ContextDependent);
        assert!(
            corp.message.contains("other origins"),
            "message should name the cross-origin resource-loading scenario: {}",
            corp.message
        );
        assert!(
            corp.message.contains("intentionally public"),
            "message should tell the reader when CORP does NOT apply: {}",
            corp.message
        );
    }

    #[test]
    fn permissive_csp_scores_at_least_as_high_as_missing_csp() {
        let ssl = SslInfo::default();
        // Same baseline issue set; one variant has no CSP, the other has a
        // present-but-permissive CSP that fires several quality issues.
        let missing_csp = vec![SecurityIssue {
            header: "Content-Security-Policy".into(),
            issue_type: "missing_header".into(),
            message: "Missing Content-Security-Policy header".into(),
            severity: Severity::High,
            tier: HeaderTier::Baseline,
            values: Default::default(),
        }];
        let permissive_csp: Vec<SecurityIssue> = [
            "unsafe_inline_script",
            "unsafe_eval_script",
            "wildcard_script_source",
            "unsafe_inline_style",
            "wildcard_source",
        ]
        .iter()
        .map(|t| SecurityIssue {
            header: "Content-Security-Policy".into(),
            issue_type: (*t).into(),
            message: "csp quality".into(),
            severity: Severity::High,
            tier: HeaderTier::Baseline,
            values: Default::default(),
        })
        .collect();
        let s_missing = calculate_security_score(&SecurityHeaders::default(), &ssl, &missing_csp);
        let s_permissive =
            calculate_security_score(&SecurityHeaders::default(), &ssl, &permissive_csp);
        assert!(
            s_permissive >= s_missing,
            "a present (permissive) CSP must not score worse than no CSP: permissive={s_permissive} missing={s_missing}"
        );
    }

    #[test]
    fn test_calculate_grade() {
        assert_eq!(calculate_grade(95), "A+");
        assert_eq!(calculate_grade(85), "A");
        assert_eq!(calculate_grade(75), "B");
        assert_eq!(calculate_grade(65), "C");
        assert_eq!(calculate_grade(55), "D");
        assert_eq!(calculate_grade(40), "F");
    }

    #[test]
    fn test_analyze_ssl_with_hsts() {
        let headers = SecurityHeaders {
            strict_transport_security: Some(
                "max-age=31536000; includeSubDomains; preload".to_string(),
            ),
            ..Default::default()
        };

        let ssl = analyze_ssl(true, &headers);
        assert!(ssl.https);
        assert!(ssl.has_hsts);
        assert_eq!(ssl.hsts_max_age, Some(31536000));
        assert!(ssl.hsts_include_subdomains);
        assert!(ssl.hsts_preload);
    }

    #[test]
    fn test_analyze_ssl_without_hsts() {
        let headers = SecurityHeaders::default();
        let ssl = analyze_ssl(false, &headers);
        assert!(!ssl.https);
        assert!(!ssl.has_hsts);
        assert_eq!(ssl.hsts_max_age, None);
    }

    #[test]
    fn test_generate_security_issues_no_https() {
        let headers = SecurityHeaders::default();
        let issues = generate_security_issues(&headers, false);

        assert!(issues.iter().any(|i| i.header == "HTTPS"));
        assert!(issues.iter().any(|i| i.header == "Content-Security-Policy"));
        assert!(issues.iter().any(|i| i.header == "X-Content-Type-Options"));
        // HSTS issue should NOT appear for non-HTTPS sites
        assert!(!issues
            .iter()
            .any(|i| i.header == "Strict-Transport-Security"));
    }

    #[test]
    fn test_generate_security_issues_https_no_hsts() {
        let headers = SecurityHeaders::default();
        let issues = generate_security_issues(&headers, true);

        // No HTTPS issue
        assert!(!issues.iter().any(|i| i.header == "HTTPS"));
        // But HSTS should be flagged
        assert!(issues
            .iter()
            .any(|i| i.header == "Strict-Transport-Security"));
    }

    #[test]
    fn test_generate_security_issues_all_headers_present() {
        let headers = SecurityHeaders {
            content_security_policy: Some(strong_csp()),
            x_content_type_options: Some("nosniff".to_string()),
            x_frame_options: Some("DENY".to_string()),
            strict_transport_security: Some("max-age=31536000".to_string()),
            referrer_policy: Some("strict-origin".to_string()),
            permissions_policy: Some("camera=()".to_string()),
            cross_origin_opener_policy: Some("same-origin".to_string()),
            cross_origin_resource_policy: Some("same-origin".to_string()),
            ..Default::default()
        };
        let issues = generate_security_issues(&headers, true);
        assert!(issues.is_empty());
    }

    #[test]
    fn test_cors_wildcard_credentials_generates_high_issue() {
        let headers = SecurityHeaders {
            access_control_allow_origin: Some("*".to_string()),
            access_control_allow_credentials: Some("true".to_string()),
            ..Default::default()
        };

        let issues = generate_security_issues(&headers, true);
        assert!(issues.iter().any(|issue| {
            issue.issue_type == "cors_wildcard_credentials" && issue.severity == Severity::High
        }));
    }

    #[test]
    fn test_cors_wildcard_without_credentials_is_not_flagged() {
        let headers = SecurityHeaders {
            access_control_allow_origin: Some("*".to_string()),
            ..Default::default()
        };

        let issues = generate_security_issues(&headers, true);
        assert!(!issues
            .iter()
            .any(|issue| issue.issue_type == "cors_wildcard_credentials"));
    }

    #[test]
    fn hsts_preload_ineligible_flags_short_max_age() {
        let ssl = SslInfo {
            hsts_preload: true,
            hsts_max_age: Some(3600),
            hsts_include_subdomains: true,
            ..Default::default()
        };
        assert!(hsts_preload_ineligible(&ssl));
    }

    #[test]
    fn hsts_preload_ineligible_flags_missing_subdomains() {
        let ssl = SslInfo {
            hsts_preload: true,
            hsts_max_age: Some(31536000),
            hsts_include_subdomains: false,
            ..Default::default()
        };
        assert!(hsts_preload_ineligible(&ssl));
    }

    #[test]
    fn hsts_preload_eligible_is_not_flagged() {
        let ssl = SslInfo {
            hsts_preload: true,
            hsts_max_age: Some(31536000),
            hsts_include_subdomains: true,
            ..Default::default()
        };
        assert!(!hsts_preload_ineligible(&ssl));
    }

    #[test]
    fn hsts_preload_not_set_is_not_flagged_regardless_of_max_age() {
        let ssl = SslInfo {
            hsts_preload: false,
            hsts_max_age: Some(60),
            hsts_include_subdomains: false,
            ..Default::default()
        };
        assert!(!hsts_preload_ineligible(&ssl));
    }

    #[test]
    fn permissions_policy_empty_value_is_permissive() {
        let headers = SecurityHeaders {
            permissions_policy: Some("".to_string()),
            ..Default::default()
        };
        assert!(permissions_policy_is_permissive(&headers));
    }

    #[test]
    fn permissions_policy_wildcard_only_is_permissive() {
        let headers = SecurityHeaders {
            permissions_policy: Some("camera=*, microphone=*".to_string()),
            ..Default::default()
        };
        assert!(permissions_policy_is_permissive(&headers));
    }

    #[test]
    fn permissions_policy_restrictive_is_not_flagged() {
        let headers = SecurityHeaders {
            permissions_policy: Some("camera=(), microphone=(self)".to_string()),
            ..Default::default()
        };
        assert!(!permissions_policy_is_permissive(&headers));
    }

    #[test]
    fn permissions_policy_absent_is_not_flagged_as_permissive() {
        let headers = SecurityHeaders::default();
        assert!(!permissions_policy_is_permissive(&headers));
    }

    #[test]
    fn test_csp_quality_flags_unsafe_and_wildcards() {
        let issues = collect_csp_quality_issues(
            "default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*",
        );

        assert!(issues
            .iter()
            .any(|issue| issue.issue_type == "unsafe_inline_script"));
        assert!(issues
            .iter()
            .any(|issue| issue.issue_type == "unsafe_eval_script"));
        assert!(issues
            .iter()
            .any(|issue| issue.issue_type == "wildcard_script_source"));
        assert!(issues
            .iter()
            .any(|issue| issue.issue_type == "missing_object-src"));
    }

    #[test]
    fn test_csp_quality_accepts_nonce_hardened_policy() {
        let issues = collect_csp_quality_issues(
            "default-src 'self'; script-src 'self' 'nonce-abc123'; style-src 'self' 'sha256-abc'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'",
        );

        assert!(issues.is_empty());
    }

    #[test]
    fn test_csp_recommendations_explain_quality_findings() {
        let recommendations =
            generate_csp_recommendations("default-src *; script-src 'unsafe-inline' 'unsafe-eval'");

        assert!(recommendations
            .iter()
            .any(|recommendation| recommendation.contains("unsafe-inline")));
        assert!(recommendations
            .iter()
            .any(|recommendation| recommendation.contains("unsafe-eval")));
        assert!(recommendations
            .iter()
            .any(|recommendation| recommendation.contains("wildcard")));
    }

    #[test]
    fn test_generate_recommendations() {
        let headers = SecurityHeaders::default();
        let recs = generate_recommendations(&headers, true);

        assert!(recs.iter().any(|r| r.contains("Content-Security-Policy")));
        assert!(recs.iter().any(|r| r.contains("X-Content-Type-Options")));
        assert!(recs.iter().any(|r| r.contains("Strict-Transport-Security")));
    }

    #[test]
    fn test_calculate_security_score_perfect() {
        let headers = SecurityHeaders::default();
        let ssl = SslInfo {
            https: true,
            valid_certificate: true,
            has_hsts: true,
            hsts_max_age: Some(31536000),
            hsts_include_subdomains: true,
            hsts_preload: true,
            ..Default::default()
        };
        let issues = vec![];
        let score = calculate_security_score(&headers, &ssl, &issues);
        // 100 base + 5 (hsts) + 3 (subdomains) + 2 (preload) = 110, capped at 100
        assert_eq!(score, 100);
    }

    #[test]
    fn test_calculate_security_score_no_https() {
        let headers = SecurityHeaders::default();
        let ssl = SslInfo::default();
        let issues = generate_security_issues(&headers, false);
        let score = calculate_security_score(&headers, &ssl, &issues);
        // Should lose points for critical (HTTPS) + high (CSP) + medium (XCT, XFO) + low (referrer)
        assert!(score < 50);
    }

    fn strong_csp() -> String {
        "default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'".to_string()
    }
}