rma-analyzer 0.11.0

Code analysis and security scanning for Rust Monorepo Analyzer
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
//! Generic security and code quality DETECTION rules
//!
//! These rules apply across multiple languages for static analysis.

use crate::rules::{Rule, create_finding, create_finding_at_line};
use regex::Regex;
use rma_common::{Finding, Language, Severity};
use rma_parser::ParsedFile;
use std::collections::HashSet;
use std::path::Path;
use std::sync::LazyLock;
use tree_sitter::Node;

// =============================================================================
// TEST FILE DETECTION - Skip false positives in test/fixture/example files
// =============================================================================

/// Check if a file is auto-generated code (e.g., Kubernetes, protobuf, code generators)
/// These files often use patterns like unsafe.Pointer that are intentional and safe
#[inline]
pub fn is_generated_file(path: &Path, content: &str) -> bool {
    // Check file name patterns
    if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
        let name_lower = file_name.to_lowercase();

        // Kubernetes generated files
        if name_lower.starts_with("zz_generated")
            || name_lower.contains("_zz_generated")
            || name_lower.ends_with("_generated.go")
            || name_lower.starts_with("generated_")
        {
            return true;
        }

        // Protobuf and gRPC generated files
        if name_lower.ends_with(".pb.go")
            || name_lower.ends_with("_pb2.py")
            || name_lower.ends_with(".pb.ts")
            || name_lower.ends_with(".pb.js")
            || name_lower.ends_with("_grpc.pb.go")
        {
            return true;
        }

        // Other common generated file patterns
        if name_lower.ends_with(".gen.go")
            || name_lower.ends_with("_gen.go")
            || name_lower.ends_with(".generated.ts")
            || name_lower.ends_with(".generated.js")
            || name_lower.contains("_mock.go")  // mockgen generated
            || name_lower.contains("mock_")
        // mockgen generated
        {
            return true;
        }
    }

    // Check for code generator comment in first few lines
    // Common patterns: "// Code generated by ... DO NOT EDIT."
    // "// DO NOT EDIT" alone, "// AUTO-GENERATED", etc.
    let header = content.lines().take(10).collect::<Vec<_>>().join("\n");
    let header_upper = header.to_uppercase();

    if header_upper.contains("DO NOT EDIT")
        || header_upper.contains("AUTOMATICALLY GENERATED")
        || header_upper.contains("AUTO-GENERATED")
        || header_upper.contains("CODE GENERATED BY")
        || header_upper.contains("GENERATED BY")
        || header_upper.contains("THIS FILE IS GENERATED")
    {
        return true;
    }

    false
}

/// Check if a file path indicates a test, fixture, or example file
/// These files commonly contain fake secrets for testing purposes
#[inline]
pub fn is_test_or_fixture_file(path: &Path) -> bool {
    let path_str = path.to_string_lossy().to_lowercase();

    // Directory patterns that indicate test/fixture/example code
    if path_str.contains("/test/")
        || path_str.contains("/tests/")
        || path_str.contains("/testing/")
        || path_str.contains("/__tests__/")
        || path_str.contains("/spec/")
        || path_str.contains("/specs/")
        || path_str.contains("/fixture/")
        || path_str.contains("/fixtures/")
        || path_str.contains("/testdata/")
        || path_str.contains("/test_data/")
        || path_str.contains("/mock/")
        || path_str.contains("/mocks/")
        || path_str.contains("/fake/")
        || path_str.contains("/fakes/")
        || path_str.contains("/stub/")
        || path_str.contains("/stubs/")
        || path_str.contains("/example/")
        || path_str.contains("/examples/")
        || path_str.contains("/sample/")
        || path_str.contains("/samples/")
        || path_str.contains("/demo/")
        || path_str.contains("/testutil/")
        || path_str.contains("/testutils/")
    {
        return true;
    }

    // File name patterns
    if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
        let name_lower = file_name.to_lowercase();

        // Test file naming conventions
        if name_lower.starts_with("test_")
            || name_lower.starts_with("test.")
            || name_lower.ends_with("_test.go")
            || name_lower.ends_with("_test.rs")
            || name_lower.ends_with("_test.py")
            || name_lower.ends_with(".test.js")
            || name_lower.ends_with(".test.ts")
            || name_lower.ends_with(".test.jsx")
            || name_lower.ends_with(".test.tsx")
            || name_lower.ends_with(".spec.js")
            || name_lower.ends_with(".spec.ts")
            || name_lower.ends_with(".spec.jsx")
            || name_lower.ends_with(".spec.tsx")
            || name_lower.ends_with("_spec.rb")
            || name_lower.contains("_mock")
            || name_lower.contains("_fake")
            || name_lower.contains("_stub")
            || name_lower.contains("_fixture")
            || name_lower == "conftest.py"
            || name_lower == "setup_test.go"
        {
            return true;
        }
    }

    false
}

