repotoire 0.7.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
//! Insecure-crypto detector (CWE-327, CWE-328).
//!
//! Detects use of cryptographically broken or weak primitives (MD5, SHA1,
//! DES, RC4, ECB-mode ciphers, ...). Unlike eval/command-injection/pickle,
//! the danger signal here is the **algorithm name** more than the argument
//! shape, which makes the AST migration's value the ability to reliably
//! extract that name from a call expression rather than fishing it out of
//! line-text with regex.
//!
//! # Architecture
//!
//! Two scan paths, picked by file language (mirrors `eval_detector.rs`,
//! `command_injection.rs`, and `pickle_detector.rs`):
//!
//! 1. **AST path** (Python, JS, TS, JSX, TSX): walks the tree-sitter
//!    parse tree looking for **call expressions** whose callee names a
//!    known weak primitive, or whose first string-literal argument names
//!    one. Argument-shape classifiers descend through transparent
//!    wrappers (`await`, ternary, TS `as`/`!`/`<T>x`/`satisfies`,
//!    parentheses) so `crypto.createHash(await getAlgo())` is correctly
//!    classified as `UnknownAlgoFromVariable`, not `Unknown`.
//!
//!      - **Python**:
//!        - `hashlib.md5(...)`, `hashlib.sha1(...)`, `hashlib.md4(...)`
//!        - `hashlib.new('md5'|'sha1'|...)` — string-arg algorithm name
//!        - `Crypto.Cipher.DES.new(...)`, `Crypto.Cipher.AES.new(key, AES.MODE_ECB, ...)`
//!        - `cryptography.hazmat.primitives.hashes.MD5()` etc.
//!        - **Bare-identifier from-import**: `from hashlib import md5;
//!          md5(data)` — resolved via per-file from-import alias map
//!          (this is the first AST detector to do bare-call from-import
//!          resolution; the same pattern can be applied to eval/command
//!          /pickle in follow-up work).
//!
//!      - **JavaScript / TypeScript**:
//!        - `crypto.createHash('md5')`, `crypto.createCipheriv('aes-128-ecb', ...)`,
//!          `crypto.createSign('RSA-MD5')`. Algorithm is the first string-literal
//!          argument.
//!        - `require('crypto').createHash(...)` and
//!          `(await import('crypto')).createHash(...)` — receiver descent
//!          through `require()`/`import()` (B1 lesson from CommandInjection
//!          commit `3c88328e`).
//!
//! 2. **Line path** (Java, C/C++, Ruby, PHP, Go): for languages without a
//!    tree-sitter grammar in our dispatch list, a small line-based regex
//!    scanner matches the canonical forms (`Cipher.getInstance("DES")`,
//!    `MessageDigest.getInstance("MD5")`, `mcrypt_encrypt(MCRYPT_DES,
//!    ...)`, `Digest::MD5`, `des.NewCipher(...)`, ...).
//!
//! The classifier emits one of:
//!
//!   - `BrokenAlgoIdentifier(name)` — `hashlib.md5(...)` (attribute name).
//!   - `BrokenAlgoStringLiteral(name)` — `crypto.createHash('md5')`.
//!   - `WeakModeCombo(algo, mode)` — `crypto.createCipheriv('aes-128-ecb', ...)`.
//!   - `UnknownAlgoFromVariable` — `crypto.createHash(userChoice)`.
//!   - `SafeAlgo` — `hashlib.sha256(...)` etc. → skipped.
//!
//! Severity table:
//!
//!   - Broken algo (md5/sha1/md4/des/rc4/3des/tripledes) → **High**.
//!   - ECB mode (any cipher) → **High** (ECB is broken regardless of
//!     cipher choice — pattern leakage).
//!   - DES (any mode) → **High**.
//!   - Variable-algo (`createHash(userChoice)`) → **Low** (we can't tell
//!     statically; informational).
//!   - Route-handler boost: if the call sits inside a request-handler /
//!     route function (matched the same way as eval/command/pickle),
//!     severity is bumped one tier up.

use crate::detectors::ast_fingerprint::parse_root_ext;
use crate::detectors::ast_walk::AstWalkCtx;
use crate::detectors::base::{Detector, DetectorConfig};
use crate::detectors::fast_search::*;
use crate::detectors::security::ast_helpers::{
    collect_named_args, node_text, receiver_chain_label as receiver_chain_label_shared,
    unwrap_callee,
};
use crate::detectors::security::scan_inputs::{ScanAstInputs, ScanInputs};
use crate::graph::GraphQueryExt;
use crate::models::{Finding, Severity};
use crate::parsers::lightweight::Language;
use anyhow::Result;
use regex::Regex;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use tracing::{debug, info};

// ---------------------------------------------------------------------------
// Single source of truth for supported file extensions.
// ---------------------------------------------------------------------------

/// Extensions this detector processes. AST-eligible extensions
/// (Python + JS/TS/JSX/TSX) flow through `scan_file_ast`; the rest fall
/// through to the line scanner.
const SUPPORTED_EXTS: &[&str] = &[
    // AST path
    "py", "js", "ts", "jsx", "tsx", // Line path
    "rb", "java", "go", "php", "c", "cc", "cpp", "h", "hpp", "cs",
];

/// Subset of `SUPPORTED_EXTS` that has tree-sitter grammars in our
/// dispatch list.
const AST_EXTS: &[&str] = &["py", "js", "ts", "jsx", "tsx"];

// ---------------------------------------------------------------------------
// Algorithm classification
// ---------------------------------------------------------------------------

/// Lowercased name → broken / weak / safe.
fn classify_algo_name(name: &str) -> AlgoKind {
    let n = name.to_lowercase();
    let n = n.replace([' ', '_', '-'], "");
    if matches!(
        n.as_str(),
        "md5"
            | "md4"
            | "md2"
            | "sha"
            | "sha1"
            | "sha0"
            | "ripemd"
            | "ripemd128"
            | "ripemd160"
            | "des"
            | "rc4"
            | "rc2"
            | "arc4"
            | "blowfish"
            | "3des"
            | "tripledes"
    ) {
        return AlgoKind::Broken(name.to_string());
    }
    if matches!(
        n.as_str(),
        "sha256"
            | "sha384"
            | "sha512"
            | "sha224"
            | "sha3"
            | "sha3256"
            | "sha3384"
            | "sha3512"
            | "blake2"
            | "blake2b"
            | "blake2s"
            | "blake3"
            | "aes"
            | "aes128"
            | "aes192"
            | "aes256"
            | "chacha20"
            | "chacha20poly1305"
            | "xchacha20poly1305"
    ) {
        return AlgoKind::Safe;
    }
    AlgoKind::Unknown
}

