lonkero 3.6.2

Web scanner built for actual pentests. Fast, modular, 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
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

/**
 * Bountyy Oy - BFLA (Broken Function Level Authorization) Scanner
 * OWASP API Security Top 10 #5 - Broken Function Level Authorization
 *
 * Tests for vertical privilege escalation where users can access
 * administrative or privileged functions without proper authorization.
 *
 * @copyright 2026 Bountyy Oy
 * @license Proprietary
 */
use crate::detection_helpers::AppCharacteristics;
use crate::http_client::HttpClient;
use crate::types::{Confidence, ScanConfig, Severity, Vulnerability};
use anyhow::Result;
use rand::Rng;
use regex::Regex;
use std::collections::HashSet;
use std::sync::Arc;
use tracing::{debug, info, warn};

/// BFLA (Broken Function Level Authorization) Scanner
///
/// This scanner identifies endpoints where function-level authorization checks
/// are missing or improperly implemented, allowing regular users to access
/// privileged/administrative functions.
pub struct BrokenFunctionAuthScanner {
    http_client: Arc<HttpClient>,
}

/// Detected API pattern
#[derive(Debug, Clone, PartialEq)]
pub enum ApiPattern {
    Rest,
    GraphQL,
    JsonRpc,
    Soap,
    Unknown,
}

/// Authorization scheme detected
#[derive(Debug, Clone, PartialEq)]
pub enum AuthScheme {
    Jwt,
    Session,
    ApiKey,
    Basic,
    OAuth,
    None,
    Unknown,
}

/// Privilege level of an endpoint
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum PrivilegeLevel {
    Public,
    Authenticated,
    Elevated,
    Admin,
    SuperAdmin,
}

/// Information about a discovered endpoint
#[derive(Debug, Clone)]
pub struct EndpointInfo {
    pub url: String,
    pub path: String,
    pub method: String,
    pub privilege_level: PrivilegeLevel,
    pub function_category: FunctionCategory,
    pub requires_auth: bool,
}

/// Function categories to test for BFLA
#[derive(Debug, Clone, PartialEq)]
pub enum FunctionCategory {
    UserManagement,    // Create/delete users
    Configuration,     // System configuration
    DataExport,        // Data export/import
    SystemOperations,  // System-level operations
    AuditLogs,         // Audit/logging controls
    FinancialOps,      // Financial operations
    RoleManagement,    // Role/permission changes
    ContentModeration, // Content moderation
    Analytics,         // Analytics/reporting
    Deployment,        // Deployment operations
    General,           // General admin functions
}