// Regex patterns for security checks
//
// IMPORTANT: These patterns are designed to minimize false positives.
// We only match SPECIFIC secret patterns, not generic "key" or "token" words.

/// Matches specific secret variable assignments like `api_key = "..."` or `password: "..."`
/// Note: Requires the variable name to be a COMPOUND secret name (api_key, secret_key, etc.)
/// NOT just "key" or "token" alone which are too generic.
static SECRET_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?i)\b(api[_-]?key|secret[_-]?key|auth[_-]?token|access[_-]?token|private[_-]?key|access[_-]?key|client[_-]?secret|db[_-]?password|database[_-]?password|admin[_-]?password)\s*[:=]\s*["'][^"']{8,}["']"#).unwrap()
});

/// Matches AWS access key IDs (always start with AKIA)
static AWS_KEY_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"AKIA[0-9A-Z]{16}"#).unwrap());

/// Matches AWS secret access keys with the variable name
static AWS_SECRET_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?i)aws[_-]?secret[_-]?access[_-]?key\s*[:=]\s*["'][A-Za-z0-9/+=]{40}["']"#)
        .unwrap()
});

/// Matches GitHub personal access tokens (ghp_) and GitHub app tokens (ghs_)
static GITHUB_TOKEN_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"gh[ps]_[A-Za-z0-9]{36,}"#).unwrap());

/// Matches PEM-encoded private keys
static PRIVATE_KEY_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----"#).unwrap());

/// Matches password assignments with actual password values (not empty, not placeholders)
/// More restrictive: only `password` or `passwd` followed by a value that looks like a real password
static PASSWORD_ASSIGNMENT_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?i)\b(password|passwd|pwd)\s*[:=]\s*["']([^"']{6,})["']"#).unwrap()
});

/// DETECTS TODO/FIXME comments that may indicate incomplete code
pub struct TodoFixmeRule;

impl Rule for TodoFixmeRule {
    fn id(&self) -> &str {
        "generic/todo-fixme"
    }

    fn description(&self) -> &str {
        "Detects TODO and FIXME comments that may indicate incomplete functionality"
    }

    fn applies_to(&self, _lang: Language) -> bool {
        true
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();

        for (line_num, line) in parsed.content.lines().enumerate() {
            let upper = line.to_uppercase();
            if upper.contains("TODO")
                || upper.contains("FIXME")
                || upper.contains("HACK")
                || upper.contains("XXX")
            {
                let mut finding = Finding {
                    id: format!("{}-{}", self.id(), line_num),
                    rule_id: self.id().to_string(),
                    message: "TODO/FIXME comment indicates potentially incomplete code".to_string(),
                    severity: Severity::Info,
                    location: rma_common::SourceLocation::new(
                        parsed.path.clone(),
                        line_num + 1,
                        1,
                        line_num + 1,
                        line.len(),
                    ),
                    language: parsed.language,
                    snippet: Some(line.trim().to_string()),
                    suggestion: None,
                    confidence: rma_common::Confidence::High,
                    category: rma_common::FindingCategory::Style,
                    fingerprint: None,
                    properties: None,
                };
                finding.compute_fingerprint();
                findings.push(finding);
            }
        }
        findings
    }
}

/// DETECTS functions that exceed a line count threshold
pub struct LongFunctionRule {
    max_lines: usize,
}

impl LongFunctionRule {
    pub fn new(max_lines: usize) -> Self {
        Self { max_lines }
    }
}

impl Rule for LongFunctionRule {
    fn id(&self) -> &str {
        "generic/long-function"
    }

    fn description(&self) -> &str {
        "Detects functions that exceed the recommended line count"
    }