/// Recognise an `algo-mode` style label (`aes-128-ecb`, `des-cbc`, ...)
/// and return `(algo, mode)` if the trailing token is a known mode.
fn split_algo_mode(name: &str) -> Option<(String, String)> {
    let lower = name.to_lowercase();
    const MODES: &[&str] = &["ecb", "cbc", "ctr", "ofb", "cfb", "gcm", "ccm", "xts"];
    for mode in MODES {
        for sep in ['-', '_', '/'] {
            let needle = format!("{sep}{mode}");
            if let Some(idx) = lower.rfind(&needle) {
                let algo = &lower[..idx];
                let algo_canonical: String =
                    algo.chars().take_while(|c| c.is_alphabetic()).collect();
                let algo_canonical = if algo_canonical.is_empty() {
                    algo.to_string()
                } else {
                    algo_canonical
                };
                return Some((algo_canonical, (*mode).to_string()));
            }
        }
    }
    None
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum AlgoKind {
    Broken(String),
    Safe,
    Unknown,
}

/// Classification of a detected weak-crypto call.
#[derive(Debug, Clone, PartialEq, Eq)]
enum WeakCryptoCallKind {
    /// `hashlib.md5(...)` — attribute / identifier names a broken algo.
    BrokenAlgoIdentifier(String),
    /// `crypto.createHash('md5')` — string-literal arg names a broken algo.
    BrokenAlgoStringLiteral(String),
    /// `crypto.createCipheriv('aes-128-ecb', ...)` — algo+mode combo where
    /// the mode is weak (ECB) regardless of the underlying cipher.
    #[allow(dead_code)]
    WeakModeCombo { algo: String, mode: String },
    /// `crypto.createHash(userChoice)` — algo is a non-literal expression.
    UnknownAlgoFromVariable,
}

impl WeakCryptoCallKind {
    fn algo_label(&self) -> String {
        match self {
            WeakCryptoCallKind::BrokenAlgoIdentifier(n)
            | WeakCryptoCallKind::BrokenAlgoStringLiteral(n) => n.clone(),
            WeakCryptoCallKind::WeakModeCombo { algo, mode } => format!("{algo}/{mode}"),
            WeakCryptoCallKind::UnknownAlgoFromVariable => "<dynamic>".to_string(),
        }
    }
}

/// Map a `WeakCryptoCallKind` to a base severity.
fn severity_for(kind: &WeakCryptoCallKind) -> Severity {
    match kind {
        WeakCryptoCallKind::BrokenAlgoIdentifier(_)
        | WeakCryptoCallKind::BrokenAlgoStringLiteral(_) => Severity::High,
        WeakCryptoCallKind::WeakModeCombo { .. } => {
            // DES is broken at any mode; ECB mode is broken at any cipher.
            // Either way: High.
            Severity::High
        }
        WeakCryptoCallKind::UnknownAlgoFromVariable => Severity::Low,
    }
}

// ---------------------------------------------------------------------------
// Detector
// ---------------------------------------------------------------------------

pub struct InsecureCryptoDetector {
    repository_path: PathBuf,
    max_findings: usize,
}

impl InsecureCryptoDetector {
    crate::detectors::detector_new!(50);

    fn relative_path(&self, path: &Path) -> PathBuf {
        crate::detectors::detector_relative_path(&self.repository_path, path)
    }

    /// AST-first scanner. Walks the tree once, emitting findings for
    /// every call expression whose callee or string argument names a
    /// weak primitive.
    fn scan_file_ast(&self, inputs: &ScanAstInputs<'_>) -> Vec<Finding> {
        let path = inputs.path();
        let content = inputs.content();
        let ext = inputs.ext();
        let lang = inputs.lang;
        let cached_tree = inputs.cached_tree;
        let mut findings = vec![];
        if content.contains('\0') || content.len() > 500_000 {
            return findings;
        }

        let owned;
        let root = match cached_tree {
            Some(tree) => tree.root_node(),
            None => match parse_root_ext(content, lang, ext) {
                Some(t) => {
                    owned = t;
                    owned.root_node()
                }
                None => return findings,
            },
        };

        let bytes = content.as_bytes();
        let lines: Vec<&str> = content.lines().collect();

        // Build per-file from-import alias map (Python only). Lets us
        // resolve `from hashlib import md5; md5(data)` to a `hashlib.md5`
        // call without any whole-program analysis.
        let alias_map = if matches!(lang, Language::Python) {
            collect_python_from_imports(root, bytes)
        } else {
            HashMap::new()
        };
        // Per-file Python module-alias map: resolves
        // `import hashlib as hl; hl.md5(data)` by mapping the
        // attribute-receiver text `hl` back to the canonical
        // module name `hashlib` before matching.
        let module_aliases = if matches!(lang, Language::Python) {
            collect_python_module_aliases(root, bytes)
        } else {
            HashMap::new()
        };

        let mut sites: Vec<CryptoSite> = Vec::new();
        let ctx = AstWalkCtx {
            lang,
            source: bytes,
        };
        let aliases = PythonAliases::new(&alias_map, &module_aliases);
        collect_crypto_sites(&ctx, root, &aliases, &mut sites);

        for site in sites {
            if findings.len() >= self.max_findings {
                break;
            }
            let line_idx = site.call_node.start_position().row;
            if let Some(line) = lines.get(line_idx) {
                let prev = if line_idx > 0 {
                    Some(lines[line_idx - 1])
                } else {
                    None
                };
                if crate::detectors::is_line_suppressed(line, prev) {
                    continue;
                }
            }
            let snippet = lines.get(line_idx).map(|s| s.trim()).unwrap_or("");
            let line_num = (line_idx + 1) as u32;

            findings.push(self.build_finding(path, line_num, &site.kind, snippet, ext));
        }

        findings
    }

    /// Legacy line scanner for non-AST languages (Java, C/C++, Go, Ruby,
    /// PHP, C#).
    fn scan_file_line(&self, inputs: &ScanInputs<'_>) -> Vec<Finding> {
        let path = inputs.path;
        let content = inputs.content;
        let ext = inputs.ext;
        let mut findings = vec![];
        if content.len() > 500_000 {
            return findings;
        }
        let lines: Vec<&str> = content.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if findings.len() >= self.max_findings {
                break;
            }
            let prev = if i > 0 { Some(lines[i - 1]) } else { None };
            if crate::detectors::is_line_suppressed(line, prev) {
                continue;
            }
            let trimmed = line.trim_start();
            if trimmed.starts_with('#') || trimmed.starts_with("//") || trimmed.starts_with('*') {
                continue;
            }
            if let Some(kind) = match_line_crypto(line, ext) {
                let line_num = (i + 1) as u32;
                findings.push(self.build_finding(path, line_num, &kind, line.trim(), ext));
            }
        }
        findings
    }

    fn build_finding(
        &self,
        path: &Path,
        line_num: u32,
        kind: &WeakCryptoCallKind,
        snippet: &str,
        _ext: &str,
    ) -> Finding {
        let (title, suggested_fix, cwe) = match kind {
            WeakCryptoCallKind::BrokenAlgoIdentifier(name)
            | WeakCryptoCallKind::BrokenAlgoStringLiteral(name) => {
                let upper = name.to_uppercase();
                if matches!(
                    upper.as_str(),
                    "MD5" | "SHA1" | "SHA-1" | "MD4" | "MD2" | "SHA"
                ) {
                    (
                        format!("Weak hash algorithm ({upper})"),
                        "Use SHA-256 / SHA-3 / BLAKE3 instead. For password hashing use Argon2 or scrypt.".to_string(),
                        "CWE-328",
                    )
                } else {
                    (
                        format!("Weak cipher algorithm ({upper})"),
                        "Use AES-GCM or ChaCha20-Poly1305 instead.".to_string(),
                        "CWE-327",
                    )
                }
            }
            WeakCryptoCallKind::WeakModeCombo { algo, mode } => (
                format!(
                    "Weak cipher mode ({}/{})",
                    algo.to_uppercase(),
                    mode.to_uppercase()
                ),
                "ECB mode leaks plaintext patterns. Use AES-GCM or ChaCha20-Poly1305.".to_string(),
                "CWE-327",
            ),
            WeakCryptoCallKind::UnknownAlgoFromVariable => (
                "Cryptographic algorithm chosen at runtime".to_string(),
                "Validate the algorithm against an allowlist (SHA-256+, AES-GCM, ChaCha20-Poly1305).".to_string(),
                "CWE-327",
            ),
        };

        let description = format!(
            "**Insecure cryptographic primitive**\n\n\
             **Algorithm**: `{}`\n\n\
             **Location**: {}:{}\n\n\
             **Code**:\n```\n{}\n```\n\n\
             Cryptographically broken primitives (MD5, SHA-1, DES, RC4, ECB mode) can be \
             exploited via collision attacks, key recovery, or plaintext-pattern leakage. \
             Replace them with modern primitives.",
            kind.algo_label(),
            path.display(),
            line_num,
            snippet,
        );

        Finding {
            id: String::new(),
            detector: "InsecureCryptoDetector".to_string(),
            severity: severity_for(kind),
            title,
            description,
            affected_files: vec![self.relative_path(path)],
            line_start: Some(line_num),
            line_end: Some(line_num),
            suggested_fix: Some(suggested_fix),
            estimated_effort: Some("30 minutes".to_string()),
            category: Some("security".to_string()),
            cwe_id: Some(cwe.to_string()),
            why_it_matters: Some(
                "Broken primitives let attackers forge signatures, recover keys, or leak \
                 plaintext patterns."
                    .to_string(),
            ),
            ..Default::default()
        }
    }
}