impl BrokenFunctionAuthScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        Self { http_client }
    }

    /// Main scan entry point
    ///
    /// Tests for BFLA vulnerabilities by:
    /// 1. Detecting API patterns and authorization schemes
    /// 2. Discovering admin/privileged endpoints
    /// 3. Testing cross-privilege access
    /// 4. HTTP method tampering
    /// 5. Authorization bypass techniques
    pub async fn scan(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        // License check
        if !crate::license::verify_scan_authorized() {
            info!("[SKIP] BFLA scanning requires valid license");
            return Ok((Vec::new(), 0));
        }

        info!(
            "Starting BFLA (Broken Function Level Authorization) scan on {}",
            url
        );

        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // Phase 1: Fetch baseline and detect application characteristics
        let baseline_response = match self.http_client.get(url).await {
            Ok(response) => response,
            Err(e) => {
                warn!("Failed to fetch baseline response: {}", e);
                return Ok((Vec::new(), 0));
            }
        };

        let characteristics = AppCharacteristics::from_response(&baseline_response, url);

        // Skip if target is static/non-API site
        if characteristics.is_static && !characteristics.is_api {
            info!("[BFLA] Target appears to be a static site - skipping BFLA tests");
            return Ok((Vec::new(), 0));
        }

        // Phase 2: Detect API pattern and authorization scheme
        let api_pattern = self.detect_api_pattern(&baseline_response, url);
        let auth_scheme = self.detect_auth_scheme(&baseline_response);

        info!(
            "[BFLA] Detected API pattern: {:?}, Auth scheme: {:?}",
            api_pattern, auth_scheme
        );

        // Phase 3: Discover admin/privileged endpoints
        let admin_endpoints = self
            .discover_admin_endpoints(url, &baseline_response)
            .await?;
        info!(
            "[BFLA] Discovered {} potential admin endpoints",
            admin_endpoints.len()
        );

        if admin_endpoints.is_empty() {
            debug!("[BFLA] No admin endpoints discovered");
            return Ok((vulnerabilities, tests_run));
        }

        // Phase 4: Test each admin endpoint for BFLA
        for endpoint in &admin_endpoints {
            // Test with no authorization
            tests_run += 1;
            if let Some(vuln) = self.test_no_auth_access(endpoint).await? {
                vulnerabilities.push(vuln);
            }

            // Test with removed authorization header
            tests_run += 1;
            if let Some(vuln) = self
                .test_removed_auth_header(endpoint, &auth_scheme)
                .await?
            {
                vulnerabilities.push(vuln);
            }

            // Test HTTP method tampering
            let (method_vulns, method_tests) = self.test_http_method_tampering(endpoint).await?;
            vulnerabilities.extend(method_vulns);
            tests_run += method_tests;

            // Test role parameter manipulation
            tests_run += 1;
            if let Some(vuln) = self.test_role_parameter_manipulation(endpoint).await? {
                vulnerabilities.push(vuln);
            }

            // Test path traversal to admin functions
            tests_run += 1;
            if let Some(vuln) = self.test_path_traversal_bypass(endpoint).await? {
                vulnerabilities.push(vuln);
            }
        }

        // Phase 5: Test version enumeration bypass
        let (version_vulns, version_tests) = self.test_version_enumeration(url).await?;
        vulnerabilities.extend(version_vulns);
        tests_run += version_tests;

        // Phase 6: GraphQL-specific tests if GraphQL detected
        if api_pattern == ApiPattern::GraphQL {
            let (graphql_vulns, graphql_tests) =
                self.test_graphql_function_authorization(url).await?;
            vulnerabilities.extend(graphql_vulns);
            tests_run += graphql_tests;
        }

        // Phase 7: Test function category access patterns
        let (category_vulns, category_tests) = self
            .test_function_category_access(url, &admin_endpoints)
            .await?;
        vulnerabilities.extend(category_vulns);
        tests_run += category_tests;

        info!(
            "[BFLA] Scan completed: {} tests run, {} vulnerabilities found",
            tests_run,
            vulnerabilities.len()
        );

        Ok((vulnerabilities, tests_run))
    }

    /// Detect API pattern from response
    fn detect_api_pattern(
        &self,
        response: &crate::http_client::HttpResponse,
        url: &str,
    ) -> ApiPattern {
        let body = &response.body;
        let body_lower = body.to_lowercase();
        let url_lower = url.to_lowercase();

        // GraphQL detection
        if url_lower.contains("/graphql") || body.contains("__schema") || body.contains("query {") {
            return ApiPattern::GraphQL;
        }

        // JSON-RPC detection
        if body.contains("\"jsonrpc\"")
            || body.contains("\"method\"") && body.contains("\"params\"")
        {
            return ApiPattern::JsonRpc;
        }

        // SOAP detection
        if body_lower.contains("soap:envelope") || body_lower.contains("wsdl") {
            return ApiPattern::Soap;
        }

        // REST detection (most common)
        if let Some(content_type) = response.headers.get("content-type") {
            if content_type.contains("application/json") {
                return ApiPattern::Rest;
            }
        }

        // Check URL patterns for REST
        if url_lower.contains("/api/")
            || url_lower.contains("/v1/")
            || url_lower.contains("/v2/")
            || url_lower.contains("/rest/")
        {
            return ApiPattern::Rest;
        }

        ApiPattern::Unknown
    }

    /// Detect authorization scheme from response
    fn detect_auth_scheme(&self, response: &crate::http_client::HttpResponse) -> AuthScheme {
        let headers = &response.headers;
        let body = &response.body;

        // Check for JWT indicators
        if body.contains("eyJ")
            || headers
                .get("authorization")
                .map_or(false, |h| h.contains("Bearer"))
        {
            return AuthScheme::Jwt;
        }

        // Check for API key
        if headers.contains_key("x-api-key") || body.contains("api_key") || body.contains("apiKey")
        {
            return AuthScheme::ApiKey;
        }

        // Check for OAuth
        if body.contains("oauth") || body.contains("access_token") {
            return AuthScheme::OAuth;
        }

        // Check for session cookies
        if let Some(cookie) = headers.get("set-cookie") {
            let cookie_lower = cookie.to_lowercase();
            if cookie_lower.contains("session")
                || cookie_lower.contains("phpsessid")
                || cookie_lower.contains("jsessionid")
            {
                return AuthScheme::Session;
            }
        }

        // Check for Basic auth
        if headers
            .get("www-authenticate")
            .map_or(false, |h| h.contains("Basic"))
        {
            return AuthScheme::Basic;
        }

        AuthScheme::Unknown
    }

    /// Discover admin/privileged endpoints
    async fn discover_admin_endpoints(
        &self,
        base_url: &str,
        baseline_response: &crate::http_client::HttpResponse,
    ) -> Result<Vec<EndpointInfo>> {
        let mut endpoints = Vec::new();
        let parsed_url = match url::Url::parse(base_url) {
            Ok(u) => u,
            Err(_) => return Ok(endpoints),
        };

        let base = format!(
            "{}://{}",
            parsed_url.scheme(),
            parsed_url.host_str().unwrap_or("")
        );

        // Common admin endpoint patterns
        let admin_patterns = vec![
            // Top-level admin paths
            ("/admin", PrivilegeLevel::Admin, FunctionCategory::General),
            ("/admin/", PrivilegeLevel::Admin, FunctionCategory::General),
            (
                "/administrator",
                PrivilegeLevel::Admin,
                FunctionCategory::General,
            ),
            (
                "/management",
                PrivilegeLevel::Admin,
                FunctionCategory::General,
            ),
            (
                "/internal",
                PrivilegeLevel::Elevated,
                FunctionCategory::General,
            ),
            (
                "/console",
                PrivilegeLevel::Admin,
                FunctionCategory::SystemOperations,
            ),
            (
                "/dashboard",
                PrivilegeLevel::Elevated,
                FunctionCategory::Analytics,
            ),
            ("/panel", PrivilegeLevel::Admin, FunctionCategory::General),
            (
                "/control",
                PrivilegeLevel::Admin,
                FunctionCategory::SystemOperations,
            ),
            (
                "/superadmin",
                PrivilegeLevel::SuperAdmin,
                FunctionCategory::General,
            ),
            // API admin paths
            (
                "/api/admin",
                PrivilegeLevel::Admin,
                FunctionCategory::General,
            ),
            (
                "/api/v1/admin",
                PrivilegeLevel::Admin,
                FunctionCategory::General,
            ),
            (
                "/api/v2/admin",
                PrivilegeLevel::Admin,
                FunctionCategory::General,
            ),
            (
                "/api/internal",
                PrivilegeLevel::Elevated,
                FunctionCategory::General,
            ),
            (
                "/api/management",
                PrivilegeLevel::Admin,
                FunctionCategory::General,
            ),
            (
                "/api/admin/users",
                PrivilegeLevel::Admin,
                FunctionCategory::UserManagement,
            ),
            (
                "/api/admin/roles",
                PrivilegeLevel::Admin,
                FunctionCategory::RoleManagement,
            ),
            (
                "/api/admin/config",
                PrivilegeLevel::Admin,
                FunctionCategory::Configuration,
            ),
            (
                "/api/admin/settings",
                PrivilegeLevel::Admin,
                FunctionCategory::Configuration,
            ),
            // User management
            (
                "/api/users/create",
                PrivilegeLevel::Admin,
                FunctionCategory::UserManagement,
            ),
            (
                "/api/users/delete",
                PrivilegeLevel::Admin,
                FunctionCategory::UserManagement,
            ),
            (
                "/api/users/all",
                PrivilegeLevel::Admin,
                FunctionCategory::UserManagement,
            ),
            (
                "/api/users/list",
                PrivilegeLevel::Elevated,
                FunctionCategory::UserManagement,
            ),
            (
                "/users/manage",
                PrivilegeLevel::Admin,
                FunctionCategory::UserManagement,
            ),
            (
                "/users/admin",
                PrivilegeLevel::Admin,
                FunctionCategory::UserManagement,
            ),
            // Configuration
            (
                "/api/config",
                PrivilegeLevel::Admin,
                FunctionCategory::Configuration,
            ),
            (
                "/api/settings",
                PrivilegeLevel::Elevated,
                FunctionCategory::Configuration,
            ),
            (
                "/api/configuration",
                PrivilegeLevel::Admin,
                FunctionCategory::Configuration,
            ),
            (
                "/settings/system",
                PrivilegeLevel::Admin,
                FunctionCategory::Configuration,
            ),
            (
                "/config/global",
                PrivilegeLevel::Admin,
                FunctionCategory::Configuration,
            ),
            // Data export/import
            (
                "/api/export",
                PrivilegeLevel::Elevated,
                FunctionCategory::DataExport,
            ),
            (
                "/api/import",
                PrivilegeLevel::Elevated,
                FunctionCategory::DataExport,
            ),
            (
                "/api/backup",
                PrivilegeLevel::Admin,
                FunctionCategory::DataExport,
            ),
            (
                "/api/data/export",
                PrivilegeLevel::Elevated,
                FunctionCategory::DataExport,
            ),
            (
                "/api/data/dump",
                PrivilegeLevel::Admin,
                FunctionCategory::DataExport,
            ),
            (
                "/export/all",
                PrivilegeLevel::Admin,
                FunctionCategory::DataExport,
            ),
            // System operations
            (
                "/api/system",
                PrivilegeLevel::Admin,
                FunctionCategory::SystemOperations,
            ),
            (
                "/api/health",
                PrivilegeLevel::Authenticated,
                FunctionCategory::SystemOperations,
            ),
            (
                "/api/status",
                PrivilegeLevel::Authenticated,
                FunctionCategory::SystemOperations,
            ),
            (
                "/api/restart",
                PrivilegeLevel::SuperAdmin,
                FunctionCategory::SystemOperations,
            ),
            (
                "/api/shutdown",
                PrivilegeLevel::SuperAdmin,
                FunctionCategory::SystemOperations,
            ),
            (
                "/system/info",
                PrivilegeLevel::Admin,
                FunctionCategory::SystemOperations,
            ),
            // Audit/logging
            (
                "/api/audit",
                PrivilegeLevel::Admin,
                FunctionCategory::AuditLogs,
            ),
            (
                "/api/logs",
                PrivilegeLevel::Admin,
                FunctionCategory::AuditLogs,
            ),
            (
                "/api/audit/logs",
                PrivilegeLevel::Admin,
                FunctionCategory::AuditLogs,
            ),
            (
                "/logs/access",
                PrivilegeLevel::Admin,
                FunctionCategory::AuditLogs,
            ),
            (
                "/logs/security",
                PrivilegeLevel::Admin,
                FunctionCategory::AuditLogs,
            ),
            // Financial operations
            (
                "/api/billing",
                PrivilegeLevel::Elevated,
                FunctionCategory::FinancialOps,
            ),
            (
                "/api/payments",
                PrivilegeLevel::Elevated,
                FunctionCategory::FinancialOps,
            ),
            (
                "/api/transactions",
                PrivilegeLevel::Elevated,
                FunctionCategory::FinancialOps,
            ),
            (
                "/api/refund",
                PrivilegeLevel::Elevated,
                FunctionCategory::FinancialOps,
            ),
            (
                "/api/invoice/create",
                PrivilegeLevel::Elevated,
                FunctionCategory::FinancialOps,
            ),
            // Role management
            (
                "/api/roles",
                PrivilegeLevel::Admin,
                FunctionCategory::RoleManagement,
            ),
            (
                "/api/permissions",
                PrivilegeLevel::Admin,
                FunctionCategory::RoleManagement,
            ),
            (
                "/api/acl",
                PrivilegeLevel::Admin,
                FunctionCategory::RoleManagement,
            ),
            (
                "/roles/assign",
                PrivilegeLevel::Admin,
                FunctionCategory::RoleManagement,
            ),
            // Content moderation
            (
                "/api/moderate",
                PrivilegeLevel::Elevated,
                FunctionCategory::ContentModeration,
            ),
            (
                "/api/content/approve",
                PrivilegeLevel::Elevated,
                FunctionCategory::ContentModeration,
            ),
            (
                "/api/content/delete",
                PrivilegeLevel::Elevated,
                FunctionCategory::ContentModeration,
            ),
            // Analytics
            (
                "/api/analytics",
                PrivilegeLevel::Elevated,
                FunctionCategory::Analytics,
            ),
            (
                "/api/reports",
                PrivilegeLevel::Elevated,
                FunctionCategory::Analytics,
            ),
            (
                "/api/stats",
                PrivilegeLevel::Elevated,
                FunctionCategory::Analytics,
            ),
            (
                "/api/metrics",
                PrivilegeLevel::Elevated,
                FunctionCategory::Analytics,
            ),
            // Deployment
            (
                "/api/deploy",
                PrivilegeLevel::Admin,
                FunctionCategory::Deployment,
            ),
            (
                "/api/release",
                PrivilegeLevel::Admin,
                FunctionCategory::Deployment,
            ),
            (
                "/api/publish",
                PrivilegeLevel::Elevated,
                FunctionCategory::Deployment,
            ),
        ];

        // Also extract endpoints from the response body
        let extracted_paths = self.extract_api_paths_from_body(&baseline_response.body);

        // Test common admin patterns
        for (path, privilege_level, category) in admin_patterns {
            let full_url = format!("{}{}", base, path);

            match self.http_client.get(&full_url).await {
                Ok(response) => {
                    // Consider endpoint exists if not 404
                    if response.status_code != 404 {
                        let requires_auth =
                            response.status_code == 401 || response.status_code == 403;

                        endpoints.push(EndpointInfo {
                            url: full_url,
                            path: path.to_string(),
                            method: "GET".to_string(),
                            privilege_level: privilege_level.clone(),
                            function_category: category.clone(),
                            requires_auth,
                        });

                        debug!(
                            "[BFLA] Found endpoint: {} (status: {})",
                            path, response.status_code
                        );
                    }
                }
                Err(e) => {
                    debug!("[BFLA] Error checking {}: {}", path, e);
                }
            }
        }

        // Add extracted paths
        for path in extracted_paths {
            let full_url = format!("{}{}", base, path);
            if !endpoints.iter().any(|e| e.url == full_url) {
                let privilege_level = self.classify_path_privilege(&path);
                let category = self.classify_function_category(&path);

                endpoints.push(EndpointInfo {
                    url: full_url,
                    path: path.clone(),
                    method: "GET".to_string(),
                    privilege_level,
                    function_category: category,
                    requires_auth: true,
                });
            }
        }

        Ok(endpoints)
    }

    /// Extract API paths from response body
    fn extract_api_paths_from_body(&self, body: &str) -> Vec<String> {
        let mut paths = HashSet::new();

        // Pattern for API paths
        let patterns = vec![
            r#"["'](/api/[a-zA-Z0-9_/-]+)["']"#,
            r#"["'](/admin[a-zA-Z0-9_/-]*)["']"#,
            r#"["'](/management[a-zA-Z0-9_/-]*)["']"#,
            r#"["'](/internal[a-zA-Z0-9_/-]*)["']"#,
            r#"href=["']([^"']*admin[^"']*)["']"#,
            r#"action=["']([^"']*admin[^"']*)["']"#,
        ];

        for pattern_str in patterns {
            if let Ok(re) = Regex::new(pattern_str) {
                for cap in re.captures_iter(body) {
                    if let Some(path_match) = cap.get(1) {
                        let path = path_match.as_str();
                        // Filter out static assets
                        if !path.contains(".js")
                            && !path.contains(".css")
                            && !path.contains(".png")
                            && !path.contains(".jpg")
                            && !path.contains(".svg")
                        {
                            if path.starts_with('/') {
                                paths.insert(path.to_string());
                            }
                        }
                    }
                }
            }
        }

        paths.into_iter().collect()
    }

    /// Classify path privilege level
    fn classify_path_privilege(&self, path: &str) -> PrivilegeLevel {
        let path_lower = path.to_lowercase();

        if path_lower.contains("superadmin") || path_lower.contains("super_admin") {
            return PrivilegeLevel::SuperAdmin;
        }

        if path_lower.contains("admin")
            || path_lower.contains("management")
            || path_lower.contains("system")
        {
            return PrivilegeLevel::Admin;
        }

        if path_lower.contains("internal")
            || path_lower.contains("moderate")
            || path_lower.contains("elevated")
        {
            return PrivilegeLevel::Elevated;
        }

        if path_lower.contains("user") || path_lower.contains("account") {
            return PrivilegeLevel::Authenticated;
        }

        PrivilegeLevel::Authenticated
    }

    /// Classify function category
    fn classify_function_category(&self, path: &str) -> FunctionCategory {
        let path_lower = path.to_lowercase();

        if path_lower.contains("user") || path_lower.contains("account") {
            return FunctionCategory::UserManagement;
        }
        if path_lower.contains("config") || path_lower.contains("setting") {
            return FunctionCategory::Configuration;
        }
        if path_lower.contains("export")
            || path_lower.contains("import")
            || path_lower.contains("backup")
        {
            return FunctionCategory::DataExport;
        }
        if path_lower.contains("system")
            || path_lower.contains("restart")
            || path_lower.contains("shutdown")
        {
            return FunctionCategory::SystemOperations;
        }
        if path_lower.contains("audit") || path_lower.contains("log") {
            return FunctionCategory::AuditLogs;
        }
        if path_lower.contains("billing")
            || path_lower.contains("payment")
            || path_lower.contains("invoice")
        {
            return FunctionCategory::FinancialOps;
        }
        if path_lower.contains("role")
            || path_lower.contains("permission")
            || path_lower.contains("acl")
        {
            return FunctionCategory::RoleManagement;
        }
        if path_lower.contains("moderate") || path_lower.contains("approve") {
            return FunctionCategory::ContentModeration;
        }
        if path_lower.contains("analytics")
            || path_lower.contains("report")
            || path_lower.contains("stats")
        {
            return FunctionCategory::Analytics;
        }
        if path_lower.contains("deploy") || path_lower.contains("release") {
            return FunctionCategory::Deployment;
        }

        FunctionCategory::General
    }

    /// Test access without any authorization
    async fn test_no_auth_access(&self, endpoint: &EndpointInfo) -> Result<Option<Vulnerability>> {
        debug!("[BFLA] Testing no-auth access: {}", endpoint.url);

        let response = self.http_client.get(&endpoint.url).await?;

        // Check if we got access without authentication
        if response.status_code == 200 {
            let is_real_content =
                self.is_privileged_content(&response.body, &endpoint.function_category);

            if is_real_content {
                return Ok(Some(self.create_bfla_vulnerability(
                    &endpoint.url,
                    &endpoint.path,
                    "GET",
                    "No Authorization",
                    "Accessed admin endpoint without any authentication",
                    &response,
                    &endpoint.function_category,
                    &endpoint.privilege_level,
                )));
            }
        }

        Ok(None)
    }

    /// Test with removed authorization header
    async fn test_removed_auth_header(
        &self,
        endpoint: &EndpointInfo,
        auth_scheme: &AuthScheme,
    ) -> Result<Option<Vulnerability>> {
        debug!("[BFLA] Testing removed auth header: {}", endpoint.url);

        // Only test if endpoint previously required auth
        if !endpoint.requires_auth {
            return Ok(None);
        }

        // Headers that bypass auth checks
        let bypass_headers = match auth_scheme {
            AuthScheme::Jwt => vec![
                ("Authorization", "Bearer invalidtoken"),
                ("Authorization", "Bearer "),
                ("X-Auth-Token", ""),
            ],
            AuthScheme::ApiKey => vec![
                ("X-Api-Key", ""),
                ("X-API-Key", "invalid"),
                ("Api-Key", "test"),
            ],
            AuthScheme::Session => vec![("Cookie", "session=invalid"), ("Cookie", "")],
            _ => vec![("Authorization", ""), ("X-Auth-Token", "")],
        };

        for (header_name, header_value) in bypass_headers {
            let headers = vec![(header_name.to_string(), header_value.to_string())];

            match self
                .http_client
                .get_with_headers(&endpoint.url, headers)
                .await
            {
                Ok(response) => {
                    if response.status_code == 200 {
                        let is_real_content =
                            self.is_privileged_content(&response.body, &endpoint.function_category);

                        if is_real_content {
                            return Ok(Some(self.create_bfla_vulnerability(
                                &endpoint.url,
                                &endpoint.path,
                                "GET",
                                &format!("Empty/Invalid {} Header", header_name),
                                &format!(
                                    "Bypassed authorization using {}: {}",
                                    header_name, header_value
                                ),
                                &response,
                                &endpoint.function_category,
                                &endpoint.privilege_level,
                            )));
                        }
                    }
                }
                Err(e) => {
                    debug!("[BFLA] Header bypass test error: {}", e);
                }
            }
        }

        Ok(None)
    }

    /// Test HTTP method tampering
    async fn test_http_method_tampering(
        &self,
        endpoint: &EndpointInfo,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let methods_to_test = vec!["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"];

        for method in methods_to_test {
            if method == endpoint.method {
                continue;
            }

            tests_run += 1;

            match self
                .http_client
                .request_with_method(method, &endpoint.url)
                .await
            {
                Ok(response) => {
                    // Check if different method bypassed auth
                    if response.status_code == 200 && endpoint.requires_auth {
                        let is_real_content =
                            self.is_privileged_content(&response.body, &endpoint.function_category);

                        if is_real_content {
                            vulnerabilities.push(self.create_bfla_vulnerability(
                                &endpoint.url,
                                &endpoint.path,
                                method,
                                "HTTP Method Tampering",
                                &format!(
                                    "Changed HTTP method from {} to {} to bypass authorization",
                                    endpoint.method, method
                                ),
                                &response,
                                &endpoint.function_category,
                                &endpoint.privilege_level,
                            ));
                        }
                    }

                    // Check for method-specific vulnerabilities
                    if method == "DELETE" && response.status_code == 200 {
                        vulnerabilities.push(Vulnerability {
                            id: generate_uuid(),
                            vuln_type: "BFLA - Unprotected DELETE Method".to_string(),
                            severity: Severity::Critical,
                            confidence: Confidence::High,
                            category: "Authorization".to_string(),
                            url: endpoint.url.clone(),
                            parameter: Some("HTTP Method".to_string()),
                            payload: format!("DELETE {}", endpoint.path),
                            description: format!(
                                "The DELETE method is allowed on admin endpoint {} without proper authorization. \
                                This could allow attackers to delete critical data or resources.",
                                endpoint.path
                            ),
                            evidence: Some(format!("DELETE request returned HTTP 200")),
                            cwe: "CWE-285".to_string(),
                            cvss: 9.0,
                            verified: true,
                            false_positive: false,
                            remediation: self.get_bfla_remediation(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
                        });
                    }
                }
                Err(e) => {
                    debug!("[BFLA] Method {} test error: {}", method, e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test role parameter manipulation
    async fn test_role_parameter_manipulation(
        &self,
        endpoint: &EndpointInfo,
    ) -> Result<Option<Vulnerability>> {
        debug!(
            "[BFLA] Testing role parameter manipulation: {}",
            endpoint.url
        );

        let role_params = vec![
            ("role", "admin"),
            ("role", "administrator"),
            ("role", "superuser"),
            ("user_role", "admin"),
            ("userRole", "admin"),
            ("is_admin", "true"),
            ("isAdmin", "true"),
            ("admin", "true"),
            ("privilege", "admin"),
            ("access_level", "admin"),
            ("accessLevel", "9999"),
            ("permissions", "all"),
        ];

        for (param_name, param_value) in role_params {
            let test_url = if endpoint.url.contains('?') {
                format!("{}&{}={}", endpoint.url, param_name, param_value)
            } else {
                format!("{}?{}={}", endpoint.url, param_name, param_value)
            };

            match self.http_client.get(&test_url).await {
                Ok(response) => {
                    if response.status_code == 200 {
                        let is_real_content =
                            self.is_privileged_content(&response.body, &endpoint.function_category);

                        if is_real_content {
                            return Ok(Some(self.create_bfla_vulnerability(
                                &test_url,
                                &endpoint.path,
                                "GET",
                                "Role Parameter Manipulation",
                                &format!(
                                    "Bypassed authorization by setting {}={}",
                                    param_name, param_value
                                ),
                                &response,
                                &endpoint.function_category,
                                &endpoint.privilege_level,
                            )));
                        }
                    }
                }
                Err(e) => {
                    debug!("[BFLA] Role param test error: {}", e);
                }
            }
        }

        Ok(None)
    }

    /// Test path traversal to admin functions
    async fn test_path_traversal_bypass(
        &self,
        endpoint: &EndpointInfo,
    ) -> Result<Option<Vulnerability>> {
        debug!("[BFLA] Testing path traversal bypass: {}", endpoint.url);

        let parsed = match url::Url::parse(&endpoint.url) {
            Ok(u) => u,
            Err(_) => return Ok(None),
        };

        let base = format!("{}://{}", parsed.scheme(), parsed.host_str().unwrap_or(""));

        let path_bypasses = vec![
            // Path normalization bypasses
            format!("{}/./admin", base),
            format!("{}/../admin", base),
            format!("{}/;/admin", base),
            format!("{}/.;/admin", base),
            format!("{}/..;/admin", base),
            format!("{}//admin", base),
            format!("{}/%2e/admin", base),
            format!("{}/%2e%2e/admin", base),
            format!("{}/.%2e/admin", base),
            format!("{}/admin%00", base),
            format!("{}/admin%20", base),
            format!("{}/admin%09", base),
            // Case variation
            format!("{}/ADMIN", base),
            format!("{}/Admin", base),
            format!("{}/aDmIn", base),
        ];

        for bypass_url in path_bypasses {
            match self.http_client.get(&bypass_url).await {
                Ok(response) => {
                    if response.status_code == 200 {
                        let is_real_content =
                            self.is_privileged_content(&response.body, &endpoint.function_category);

                        if is_real_content {
                            return Ok(Some(Vulnerability {
                                id: generate_uuid(),
                                vuln_type: "BFLA - Path Traversal Authorization Bypass".to_string(),
                                severity: Severity::High,
                                confidence: Confidence::High,
                                category: "Authorization".to_string(),
                                url: bypass_url.clone(),
                                parameter: Some("Path".to_string()),
                                payload: bypass_url.clone(),
                                description: format!(
                                    "Admin functionality accessible via path traversal bypass. \
                                    The application's URL normalization allows bypassing function-level authorization checks."
                                ),
                                evidence: Some(format!("Bypass URL {} returned HTTP 200 with admin content", bypass_url)),
                                cwe: "CWE-285".to_string(),
                                cvss: 8.5,
                                verified: true,
                                false_positive: false,
                                remediation: self.get_bfla_remediation(),
                                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
                            }));
                        }
                    }
                }
                Err(e) => {
                    debug!("[BFLA] Path traversal test error: {}", e);
                }
            }
        }

        Ok(None)
    }

    /// Test API version enumeration bypass
    async fn test_version_enumeration(
        &self,
        base_url: &str,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let parsed = match url::Url::parse(base_url) {
            Ok(u) => u,
            Err(_) => return Ok((vulnerabilities, 0)),
        };

        let base = format!("{}://{}", parsed.scheme(), parsed.host_str().unwrap_or(""));

        // Version enumeration patterns
        let version_patterns = vec![
            ("/api/v0/admin", "/api/v1/admin"),
            ("/api/v1/admin", "/api/v2/admin"),
            ("/api/v2/admin", "/api/v3/admin"),
            ("/api/admin", "/api/v0/admin"),
            ("/api/admin", "/api/beta/admin"),
            ("/api/admin", "/api/internal/admin"),
            ("/api/admin", "/api/dev/admin"),
            ("/api/admin", "/api/test/admin"),
        ];

        for (protected_path, bypass_path) in version_patterns {
            tests_run += 1;

            // First check if protected path is actually protected
            let protected_url = format!("{}{}", base, protected_path);
            let protected_response = match self.http_client.get(&protected_url).await {
                Ok(r) => r,
                Err(_) => continue,
            };

            if protected_response.status_code != 401 && protected_response.status_code != 403 {
                continue;
            }

            // Try the bypass version
            let bypass_url = format!("{}{}", base, bypass_path);
            match self.http_client.get(&bypass_url).await {
                Ok(response) => {
                    if response.status_code == 200 {
                        let is_real_content =
                            self.is_privileged_content(&response.body, &FunctionCategory::General);

                        if is_real_content {
                            vulnerabilities.push(Vulnerability {
                                id: generate_uuid(),
                                vuln_type: "BFLA - API Version Bypass".to_string(),
                                severity: Severity::High,
                                confidence: Confidence::High,
                                category: "Authorization".to_string(),
                                url: bypass_url.clone(),
                                parameter: Some("API Version".to_string()),
                                payload: format!("{} -> {}", protected_path, bypass_path),
                                description: format!(
                                    "Admin functionality accessible via different API version. \
                                    Protected path '{}' returns 401/403, but '{}' is accessible. \
                                    This indicates inconsistent authorization across API versions.",
                                    protected_path, bypass_path
                                ),
                                evidence: Some(format!(
                                    "Protected {} returned {}, Bypass {} returned 200",
                                    protected_path, protected_response.status_code, bypass_path
                                )),
                                cwe: "CWE-285".to_string(),
                                cvss: 8.1,
                                verified: true,
                                false_positive: false,
                                remediation: self.get_bfla_remediation(),
                                discovered_at: chrono::Utc::now().to_rfc3339(),
                                ml_data: None,
                            });
                        }
                    }
                }
                Err(e) => {
                    debug!("[BFLA] Version bypass test error: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test GraphQL function-level authorization
    async fn test_graphql_function_authorization(
        &self,
        base_url: &str,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let parsed = match url::Url::parse(base_url) {
            Ok(u) => u,
            Err(_) => return Ok((vulnerabilities, 0)),
        };

        let graphql_url = format!(
            "{}://{}/graphql",
            parsed.scheme(),
            parsed.host_str().unwrap_or("")
        );

        // Admin mutations to test
        let admin_mutations = vec![
            (
                r#"{"query":"mutation { createUser(input: {email: \"test@test.com\", role: \"admin\"}) { id } }"}"#,
                "createUser with admin role",
                FunctionCategory::UserManagement,
            ),
            (
                r#"{"query":"mutation { deleteUser(id: \"1\") { success } }"}"#,
                "deleteUser",
                FunctionCategory::UserManagement,
            ),
            (
                r#"{"query":"mutation { updateRole(userId: \"1\", role: \"admin\") { success } }"}"#,
                "updateRole to admin",
                FunctionCategory::RoleManagement,
            ),
            (
                r#"{"query":"mutation { updateConfig(key: \"debug\", value: \"true\") { success } }"}"#,
                "updateConfig",
                FunctionCategory::Configuration,
            ),
            (
                r#"{"query":"mutation { exportAllData { url } }"}"#,
                "exportAllData",
                FunctionCategory::DataExport,
            ),
            (
                r#"{"query":"query { allUsers { id email role } }"}"#,
                "allUsers query",
                FunctionCategory::UserManagement,
            ),
            (
                r#"{"query":"query { systemConfig { key value } }"}"#,
                "systemConfig query",
                FunctionCategory::Configuration,
            ),
            (
                r#"{"query":"query { auditLogs { action user timestamp } }"}"#,
                "auditLogs query",
                FunctionCategory::AuditLogs,
            ),
        ];

        let headers = vec![("Content-Type".to_string(), "application/json".to_string())];

        for (query, operation_name, category) in admin_mutations {
            tests_run += 1;

            match self
                .http_client
                .post_with_headers(&graphql_url, query, headers.clone())
                .await
            {
                Ok(response) => {
                    if response.status_code == 200 && !response.body.contains("\"errors\"") {
                        // Check if we got actual data back
                        if response.body.contains("\"data\"") && !response.body.contains("null") {
                            vulnerabilities.push(Vulnerability {
                                id: generate_uuid(),
                                vuln_type: "BFLA - GraphQL Admin Operation Accessible".to_string(),
                                severity: Severity::Critical,
                                confidence: Confidence::High,
                                category: "Authorization".to_string(),
                                url: graphql_url.clone(),
                                parameter: Some("GraphQL Operation".to_string()),
                                payload: operation_name.to_string(),
                                description: format!(
                                    "GraphQL admin operation '{}' is accessible without proper authorization. \
                                    This allows unauthorized users to execute privileged {} operations.",
                                    operation_name,
                                    format!("{:?}", category).to_lowercase()
                                ),
                                evidence: Some(format!(
                                    "GraphQL {} operation succeeded without authorization",
                                    operation_name
                                )),
                                cwe: "CWE-285".to_string(),
                                cvss: 9.0,
                                verified: true,
                                false_positive: false,
                                remediation: self.get_graphql_bfla_remediation(),
                                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
                            });
                        }
                    }
                }
                Err(e) => {
                    debug!("[BFLA] GraphQL test error: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Test access patterns for specific function categories
    async fn test_function_category_access(
        &self,
        base_url: &str,
        _admin_endpoints: &[EndpointInfo],
    ) -> Result<(Vec<Vulnerability>, usize)> {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let parsed = match url::Url::parse(base_url) {
            Ok(u) => u,
            Err(_) => return Ok((vulnerabilities, 0)),
        };

        let base = format!("{}://{}", parsed.scheme(), parsed.host_str().unwrap_or(""));

        // High-risk function patterns
        let high_risk_patterns: Vec<(&str, FunctionCategory, &str)> = vec![
            // User management - critical
            (
                "/api/users/promote",
                FunctionCategory::UserManagement,
                "POST",
            ),
            (
                "/api/users/demote",
                FunctionCategory::UserManagement,
                "POST",
            ),
            ("/api/users/ban", FunctionCategory::UserManagement, "POST"),
            ("/api/users/unban", FunctionCategory::UserManagement, "POST"),
            (
                "/api/admin/impersonate",
                FunctionCategory::UserManagement,
                "POST",
            ),
            // Configuration - critical
            (
                "/api/config/security",
                FunctionCategory::Configuration,
                "PUT",
            ),
            ("/api/config/auth", FunctionCategory::Configuration, "PUT"),
            ("/api/settings/cors", FunctionCategory::Configuration, "PUT"),
            // System operations - critical
            (
                "/api/system/restart",
                FunctionCategory::SystemOperations,
                "POST",
            ),
            (
                "/api/system/maintenance",
                FunctionCategory::SystemOperations,
                "POST",
            ),
            (
                "/api/cache/clear",
                FunctionCategory::SystemOperations,
                "POST",
            ),
            (
                "/api/db/migrate",
                FunctionCategory::SystemOperations,
                "POST",
            ),
            // Financial - critical
            (
                "/api/billing/adjust",
                FunctionCategory::FinancialOps,
                "POST",
            ),
            ("/api/credits/add", FunctionCategory::FinancialOps, "POST"),
            (
                "/api/subscription/override",
                FunctionCategory::FinancialOps,
                "POST",
            ),
        ];

        for (path, category, method) in high_risk_patterns {
            tests_run += 1;
            let full_url = format!("{}{}", base, path);

            let response = if method == "POST" {
                self.http_client.post(&full_url, String::new()).await
            } else {
                self.http_client.get(&full_url).await
            };

            match response {
                Ok(response) => {
                    if response.status_code == 200 {
                        let is_real_content = self.is_privileged_content(&response.body, &category);

                        if is_real_content || !response.body.contains("error") {
                            vulnerabilities.push(Vulnerability {
                                id: generate_uuid(),
                                vuln_type: format!("BFLA - Unprotected {} Function", format!("{:?}", category)),
                                severity: Severity::Critical,
                                confidence: Confidence::High,
                                category: "Authorization".to_string(),
                                url: full_url.clone(),
                                parameter: Some("Function".to_string()),
                                payload: format!("{} {}", method, path),
                                description: format!(
                                    "Critical {} function '{}' is accessible without proper authorization. \
                                    This allows unauthorized users to perform privileged operations.",
                                    format!("{:?}", category).to_lowercase(),
                                    path
                                ),
                                evidence: Some(format!(
                                    "{} {} returned HTTP 200",
                                    method, path
                                )),
                                cwe: "CWE-285".to_string(),
                                cvss: 9.5,
                                verified: true,
                                false_positive: false,
                                remediation: self.get_bfla_remediation(),
                                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_data: None,
                            });
                        }
                    }
                }
                Err(e) => {
                    debug!("[BFLA] High-risk function test error: {}", e);
                }
            }
        }

        Ok((vulnerabilities, tests_run))
    }

    /// Check if response contains privileged content
    fn is_privileged_content(&self, body: &str, category: &FunctionCategory) -> bool {
        let body_lower = body.to_lowercase();

        // Check for error responses
        if body_lower.contains("error") && body_lower.contains("unauthorized") {
            return false;
        }
        if body_lower.contains("access denied") || body_lower.contains("forbidden") {
            return false;
        }

        // Minimum content length
        if body.len() < 50 {
            return false;
        }

        // Category-specific content indicators
        let indicators = match category {
            FunctionCategory::UserManagement => {
                vec!["users", "email", "role", "permissions", "account"]
            }
            FunctionCategory::Configuration => {
                vec!["config", "settings", "enabled", "disabled", "value"]
            }
            FunctionCategory::DataExport => {
                vec!["export", "download", "data", "file", "url"]
            }
            FunctionCategory::SystemOperations => {
                vec!["status", "health", "system", "process", "memory"]
            }
            FunctionCategory::AuditLogs => {
                vec!["log", "audit", "action", "timestamp", "event"]
            }
            FunctionCategory::FinancialOps => {
                vec!["balance", "transaction", "payment", "amount", "invoice"]
            }
            FunctionCategory::RoleManagement => {
                vec!["role", "permission", "grant", "revoke", "access"]
            }
            FunctionCategory::ContentModeration => {
                vec!["content", "approve", "reject", "moderate", "flag"]
            }
            FunctionCategory::Analytics => {
                vec!["stats", "metrics", "analytics", "report", "chart"]
            }
            FunctionCategory::Deployment => {
                vec!["deploy", "release", "version", "build", "artifact"]
            }
            FunctionCategory::General => {
                vec!["admin", "management", "dashboard", "panel"]
            }
        };

        // Check for JSON structure
        let is_json = body.trim().starts_with('{') || body.trim().starts_with('[');

        // Check for HTML admin panel
        let is_admin_html = body_lower.contains("dashboard")
            || body_lower.contains("admin panel")
            || body_lower.contains("management");

        // Count matching indicators
        let matches = indicators
            .iter()
            .filter(|ind| body_lower.contains(*ind))
            .count();

        (is_json && matches >= 2) || (is_admin_html && matches >= 1) || matches >= 3
    }

    /// Create BFLA vulnerability
    fn create_bfla_vulnerability(
        &self,
        url: &str,
        path: &str,
        method: &str,
        technique: &str,
        detail: &str,
        response: &crate::http_client::HttpResponse,
        category: &FunctionCategory,
        privilege_level: &PrivilegeLevel,
    ) -> Vulnerability {
        let severity = match privilege_level {
            PrivilegeLevel::SuperAdmin => Severity::Critical,
            PrivilegeLevel::Admin => Severity::Critical,
            PrivilegeLevel::Elevated => Severity::High,
            _ => Severity::High,
        };

        let cvss = match privilege_level {
            PrivilegeLevel::SuperAdmin => 9.8,
            PrivilegeLevel::Admin => 9.0,
            PrivilegeLevel::Elevated => 8.1,
            _ => 7.5,
        };

        Vulnerability {
            id: generate_uuid(),
            vuln_type: format!("BFLA - Broken Function Level Authorization ({})", technique),
            severity,
            confidence: Confidence::High,
            category: "Authorization".to_string(),
            url: url.to_string(),
            parameter: Some(format!("{} method", method)),
            payload: format!("{} {} - {}", method, path, technique),
            description: format!(
                "Critical BFLA vulnerability detected on {} function: {}. \
                {} endpoint '{}' is accessible without proper {:?}-level authorization. \
                {} This allows unauthorized users to access privileged {} functionality.",
                format!("{:?}", category).to_lowercase(),
                path,
                format!("{:?}", privilege_level),
                path,
                privilege_level,
                detail,
                format!("{:?}", category).to_lowercase()
            ),
            evidence: Some(format!(
                "{} {} returned HTTP {} with {} bytes of {} content",
                method,
                path,
                response.status_code,
                response.body.len(),
                format!("{:?}", category).to_lowercase()
            )),
            cwe: "CWE-285".to_string(),
            cvss: cvss as f32,
            verified: true,
            false_positive: false,
            remediation: self.get_bfla_remediation(),
            discovered_at: chrono::Utc::now().to_rfc3339(),
            ml_data: None,
        }
    }

    /// Get BFLA remediation advice
    fn get_bfla_remediation(&self) -> String {
        r#"CRITICAL: Implement proper function-level authorization

1. **Implement Role-Based Access Control (RBAC)**
   ```python
   from functools import wraps

   def require_role(required_role):
       def decorator(f):
           @wraps(f)
           def decorated_function(*args, **kwargs):
               user = get_current_user()
               if not user or user.role != required_role:
                   abort(403)  # Forbidden
               return f(*args, **kwargs)
           return decorated_function
       return decorator

   @app.route('/api/admin/users')
   @require_role('admin')
   def admin_users():
       return get_all_users()
   ```

2. **Centralized Authorization Middleware**
   ```javascript
   // Express.js middleware
   const authorizeAdmin = (req, res, next) => {
       const user = req.user;
       if (!user || !user.roles.includes('admin')) {
           return res.status(403).json({ error: 'Admin access required' });
       }
       next();
   };

   app.use('/api/admin/*', authorizeAdmin);
   ```

3. **Policy-Based Authorization**
   ```java
   @PreAuthorize("hasRole('ADMIN')")
   @GetMapping("/api/admin/config")
   public ResponseEntity<?> getConfig() {
       return ResponseEntity.ok(configService.getConfig());
   }
   ```

4. **Verify Authorization on Every Request**
   - Never rely on client-side role checks
   - Always verify roles server-side
   - Check both authentication AND authorization

5. **Consistent API Versioning**
   - Apply same authorization to all API versions
   - Deprecate old versions properly
   - Audit all endpoints across versions

6. **HTTP Method Authorization**
   - Authorize each HTTP method separately
   - DELETE/PUT/PATCH typically need higher privileges
   - Don't assume GET is safe

7. **Audit and Monitor**
   - Log all admin function access
   - Alert on unauthorized access attempts
   - Regular access control reviews

8. **Principle of Least Privilege**
   - Grant minimum required permissions
   - Separate read/write permissions
   - Use granular roles, not just admin/user

9. **Defense in Depth**
   - Multiple authorization layers
   - Network-level restrictions for admin endpoints
   - IP whitelisting for critical functions

References:
- OWASP API5:2023 - https://owasp.org/API-Security/editions/2023/en/0xa5-broken-function-level-authorization/
- CWE-285: https://cwe.mitre.org/data/definitions/285.html
"#.to_string()
    }

    /// Get GraphQL-specific BFLA remediation
    fn get_graphql_bfla_remediation(&self) -> String {
        r#"CRITICAL: Implement GraphQL function-level authorization

1. **Field-Level Authorization with Directives**
   ```graphql
   type Query {
       publicData: String
       adminData: String @auth(requires: ADMIN)
       allUsers: [User!]! @auth(requires: ADMIN)
   }

   type Mutation {
       createUser(input: CreateUserInput!): User! @auth(requires: ADMIN)
       deleteUser(id: ID!): Boolean! @auth(requires: ADMIN)
   }
   ```

2. **Resolver-Level Authorization**
   ```javascript
   const resolvers = {
       Mutation: {
           deleteUser: async (_, { id }, context) => {
               // Always check authorization in resolver
               if (!context.user || context.user.role !== 'ADMIN') {
                   throw new ForbiddenError('Admin access required');
               }
               return await UserService.deleteUser(id);
           }
       }
   };
   ```

3. **Use GraphQL Shield**
   ```javascript
   import { shield, rule, and, or } from 'graphql-shield';

   const isAdmin = rule()(async (parent, args, ctx) => {
       return ctx.user && ctx.user.role === 'ADMIN';
   });

   const permissions = shield({
       Query: {
           allUsers: isAdmin,
           systemConfig: isAdmin,
       },
       Mutation: {
           createUser: isAdmin,
           deleteUser: isAdmin,
       }
   });
   ```

4. **Disable Introspection in Production**
   ```javascript
   const server = new ApolloServer({
       schema,
       introspection: process.env.NODE_ENV !== 'production',
   });
   ```

5. **Query Complexity Analysis**
   - Limit query depth
   - Limit field count
   - Prevent expensive queries

References:
- GraphQL Security: https://graphql.org/learn/authorization/
- GraphQL Shield: https://github.com/maticzav/graphql-shield
"#
        .to_string()
    }
}

/// Generate unique vulnerability ID
fn generate_uuid() -> String {
    let mut rng = rand::rng();
    format!(
        "bfla_{:08x}{:04x}{:04x}{:04x}{:012x}",
        rng.random::<u32>(),
        rng.random::<u16>(),
        rng.random::<u16>(),
        rng.random::<u16>(),
        rng.random::<u64>() & 0xffffffffffff
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http_client::HttpResponse;
    use std::collections::HashMap;

    fn create_test_scanner() -> BrokenFunctionAuthScanner {
        let http_client = Arc::new(HttpClient::new(5, 2).unwrap());
        BrokenFunctionAuthScanner::new(http_client)
    }

    #[test]
    fn test_classify_path_privilege() {
        let scanner = create_test_scanner();

        assert_eq!(
            scanner.classify_path_privilege("/api/superadmin/users"),
            PrivilegeLevel::SuperAdmin
        );
        assert_eq!(
            scanner.classify_path_privilege("/api/admin/config"),
            PrivilegeLevel::Admin
        );
        assert_eq!(
            scanner.classify_path_privilege("/api/internal/stats"),
            PrivilegeLevel::Elevated
        );
        assert_eq!(
            scanner.classify_path_privilege("/api/users/me"),
            PrivilegeLevel::Authenticated
        );
    }

    #[test]
    fn test_classify_function_category() {
        let scanner = create_test_scanner();

        assert_eq!(
            scanner.classify_function_category("/api/users/create"),
            FunctionCategory::UserManagement
        );
        assert_eq!(
            scanner.classify_function_category("/api/config/security"),
            FunctionCategory::Configuration
        );
        assert_eq!(
            scanner.classify_function_category("/api/export/data"),
            FunctionCategory::DataExport
        );
        assert_eq!(
            scanner.classify_function_category("/api/billing/invoice"),
            FunctionCategory::FinancialOps
        );
    }

    #[test]
    fn test_detect_api_pattern() {
        let scanner = create_test_scanner();

        // REST API
        let rest_response = HttpResponse {
            status_code: 200,
            body: r#"{"users": []}"#.to_string(),
            headers: {
                let mut h = HashMap::new();
                h.insert("content-type".to_string(), "application/json".to_string());
                h
            },
            duration_ms: 100,
        };
        assert_eq!(
            scanner.detect_api_pattern(&rest_response, "https://api.example.com/users"),
            ApiPattern::Rest
        );

        // GraphQL
        let graphql_response = HttpResponse {
            status_code: 200,
            body: r#"{"data": {"__schema": {}}}"#.to_string(),
            headers: HashMap::new(),
            duration_ms: 100,
        };
        assert_eq!(
            scanner.detect_api_pattern(&graphql_response, "https://api.example.com/graphql"),
            ApiPattern::GraphQL
        );
    }

    #[test]
    fn test_detect_auth_scheme() {
        let scanner = create_test_scanner();

        // JWT
        let jwt_response = HttpResponse {
            status_code: 200,
            body: r#"{"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}"#.to_string(),
            headers: HashMap::new(),
            duration_ms: 100,
        };
        assert_eq!(scanner.detect_auth_scheme(&jwt_response), AuthScheme::Jwt);

        // Session
        let session_response = HttpResponse {
            status_code: 200,
            body: String::new(),
            headers: {
                let mut h = HashMap::new();
                h.insert(
                    "set-cookie".to_string(),
                    "sessionid=abc123; HttpOnly".to_string(),
                );
                h
            },
            duration_ms: 100,
        };
        assert_eq!(
            scanner.detect_auth_scheme(&session_response),
            AuthScheme::Session
        );
    }

    #[test]
    fn test_is_privileged_content() {
        let scanner = create_test_scanner();

        // User management content
        assert!(scanner.is_privileged_content(
            r#"{"users": [{"id": 1, "email": "admin@example.com", "role": "admin"}]}"#,
            &FunctionCategory::UserManagement
        ));

        // Error response - not privileged
        assert!(!scanner.is_privileged_content(
            r#"{"error": "Unauthorized access"}"#,
            &FunctionCategory::UserManagement
        ));

        // Too short - not privileged
        assert!(!scanner.is_privileged_content("ok", &FunctionCategory::General));
    }

    #[test]
    fn test_extract_api_paths_from_body() {
        let scanner = create_test_scanner();

        let body = r#"
            <a href="/admin/users">Users</a>
            <script>
                fetch('/api/admin/config');
                const url = '/api/internal/stats';
            </script>
        "#;

        let paths = scanner.extract_api_paths_from_body(body);

        assert!(paths.contains(&"/admin/users".to_string()));
        assert!(paths.contains(&"/api/admin/config".to_string()));
    }

    #[test]
    fn test_generate_uuid() {
        let uuid1 = generate_uuid();
        let uuid2 = generate_uuid();

        assert!(uuid1.starts_with("bfla_"));
        assert!(uuid2.starts_with("bfla_"));
        assert_ne!(uuid1, uuid2);
    }
}