    fn applies_to(&self, _lang: Language) -> bool {
        true
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        let function_kinds = [
            "function_item",
            "function_declaration",
            "function_definition",
            "method_declaration",
            "arrow_function",
        ];

        find_nodes_by_kinds(&mut cursor, &function_kinds, |node: Node| {
            let start = node.start_position().row;
            let end = node.end_position().row;
            let lines = end - start + 1;

            if lines > self.max_lines {
                findings.push(create_finding(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    &format!(
                        "Function has {} lines (max: {}) - consider refactoring",
                        lines, self.max_lines
                    ),
                    parsed.language,
                ));
            }
        });
        findings
    }
}

/// DETECTS high cyclomatic complexity
pub struct HighComplexityRule {
    max_complexity: usize,
}

impl HighComplexityRule {
    pub fn new(max_complexity: usize) -> Self {
        Self { max_complexity }
    }
}

/// DETECTS duplicate functions (copy-paste code)
pub struct DuplicateFunctionRule {
    min_lines: usize,
}

impl DuplicateFunctionRule {
    pub fn new(min_lines: usize) -> Self {
        Self { min_lines }
    }

    /// Extract and normalize just the function body (inside braces) for comparison
    fn normalize_body(content: &str, node: &Node) -> String {
        // Find the block/body child node (the part inside braces)
        let mut cursor = node.walk();
        let mut body_node: Option<Node> = None;

        if cursor.goto_first_child() {
            loop {
                let child = cursor.node();
                // Look for block-like nodes that contain the function body
                if child.kind() == "block"
                    || child.kind() == "statement_block"
                    || child.kind() == "compound_statement"
                    || child.kind() == "function_body"
                {
                    body_node = Some(child);
                    break;
                }
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }

        let body = if let Some(bn) = body_node {
            let start = bn.start_byte();
            let end = bn.end_byte();
            if end <= content.len() && start < end {
                &content[start..end]
            } else {
                return String::new();
            }
        } else {
            // Fallback: use entire node but try to skip signature
            let start = node.start_byte();
            let end = node.end_byte();
            if end > content.len() || start >= end {
                return String::new();
            }
            &content[start..end]
        };

        // Normalize: remove whitespace, lowercase, strip comments
        let mut result = String::new();
        let mut in_line_comment = false;
        let mut in_block_comment = false;
        let mut prev_char = ' ';

        for c in body.chars() {
            if in_line_comment {
                if c == '\n' {
                    in_line_comment = false;
                }
                continue;
            }
            if in_block_comment {
                if prev_char == '*' && c == '/' {
                    in_block_comment = false;
                }
                prev_char = c;
                continue;
            }
            if prev_char == '/' && c == '/' {
                in_line_comment = true;
                result.pop(); // remove the first /
                continue;
            }
            if prev_char == '/' && c == '*' {
                in_block_comment = true;
                result.pop(); // remove the first /
                continue;
            }
            if !c.is_whitespace() {
                result.push(c.to_ascii_lowercase());
            }
            prev_char = c;
        }

        result
    }

    /// Get function name from node
    fn get_function_name(node: &Node, content: &str) -> Option<String> {
        let mut cursor = node.walk();
        if cursor.goto_first_child() {
            loop {
                let child = cursor.node();
                if child.kind() == "identifier"
                    || child.kind() == "name"
                    || child.kind() == "property_identifier"
                {
                    let start = child.start_byte();
                    let end = child.end_byte();
                    if end <= content.len() {
                        return Some(content[start..end].to_string());
                    }
                }
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
        None
    }
}

impl Rule for HighComplexityRule {
    fn id(&self) -> &str {
        "generic/high-complexity"
    }

    fn description(&self) -> &str {
        "Detects functions with high cyclomatic complexity"
    }

    fn applies_to(&self, _lang: Language) -> bool {
        true
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        let function_kinds = [
            "function_item",
            "function_declaration",
            "function_definition",
            "method_declaration",
        ];

        find_nodes_by_kinds(&mut cursor, &function_kinds, |node: Node| {
            let complexity = count_branches(&node, parsed.language);

            if complexity > self.max_complexity {
                findings.push(create_finding(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    &format!(
                        "Function has complexity {} (max: {}) - consider simplifying",
                        complexity, self.max_complexity
                    ),
                    parsed.language,
                ));
            }
        });
        findings
    }
}

impl Rule for DuplicateFunctionRule {
    fn id(&self) -> &str {
        "generic/duplicate-function"
    }

    fn description(&self) -> &str {
        "Detects duplicate functions that could be refactored"
    }

    fn applies_to(&self, _lang: Language) -> bool {
        true
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        use std::collections::HashMap;

        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        let function_kinds = [
            "function_item",
            "function_declaration",
            "function_definition",
            "method_declaration",
            "arrow_function",
        ];

        // Collect all functions with their normalized bodies
        struct FuncInfo {
            name: String,
            line: usize,
            col: usize,
        }

        let mut body_to_funcs: HashMap<String, Vec<FuncInfo>> = HashMap::new();

        find_nodes_by_kinds(&mut cursor, &function_kinds, |node: Node| {
            let start = node.start_position().row;
            let end = node.end_position().row;
            let lines = end - start + 1;

            // Only check functions above minimum line threshold
            if lines < self.min_lines {
                return;
            }

            let normalized = Self::normalize_body(&parsed.content, &node);
            if normalized.len() < 50 {
                // Skip very small functions
                return;
            }

            let name = Self::get_function_name(&node, &parsed.content)
                .unwrap_or_else(|| format!("anonymous@{}", start + 1));

            body_to_funcs.entry(normalized).or_default().push(FuncInfo {
                name,
                line: start + 1,
                col: node.start_position().column + 1,
            });
        });

        // Report duplicates
        for (_body, funcs) in body_to_funcs.iter() {
            if funcs.len() > 1 {
                // Report all but the first as duplicates
                let first = &funcs[0];
                for dup in funcs.iter().skip(1) {
                    let mut finding = Finding {
                        id: format!("{}-{}-{}", self.id(), dup.line, dup.col),
                        rule_id: self.id().to_string(),
                        message: format!(
                            "Function '{}' is a duplicate of '{}' at line {} - consider extracting to shared function",
                            dup.name, first.name, first.line
                        ),
                        severity: Severity::Warning,
                        location: rma_common::SourceLocation::new(
                            parsed.path.clone(),
                            dup.line,
                            dup.col,
                            dup.line,
                            dup.col + 10,
                        ),
                        language: parsed.language,
                        snippet: Some(format!("fn {}(...)", dup.name)),
                        suggestion: Some(format!(
                            "Extract shared logic from '{}' and '{}'",
                            first.name, dup.name
                        )),
                        confidence: rma_common::Confidence::High,
                        category: rma_common::FindingCategory::Style,
                        fingerprint: None,
                        properties: None,
                    };
                    finding.compute_fingerprint();
                    findings.push(finding);
                }
            }
        }

        findings
    }
}

/// DETECTS hardcoded secrets, API keys, and passwords in any language
///
/// This rule focuses on HIGH-CONFIDENCE detection to minimize false positives.
/// It looks for:
/// - Specific secret patterns (api_key, secret_key, auth_token, etc.)
/// - Known credential formats (AWS keys, GitHub tokens, private keys)
/// - Password assignments with actual values
///
/// It does NOT flag:
/// - Generic "key" or "token" variable names (too many false positives)
/// - Object property keys (accessorKey, storageKey, etc.)
/// - HTTP header names
/// - Configuration constants that aren't secrets
pub struct HardcodedSecretRule;

impl HardcodedSecretRule {
    /// Check if a password value looks like a real password (not a placeholder)
    fn is_real_password(value: &str) -> bool {
        // Skip obvious placeholders and test values
        let lower = value.to_lowercase();
        if lower.is_empty()
            || lower == "password"
            || lower == "changeme"
            || lower == "placeholder"
            || lower == "your_password"
            || lower == "your-password"
            || lower == "xxx"
            || lower == "***"
            || lower.starts_with("${")
            || lower.starts_with("{{")
            || lower.contains("example")
            || lower.contains("test")
            || lower.contains("dummy")
            || lower.contains("sample")
            || lower.contains("fake")
            || lower.contains("mock")
        {
            return false;
        }

        // A real password typically has mixed characters or is long enough
        // to suggest it's not just a simple word
        let has_digit = value.chars().any(|c| c.is_ascii_digit());
        let has_upper = value.chars().any(|c| c.is_ascii_uppercase());
        let has_lower = value.chars().any(|c| c.is_ascii_lowercase());
        let has_special = value.chars().any(|c| !c.is_alphanumeric());

        // Strong signal: mixed case + digits + special chars
        // Or: long enough to be suspicious
        (has_digit && has_upper && has_lower)
            || (has_special && value.len() >= 8)
            || value.len() >= 16
    }

    /// Check if a line is a false positive context (object properties, configs, etc.)
    fn is_false_positive_context(line: &str) -> bool {
        let lower = line.to_lowercase();

        // Skip lines that are clearly not secrets
        // Object/struct property definitions
        if lower.contains("accessorkey")
            || lower.contains("storagekey")
            || lower.contains("cachekey")
            || lower.contains("localstoragekey")
            || lower.contains("sessionkey")
            || lower.contains("sortkey")
            || lower.contains("primarykey")
            || lower.contains("foreignkey")
            || lower.contains("uniquekey")
            || lower.contains("indexkey")
        {
            return true;
        }

        // HTTP headers and common config keys
        if lower.contains("cache-control")
            || lower.contains("content-type")
            || lower.contains("accept")
            || lower.contains("authorization: bearer")  // the header name, not value
            || lower.contains("x-api-key")
        // header name
        {
            return true;
        }

        // React/Vue/Angular component props and table columns
        if lower.contains("accessor:")
            || lower.contains("header:")
            || lower.contains("field:")
            || lower.contains("dataindex:")
        {
            return true;
        }

        // Translation keys, i18n
        if lower.contains("t('") || lower.contains("i18n") || lower.contains("translate") {
            return true;
        }

        // Type definitions and interfaces (TypeScript)
        if lower.contains(": string") || lower.contains(": number") || lower.contains("interface ")
        {
            return true;
        }

        false
    }
}

impl Rule for HardcodedSecretRule {
    fn id(&self) -> &str {
        "generic/hardcoded-secret"
    }

    fn description(&self) -> &str {
        "Detects hardcoded secrets, API keys, and passwords"
    }

    fn applies_to(&self, _lang: Language) -> bool {
        true
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        // Skip test/fixture files - they commonly contain fake secrets for testing
        if is_test_or_fixture_file(&parsed.path) {
            return Vec::new();
        }

        let mut findings = Vec::new();

        for (line_num, line) in parsed.content.lines().enumerate() {
            let trimmed = line.trim();

            // Skip comments in various languages
            if trimmed.starts_with("//")
                || trimmed.starts_with('#')
                || trimmed.starts_with("/*")
                || trimmed.starts_with('*')
                || trimmed.starts_with("'''")
                || trimmed.starts_with("\"\"\"")
            {
                continue;
            }

            // Skip false positive contexts
            if Self::is_false_positive_context(line) {
                continue;
            }

            // HIGH CONFIDENCE: Specific secret patterns (api_key, secret_key, auth_token, etc.)
            if SECRET_PATTERN.is_match(line) {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    "[REDACTED SECRET]",
                    Severity::Critical,
                    "Hardcoded secret detected - use environment variables or a secrets manager",
                    parsed.language,
                ));
                continue;
            }

            // HIGH CONFIDENCE: AWS access keys (distinctive AKIA prefix)
            if AWS_KEY_PATTERN.is_match(line) {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    "[REDACTED AWS KEY]",
                    Severity::Critical,
                    "AWS access key ID detected - never commit credentials",
                    parsed.language,
                ));
                continue;
            }

            // HIGH CONFIDENCE: AWS secret access keys
            if AWS_SECRET_PATTERN.is_match(line) {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    "[REDACTED AWS SECRET]",
                    Severity::Critical,
                    "AWS secret access key detected - never commit credentials",
                    parsed.language,
                ));
                continue;
            }

            // HIGH CONFIDENCE: GitHub tokens (distinctive ghp_/ghs_ prefix)
            if GITHUB_TOKEN_PATTERN.is_match(line) {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    "[REDACTED GITHUB TOKEN]",
                    Severity::Critical,
                    "GitHub token detected - use GITHUB_TOKEN secret instead",
                    parsed.language,
                ));
                continue;
            }

            // HIGH CONFIDENCE: PEM-encoded private keys
            if PRIVATE_KEY_PATTERN.is_match(line) {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    "[REDACTED PRIVATE KEY]",
                    Severity::Critical,
                    "Private key detected in source - store in secure key management",
                    parsed.language,
                ));
                continue;
            }

            // MEDIUM CONFIDENCE: Password assignments with real-looking values
            if let Some(caps) = PASSWORD_ASSIGNMENT_PATTERN.captures(line)
                && let Some(value_match) = caps.get(2)
            {
                let value = value_match.as_str();
                if Self::is_real_password(value) {
                    findings.push(create_finding_at_line(
                        self.id(),
                        &parsed.path,
                        line_num + 1,
                        "[REDACTED PASSWORD]",
                        Severity::Critical,
                        "Hardcoded password detected - use environment variables or a secrets manager",
                        parsed.language,
                    ));
                }
            }
        }
        findings
    }
}