impl Detector for InsecureCryptoDetector {
    fn name(&self) -> &'static str {
        "insecure-crypto"
    }
    fn description(&self) -> &'static str {
        "Detects weak cryptographic algorithms"
    }

    fn requires_graph(&self) -> bool {
        false
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        SUPPORTED_EXTS
    }

    fn content_requirements(&self) -> crate::detectors::detector_context::ContentFlags {
        crate::detectors::detector_context::ContentFlags::HAS_CRYPTO
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        debug!("Starting insecure-crypto detection (AST-first)");

        let mut findings: Vec<Finding> = Vec::new();

        for path in files.files_with_extensions(SUPPORTED_EXTS) {
            if findings.len() >= self.max_findings {
                break;
            }

            let path_str = path.to_string_lossy().to_lowercase();
            if crate::detectors::base::is_test_path(&path_str) {
                continue;
            }
            // Skip translation/localization files (French "des" = "of the").
            if path_str.contains("/lang/")
                || path_str.contains("/locale")
                || path_str.contains("/i18n/")
                || path_str.contains("/translations/")
                || path_str.contains("_lang")
                || path_str.contains(".lang.")
            {
                continue;
            }
            if path_str.contains("scripts/") || path_str.contains("/script/") {
                continue;
            }

            let content = match files.content(path) {
                Some(c) => c,
                None => continue,
            };
            // Cheap pre-filter: skip files with no crypto-related keyword.
            if !contains_any(CRYPTO_KEYWORD_FINDERS, &content) {
                continue;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            let scan = ScanInputs::new(path, &content, ext);
            let new_findings = if AST_EXTS.contains(&ext) {
                let cached = files.tree(path);
                let lang = Language::from_path(path);
                let ast_inputs = ScanAstInputs::new(scan, lang, cached.as_deref());
                self.scan_file_ast(&ast_inputs)
            } else {
                self.scan_file_line(&scan)
            };
            findings.extend(new_findings);
        }

        // Severity boost when call appears in a request-handler / route
        // function. Mirrors `eval_detector` / `command_injection` /
        // `pickle_detector`.
        static HANDLER_VERB_RE: LazyLock<Regex> = LazyLock::new(|| {
            Regex::new(r"^(get|post|put|delete|patch|head|options)[A-Z]").expect("valid regex")
        });
        for finding in &mut findings {
            if !matches!(finding.severity, Severity::High | Severity::Medium) {
                continue;
            }
            if let (Some(file_path), Some(line)) =
                (finding.affected_files.first(), finding.line_start)
            {
                let path_str = file_path.to_string_lossy().to_string();
                let i = graph.interner();
                if let Some(func) = graph.find_function_at(&path_str, line) {
                    let raw_name = func.node_name(i);
                    let name_lower = raw_name.to_lowercase();
                    let is_route = name_lower.contains("handler")
                        || name_lower.contains("route")
                        || name_lower.contains("endpoint")
                        || name_lower.contains("view")
                        || name_lower.contains("controller")
                        || name_lower.contains("middleware")
                        || name_lower.contains("request")
                        || name_lower.contains("response")
                        || HANDLER_VERB_RE.is_match(raw_name);
                    if is_route && finding.severity == Severity::High {
                        finding.severity = Severity::Critical;
                    }
                }
            }
        }

        info!(
            "InsecureCryptoDetector found {} potential vulnerabilities",
            findings.len()
        );
        Ok(findings)
    }

    fn bypass_postprocessor(&self) -> bool {
        true
    }
}

