lonkero 3.7.0

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
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

use crate::http_client::HttpClient;
use crate::types::{Confidence, ScanConfig, Severity, Vulnerability};
use anyhow::Result;
use std::sync::Arc;
use tracing::{debug, info};

#[derive(Debug, Clone, PartialEq)]
pub enum GoFramework {
    Gin,
    Echo,
    Fiber,
    Chi,
    Unknown,
}

impl std::fmt::Display for GoFramework {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GoFramework::Gin => write!(f, "Gin"),
            GoFramework::Echo => write!(f, "Echo"),
            GoFramework::Fiber => write!(f, "Fiber"),
            GoFramework::Chi => write!(f, "Chi"),
            GoFramework::Unknown => write!(f, "Unknown Go Framework"),
        }
    }
}

pub struct GoFrameworksScanner {
    http_client: Arc<HttpClient>,
}

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

    pub async fn scan(
        &self,
        target: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        if !crate::license::has_feature("cms_security") {
            debug!("Go frameworks scanner requires Personal+ license");
            return Ok((vec![], 0));
        }

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

        let (detected_framework, is_go_app) = self.detect_go_framework(target).await;
        tests_run += 1;

        if !is_go_app {
            debug!("Target does not appear to be a Go web application");
            return Ok((vulnerabilities, tests_run));
        }

        info!(
            "[Go] Detected {} application at {}",
            detected_framework, target
        );

        let (debug_vulns, debug_tests) = self.check_debug_mode(target, &detected_framework).await;
        vulnerabilities.extend(debug_vulns);
        tests_run += debug_tests;

        let (pprof_vulns, pprof_tests) = self.check_pprof_exposure(target).await;
        vulnerabilities.extend(pprof_vulns);
        tests_run += pprof_tests;

        let (expvar_vulns, expvar_tests) = self.check_expvar_exposure(target).await;
        vulnerabilities.extend(expvar_vulns);
        tests_run += expvar_tests;

        let (swagger_vulns, swagger_tests) = self.check_swagger_exposure(target).await;
        vulnerabilities.extend(swagger_vulns);
        tests_run += swagger_tests;

        let (error_vulns, error_tests) =
            self.check_error_handling(target, &detected_framework).await;
        vulnerabilities.extend(error_vulns);
        tests_run += error_tests;

        let (cors_vulns, cors_tests) = self.check_cors_misconfiguration(target).await;
        vulnerabilities.extend(cors_vulns);
        tests_run += cors_tests;

        let (middleware_vulns, middleware_tests) = self
            .check_middleware_bypass(target, &detected_framework)
            .await;
        vulnerabilities.extend(middleware_vulns);
        tests_run += middleware_tests;

        let (health_vulns, health_tests) = self.check_health_metrics_exposure(target).await;
        vulnerabilities.extend(health_vulns);
        tests_run += health_tests;

        let (template_vulns, template_tests) = self.check_template_injection(target).await;
        vulnerabilities.extend(template_vulns);
        tests_run += template_tests;

        info!(
            "[Go] Completed: {} vulnerabilities found in {} tests",
            vulnerabilities.len(),
            tests_run
        );

        Ok((vulnerabilities, tests_run))
    }

    async fn detect_go_framework(&self, target: &str) -> (GoFramework, bool) {
        let mut is_go_app = false;
        let mut detected_framework = GoFramework::Unknown;

        if let Ok(response) = self.http_client.get(target).await {
            if let Some(server) = response.headers.get("server") {
                let server_lower = server.to_lowercase();
                if server_lower.contains("gin") {
                    detected_framework = GoFramework::Gin;
                    is_go_app = true;
                } else if server_lower.contains("echo") {
                    detected_framework = GoFramework::Echo;
                    is_go_app = true;
                } else if server_lower.contains("fiber") {
                    detected_framework = GoFramework::Fiber;
                    is_go_app = true;
                }
            }

            if let Some(powered_by) = response.headers.get("x-powered-by") {
                let powered_lower = powered_by.to_lowercase();
                if powered_lower.contains("go") || powered_lower.contains("golang") {
                    is_go_app = true;
                }
            }

            let body = &response.body;
            if body.contains("runtime error:")
                || body.contains("goroutine")
                || body.contains("panic:")
                || body.contains(".go:")
            {
                is_go_app = true;
            }
        }

        let error_url = format!(
            "{}/this-path-does-not-exist-go-test-12345",
            target.trim_end_matches('/')
        );
        if let Ok(response) = self.http_client.get(&error_url).await {
            let body = &response.body;

            if body.contains("gin-gonic")
                || body.contains("Gin Framework")
                || (body.contains("404") && body.contains("gin"))
            {
                detected_framework = GoFramework::Gin;
                is_go_app = true;
            } else if body.contains("Echo") && body.contains("message") {
                detected_framework = GoFramework::Echo;
                is_go_app = true;
            } else if body.contains("Cannot") && body.contains("fiber") {
                detected_framework = GoFramework::Fiber;
                is_go_app = true;
            } else if body.contains("chi router") {
                detected_framework = GoFramework::Chi;
                is_go_app = true;
            }

            if body.contains("runtime/")
                || body.contains("goroutine ")
                || body.contains("net/http")
                || body.contains(".go:")
            {
                is_go_app = true;
            }
        }

        let go_endpoints = [
            "/debug/pprof/",
            "/debug/vars",
            "/health",
            "/healthz",
            "/ready",
            "/readyz",
            "/metrics",
        ];

        for endpoint in &go_endpoints {
            let url = format!("{}{}", target.trim_end_matches('/'), endpoint);
            if let Ok(response) = self.http_client.get(&url).await {
                if response.status_code == 200 {
                    let body = &response.body;
                    if body.contains("goroutine")
                        || body.contains("heap")
                        || body.contains("cmdline")
                        || body.contains("memstats")
                        || body.contains("go_")
                    {
                        is_go_app = true;
                        break;
                    }
                }
            }
        }

        (detected_framework, is_go_app)
    }

    async fn check_debug_mode(
        &self,
        target: &str,
        framework: &GoFramework,
    ) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let debug_indicators = match framework {
            GoFramework::Gin => vec![
                ("/debug", "Gin debug endpoint"),
                ("/gin-debug", "Gin framework debug"),
            ],
            GoFramework::Echo => vec![
                ("/debug", "Echo debug endpoint"),
                ("/.echo", "Echo internal endpoint"),
            ],
            GoFramework::Fiber => vec![
                ("/fiber/debug", "Fiber debug endpoint"),
                ("/.fiber", "Fiber internal endpoint"),
            ],
            GoFramework::Chi => vec![("/debug", "Chi debug endpoint")],
            GoFramework::Unknown => vec![
                ("/debug", "Debug endpoint"),
                ("/_debug", "Internal debug endpoint"),
            ],
        };

        for (path, description) in debug_indicators {
            tests_run += 1;
            let url = format!("{}{}", target.trim_end_matches('/'), path);

            if let Ok(response) = self.http_client.get(&url).await {
                if response.status_code == 200 {
                    let body = &response.body;
                    let debug_patterns = [
                        "debug",
                        "goroutine",
                        "stack",
                        "heap",
                        "runtime",
                        "env",
                        "config",
                        "settings",
                        "internal",
                    ];

                    let found_patterns: Vec<&str> = debug_patterns
                        .iter()
                        .filter(|p| body.to_lowercase().contains(*p))
                        .copied()
                        .collect();

                    if !found_patterns.is_empty() {
                        vulnerabilities.push(Vulnerability {
                            id: generate_vuln_id("GO_DEBUG"),
                            vuln_type: "Debug Mode Enabled".to_string(),
                            severity: Severity::High,
                            confidence: Confidence::High,
                            category: "Security Misconfiguration".to_string(),
                            url: url.clone(),
                            parameter: None,
                            payload: path.to_string(),
                            description: format!(
                                "{} ({}) is accessible in production.\n\n\
                                Debug mode exposes:\n\
                                - Internal application state\n\
                                - Configuration values\n\
                                - Runtime information\n\
                                - Potential secrets and credentials\n\n\
                                Patterns found: {:?}",
                                description, framework, found_patterns
                            ),
                            evidence: Some(format!(
                                "Endpoint: {}, Patterns: {:?}",
                                path, found_patterns
                            )),
                            cwe: "CWE-489".to_string(),
                            cvss: 7.5,
                            verified: true,
                            false_positive: false,
                            remediation: format!(
                                "Disable debug mode in production:\n\
                                - For Gin: Set gin.SetMode(gin.ReleaseMode)\n\
                                - For Echo: Disable debug mode in production config\n\
                                - For Fiber: Set app.Config.DisableStartupMessage = true\n\
                                - Remove or protect all debug endpoints with authentication"
                            ),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                        break;
                    }
                }
            }
        }

        (vulnerabilities, tests_run)
    }

    async fn check_pprof_exposure(&self, target: &str) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let pprof_endpoints = [
            ("/debug/pprof/", "pprof index", Severity::Critical),
            (
                "/debug/pprof/cmdline",
                "Command line arguments",
                Severity::High,
            ),
            ("/debug/pprof/profile", "CPU profile", Severity::Critical),
            ("/debug/pprof/symbol", "Symbol lookup", Severity::Medium),
            ("/debug/pprof/trace", "Execution trace", Severity::Critical),
            ("/debug/pprof/heap", "Heap profile", Severity::Critical),
            (
                "/debug/pprof/goroutine",
                "Goroutine stack traces",
                Severity::High,
            ),
            (
                "/debug/pprof/threadcreate",
                "Thread creation profile",
                Severity::Medium,
            ),
            ("/debug/pprof/block", "Block profile", Severity::Medium),
            (
                "/debug/pprof/mutex",
                "Mutex contention profile",
                Severity::Medium,
            ),
            (
                "/debug/pprof/allocs",
                "Memory allocation profile",
                Severity::High,
            ),
        ];

        let mut found_pprof = false;

        for (path, name, severity) in &pprof_endpoints {
            tests_run += 1;
            let url = format!("{}{}", target.trim_end_matches('/'), path);

            if let Ok(response) = self.http_client.get(&url).await {
                if response.status_code == 200 {
                    let body = &response.body;

                    let is_pprof = body.contains("goroutine")
                        || body.contains("heap")
                        || body.contains("profile")
                        || body.contains("pprof")
                        || body.contains("Types of profiles")
                        || body.len() > 100;

                    if is_pprof {
                        found_pprof = true;

                        let cvss = match severity {
                            Severity::Critical => 9.8,
                            Severity::High => 8.5,
                            Severity::Medium => 6.5,
                            _ => 4.0,
                        };

                        vulnerabilities.push(Vulnerability {
                            id: generate_vuln_id("GO_PPROF"),
                            vuln_type: "pprof Profiling Exposed".to_string(),
                            severity: severity.clone(),
                            confidence: Confidence::High,
                            category: "Information Disclosure".to_string(),
                            url: url.clone(),
                            parameter: None,
                            payload: path.to_string(),
                            description: format!(
                                "Go pprof endpoint ({}) is publicly accessible.\n\n\
                                pprof exposure allows attackers to:\n\
                                - Download heap dumps containing secrets and session data\n\
                                - Obtain CPU profiles revealing business logic\n\
                                - Access command line arguments (may contain secrets)\n\
                                - View goroutine stacks exposing internal state\n\
                                - Perform denial of service via heavy profiling\n\n\
                                This is particularly dangerous as heap dumps can contain:\n\
                                - Database credentials\n\
                                - API keys and tokens\n\
                                - Session data and user information",
                                name
                            ),
                            evidence: Some(format!("Endpoint accessible: {}", path)),
                            cwe: "CWE-200".to_string(),
                            cvss,
                            verified: true,
                            false_positive: false,
                            remediation: "Remove pprof from production builds:\n\
                                          1. Do not import _ \"net/http/pprof\" in production\n\
                                          2. Use build tags to exclude pprof:\n\
                                             //go:build !release\n\
                                          3. If needed, protect with authentication:\n\
                                             ```go\n\
                                             pprofMux := http.NewServeMux()\n\
                                             pprofMux.HandleFunc(\"/debug/pprof/\", pprof.Index)\n\
                                             // Add auth middleware\n\
                                             ```\n\
                                          4. Bind pprof to localhost only in development"
                                .to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                    }
                }
            }
        }

        if found_pprof && vulnerabilities.len() > 3 {
            vulnerabilities.truncate(3);
        }

        (vulnerabilities, tests_run)
    }

    async fn check_expvar_exposure(&self, target: &str) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let expvar_paths = ["/debug/vars", "/vars", "/expvar"];

        for path in &expvar_paths {
            tests_run += 1;
            let url = format!("{}{}", target.trim_end_matches('/'), path);

            if let Ok(response) = self.http_client.get(&url).await {
                if response.status_code == 200 {
                    let body = &response.body;

                    let expvar_indicators = [
                        "cmdline",
                        "memstats",
                        "Alloc",
                        "TotalAlloc",
                        "Sys",
                        "NumGC",
                        "HeapAlloc",
                        "HeapSys",
                    ];

                    let found_indicators: Vec<&str> = expvar_indicators
                        .iter()
                        .filter(|i| body.contains(*i))
                        .copied()
                        .collect();

                    if !found_indicators.is_empty() {
                        let has_cmdline = body.contains("cmdline");
                        let severity = if has_cmdline {
                            Severity::High
                        } else {
                            Severity::Medium
                        };

                        vulnerabilities.push(Vulnerability {
                            id: generate_vuln_id("GO_EXPVAR"),
                            vuln_type: "expvar Debug Variables Exposed".to_string(),
                            severity,
                            confidence: Confidence::High,
                            category: "Information Disclosure".to_string(),
                            url: url.clone(),
                            parameter: None,
                            payload: path.to_string(),
                            description: format!(
                                "Go expvar endpoint is publicly accessible.\n\n\
                                expvar exposes:\n\
                                - Memory statistics (heap, stack, GC)\n\
                                - Command line arguments (may contain secrets)\n\
                                - Custom application metrics\n\
                                - Runtime configuration\n\n\
                                Indicators found: {:?}",
                                found_indicators
                            ),
                            evidence: Some(format!("Endpoint: {}, Indicators: {:?}", path, found_indicators)),
                            cwe: "CWE-200".to_string(),
                            cvss: if has_cmdline { 7.5 } else { 5.5 },
                            verified: true,
                            false_positive: false,
                            remediation: "Remove expvar from production:\n\
                                          1. Do not import _ \"expvar\" in production\n\
                                          2. Use build tags for conditional compilation\n\
                                          3. If needed, protect with authentication middleware\n\
                                          4. Consider using Prometheus metrics instead with proper access control".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                        break;
                    }
                }
            }
        }

        (vulnerabilities, tests_run)
    }

    async fn check_swagger_exposure(&self, target: &str) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let swagger_paths = [
            ("/swagger/", "Swagger UI"),
            ("/swagger/index.html", "Swagger UI Index"),
            ("/swagger-ui/", "Swagger UI Alternative"),
            ("/api-docs", "API Documentation"),
            ("/docs", "Documentation"),
            ("/swagger.json", "Swagger JSON Spec"),
            ("/swagger.yaml", "Swagger YAML Spec"),
            ("/openapi.json", "OpenAPI JSON Spec"),
            ("/openapi.yaml", "OpenAPI YAML Spec"),
            ("/v1/swagger.json", "V1 Swagger Spec"),
            ("/v2/swagger.json", "V2 Swagger Spec"),
            ("/api/v1/swagger.json", "API V1 Swagger"),
        ];

        for (path, name) in &swagger_paths {
            tests_run += 1;
            let url = format!("{}{}", target.trim_end_matches('/'), path);

            if let Ok(response) = self.http_client.get(&url).await {
                if response.status_code == 200 {
                    let body = &response.body;

                    let is_swagger = body.contains("swagger")
                        || body.contains("openapi")
                        || body.contains("\"paths\"")
                        || body.contains("\"info\"")
                        || body.contains("Swagger UI");

                    if is_swagger {
                        vulnerabilities.push(Vulnerability {
                            id: generate_vuln_id("GO_SWAGGER"),
                            vuln_type: "API Documentation Exposed".to_string(),
                            severity: Severity::Medium,
                            confidence: Confidence::High,
                            category: "Information Disclosure".to_string(),
                            url: url.clone(),
                            parameter: None,
                            payload: path.to_string(),
                            description: format!(
                                "{} is publicly accessible.\n\n\
                                Exposed API documentation reveals:\n\
                                - Complete API endpoint structure\n\
                                - Request/response schemas\n\
                                - Authentication requirements\n\
                                - Internal business logic and workflows\n\
                                - Parameter names and validation rules",
                                name
                            ),
                            evidence: Some(format!("Swagger/OpenAPI at: {}", path)),
                            cwe: "CWE-200".to_string(),
                            cvss: 5.3,
                            verified: true,
                            false_positive: false,
                            remediation: "Protect API documentation in production:\n\
                                          1. Disable swagger in production builds:\n\
                                             ```go\n\
                                             if os.Getenv(\"ENV\") != \"production\" {\n\
                                                 r.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\
                                             }\n\
                                             ```\n\
                                          2. Add authentication middleware to swagger routes\n\
                                          3. Use IP whitelisting for internal access only".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                        break;
                    }
                }
            }
        }

        (vulnerabilities, tests_run)
    }

    async fn check_error_handling(
        &self,
        target: &str,
        framework: &GoFramework,
    ) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let error_triggers = [
            ("/api/nonexistent-endpoint-test-12345", "Invalid endpoint"),
            ("/%00", "Null byte"),
            ("/api?id=", "Empty parameter"),
            ("/api?id[]=1&id[]=2", "Array parameter"),
            ("/api/../../../etc/passwd", "Path traversal attempt"),
            ("/api?callback=<script>", "XSS in callback"),
        ];

        for (path, trigger_type) in &error_triggers {
            tests_run += 1;
            let url = format!("{}{}", target.trim_end_matches('/'), path);

            if let Ok(response) = self.http_client.get(&url).await {
                let body = &response.body;

                // Go stack trace detection - require STRONG indicators.
                // "goroutine" and "runtime/" could appear in documentation.
                // Require at least one "strong" indicator (panic/file path) plus others.
                let strong_indicators = [
                    "panic:",         // Go panic output
                    ".go:",           // Go file path with line number
                    "runtime error:", // Runtime error prefix
                ];
                let supporting_indicators = [
                    "goroutine",
                    "runtime/",
                    "net/http",
                    "reflect.",
                    "main.go",
                    "handler.go",
                ];

                let strong_found: Vec<&str> = strong_indicators
                    .iter()
                    .filter(|i| body.contains(*i))
                    .copied()
                    .collect();
                let supporting_found: Vec<&str> = supporting_indicators
                    .iter()
                    .filter(|i| body.contains(*i))
                    .copied()
                    .collect();

                let found_traces: Vec<&str> = strong_found
                    .iter()
                    .chain(supporting_found.iter())
                    .copied()
                    .collect();

                // Require at least 1 strong indicator AND 1+ supporting
                if !strong_found.is_empty() && found_traces.len() >= 3 {
                    let has_file_paths = body.contains(".go:");
                    let severity = if has_file_paths {
                        Severity::High
                    } else {
                        Severity::Medium
                    };

                    vulnerabilities.push(Vulnerability {
                        id: generate_vuln_id("GO_STACK_TRACE"),
                        vuln_type: "Stack Trace Exposure".to_string(),
                        severity,
                        confidence: Confidence::High,
                        category: "Information Disclosure".to_string(),
                        url: url.clone(),
                        parameter: None,
                        payload: format!("{} ({})", path, trigger_type),
                        description: format!(
                            "Go application ({}) exposes stack traces in error responses.\n\n\
                            Stack traces reveal:\n\
                            - Internal file paths and structure\n\
                            - Function names and call flow\n\
                            - Line numbers for targeted attacks\n\
                            - Third-party library versions\n\
                            - Business logic implementation\n\n\
                            Trigger: {}\n\
                            Indicators found: {:?}",
                            framework, trigger_type, found_traces
                        ),
                        evidence: Some(format!("Stack trace indicators: {:?}", found_traces)),
                        cwe: "CWE-209".to_string(),
                        cvss: if has_file_paths { 6.5 } else { 5.0 },
                        verified: true,
                        false_positive: false,
                        remediation: format!(
                            "Implement custom error handling:\n\
                            For {}:\n\
                            ```go\n\
                            // Use recovery middleware\n\
                            r.Use(gin.Recovery())\n\
                            \n\
                            // Custom error handler\n\
                            r.NoRoute(func(c *gin.Context) {{\n\
                                c.JSON(404, gin.H{{\"error\": \"Not found\"}})\n\
                            }})\n\
                            ```\n\
                            Never expose stack traces in production responses.",
                            framework
                        ),
                        discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                    });
                    break;
                }
            }
        }

        (vulnerabilities, tests_run)
    }

    async fn check_cors_misconfiguration(&self, target: &str) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let test_origins = [
            ("https://evil.com", "arbitrary origin"),
            ("null", "null origin"),
            (
                &format!(
                    "{}.evil.com",
                    target
                        .replace("https://", "")
                        .replace("http://", "")
                        .split('.')
                        .next()
                        .unwrap_or("test")
                ),
                "subdomain variant",
            ),
        ];

        for (origin, origin_type) in &test_origins {
            tests_run += 1;

            let headers = vec![("Origin".to_string(), origin.to_string())];

            if let Ok(response) = self.http_client.get_with_headers(target, headers).await {
                if let Some(acao) = response.headers.get("access-control-allow-origin") {
                    let acao_value = acao.as_str();
                    let allows_credentials = response
                        .headers
                        .get("access-control-allow-credentials")
                        .map(|v| v.as_str() == "true")
                        .unwrap_or(false);

                    let is_wildcard = acao_value == "*";
                    let reflects_origin = acao_value == *origin;
                    let allows_null = acao_value == "null";

                    if (is_wildcard && allows_credentials) || reflects_origin || allows_null {
                        let severity = if allows_credentials && (reflects_origin || allows_null) {
                            Severity::High
                        } else if reflects_origin || allows_null {
                            Severity::Medium
                        } else {
                            Severity::Low
                        };

                        vulnerabilities.push(Vulnerability {
                            id: generate_vuln_id("GO_CORS"),
                            vuln_type: "CORS Misconfiguration".to_string(),
                            severity,
                            confidence: Confidence::High,
                            category: "Security Misconfiguration".to_string(),
                            url: target.to_string(),
                            parameter: Some("Origin".to_string()),
                            payload: origin.to_string(),
                            description: format!(
                                "CORS is misconfigured allowing potentially malicious cross-origin requests.\n\n\
                                Test: {} origin\n\
                                Access-Control-Allow-Origin: {}\n\
                                Access-Control-Allow-Credentials: {}\n\n\
                                This can allow:\n\
                                - Cross-origin data theft\n\
                                - Session hijacking (if credentials allowed)\n\
                                - CSRF-like attacks",
                                origin_type, acao_value, allows_credentials
                            ),
                            evidence: Some(format!("ACAO: {}, Credentials: {}", acao_value, allows_credentials)),
                            cwe: "CWE-942".to_string(),
                            cvss: if allows_credentials { 8.0 } else { 5.5 },
                            verified: true,
                            false_positive: false,
                            remediation: "Configure CORS properly:\n\
                                          ```go\n\
                                          // For Gin\n\
                                          config := cors.DefaultConfig()\n\
                                          config.AllowOrigins = []string{\"https://trusted-site.com\"}\n\
                                          config.AllowCredentials = true\n\
                                          r.Use(cors.New(config))\n\
                                          \n\
                                          // Never reflect arbitrary origins\n\
                                          // Never use * with credentials\n\
                                          ```".to_string(),
                            discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                        });
                        break;
                    }
                }
            }
        }

        (vulnerabilities, tests_run)
    }

    async fn check_middleware_bypass(
        &self,
        target: &str,
        framework: &GoFramework,
    ) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let protected_paths = [
            "/admin",
            "/api/admin",
            "/internal",
            "/private",
            "/dashboard",
        ];

        for path in &protected_paths {
            let base_url = format!("{}{}", target.trim_end_matches('/'), path);

            if let Ok(base_response) = self.http_client.get(&base_url).await {
                if base_response.status_code == 401 || base_response.status_code == 403 {
                    let bypass_attempts = [
                        (format!("{}//", base_url), "double slash"),
                        (format!("{}/./", base_url), "dot segment"),
                        (
                            format!("{}/../{}", base_url, path.trim_start_matches('/')),
                            "path traversal",
                        ),
                        (format!("{}%2f", base_url), "URL encoded slash"),
                        (format!("{};", base_url), "semicolon"),
                        (format!("{}..;/", base_url), "dotdot semicolon"),
                        (format!("{}%00", base_url), "null byte"),
                        (format!("{}.json", base_url), "extension append"),
                    ];

                    for (bypass_url, technique) in &bypass_attempts {
                        tests_run += 1;

                        if let Ok(bypass_response) = self.http_client.get(bypass_url).await {
                            if bypass_response.status_code == 200
                                && bypass_response.body.len() > base_response.body.len() + 50
                            {
                                vulnerabilities.push(Vulnerability {
                                    id: generate_vuln_id("GO_MIDDLEWARE_BYPASS"),
                                    vuln_type: "Middleware/Auth Bypass".to_string(),
                                    severity: Severity::Critical,
                                    confidence: Confidence::Medium,
                                    category: "Authorization Bypass".to_string(),
                                    url: bypass_url.clone(),
                                    parameter: None,
                                    payload: format!("{} technique", technique),
                                    description: format!(
                                        "Authentication/authorization middleware can be bypassed in {} framework.\n\n\
                                        Original path: {} (returned {})\n\
                                        Bypass path: {} (returned 200)\n\
                                        Technique: {}\n\n\
                                        This indicates the routing middleware does not properly normalize paths \
                                        before checking authorization.",
                                        framework, path, base_response.status_code, bypass_url, technique
                                    ),
                                    evidence: Some(format!(
                                        "Protected: {} -> {}, Bypassed: {} -> 200",
                                        path, base_response.status_code, bypass_url
                                    )),
                                    cwe: "CWE-863".to_string(),
                                    cvss: 9.8,
                                    verified: false,
                                    false_positive: false,
                                    remediation: format!(
                                        "Fix path normalization in {} middleware:\n\
                                        1. Normalize paths before authorization checks:\n\
                                           ```go\n\
                                           path := filepath.Clean(c.Request.URL.Path)\n\
                                           ```\n\
                                        2. Use strict route matching\n\
                                        3. Apply auth middleware at the router group level\n\
                                        4. Consider using a WAF for path normalization",
                                        framework
                                    ),
                                    discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                                });
                                break;
                            }
                        }
                    }
                }
            }
            tests_run += 1;
        }

        (vulnerabilities, tests_run)
    }

    async fn check_health_metrics_exposure(&self, target: &str) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let health_endpoints = [
            ("/health", "Health check", Severity::Low),
            ("/healthz", "Kubernetes health", Severity::Low),
            ("/ready", "Readiness probe", Severity::Low),
            ("/readyz", "Kubernetes readiness", Severity::Low),
            ("/live", "Liveness probe", Severity::Low),
            ("/livez", "Kubernetes liveness", Severity::Low),
            ("/metrics", "Prometheus metrics", Severity::Medium),
            ("/prometheus", "Prometheus endpoint", Severity::Medium),
            ("/actuator", "Actuator-like endpoint", Severity::Medium),
            ("/status", "Status endpoint", Severity::Low),
            ("/_status", "Internal status", Severity::Medium),
            ("/info", "Info endpoint", Severity::Low),
            ("/version", "Version endpoint", Severity::Low),
            ("/build-info", "Build information", Severity::Low),
        ];

        let mut found_endpoints: Vec<(String, String, Severity)> = Vec::new();

        for (path, name, severity) in &health_endpoints {
            tests_run += 1;
            let url = format!("{}{}", target.trim_end_matches('/'), path);

            if let Ok(response) = self.http_client.get(&url).await {
                if response.status_code == 200 {
                    let body = &response.body;

                    // Require Go-specific or monitoring-specific content, not just
                    // any JSON response. Previously `contains("{")` matched everything.
                    // Only flag endpoints that expose Go runtime or Prometheus metrics.
                    let has_go_specific_content = body.contains("go_")
                        || body.contains("process_")
                        || body.contains("http_request")
                        || body.contains("goroutine")
                        || body.contains("go_gc_")
                        || body.contains("go_memstats_");
                    let has_monitoring_content = body.contains("# HELP ")
                        || body.contains("# TYPE ")
                        || (body.contains("\"status\"") && body.contains("\"UP\""));
                    if body.len() > 10
                        && (has_go_specific_content || has_monitoring_content)
                    {
                        found_endpoints.push((
                            path.to_string(),
                            name.to_string(),
                            severity.clone(),
                        ));
                    }
                }
            }
        }

        if !found_endpoints.is_empty() {
            let has_metrics = found_endpoints
                .iter()
                .any(|(p, _, _)| p.contains("metrics") || p.contains("prometheus"));
            let severity = if has_metrics {
                Severity::Medium
            } else {
                Severity::Low
            };

            let endpoint_list: Vec<String> = found_endpoints
                .iter()
                .map(|(p, n, _)| format!("{} ({})", p, n))
                .collect();

            vulnerabilities.push(Vulnerability {
                id: generate_vuln_id("GO_HEALTH_METRICS"),
                vuln_type: "Health/Metrics Endpoints Exposed".to_string(),
                severity,
                confidence: Confidence::High,
                category: "Information Disclosure".to_string(),
                url: target.to_string(),
                parameter: None,
                payload: endpoint_list.join(", "),
                description: format!(
                    "Multiple health and metrics endpoints are publicly accessible.\n\n\
                    Exposed endpoints:\n{}\n\n\
                    These endpoints may reveal:\n\
                    - Internal service status and dependencies\n\
                    - Database connection health\n\
                    - Memory and CPU usage patterns\n\
                    - Request latencies and error rates\n\
                    - Version and build information\n\
                    - Infrastructure details",
                    endpoint_list
                        .iter()
                        .map(|e| format!("- {}", e))
                        .collect::<Vec<_>>()
                        .join("\n")
                ),
                evidence: Some(format!("Found {} exposed endpoints", found_endpoints.len())),
                cwe: "CWE-200".to_string(),
                cvss: if has_metrics { 5.3 } else { 3.7 },
                verified: true,
                false_positive: false,
                remediation: "Protect health and metrics endpoints:\n\
                              1. Restrict access by IP (internal network only)\n\
                              2. Use separate port for internal endpoints:\n\
                                 ```go\n\
                                 go func() {\n\
                                     internalMux := http.NewServeMux()\n\
                                     internalMux.HandleFunc(\"/health\", healthHandler)\n\
                                     http.ListenAndServe(\"127.0.0.1:8081\", internalMux)\n\
                                 }()\n\
                                 ```\n\
                              3. Add authentication for metrics endpoint\n\
                              4. Use Kubernetes network policies to restrict access"
                    .to_string(),
                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
            });
        }

        (vulnerabilities, tests_run)
    }

    async fn check_template_injection(&self, target: &str) -> (Vec<Vulnerability>, usize) {
        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        let template_payloads = [
            ("{{.}}", "Go template dot", "object dump"),
            ("{{printf \"%s\" .}}", "Printf injection", "format string"),
            (
                "{{range .}}{{.}}{{end}}",
                "Range iteration",
                "data iteration",
            ),
            (
                "{{template \"name\"}}",
                "Template include",
                "template loading",
            ),
            (
                "{{define \"x\"}}{{end}}",
                "Template define",
                "template definition",
            ),
            ("{{$x := .}}", "Variable assignment", "variable access"),
        ];

        let test_endpoints = [
            "/search",
            "/api/search",
            "/render",
            "/template",
            "/preview",
            "/",
        ];

        let test_params = [
            "q", "query", "search", "name", "template", "text", "message", "title",
        ];

        for endpoint in &test_endpoints {
            let base_url = format!("{}{}", target.trim_end_matches('/'), endpoint);

            for param in &test_params {
                for (payload, name, category) in &template_payloads {
                    tests_run += 1;

                    let test_url =
                        format!("{}?{}={}", base_url, param, urlencoding::encode(payload));

                    if let Ok(response) = self.http_client.get(&test_url).await {
                        let body = &response.body;

                        let injection_indicators = [
                            "map[",
                            "struct",
                            "<nil>",
                            "runtime error",
                            "template:",
                            "execute template",
                            "unexpected",
                            "invalid",
                        ];

                        let rendered_cleanly =
                            !body.contains("{{") && !body.contains(payload) && body.len() > 50;

                        let has_error = injection_indicators
                            .iter()
                            .any(|i| body.to_lowercase().contains(&i.to_lowercase()));

                        if (rendered_cleanly && body.contains("[")) || has_error {
                            let severity = if has_error && body.contains("runtime") {
                                Severity::High
                            } else {
                                Severity::Medium
                            };

                            vulnerabilities.push(Vulnerability {
                                id: generate_vuln_id("GO_TEMPLATE_INJECTION"),
                                vuln_type: "Go Template Injection".to_string(),
                                severity,
                                confidence: Confidence::Medium,
                                category: "Server-Side Template Injection".to_string(),
                                url: test_url.clone(),
                                parameter: Some(param.to_string()),
                                payload: payload.to_string(),
                                description: format!(
                                    "Potential Go template injection vulnerability detected.\n\n\
                                    Payload: {} ({})\n\
                                    Category: {}\n\
                                    Parameter: {}\n\n\
                                    Go template injection can lead to:\n\
                                    - Information disclosure via {{{{.}}}}\n\
                                    - Data enumeration via range\n\
                                    - Potential denial of service\n\
                                    - In some cases, code execution via custom functions",
                                    payload, name, category, param
                                ),
                                evidence: Some(format!(
                                    "Payload processed differently: {} bytes response",
                                    body.len()
                                )),
                                cwe: "CWE-1336".to_string(),
                                cvss: if has_error { 7.5 } else { 5.5 },
                                verified: false,
                                false_positive: false,
                                remediation: "Prevent Go template injection:\n\
                                              1. Never pass user input directly to templates:\n\
                                                 ```go\n\
                                                 // Bad\n\
                                                 tmpl.Execute(w, userInput)\n\
                                                 \n\
                                                 // Good\n\
                                                 data := struct{ Content string }{Content: userInput}\n\
                                                 tmpl.Execute(w, data)\n\
                                                 ```\n\
                                              2. Use text/template for untrusted input\n\
                                              3. Sanitize input before template rendering\n\
                                              4. Avoid dynamic template compilation from user input".to_string(),
                                discovered_at: chrono::Utc::now().to_rfc3339(),
                ml_confidence: None,
                ml_data: None,
                            });

                            return (vulnerabilities, tests_run);
                        }
                    }
                }
            }
        }

        (vulnerabilities, tests_run)
    }
}

fn generate_vuln_id(prefix: &str) -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    format!("{}-{:x}", prefix, timestamp)
}

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

    #[test]
    fn test_framework_display() {
        assert_eq!(format!("{}", GoFramework::Gin), "Gin");
        assert_eq!(format!("{}", GoFramework::Echo), "Echo");
        assert_eq!(format!("{}", GoFramework::Fiber), "Fiber");
        assert_eq!(format!("{}", GoFramework::Chi), "Chi");
        assert_eq!(format!("{}", GoFramework::Unknown), "Unknown Go Framework");
    }

    #[test]
    fn test_generate_vuln_id() {
        let id1 = generate_vuln_id("GO_TEST");
        let id2 = generate_vuln_id("GO_TEST");
        assert!(id1.starts_with("GO_TEST-"));
        assert!(id1 != id2);
    }

    #[test]
    fn test_framework_equality() {
        assert_eq!(GoFramework::Gin, GoFramework::Gin);
        assert_ne!(GoFramework::Gin, GoFramework::Echo);
    }
}