/// DETECTS use of weak cryptographic algorithms
pub struct InsecureCryptoRule;

impl Rule for InsecureCryptoRule {
    fn id(&self) -> &str {
        "generic/insecure-crypto"
    }

    fn description(&self) -> &str {
        "Detects use of weak or deprecated cryptographic algorithms"
    }

    fn applies_to(&self, _lang: Language) -> bool {
        true
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();

        for (line_num, line) in parsed.content.lines().enumerate() {
            let trimmed = line.trim();
            let lower = line.to_lowercase();

            // Skip comments (various languages)
            if trimmed.starts_with("//")
                || trimmed.starts_with("/*")
                || trimmed.starts_with('*')
                || trimmed.starts_with('#')
                || trimmed.starts_with("<!--")
            {
                continue;
            }

            // Skip detection code (lines that are checking for patterns)
            if lower.contains(".contains(")
                || lower.contains(".is_match(")
                || lower.contains("regex")
            {
                continue;
            }

            // Skip string literals that are error messages or documentation
            // (lines where the crypto term appears inside quotes for display)
            if is_in_string_literal(&lower, "md5")
                || is_in_string_literal(&lower, "sha1")
                || is_in_string_literal(&lower, "des")
                || is_in_string_literal(&lower, "rc4")
                || is_in_string_literal(&lower, "ecb")
            {
                continue;
            }

            // MD5 - broken for security use
            if lower.contains("md5")
                && (lower.contains("hash")
                    || lower.contains("digest")
                    || lower.contains("::")
                    || lower.contains("import")
                    || lower.contains("require"))
            {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    line.trim(),
                    Severity::Error,
                    "MD5 is cryptographically broken - use SHA-256 or better for security",
                    parsed.language,
                ));
            }