impl crate::detectors::RegisteredDetector for InsecureCryptoDetector {
    fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
        std::sync::Arc::new(Self::new(init.repo_path))
    }
}

// ---------------------------------------------------------------------------
// Pre-filter
// ---------------------------------------------------------------------------

/// Cheap pre-filter: does this file contain any crypto keyword?
///
/// Each callee name we match downstream MUST be covered by one of the
/// substrings here, otherwise the AST scan never runs on a file
/// containing only that callee. Mirrors the `pickle_detector` audit.
///
/// Cross-checked against every matcher below:
///   - `hashlib.md5` / `hashlib.new` → FIND_HASHLIB or FIND_MD5_LOWER.
///   - `from hashlib import md5; md5(data)` → FIND_HASHLIB.
///   - `Crypto.Cipher.DES.new` → FIND_CRYPTO_CIPHER or FIND_DES_UPPER.
///   - `cryptography.hazmat.primitives.hashes.MD5()` → FIND_HAZMAT or
///     FIND_MD5_UPPER.
///   - `crypto.createHash('md5')` → FIND_CREATE_HASH.
///   - `crypto.createCipheriv('aes-128-ecb', ...)` → FIND_CREATE_CIPHER
///     or FIND_ECB.
///   - `crypto.createSign('RSA-MD5')` → FIND_CREATE_SIGN.
///   - `MessageDigest.getInstance("MD5")` → FIND_MESSAGE_DIGEST or
///     FIND_MD5_UPPER.
///   - `Cipher.getInstance("DES/ECB/PKCS5Padding")` →
///     FIND_CIPHER_GETINSTANCE or FIND_DES_UPPER or FIND_ECB.
static CRYPTO_KEYWORD_FINDERS: &[&LazyLock<memchr::memmem::Finder<'static>>] = &[
    &FIND_HASHLIB,
    &FIND_CRYPTO_CIPHER,
    &FIND_HAZMAT,
    &FIND_CREATE_HASH,
    &FIND_CREATE_CIPHER,
    &FIND_CREATE_DECIPHER,
    &FIND_CREATE_SIGN,
    &FIND_REQUIRE_CRYPTO,
    &FIND_REQUIRE_CRYPTO_DQ,
    &FIND_MD5_UPPER,
    &FIND_SHA1_UPPER,
    &FIND_MD4_UPPER,
    &FIND_DES_UPPER,
    &FIND_RC4_UPPER,
    &FIND_RC2_UPPER,
    &FIND_BLOWFISH,
    &FIND_ECB,
    &FIND_MD5_LOWER,
    &FIND_SHA1_LOWER,
    &FIND_MESSAGE_DIGEST,
    &FIND_CIPHER_GETINSTANCE,
];

// ---------------------------------------------------------------------------
// AST walking
// ---------------------------------------------------------------------------

struct CryptoSite<'a> {
    call_node: tree_sitter::Node<'a>,
    kind: WeakCryptoCallKind,
}

fn collect_crypto_sites<'a>(
    ctx: &AstWalkCtx<'a>,
    node: tree_sitter::Node<'a>,
    aliases: &PythonAliases<'_>,
    out: &mut Vec<CryptoSite<'a>>,
) {
    if let Some(site) = match_crypto_site(node, ctx.source, ctx.lang, aliases) {
        out.push(site);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_crypto_sites(ctx, child, aliases, out);
    }
}