            // SHA-1 - deprecated for security
            if lower.contains("sha1")
                && !lower.contains("sha1sum")
                && (lower.contains("hash")
                    || lower.contains("digest")
                    || lower.contains("::")
                    || lower.contains("import"))
            {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    line.trim(),
                    Severity::Warning,
                    "SHA-1 is deprecated for security - use SHA-256 or better",
                    parsed.language,
                ));
            }

            // DES - broken
            if (lower.contains("des") || lower.contains("3des") || lower.contains("triple_des"))
                && (lower.contains("encrypt")
                    || lower.contains("cipher")
                    || lower.contains("crypto"))
            {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    line.trim(),
                    Severity::Error,
                    "DES/3DES is insecure - use AES-256-GCM or ChaCha20-Poly1305",
                    parsed.language,
                ));
            }

            // RC4 - broken
            if lower.contains("rc4")
                && (lower.contains("cipher")
                    || lower.contains("crypto")
                    || lower.contains("encrypt"))
            {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    line.trim(),
                    Severity::Critical,
                    "RC4 is completely broken - use AES-GCM or ChaCha20-Poly1305",
                    parsed.language,
                ));
            }

            // ECB mode - insecure
            if lower.contains("ecb")
                && (lower.contains("mode") || lower.contains("cipher") || lower.contains("aes"))
            {
                findings.push(create_finding_at_line(
                    self.id(),
                    &parsed.path,
                    line_num + 1,
                    line.trim(),
                    Severity::Error,
                    "ECB mode is insecure - use GCM, CBC with HMAC, or authenticated encryption",
                    parsed.language,
                ));
            }
        }
        findings
    }
}

/// Check if a term appears inside a string literal (for skipping error messages)
fn is_in_string_literal(line: &str, term: &str) -> bool {
    // Find the term and check if it's inside quotes
    if let Some(pos) = line.find(term) {
        let before = &line[..pos];
        // Count quotes before the term
        let double_quotes = before.matches('"').count();
        let single_quotes = before.matches('\'').count();
        // If odd number of quotes, we're inside a string
        double_quotes % 2 == 1 || single_quotes % 2 == 1
    } else {
        false
    }
}

fn find_nodes_by_kinds<F>(cursor: &mut tree_sitter::TreeCursor, kinds: &[&str], mut callback: F)
where
    F: FnMut(Node),
{
    // Use HashSet for O(1) lookups instead of O(n) array contains
    let kinds_set: HashSet<&str> = kinds.iter().copied().collect();

    loop {
        let node = cursor.node();
        if kinds_set.contains(node.kind()) {
            callback(node);
        }
        if cursor.goto_first_child() {
            continue;
        }
        loop {
            if cursor.goto_next_sibling() {
                break;
            }
            if !cursor.goto_parent() {
                return;
            }
        }
    }
}

/// Pre-computed branch kinds as HashSets for O(1) lookup
static RUST_BRANCH_KINDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    [
        "if_expression",
        "match_expression",
        "while_expression",
        "for_expression",
    ]
    .into_iter()
    .collect()
});