fn match_crypto_site<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
    lang: Language,
    aliases: &PythonAliases<'_>,
) -> Option<CryptoSite<'a>> {
    match (node.kind(), lang) {
        ("call", Language::Python) => match_python_crypto_call(node, source, aliases),
        ("call_expression", Language::JavaScript | Language::TypeScript) => {
            match_js_crypto_call(node, source)
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Python from-import alias resolution
// ---------------------------------------------------------------------------

use super::python_imports::{
    collect_python_from_imports, collect_python_module_aliases, PythonAliases,
};

// ---------------------------------------------------------------------------
// Python
// ---------------------------------------------------------------------------

/// Names that are broken at the *attribute* level (`hashlib.md5`,
/// `hashlib.sha1`, ...). Lowercase.
const PY_BROKEN_HASH_ATTRS: &[&str] = &["md5", "sha1", "md4", "md2", "sha"];

/// Match a Python `call` node against the weak-crypto API list.
fn match_python_crypto_call<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
    aliases: &PythonAliases<'_>,
) -> Option<CryptoSite<'a>> {
    let func = node.child_by_field_name("function")?;
    let func = unwrap_callee(func);
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);

    let kind = match func.kind() {
        "attribute" => {
            let obj = func.child_by_field_name("object")?;
            let attr = func.child_by_field_name("attribute")?;
            let attr_text = node_text(attr, source)?.to_string();
            let raw_label = receiver_chain_label(obj, source);
            // Resolve `import hashlib as hl; hl.md5(...)` — if the
            // receiver is an aliased module, swap the label for the
            // canonical module name before matching. The map's identity
            // entries (`{"hashlib": "hashlib"}`) make this lookup safe
            // even for unaliased imports; an unknown receiver falls
            // through to the literal label.
            //
            // Look up against the case-sensitive identifier text first
            // (the import map preserves source case), then fall back to
            // the lowercased label `receiver_chain_label` produces.
            let obj_text = node_text(obj, source).unwrap_or("");
            let obj_label = aliases
                .modules
                .get(obj_text)
                .or_else(|| aliases.modules.get(raw_label.as_str()))
                .cloned()
                .unwrap_or(raw_label);

            // hashlib.md5 / hashlib.sha1 / hashlib.md4 ...
            if obj_label == "hashlib"
                && PY_BROKEN_HASH_ATTRS.contains(&attr_text.to_lowercase().as_str())
            {
                WeakCryptoCallKind::BrokenAlgoIdentifier(attr_text)
            }
            // hashlib.new('md5')
            else if obj_label == "hashlib" && attr_text == "new" {
                let first_arg = arg_nodes.first().copied();
                match first_arg.and_then(|n| python_string_literal_value(n, source)) {
                    Some(s) => match classify_algo_name(&s) {
                        AlgoKind::Broken(n) => WeakCryptoCallKind::BrokenAlgoStringLiteral(n),
                        AlgoKind::Safe => return None,
                        AlgoKind::Unknown => return None,
                    },
                    None => match first_arg {
                        Some(n) if !is_static_string(n) => {
                            WeakCryptoCallKind::UnknownAlgoFromVariable
                        }
                        _ => return None,
                    },
                }
            }
            // Crypto.Cipher.DES.new(...) / Crypto.Cipher.AES.new(key, AES.MODE_ECB, ...)
            // Also PyCrypto-imported `DES.new(...)` after `from Crypto.Cipher import DES`.
            else if attr_text == "new" {
                let recv_full = node_text(obj, source).unwrap_or("");
                let last = recv_full.rsplit('.').next().unwrap_or(recv_full);
                let last_lower = last.to_lowercase();
                match classify_algo_name(last) {
                    AlgoKind::Broken(_) => {
                        WeakCryptoCallKind::BrokenAlgoIdentifier(last.to_string())
                    }
                    _ if last_lower == "aes" => {
                        // AES is fine — but check for ECB mode in the
                        // second positional argument.
                        if let Some(mode_arg) = positional_arg(&arg_nodes, 1) {
                            let mode_text = node_text(mode_arg, source).unwrap_or("");
                            if mode_text.to_uppercase().ends_with("MODE_ECB") {
                                WeakCryptoCallKind::WeakModeCombo {
                                    algo: "aes".to_string(),
                                    mode: "ecb".to_string(),
                                }
                            } else {
                                return None;
                            }
                        } else {
                            return None;
                        }
                    }
                    _ => return None,
                }
            }
            // cryptography.hazmat.primitives.hashes.MD5()
            else if matches!(attr_text.to_uppercase().as_str(), "MD5" | "SHA1" | "MD4")
                && obj_label == "hashes"
            {
                WeakCryptoCallKind::BrokenAlgoIdentifier(attr_text)
            } else {
                return None;
            }
        }
        // Bare-identifier call: only interesting if it's a from-import alias.
        "identifier" => {
            let name = node_text(func, source)?.to_string();
            if let Some(module) = aliases.imports.get(&name) {
                if module == "hashlib"
                    && PY_BROKEN_HASH_ATTRS.contains(&name.to_lowercase().as_str())
                {
                    WeakCryptoCallKind::BrokenAlgoIdentifier(name)
                } else {
                    return None;
                }
            } else {
                return None;
            }
        }
        _ => return None,
    };

    Some(CryptoSite {
        call_node: node,
        kind,
    })
}

fn positional_arg<'a>(args: &[tree_sitter::Node<'a>], idx: usize) -> Option<tree_sitter::Node<'a>> {
    let mut count = 0;
    for a in args {
        if a.kind() == "keyword_argument" {
            continue;
        }
        if count == idx {
            return Some(*a);
        }
        count += 1;
    }
    None
}

fn is_static_string(node: tree_sitter::Node<'_>) -> bool {
    matches!(node.kind(), "string" | "concatenated_string")
}

fn python_string_literal_value(node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
    if node.kind() != "string" {
        return None;
    }
    let raw = node_text(node, source)?;
    let bytes = raw.as_bytes();
    let mut i = 0;
    while i < bytes.len() && bytes[i].is_ascii_alphabetic() {
        i += 1;
    }
    let after_prefix = &raw[i..];
    let inner = after_prefix
        .strip_prefix("\"\"\"")
        .and_then(|s| s.strip_suffix("\"\"\""))
        .or_else(|| {
            after_prefix
                .strip_prefix("'''")
                .and_then(|s| s.strip_suffix("'''"))
        })
        .or_else(|| {
            after_prefix
                .strip_prefix('"')
                .and_then(|s| s.strip_suffix('"'))
        })
        .or_else(|| {
            after_prefix
                .strip_prefix('\'')
                .and_then(|s| s.strip_suffix('\''))
        })?;
    Some(inner.to_string())
}

// ---------------------------------------------------------------------------
// JavaScript / TypeScript
// ---------------------------------------------------------------------------

fn match_js_crypto_call<'a>(
    node: tree_sitter::Node<'a>,
    source: &'a [u8],
) -> Option<CryptoSite<'a>> {
    let func = node.child_by_field_name("function")?;
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);
    let func = unwrap_callee(func);

    let kind = match func.kind() {
        "member_expression" => {
            let obj = func.child_by_field_name("object")?;
            let prop = func.child_by_field_name("property")?;
            let prop_text = node_text(prop, source)?.to_string();
            let recv = receiver_chain_label(obj, source);

            // Only inspect calls whose receiver looks like the `crypto`
            // module (bare alias `crypto`, `Crypto`, or resolved through
            // `require('crypto')` / `import('crypto')`).
            let is_crypto_recv =
                recv == "crypto" || recv == "Crypto".to_lowercase() || recv == "node:crypto";

            if !is_crypto_recv {
                return None;
            }

            match prop_text.as_str() {
                "createHash" | "createHmac" => {
                    classify_string_algo_arg(&arg_nodes, source, /*allow_mode=*/ false)?
                }
                "createCipheriv" | "createDecipheriv" | "createCipher" | "createDecipher" => {
                    classify_string_algo_arg(&arg_nodes, source, /*allow_mode=*/ true)?
                }
                "createSign" | "createVerify" => {
                    classify_string_algo_arg(&arg_nodes, source, /*allow_mode=*/ false)?
                }
                _ => return None,
            }
        }
        _ => return None,
    };

    Some(CryptoSite {
        call_node: node,
        kind,
    })
}