static JS_BRANCH_KINDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    [
        "if_statement",
        "switch_statement",
        "for_statement",
        "while_statement",
    ]
    .into_iter()
    .collect()
});

static PYTHON_BRANCH_KINDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    [
        "if_statement",
        "for_statement",
        "while_statement",
        "try_statement",
    ]
    .into_iter()
    .collect()
});

static GO_BRANCH_KINDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    ["if_statement", "for_statement", "switch_statement"]
        .into_iter()
        .collect()
});

static JAVA_BRANCH_KINDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    [
        "if_statement",
        "for_statement",
        "while_statement",
        "switch_expression",
    ]
    .into_iter()
    .collect()
});

fn count_branches(node: &Node, lang: Language) -> usize {
    // Use pre-computed HashSets for O(1) lookup
    let branch_kinds: &HashSet<&str> = match lang {
        Language::Rust => &RUST_BRANCH_KINDS,
        Language::JavaScript | Language::TypeScript => &JS_BRANCH_KINDS,
        Language::Python => &PYTHON_BRANCH_KINDS,
        Language::Go => &GO_BRANCH_KINDS,
        Language::Java => &JAVA_BRANCH_KINDS,
        Language::Unknown => return 1,
    };

    let mut count = 1;
    let mut cursor = node.walk();

    loop {
        let current = cursor.node();
        if branch_kinds.contains(current.kind()) {
            count += 1;
        }
        if cursor.goto_first_child() {
            continue;
        }
        loop {
            if cursor.goto_next_sibling() {
                break;
            }
            if !cursor.goto_parent() {
                return count;
            }
        }
    }
}

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

    #[test]
    fn test_is_generated_file_by_name() {
        // Kubernetes generated files
        assert!(is_generated_file(
            Path::new("/project/pkg/apis/v1/zz_generated.conversion.go"),
            ""
        ));
        assert!(is_generated_file(
            Path::new("/project/pkg/apis/v1/zz_generated.deepcopy.go"),
            ""
        ));

        // Protobuf generated files
        assert!(is_generated_file(Path::new("/project/api/types.pb.go"), ""));
        assert!(is_generated_file(
            Path::new("/project/api/service_grpc.pb.go"),
            ""
        ));
        assert!(is_generated_file(
            Path::new("/project/proto/types_pb2.py"),
            ""
        ));

        // Other generated file patterns
        assert!(is_generated_file(
            Path::new("/project/api/types.gen.go"),
            ""
        ));
        assert!(is_generated_file(
            Path::new("/project/api/types_gen.go"),
            ""
        ));
        assert!(is_generated_file(Path::new("/project/mock_service.go"), ""));
        assert!(is_generated_file(Path::new("/project/service_mock.go"), ""));

        // Regular files - should NOT match
        assert!(!is_generated_file(Path::new("/project/main.go"), ""));
        assert!(!is_generated_file(Path::new("/project/pkg/handler.go"), ""));
        assert!(!is_generated_file(
            Path::new("/project/internal/utils.go"),
            ""
        ));
    }

    #[test]
    fn test_is_generated_file_by_content() {
        // Go generated file header
        let go_generated = r#"// Code generated by controller-gen. DO NOT EDIT.

package v1

import (
    "unsafe"
)
"#;
        assert!(is_generated_file(
            Path::new("/project/types.go"),
            go_generated
        ));

        // Protobuf generated header
        let proto_generated = r#"// Code generated by protoc-gen-go. DO NOT EDIT.
// source: api.proto

package api
"#;
        assert!(is_generated_file(
            Path::new("/project/api.go"),
            proto_generated
        ));

        // Auto-generated header
        let auto_generated = r#"// AUTO-GENERATED - Do not modify manually
package gen
"#;
        assert!(is_generated_file(
            Path::new("/project/gen.go"),
            auto_generated
        ));

        // Regular file - should NOT match
        let regular = r#"// Package main provides the entry point
package main

func main() {}
"#;
        assert!(!is_generated_file(Path::new("/project/main.go"), regular));
    }

    #[test]
    fn test_is_test_or_fixture_file_directories() {
        // Should match test directories
        assert!(is_test_or_fixture_file(Path::new(
            "/project/test/utils/helper.go"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/tests/integration.py"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/__tests__/component.test.js"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/spec/models/user_spec.rb"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/fixtures/data.json"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/testdata/sample.txt"
        )));
        assert!(is_test_or_fixture_file(Path::new("/project/mocks/api.ts")));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/examples/demo.go"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/testutil/admission_webhook.go"
        )));

        // Should NOT match production directories
        assert!(!is_test_or_fixture_file(Path::new("/project/src/main.go")));
        assert!(!is_test_or_fixture_file(Path::new("/project/lib/utils.py")));
        assert!(!is_test_or_fixture_file(Path::new(
            "/project/pkg/handler.go"
        )));
        assert!(!is_test_or_fixture_file(Path::new(
            "/project/cmd/server/main.go"
        )));
    }

    #[test]
    fn test_is_test_or_fixture_file_names() {
        // Should match test file names
        assert!(is_test_or_fixture_file(Path::new(
            "/project/src/handler_test.go"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/src/utils_test.rs"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/src/test_handler.py"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/src/component.test.js"
        )));
        assert!(is_test_or_fixture_file(Path::new(
            "/project/src/component.spec.ts"
        )));
        assert!(is_test_or_fixture_file(Path::new("/project/conftest.py")));
        assert!(is_test_or_fixture_file(Path::new("/project/api_mock.go")));

        // Should NOT match production file names
        assert!(!is_test_or_fixture_file(Path::new("/project/src/main.go")));
        assert!(!is_test_or_fixture_file(Path::new(
            "/project/src/handler.py"
        )));
        assert!(!is_test_or_fixture_file(Path::new("/project/src/utils.ts")));
        assert!(!is_test_or_fixture_file(Path::new(
            "/project/pkg/testing_helper.go"
        ))); // "testing" in name but not a test file pattern
    }

    #[test]
    fn test_hardcoded_secret_skips_test_files() {
        use rma_common::RmaConfig;
        use rma_parser::ParserEngine;

        let config = RmaConfig::default();
        let parser = ParserEngine::new(config);

        // Code with hardcoded secret
        let content = r#"
var LocalhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA1Z5/aTwqY706M34tn60l8ZHkanWDl8mM1pYf4Q7qg3zA9XqW
-----END RSA PRIVATE KEY-----`)
"#;

        // In a test file - should NOT produce findings
        let parsed_test = parser
            .parse_file(Path::new("/project/test/utils/webhook.go"), content)
            .unwrap();
        let rule = HardcodedSecretRule;
        let findings_test = rule.check(&parsed_test);
        assert!(
            findings_test.is_empty(),
            "Should skip secrets in test files"
        );

        // In a production file - SHOULD produce findings
        let parsed_prod = parser
            .parse_file(Path::new("/project/pkg/webhook.go"), content)
            .unwrap();
        let findings_prod = rule.check(&parsed_prod);
        assert!(
            !findings_prod.is_empty(),
            "Should detect secrets in production files"
        );
    }
}