/// Inspect the first argument of a JS `crypto.createX(...)` call and
/// return the appropriate `WeakCryptoCallKind`.
fn classify_string_algo_arg(
    args: &[tree_sitter::Node<'_>],
    source: &[u8],
    allow_mode: bool,
) -> Option<WeakCryptoCallKind> {
    let first = args.first().copied()?;
    let first = unwrap_arg(first);
    if let Some(s) = js_string_literal_value(first, source) {
        // Case 1: explicit algo+mode label like "aes-128-ecb".
        if allow_mode {
            if let Some((algo, mode)) = split_algo_mode(&s) {
                let algo_class = classify_algo_name(&algo);
                if mode.eq_ignore_ascii_case("ecb") || matches!(algo_class, AlgoKind::Broken(_)) {
                    return Some(WeakCryptoCallKind::WeakModeCombo { algo, mode });
                }
                if matches!(algo_class, AlgoKind::Safe) {
                    return None;
                }
            }
        }
        // Case 2: simple algo name like "md5" or composite like "RSA-MD5".
        let lower = s.to_lowercase();
        for token in lower.split(['-', '_', '/']) {
            match classify_algo_name(token) {
                AlgoKind::Broken(_) => {
                    return Some(WeakCryptoCallKind::BrokenAlgoStringLiteral(s));
                }
                AlgoKind::Safe => {
                    return None;
                }
                AlgoKind::Unknown => continue,
            }
        }
        match classify_algo_name(&s) {
            AlgoKind::Broken(_) => Some(WeakCryptoCallKind::BrokenAlgoStringLiteral(s)),
            _ => None,
        }
    } else {
        // Non-literal — algorithm chosen at runtime.
        Some(WeakCryptoCallKind::UnknownAlgoFromVariable)
    }
}

/// Descend through transparent wrappers (`await`, parens, TS type ops).
fn unwrap_arg(mut node: tree_sitter::Node<'_>) -> tree_sitter::Node<'_> {
    loop {
        match node.kind() {
            "parenthesized_expression"
            | "await_expression"
            | "as_expression"
            | "type_assertion_expression"
            | "non_null_expression"
            | "satisfies_expression" => {
                let next = node.named_child(0);
                match next {
                    Some(n) => node = n,
                    None => return node,
                }
            }
            _ => return node,
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers shared with eval / command_injection / pickle.
// `unwrap_callee`, `collect_named_args`, `node_text` live in `ast_helpers`
// (imported above). Only `receiver_chain_label` (which uses this
// detector's `call_expression_module_label`) and `js_string_literal_value`
// are kept local.
// ---------------------------------------------------------------------------

/// Lowercased "receiver label" for a JS/TS or Python member-call
/// receiver. Mirrors `pickle_detector::receiver_chain_label`.
///
/// Resolves `require('crypto')` / `(await import('crypto'))` to the
/// canonical lowercased module name, so:
///
///   - `crypto.createHash(...)` → label `"crypto"`
///   - `require('crypto').createHash(...)` → label `"crypto"`
///   - `(await import('crypto')).createHash(...)` → label `"crypto"`
///   - `self.hashlib.md5(...)` → label `"hashlib"`
///
/// Implementation: delegate to the shared
/// [`receiver_chain_label`](crate::detectors::security::ast_helpers::receiver_chain_label)
/// passing this detector's [`call_expression_module_label`] as the
/// resolver — that's the only piece that varies between detectors (it
/// names the dangerous crypto module(s) for *this* detector, e.g.
/// `crypto`).
fn receiver_chain_label(node: tree_sitter::Node<'_>, source: &[u8]) -> String {
    receiver_chain_label_shared(node, source, Some(&call_expression_module_label))
}

/// If `node` is `require('MODULE')` or `import('MODULE')` for a known
/// crypto module, return the canonical lowercased module name.
fn call_expression_module_label(
    node: tree_sitter::Node<'_>,
    source: &[u8],
) -> Option<&'static str> {
    debug_assert_eq!(node.kind(), "call_expression");
    let func = node.child_by_field_name("function")?;
    let func_text = node_text(func, source)?;
    let is_require_or_import =
        matches!(func.kind(), "identifier" | "import") && matches!(func_text, "require" | "import");
    if !is_require_or_import {
        return None;
    }
    let args = node.child_by_field_name("arguments")?;
    let arg_nodes = collect_named_args(args);
    let first = arg_nodes.first()?;
    let module = js_string_literal_value(*first, source)?;
    match module.as_str() {
        "crypto" | "node:crypto" => Some("crypto"),
        _ => None,
    }
}

fn js_string_literal_value(node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
    if node.kind() != "string" {
        return None;
    }
    let mut cursor = node.walk();
    let mut buf = String::new();
    let mut saw_fragment = false;
    for child in node.children(&mut cursor) {
        if child.kind() == "string_fragment" {
            if let Some(t) = node_text(child, source) {
                buf.push_str(t);
                saw_fragment = true;
            }
        }
    }
    if saw_fragment {
        return Some(buf);
    }
    let raw = node_text(node, source)?;
    let inner = raw
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| raw.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))?;
    Some(inner.to_string())
}

// `node_text` lives in `ast_helpers`; imported above.

// ---------------------------------------------------------------------------
// Line scanner (Java, C/C++, Go, Ruby, PHP, C#)
// ---------------------------------------------------------------------------

/// Recognise weak crypto on a line for languages without AST coverage.
fn match_line_crypto(line: &str, _ext: &str) -> Option<WeakCryptoCallKind> {
    static MESSAGE_DIGEST_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"MessageDigest\.getInstance\s*\(\s*["']([^"']+)["']"#).expect("valid regex")
    });
    static CIPHER_GETINSTANCE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"Cipher\.getInstance\s*\(\s*["']([^"']+)["']"#).expect("valid regex")
    });
    static MCRYPT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"mcrypt_(?:encrypt|decrypt)\s*\(\s*MCRYPT_(\w+)").expect("valid regex")
    });
    static OPENSSL_ENCRYPT_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r#"openssl_(?:encrypt|decrypt)\s*\([^,]*,\s*["']([^"']+)["']"#)
            .expect("valid regex")
    });
    static GO_DES_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"\bdes\.NewCipher\s*\(|\bdes\.NewTripleDESCipher\s*\(").expect("valid regex")
    });
    static GO_RC4_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"\brc4\.NewCipher\s*\(").expect("valid regex"));
    static GO_WEAK_HASH_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"\b(md5|sha1)\s*\.\s*(?:New|Sum)\s*\(").expect("valid regex"));
    static RUBY_DIGEST_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"\bDigest::(MD5|SHA1|MD4|MD2)\b").expect("valid regex"));
    static C_DIRECT_HASH_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"\b(MD5|SHA1|MD4|MD2|DES_set_key|DES_ecb_encrypt|RC4)\s*\(")
            .expect("valid regex")
    });

    if let Some(cap) = MESSAGE_DIGEST_RE.captures(line) {
        let algo = &cap[1];
        if let AlgoKind::Broken(name) = classify_algo_name(algo) {
            return Some(WeakCryptoCallKind::BrokenAlgoStringLiteral(name));
        }
    }
    if let Some(cap) = CIPHER_GETINSTANCE_RE.captures(line) {
        let spec = &cap[1];
        // Java cipher specs are `algo/mode/padding` (e.g. `DES/ECB/PKCS5Padding`).
        let parts: Vec<&str> = spec.split('/').collect();
        let algo = parts.first().copied().unwrap_or("");
        let mode = parts.get(1).copied().unwrap_or("");
        match classify_algo_name(algo) {
            AlgoKind::Broken(n) => {
                return Some(WeakCryptoCallKind::BrokenAlgoStringLiteral(n));
            }
            _ => {
                if mode.eq_ignore_ascii_case("ecb") {
                    return Some(WeakCryptoCallKind::WeakModeCombo {
                        algo: algo.to_string(),
                        mode: mode.to_string(),
                    });
                }
            }
        }
    }
    if let Some(cap) = MCRYPT_RE.captures(line) {
        let algo = &cap[1];
        if let AlgoKind::Broken(name) = classify_algo_name(algo) {
            return Some(WeakCryptoCallKind::BrokenAlgoStringLiteral(name));
        }
    }
    if let Some(cap) = OPENSSL_ENCRYPT_RE.captures(line) {
        let spec = &cap[1];
        let parts: Vec<&str> = spec.split('-').collect();
        let algo = parts.first().copied().unwrap_or("");
        let mode = parts.last().copied().unwrap_or("");
        if let AlgoKind::Broken(name) = classify_algo_name(algo) {
            return Some(WeakCryptoCallKind::BrokenAlgoStringLiteral(name));
        }
        if mode.eq_ignore_ascii_case("ecb") {
            return Some(WeakCryptoCallKind::WeakModeCombo {
                algo: algo.to_string(),
                mode: mode.to_string(),
            });
        }
    }
    if GO_DES_RE.is_match(line) {
        return Some(WeakCryptoCallKind::BrokenAlgoIdentifier("DES".to_string()));
    }
    if GO_RC4_RE.is_match(line) {
        return Some(WeakCryptoCallKind::BrokenAlgoIdentifier("RC4".to_string()));
    }
    if let Some(cap) = GO_WEAK_HASH_RE.captures(line) {
        return Some(WeakCryptoCallKind::BrokenAlgoIdentifier(
            cap[1].to_uppercase(),
        ));
    }
    if let Some(cap) = RUBY_DIGEST_RE.captures(line) {
        return Some(WeakCryptoCallKind::BrokenAlgoIdentifier(cap[1].to_string()));
    }
    if let Some(cap) = C_DIRECT_HASH_RE.captures(line) {
        let name = cap[1].to_string();
        let canonical = if name.starts_with("DES_") {
            "DES".to_string()
        } else if name.starts_with("RC4") {
            "RC4".to_string()
        } else {
            name
        };
        return Some(WeakCryptoCallKind::BrokenAlgoIdentifier(canonical));
    }
    None
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::builder::GraphBuilder;

    fn run(file: &str, content: &str) -> Vec<Finding> {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureCryptoDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(file, content)],
        );
        detector.detect(&ctx).expect("detection should succeed")
    }

    // -----------------------------------------------------------------
    // Pre-existing tests (preserved through migration).
    // -----------------------------------------------------------------

    #[test]
    fn test_detects_md5_usage() {
        let findings = run(
            "crypto_util.py",
            "import hashlib\n\ndef compute_hash(data):\n    return hashlib.md5(data).hexdigest()\n",
        );
        assert!(!findings.is_empty(), "Should detect hashlib.md5 usage");
    }

    #[test]
    fn test_no_finding_for_sha256() {
        let findings = run(
            "crypto_util.py",
            "import hashlib\n\ndef compute_hash(data):\n    return hashlib.sha256(data).hexdigest()\n",
        );
        assert!(
            findings.is_empty(),
            "sha256 must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_class_definition() {
        let findings = run(
            "text.py",
            "from django.db.models import Transform\n\nclass MD5(Transform):\n    function = 'MD5'\n    lookup_name = 'md5'\n",
        );
        assert!(
            findings.is_empty(),
            "class MD5(...) is a class def, not a call. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_detects_java_des_cipher() {
        let findings = run(
            "CryptoUtil.java",
            "import javax.crypto.*;\n\npublic class CryptoUtil {\n    public byte[] encrypt(byte[] data) throws Exception {\n        Cipher cipher = Cipher.getInstance(\"DES\");\n        return cipher.doFinal(data);\n    }\n}\n",
        );
        assert!(
            !findings.is_empty(),
            "Cipher.getInstance(\"DES\") must fire"
        );
    }

    #[test]
    fn test_detects_go_md5_new_and_sum() {
        let findings = run(
            "hash.go",
            r#"
package main
import "crypto/md5"
func hash(payload []byte) {
    h := md5.New()
    _ = h.Sum(payload)
    _ = md5.Sum(payload)
}
"#,
        );

        assert!(findings.iter().any(|f| f.line_start == Some(5)));
        assert!(findings.iter().any(|f| f.line_start == Some(7)));
    }

    #[test]
    fn test_detects_go_sha1_sum() {
        let findings = run(
            "hash.go",
            r#"
package main
import "crypto/sha1"
func hash(payload []byte) {
    _ = sha1.Sum(payload)
}
"#,
        );

        assert!(findings.iter().any(|f| f.line_start == Some(5)));
    }

    // -----------------------------------------------------------------
    // Audit / regression tests for the AST-first migration.
    //
    // Cohort 1 (currently-passing-shape, 5)
    // Cohort 2 (audit-shape, 4)
    // Cohort 3 (audit-pending, 3)
    // -----------------------------------------------------------------

    // ----- Cohort 1: currently-passing-shape -----

    #[test]
    fn test_detects_hashlib_md5_python() {
        let findings = run(
            "h.py",
            "import hashlib\ndef hash_pwd(p):\n    return hashlib.md5(p).hexdigest()\n",
        );
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::High | Severity::Critical)),
            "hashlib.md5 should fire High. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_detects_hashlib_sha1_python() {
        let findings = run(
            "h.py",
            "import hashlib\ndef hash_pwd(p):\n    return hashlib.sha1(p).hexdigest()\n",
        );
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::High | Severity::Critical)),
            "hashlib.sha1 should fire High. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_detects_crypto_createhash_md5_js() {
        let findings = run(
            "h.js",
            "const crypto = require('crypto');\nfunction f(d) { return crypto.createHash('md5').update(d).digest(); }\n",
        );
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::High | Severity::Critical)),
            "crypto.createHash('md5') should fire High. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_skips_hashlib_sha256_python() {
        let findings = run(
            "h.py",
            "import hashlib\ndef ok(p):\n    return hashlib.sha256(p).hexdigest()\n",
        );
        assert!(
            findings.is_empty(),
            "hashlib.sha256 must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_skips_md5_in_comment() {
        let findings = run(
            "h.py",
            "import hashlib\ndef ok(p):\n    # Use hashlib.md5 if needed\n    return hashlib.sha256(p).hexdigest()\n",
        );
        assert!(
            findings.is_empty(),
            "md5 in comment must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // ----- Cohort 2: audit-shape -----

    /// B1-class: `require('crypto').createHash('md5')` — receiver-chain
    /// label resolves the require() callee to the canonical module name.
    #[test]
    fn test_b1_require_crypto_createhash_md5_js() {
        let findings = run(
            "go.js",
            "function go(data) { return require('crypto').createHash('md5').update(data).digest(); }\n",
        );
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::High | Severity::Critical)),
            "B1: require('crypto').createHash('md5') must fire. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// `class C: def md5(self): pass` — `md5` is a method definition. The
    /// AST sees a function definition, not a `hashlib.md5(...)` call, so
    /// nothing fires.
    #[test]
    fn test_skips_md5_as_method_name_python() {
        let findings = run(
            "c.py",
            "class C:\n    def md5(self, data):\n        return data\n\nc = C()\nresult = c.md5(b'x')\n",
        );
        // `c.md5(...)` must NOT fire — receiver is `c`, not `hashlib`.
        assert!(
            findings.is_empty(),
            "Method name md5 must not be confused with hashlib.md5. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// `crypto.createCipheriv('aes-128-ecb', ...)` — algo+mode label.
    #[test]
    fn test_aes_ecb_mode_combo_detected_js() {
        let findings = run(
            "c.js",
            "const crypto = require('crypto');\nfunction f(k, iv) { return crypto.createCipheriv('aes-128-ecb', k, iv); }\n",
        );
        assert!(
            !findings.is_empty(),
            "AES/ECB combo must fire. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// `let msg = "compute md5 hash"` — string-literal text, no call.
    #[test]
    fn test_skips_md5_in_string_literal() {
        let findings = run(
            "s.js",
            "function doc() { let msg = \"compute md5 hash\"; return msg; }\n",
        );
        assert!(
            findings.is_empty(),
            "md5 inside a string literal must not fire. Got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    // ----- Cohort 3: audit-pending (un-ignored as the migration lands) -----

    /// `from hashlib import md5; md5(data)` — bare-call after from-import.
    /// First detector in the codebase to do this; alias map is built per
    /// file in `collect_python_from_imports`.
    #[test]
    fn test_python_bare_md5_after_from_import() {
        let findings = run(
            "h.py",
            "from hashlib import md5\ndef hash_pwd(p):\n    return md5(p).hexdigest()\n",
        );
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::High | Severity::Critical)),
            "Bare md5(...) after from hashlib import md5 must fire. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// `from Crypto.Cipher import DES; DES.new(key, DES.MODE_ECB)` — DES
    /// is broken (any mode); also AES.new(..., AES.MODE_ECB, ...).
    #[test]
    fn test_pycrypto_des_new_detected() {
        let findings = run(
            "p.py",
            "from Crypto.Cipher import DES\ndef encrypt(data, key):\n    cipher = DES.new(key, DES.MODE_ECB)\n    return cipher.encrypt(data)\n",
        );
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::High | Severity::Critical)),
            "PyCrypto DES.new must fire High. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// `crypto.createHash(userChoice)` — algo is a non-literal expression;
    /// classifier emits `UnknownAlgoFromVariable` → Low.
    #[test]
    fn test_unknown_algo_from_variable_low_severity() {
        let findings = run(
            "v.js",
            "const crypto = require('crypto');\nfunction f(userChoice, d) { return crypto.createHash(userChoice).update(d).digest(); }\n",
        );
        assert!(
            findings.iter().any(|f| matches!(f.severity, Severity::Low)),
            "Variable-algo createHash must produce a Low finding. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// Audit shape: `import hashlib as hl; hl.md5(data)`.
    ///
    /// `hl.md5(...)` parses as an attribute call whose object text is
    /// `"hl"`, not `"hashlib"`. Without the module-alias resolver the
    /// matcher compares `obj_label == "hashlib"` and misses. Mirrors
    /// `test_python_bare_md5_after_from_import`, but for the
    /// `import M as N` shape.
    #[test]
    fn test_python_aliased_module_hashlib_md5_detected() {
        let findings = run(
            "h.py",
            "import hashlib as hl\ndef hash_pwd(p):\n    return hl.md5(p).hexdigest()\n",
        );
        assert!(
            findings
                .iter()
                .any(|f| matches!(f.severity, Severity::High | Severity::Critical)),
            "Aliased `hl.md5(...)` after `import hashlib as hl` must fire. Got: {:?}",
            findings
                .iter()
                .map(|f| (&f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }
}