stakpak-shared 0.3.74

Stakpak: Your DevOps AI Agent. Generate infrastructure code, debug Kubernetes, configure CI/CD, automate deployments, without giving an LLM the keys to production.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
pub mod gitleaks;
use crate::helper::generate_simple_id;
/// Re-export the gitleaks initialization function for external access
pub use gitleaks::initialize_gitleaks_config;
use gitleaks::{DetectedSecret, detect_secrets};
use std::collections::HashMap;
use std::fmt;

/// A result containing both the redacted string and the mapping of redaction keys to original secrets
#[derive(Debug, Clone)]
pub struct RedactionResult {
    /// The input string with secrets replaced by redaction keys
    pub redacted_string: String,
    /// Mapping from redaction key to the original secret value
    pub redaction_map: HashMap<String, String>,
}

impl RedactionResult {
    pub fn new(redacted_string: String, redaction_map: HashMap<String, String>) -> Self {
        Self {
            redacted_string,
            redaction_map,
        }
    }
}

impl fmt::Display for RedactionResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.redacted_string)
    }
}

/// Redacts secrets from the input string and returns both the redacted string and redaction mapping
///
/// When privacy_mode is enabled, also detects and redacts private data like IP addresses and AWS account IDs
pub fn redact_secrets(
    content: &str,
    path: Option<&str>,
    old_redaction_map: &HashMap<String, String>,
    privacy_mode: bool,
) -> RedactionResult {
    // Skip redaction if content already contains redacted secrets (avoid double redaction)
    if content.contains("[REDACTED_SECRET:") {
        return RedactionResult::new(content.to_string(), HashMap::new());
    }

    let mut secrets = detect_secrets(content, path, privacy_mode);

    let mut redaction_map = old_redaction_map.clone();
    let mut reverse_redaction_map: HashMap<String, String> = old_redaction_map
        .clone()
        .into_iter()
        .map(|(k, v)| (v, k))
        .collect();

    for (original_secret, redaction_key) in &reverse_redaction_map {
        // Extract rule_id from redaction_key format: [REDACTED_SECRET:rule_id:id]
        let key_parts = redaction_key.split(':').collect::<Vec<&str>>();
        if key_parts.len() == 3 {
            let rule_id = key_parts[1].to_string();
            if let Some(start) = content.find(original_secret) {
                let end = start + original_secret.len();
                secrets.push(DetectedSecret {
                    rule_id,
                    value: original_secret.clone(),
                    start_pos: start,
                    end_pos: end,
                });
            }
        }
    }

    if secrets.is_empty() {
        return RedactionResult::new(content.to_string(), HashMap::new());
    }

    let mut redacted_string = content.to_string();

    // Deduplicate overlapping secrets - keep the longest one
    let mut deduplicated_secrets: Vec<DetectedSecret> = Vec::new();
    let mut sorted_by_start = secrets;
    sorted_by_start.sort_by(|a, b| a.start_pos.cmp(&b.start_pos));

    for secret in sorted_by_start {
        let mut should_add = true;
        let mut to_remove = Vec::new();

        for (i, existing) in deduplicated_secrets.iter().enumerate() {
            // Check if secrets overlap
            let overlaps =
                secret.start_pos < existing.end_pos && secret.end_pos > existing.start_pos;

            if overlaps {
                // Keep the longer secret (more specific)
                if secret.value.len() > existing.value.len() {
                    to_remove.push(i);
                } else {
                    should_add = false;
                    break;
                }
            }
        }

        // Remove secrets that should be replaced by this longer one
        for &i in to_remove.iter().rev() {
            deduplicated_secrets.remove(i);
        }

        if should_add {
            deduplicated_secrets.push(secret);
        }
    }

    // Sort by position in reverse order to avoid index shifting issues
    deduplicated_secrets.sort_by(|a, b| b.start_pos.cmp(&a.start_pos));

    for secret in deduplicated_secrets {
        // Validate character boundaries before replacement
        if !content.is_char_boundary(secret.start_pos) || !content.is_char_boundary(secret.end_pos)
        {
            continue;
        }

        // Validate positions are within bounds
        if secret.start_pos >= redacted_string.len() || secret.end_pos > redacted_string.len() {
            continue;
        }

        // make sure same secrets have the same redaction key within the same file
        // without making the hash content dependent (content addressable)
        let redaction_key = if let Some(existing_key) = reverse_redaction_map.get(&secret.value) {
            existing_key.clone()
        } else {
            let key = generate_redaction_key(&secret.rule_id);
            // Store the mapping (only once per unique secret value)
            redaction_map.insert(key.clone(), secret.value.clone());
            reverse_redaction_map.insert(secret.value, key.clone());
            key
        };

        // Replace the secret in the string
        redacted_string.replace_range(secret.start_pos..secret.end_pos, &redaction_key);
    }

    RedactionResult::new(redacted_string, redaction_map)
}

/// Restores secrets in a redacted string using the provided redaction map
pub fn restore_secrets(redacted_string: &str, redaction_map: &HashMap<String, String>) -> String {
    let mut restored = redacted_string.to_string();

    for (redaction_key, original_value) in redaction_map {
        restored = restored.replace(redaction_key, original_value);
    }

    restored
}

/// Redacts a specific password value from the content without running secret detection
pub fn redact_password(
    content: &str,
    password: &str,
    old_redaction_map: &HashMap<String, String>,
) -> RedactionResult {
    if password.is_empty() {
        return RedactionResult::new(content.to_string(), HashMap::new());
    }

    // Skip redaction if content already contains redacted secrets (avoid double redaction)
    if content.contains("[REDACTED_SECRET:") {
        return RedactionResult::new(content.to_string(), HashMap::new());
    }

    let mut redacted_string = content.to_string();
    let mut redaction_map = old_redaction_map.clone();
    let mut reverse_redaction_map: HashMap<String, String> = old_redaction_map
        .clone()
        .into_iter()
        .map(|(k, v)| (v, k))
        .collect();

    // Check if we already have a redaction key for this password
    let redaction_key = if let Some(existing_key) = reverse_redaction_map.get(password) {
        existing_key.clone()
    } else {
        let key = generate_redaction_key("password");
        // Store the mapping
        redaction_map.insert(key.clone(), password.to_string());
        reverse_redaction_map.insert(password.to_string(), key.clone());
        key
    };

    // Replace all occurrences of the password
    redacted_string = redacted_string.replace(password, &redaction_key);

    RedactionResult::new(redacted_string, redaction_map)
}

/// Generates a random redaction key
fn generate_redaction_key(rule_id: &str) -> String {
    let id = generate_simple_id(6);
    format!("[REDACTED_SECRET:{rule_id}:{id}]")
}

#[cfg(test)]
mod tests {
    use regex::Regex;

    use crate::secrets::gitleaks::{
        GITLEAKS_CONFIG, calculate_entropy, contains_any_keyword, create_simple_api_key_regex,
        is_allowed_by_rule_allowlist, should_allow_match,
    };

    use super::*;

    fn fake_aws_access_key() -> String {
        ["AKIA", "IOSFODNN7EX23PLE"].concat()
    }

    fn fake_aws_access_key_alt() -> String {
        ["AKIA", "IOSFODNN7REALKEY"].concat()
    }

    fn fake_aws_access_key_example() -> String {
        ["AKIA", "IOSFODNN7EXAMPLE"].concat()
    }

    fn fake_github_token() -> String {
        ["ghp", "_1234567890abcdef", "1234567890abcdef", "12345678"].concat()
    }

    fn fake_github_token_short() -> String {
        ["ghp", "_1234567890abcdef"].concat()
    }

    fn fake_api_key_long() -> String {
        ["abc123def456", "ghi789jkl012", "mno345pqr678"].concat()
    }

    fn fake_api_key() -> String {
        ["abc123def456", "ghi789jklmnop"].concat()
    }

    fn fake_secret_token() -> String {
        ["Kx9mP2nQ8rT4", "vW7yZ3cF6hJ1", "lN5sA0bD8eF"].concat()
    }

    fn fake_secret_token_long() -> String {
        ["Kx9mP2nQ8rT4", "vW7yZ3cF6hJ1", "lN5sA0bD8eF2gH5jK"].concat()
    }

    fn fake_password_secret() -> String {
        ["super", "secret", "password", "123456"].concat()
    }

    #[test]
    fn test_redaction_key_generation() {
        let key1 = generate_redaction_key("test");
        let key2 = generate_redaction_key("my-rule");

        // Keys should be different
        assert_ne!(key1, key2);

        // Keys should follow the expected format
        assert!(key1.starts_with("[REDACTED_SECRET:test:"));
        assert!(key1.ends_with("]"));
        assert!(key2.starts_with("[REDACTED_SECRET:my-rule:"));
        assert!(key2.ends_with("]"));
    }

    #[test]
    fn test_empty_input() {
        let result = redact_secrets("", None, &HashMap::new(), false);
        assert_eq!(result.redacted_string, "");
        assert!(result.redaction_map.is_empty());
    }

    #[test]
    fn test_restore_secrets() {
        let mut redaction_map = HashMap::new();
        redaction_map.insert("[REDACTED_abc123]".to_string(), "secret123".to_string());
        redaction_map.insert("[REDACTED_def456]".to_string(), "api_key_xyz".to_string());

        let redacted = "Password is [REDACTED_abc123] and key is [REDACTED_def456]";
        let restored = restore_secrets(redacted, &redaction_map);

        assert_eq!(restored, "Password is secret123 and key is api_key_xyz");
    }

    #[test]
    fn test_redaction_result_display() {
        let mut redaction_map = HashMap::new();
        redaction_map.insert("[REDACTED_test]".to_string(), "secret".to_string());

        let result = RedactionResult::new("Hello [REDACTED_test]".to_string(), redaction_map);
        assert_eq!(format!("{}", result), "Hello [REDACTED_test]");
    }

    #[test]
    fn test_redact_secrets_with_api_key() {
        // Use a pattern that matches the generic-api-key rule
        let input = format!("export API_KEY={}", fake_api_key_long());
        let result = redact_secrets(&input, None, &HashMap::new(), false);

        // Should detect the API key and redact it
        assert!(!result.redaction_map.is_empty());
        assert!(result.redacted_string.contains("[REDACTED_"));
        println!("Input: {}", input);
        println!("Redacted: {}", result.redacted_string);
        println!("Mapping: {:?}", result.redaction_map);
    }

    #[test]
    fn test_redact_secrets_with_aws_key() {
        let input = format!("AWS_ACCESS_KEY_ID={}", fake_aws_access_key());
        let result = redact_secrets(&input, None, &HashMap::new(), false);

        // Should detect the AWS access key
        assert!(!result.redaction_map.is_empty());
        println!("Input: {}", input);
        println!("Redacted: {}", result.redacted_string);
        println!("Mapping: {:?}", result.redaction_map);
    }

    #[test]
    fn test_redaction_identical_secrets() {
        let aws_key = fake_aws_access_key();
        let input = format!(
            "\n        export AWS_ACCESS_KEY_ID={aws_key}\n        export AWS_ACCESS_KEY_ID_2={aws_key}\n        "
        );
        let result = redact_secrets(&input, None, &HashMap::new(), false);

        assert_eq!(result.redaction_map.len(), 1);
    }

    #[test]
    fn test_redaction_identical_secrets_different_contexts() {
        let aws_key = fake_aws_access_key();
        let input_1 = format!("\n        export AWS_ACCESS_KEY_ID={aws_key}\n        ");
        let input_2 = format!("\n        export SOME_OTHER_SECRET={aws_key}\n        ");
        let result_1 = redact_secrets(&input_1, None, &HashMap::new(), false);
        let result_2 = redact_secrets(&input_2, None, &result_1.redaction_map, false);

        assert_eq!(result_1.redaction_map, result_2.redaction_map);
    }

    #[test]
    fn test_redact_secrets_with_github_token() {
        let input = format!("GITHUB_TOKEN={}", fake_github_token());
        let result = redact_secrets(&input, None, &HashMap::new(), false);

        // Should detect the GitHub PAT
        assert!(!result.redaction_map.is_empty());
        println!("Input: {}", input);
        println!("Redacted: {}", result.redacted_string);
        println!("Mapping: {:?}", result.redaction_map);
    }

    #[test]
    fn test_no_secrets() {
        let input = "This is just a normal string with no secrets";
        let result = redact_secrets(input, None, &HashMap::new(), false);

        // Should not detect any secrets
        assert_eq!(result.redaction_map.len(), 0);
        assert_eq!(result.redacted_string, input);
    }

    #[test]
    fn test_debug_generic_api_key() {
        let config = &*GITLEAKS_CONFIG;

        // Find the generic-api-key rule
        let generic_rule = config.rules.iter().find(|r| r.id == "generic-api-key");
        if let Some(rule) = generic_rule {
            println!("Generic API Key Rule:");
            println!("  Regex: {:?}", rule.regex);
            println!("  Entropy: {:?}", rule.entropy);
            println!("  Keywords: {:?}", rule.keywords);

            // Test the regex directly first
            if let Some(regex_pattern) = &rule.regex {
                if let Ok(regex) = Regex::new(regex_pattern) {
                    let test_input = format!("API_KEY={}", fake_api_key_long());
                    println!("\nTesting regex directly:");
                    println!("  Input: {}", test_input);

                    for mat in regex.find_iter(&test_input) {
                        println!("  Raw match: '{}'", mat.as_str());
                        println!("  Match position: {}-{}", mat.start(), mat.end());

                        // Check captures
                        if let Some(captures) = regex.captures(mat.as_str()) {
                            for (i, cap) in captures.iter().enumerate() {
                                if let Some(cap) = cap {
                                    println!("  Capture {}: '{}'", i, cap.as_str());
                                    if i == 1 {
                                        let entropy = calculate_entropy(cap.as_str());
                                        println!("  Entropy of capture 1: {:.2}", entropy);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                println!("  No regex pattern (path-based rule)");
            }

            // Test various input patterns
            let test_inputs = vec![
                format!("API_KEY={}", fake_api_key_long()),
                "api_key=RaNd0mH1ghEnTr0pyV4luE567890abcdef".to_string(),
                format!("access_key={}", fake_secret_token_long()),
                "secret_token=1234567890abcdef1234567890abcdef".to_string(),
                "password=9k2L8pMvB3nQ7rX1ZdF5GhJwY4AsPo6C".to_string(),
            ];

            for input in test_inputs {
                println!("\nTesting input: {}", input);
                let result = redact_secrets(&input, None, &HashMap::new(), false);
                println!("  Detected secrets: {}", result.redaction_map.len());
                if !result.redaction_map.is_empty() {
                    println!("  Redacted: {}", result.redacted_string);
                }
            }
        } else {
            println!("Generic API key rule not found!");
        }
    }

    #[test]
    fn test_simple_regex_match() {
        // Test a very simple case that should definitely match
        let input = "key=abcdefghijklmnop";
        println!("Testing simple input: {}", input);

        let config = &*GITLEAKS_CONFIG;
        let generic_rule = config
            .rules
            .iter()
            .find(|r| r.id == "generic-api-key")
            .unwrap();

        if let Some(regex_pattern) = &generic_rule.regex {
            if let Ok(regex) = Regex::new(regex_pattern) {
                println!("Regex pattern: {}", regex_pattern);

                if regex.is_match(input) {
                    println!("✓ Regex MATCHES the input!");

                    for mat in regex.find_iter(input) {
                        println!("Match found: '{}'", mat.as_str());

                        if let Some(captures) = regex.captures(mat.as_str()) {
                            println!("Full capture groups:");
                            for (i, cap) in captures.iter().enumerate() {
                                if let Some(cap) = cap {
                                    println!("  Group {}: '{}'", i, cap.as_str());
                                    if i == 1 {
                                        let entropy = calculate_entropy(cap.as_str());
                                        println!("  Entropy: {:.2} (threshold: 3.5)", entropy);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    println!("✗ Regex does NOT match the input");
                }
            }
        } else {
            println!("Rule has no regex pattern (path-based rule)");
        }

        // Also test the full redact_secrets function
        let result = redact_secrets(input, None, &HashMap::new(), false);
        println!(
            "Full function result: {} secrets detected",
            result.redaction_map.len()
        );
    }

    #[test]
    fn test_regex_breakdown() {
        let config = &*GITLEAKS_CONFIG;
        let generic_rule = config
            .rules
            .iter()
            .find(|r| r.id == "generic-api-key")
            .unwrap();

        if let Some(regex_pattern) = &generic_rule.regex {
            println!("Full regex: {}", regex_pattern);

            // Let's break down the regex and test each part
            let test_inputs = vec![
                "key=abcdefghijklmnop",
                "api_key=abcdefghijklmnop",
                "secret=abcdefghijklmnop",
                "token=abcdefghijklmnop",
                "password=abcdefghijklmnop",
                "access_key=abcdefghijklmnop",
            ];

            for input in test_inputs {
                println!("\nTesting: '{}'", input);

                // Test if the regex matches at all
                if let Ok(regex) = Regex::new(regex_pattern) {
                    let matches: Vec<_> = regex.find_iter(input).collect();
                    println!("  Matches found: {}", matches.len());

                    for (i, mat) in matches.iter().enumerate() {
                        println!("  Match {}: '{}'", i, mat.as_str());

                        // Test captures
                        if let Some(captures) = regex.captures(mat.as_str()) {
                            for (j, cap) in captures.iter().enumerate() {
                                if let Some(cap) = cap {
                                    println!("    Capture {}: '{}'", j, cap.as_str());
                                    if j == 1 {
                                        let entropy = calculate_entropy(cap.as_str());
                                        println!("    Entropy: {:.2} (threshold: 3.5)", entropy);
                                        if entropy >= 3.5 {
                                            println!("    ✓ Entropy check PASSED");
                                        } else {
                                            println!("    ✗ Entropy check FAILED");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else {
            println!("Rule has no regex pattern (path-based rule)");
        }

        // Also test with a known working pattern from AWS
        println!("\nTesting AWS pattern that we know works:");
        let aws_input = format!("AWS_ACCESS_KEY_ID={}", fake_aws_access_key_example());
        println!("Input: {}", aws_input);

        let aws_rule = config
            .rules
            .iter()
            .find(|r| r.id == "aws-access-token")
            .unwrap();
        if let Some(aws_regex_pattern) = &aws_rule.regex {
            if let Ok(regex) = Regex::new(aws_regex_pattern) {
                for mat in regex.find_iter(&aws_input) {
                    println!("AWS Match: '{}'", mat.as_str());
                    if let Some(captures) = regex.captures(mat.as_str()) {
                        for (i, cap) in captures.iter().enumerate() {
                            if let Some(cap) = cap {
                                println!("  AWS Capture {}: '{}'", i, cap.as_str());
                            }
                        }
                    }
                }
            }
        } else {
            println!("AWS rule has no regex pattern");
        }
    }

    #[test]
    fn test_working_api_key_patterns() {
        let config = &*GITLEAKS_CONFIG;
        let generic_rule = config
            .rules
            .iter()
            .find(|r| r.id == "generic-api-key")
            .unwrap();

        // Get the compiled regex
        let regex = generic_rule
            .compiled_regex
            .as_ref()
            .expect("Regex should be compiled");

        // Create test patterns that should match the regex structure
        let test_inputs = vec![
            // Pattern: prefix + keyword + separator + value + terminator
            format!("myapp_api_key = \"{}\"", fake_api_key()),
            format!("export SECRET_TOKEN={}", fake_secret_token()),
            "app.auth.password: 9k2L8pMvB3nQ7rX1ZdF5GhJwY4AsPo6C8mN".to_string(),
            "config.access_key=\"RaNd0mH1ghEnTr0pyV4luE567890abcdef\";".to_string(),
            "DB_CREDENTIALS=xy9mP2nQ8rT4vW7yZ3cF6hJ1lN5sAdefghij".to_string(),
        ];

        for input in test_inputs {
            println!("\nTesting: '{}'", input);

            let matches: Vec<_> = regex.find_iter(&input).collect();
            println!("  Matches found: {}", matches.len());

            for (i, mat) in matches.iter().enumerate() {
                println!("  Match {}: '{}'", i, mat.as_str());

                if let Some(captures) = regex.captures(mat.as_str()) {
                    for (j, cap) in captures.iter().enumerate() {
                        if let Some(cap) = cap {
                            println!("    Capture {}: '{}'", j, cap.as_str());
                            if j == 1 {
                                let entropy = calculate_entropy(cap.as_str());
                                println!("    Entropy: {:.2} (threshold: 3.5)", entropy);

                                // Also check if it would be allowed by allowlists
                                let allowed = should_allow_match(
                                    &input,
                                    None,
                                    mat.as_str(),
                                    mat.start(),
                                    mat.end(),
                                    generic_rule,
                                    &config.allowlist,
                                );
                                println!("    Allowed by allowlist: {}", allowed);
                            }
                        }
                    }
                }
            }

            // Test the full redact_secrets function
            let result = redact_secrets(&input, None, &HashMap::new(), false);
            println!(
                "  Full function detected: {} secrets",
                result.redaction_map.len()
            );
            if !result.redaction_map.is_empty() {
                println!("  Redacted result: {}", result.redacted_string);
            }
        }
    }

    #[test]
    fn test_regex_components() {
        // Test individual components of the generic API key regex
        let test_input = format!("export API_KEY={}", fake_secret_token());
        println!("Testing input: {}", test_input);

        // Test simpler regex patterns step by step
        let test_patterns = vec![
            (r"API_KEY", "Simple keyword match"),
            (r"(?i)api_key", "Case insensitive keyword"),
            (r"(?i).*key.*", "Any text with 'key'"),
            (r"(?i).*key\s*=", "Key with equals"),
            (r"(?i).*key\s*=\s*\w+", "Key with value"),
            (
                r"(?i)[\w.-]*(?:key).*?=.*?(\w{10,})",
                "Complex pattern with capture",
            ),
        ];

        for (pattern, description) in test_patterns {
            println!("\nTesting pattern: {} ({})", pattern, description);

            match Regex::new(pattern) {
                Ok(regex) => {
                    if regex.is_match(&test_input) {
                        println!("  ✓ MATCHES");
                        for mat in regex.find_iter(&test_input) {
                            println!("    Full match: '{}'", mat.as_str());
                        }
                        if let Some(captures) = regex.captures(&test_input) {
                            for (i, cap) in captures.iter().enumerate() {
                                if let Some(cap) = cap {
                                    println!("    Capture {}: '{}'", i, cap.as_str());
                                }
                            }
                        }
                    } else {
                        println!("  ✗ NO MATCH");
                    }
                }
                Err(e) => println!("  Error: {}", e),
            }
        }

        // Test if there's an issue with the actual gitleaks regex compilation
        let config = &*GITLEAKS_CONFIG;
        let generic_rule = config
            .rules
            .iter()
            .find(|r| r.id == "generic-api-key")
            .unwrap();

        println!("\nTesting actual gitleaks regex:");
        if let Some(regex_pattern) = &generic_rule.regex {
            match Regex::new(regex_pattern) {
                Ok(regex) => {
                    println!("  ✓ Regex compiles successfully");
                    println!("  Testing against: {}", test_input);
                    if regex.is_match(&test_input) {
                        println!("  ✓ MATCHES");
                    } else {
                        println!("  ✗ NO MATCH");
                    }
                }
                Err(e) => println!("  ✗ Regex compilation error: {}", e),
            }
        } else {
            println!("  Rule has no regex pattern (path-based rule)");
        }
    }

    #[test]
    fn test_comprehensive_secrets_redaction() {
        let aws_key = fake_aws_access_key_alt();
        let github_token = fake_github_token();
        let api_key = fake_api_key();
        let secret_token = fake_secret_token();
        let password = fake_password_secret();
        let input = format!(
            "\n# Configuration file with various secrets\nexport AWS_ACCESS_KEY_ID={aws_key}\nexport GITHUB_TOKEN={github_token}\nexport API_KEY={api_key}\nexport SECRET_TOKEN={secret_token}\nexport PASSWORD={password}\n\n# Some normal configuration\nexport DEBUG=true\nexport PORT=3000\n"
        );

        println!("Original input:\n{}", input);

        let result = redact_secrets(&input, None, &HashMap::new(), false);

        println!("Redacted output:\n{}", result.redacted_string);
        println!("\nDetected {} secrets:", result.redaction_map.len());
        for (key, value) in &result.redaction_map {
            println!("  {} -> {}", key, value);
        }

        // Should detect at least 5 secrets: AWS key, GitHub token, API key, secret token, password
        assert!(
            result.redaction_map.len() >= 5,
            "Should detect at least 5 secrets, found: {}",
            result.redaction_map.len()
        );

        // Verify specific secrets are redacted
        assert!(!result.redacted_string.contains(&aws_key));
        assert!(!result.redacted_string.contains(&github_token));
        assert!(!result.redacted_string.contains(&api_key));

        // Verify normal config is preserved
        assert!(result.redacted_string.contains("DEBUG=true"));
        assert!(result.redacted_string.contains("PORT=3000"));
    }

    // Helper function for keyword validation tests
    fn count_rules_that_would_process(input: &str) -> Vec<String> {
        let config = &*GITLEAKS_CONFIG;
        let mut rules = Vec::new();

        for rule in &config.rules {
            if rule.keywords.is_empty() || contains_any_keyword(input, &rule.keywords) {
                rules.push(rule.id.clone());
            }
        }

        rules
    }

    #[test]
    fn test_keyword_filtering() {
        println!("=== TESTING KEYWORD FILTERING ===");

        let config = &*GITLEAKS_CONFIG;

        // Find a rule that has keywords (like generic-api-key)
        let generic_rule = config
            .rules
            .iter()
            .find(|r| r.id == "generic-api-key")
            .unwrap();
        println!("Generic API Key rule keywords: {:?}", generic_rule.keywords);

        // Test 1: Input with keywords should be processed
        let input_with_keywords = format!("export API_KEY={}", fake_api_key());
        let result1 = redact_secrets(&input_with_keywords, None, &HashMap::new(), false);
        println!("\nTest 1 - Input WITH keywords:");
        println!("  Input: {}", input_with_keywords);
        println!(
            "  Keywords present: {}",
            contains_any_keyword(&input_with_keywords, &generic_rule.keywords)
        );
        println!("  Secrets detected: {}", result1.redaction_map.len());

        // Test 2: Input without any keywords should NOT be processed for that rule
        let input_without_keywords = "export DATABASE_URL=postgresql://user:pass@localhost/db";
        let result2 = redact_secrets(input_without_keywords, None, &HashMap::new(), false);
        println!("\nTest 2 - Input WITHOUT generic-api-key keywords:");
        println!("  Input: {}", input_without_keywords);
        println!(
            "  Keywords present: {}",
            contains_any_keyword(input_without_keywords, &generic_rule.keywords)
        );
        println!("  Secrets detected: {}", result2.redaction_map.len());

        // Test 3: Input with different rule's keywords (AWS)
        let aws_rule = config
            .rules
            .iter()
            .find(|r| r.id == "aws-access-token")
            .unwrap();
        let aws_input = format!("AWS_ACCESS_KEY_ID={}", fake_aws_access_key_example());
        let result3 = redact_secrets(&aws_input, None, &HashMap::new(), false);
        println!("\nTest 3 - AWS input:");
        println!("  Input: {}", aws_input);
        println!("  AWS rule keywords: {:?}", aws_rule.keywords);
        println!(
            "  Keywords present: {}",
            contains_any_keyword(&aws_input, &aws_rule.keywords)
        );
        println!("  Secrets detected: {}", result3.redaction_map.len());

        // Validate that keyword filtering is working
        assert!(
            contains_any_keyword(&input_with_keywords, &generic_rule.keywords),
            "API_KEY input should contain generic-api-key keywords"
        );
        assert!(
            !contains_any_keyword(input_without_keywords, &generic_rule.keywords),
            "DATABASE_URL input should NOT contain generic-api-key keywords"
        );
        assert!(
            contains_any_keyword(&aws_input, &aws_rule.keywords),
            "AWS input should contain AWS rule keywords"
        );
    }

    #[test]
    fn test_keyword_optimization_performance() {
        println!("=== TESTING KEYWORD OPTIMIZATION PERFORMANCE ===");

        let config = &*GITLEAKS_CONFIG;

        // Test case 1: Input with NO keywords for any rule should be very fast
        let no_keywords_input = "export DATABASE_CONNECTION=some_long_connection_string_that_has_no_common_secret_keywords";
        println!("Testing input with no secret keywords:");
        println!("  Input: {}", no_keywords_input);

        let mut keyword_matches = 0;
        for rule in &config.rules {
            if contains_any_keyword(no_keywords_input, &rule.keywords) {
                keyword_matches += 1;
                println!("  Rule '{}' keywords match: {:?}", rule.id, rule.keywords);
            }
        }
        println!(
            "  Rules with matching keywords: {} out of {}",
            keyword_matches,
            config.rules.len()
        );

        let result = redact_secrets(no_keywords_input, None, &HashMap::new(), false);
        println!("  Secrets detected: {}", result.redaction_map.len());

        // Test case 2: Input with specific keywords should only process relevant rules
        let specific_keywords_input = format!("export GITHUB_TOKEN={}", fake_github_token_short());
        println!("\nTesting input with specific keywords (github):");
        println!("  Input: {}", specific_keywords_input);

        let mut matching_rules = Vec::new();
        for rule in &config.rules {
            if contains_any_keyword(&specific_keywords_input, &rule.keywords) {
                matching_rules.push(&rule.id);
            }
        }
        println!("  Rules that would be processed: {:?}", matching_rules);

        let result = redact_secrets(&specific_keywords_input, None, &HashMap::new(), false);
        println!("  Secrets detected: {}", result.redaction_map.len());

        // Test case 3: Verify that rules without keywords are always processed
        let rules_without_keywords: Vec<_> = config
            .rules
            .iter()
            .filter(|rule| rule.keywords.is_empty())
            .collect();
        println!(
            "\nRules without keywords (always processed): {}",
            rules_without_keywords.len()
        );
        for rule in &rules_without_keywords {
            println!("  - {}", rule.id);
        }

        // Assertions
        assert!(
            keyword_matches < config.rules.len(),
            "Input with no keywords should not match all rules"
        );
        assert!(
            !matching_rules.is_empty(),
            "GitHub token input should match some rules"
        );
        assert!(
            matching_rules.contains(&&"github-pat".to_string())
                || matching_rules
                    .iter()
                    .any(|rule_id| rule_id.contains("github")),
            "GitHub token should match GitHub-related rules"
        );
    }

    #[test]
    fn test_keyword_filtering_efficiency() {
        println!("=== KEYWORD FILTERING EFFICIENCY TEST ===");

        let config = &*GITLEAKS_CONFIG;
        println!("Total rules in config: {}", config.rules.len());

        // Test with input that has NO matching keywords
        let non_secret_input = "export DATABASE_URL=localhost PORT=3000 DEBUG=true TIMEOUT=30";
        println!("\nTesting non-secret input: {}", non_secret_input);

        let mut rules_skipped = 0;
        let mut rules_processed = 0;

        for rule in &config.rules {
            if rule.keywords.is_empty() || contains_any_keyword(non_secret_input, &rule.keywords) {
                rules_processed += 1;
            } else {
                rules_skipped += 1;
            }
        }

        println!(
            "  Rules skipped due to keyword filtering: {}",
            rules_skipped
        );
        println!("  Rules that would be processed: {}", rules_processed);
        println!(
            "  Efficiency gain: {:.1}% of rules skipped",
            (rules_skipped as f64 / config.rules.len() as f64) * 100.0
        );

        // Verify no secrets are detected
        let result = redact_secrets(non_secret_input, None, &HashMap::new(), false);
        println!("  Secrets detected: {}", result.redaction_map.len());

        // Now test with input that has relevant keywords
        let secret_input = format!(
            "export API_KEY={} SECRET_TOKEN=xyz789uvw012rst345def678",
            fake_api_key()
        );
        println!("\nTesting input WITH secret keywords:");
        println!("  Input: {}", secret_input);

        let mut rules_with_keywords = 0;
        for rule in &config.rules {
            if contains_any_keyword(&secret_input, &rule.keywords) {
                rules_with_keywords += 1;
            }
        }

        println!("  Rules that match keywords: {}", rules_with_keywords);

        let result = redact_secrets(&secret_input, None, &HashMap::new(), false);
        println!("  Secrets detected: {}", result.redaction_map.len());

        // Assertions
        assert!(
            rules_skipped > 0,
            "Should skip at least some rules for non-secret input"
        );
        assert!(
            rules_with_keywords > 0,
            "Should find matching rules for secret input"
        );
        assert!(
            !result.redaction_map.is_empty(),
            "Should detect at least one secret"
        );
    }

    #[test]
    fn test_keyword_validation_summary() {
        println!("=== KEYWORD VALIDATION SUMMARY ===");

        let config = &*GITLEAKS_CONFIG;
        let total_rules = config.rules.len();
        println!("Total rules in gitleaks config: {}", total_rules);

        // Test no keywords - should skip most rules
        let no_keyword_input = "export DATABASE_URL=localhost PORT=3000";
        println!("\n--- No keywords - should skip all rules ---");
        println!("Input: {}", no_keyword_input);

        let no_keyword_rules = count_rules_that_would_process(no_keyword_input);
        println!(
            "Rules that would be processed: {} out of {}",
            no_keyword_rules.len(),
            total_rules
        );
        println!("  Rules: {:?}", no_keyword_rules);

        let no_keyword_secrets = detect_secrets(no_keyword_input, None, false);
        println!(
            "Secrets detected: {} (expected: 0)",
            no_keyword_secrets.len()
        );
        assert_eq!(no_keyword_secrets.len(), 0, "Should not detect any secrets");
        println!("✅ Test passed");

        // Test API keyword - should process generic-api-key rule
        let api_input = format!("export API_KEY={}", fake_api_key());
        println!("\n--- API keyword - should process generic-api-key rule ---");
        println!("Input: {}", api_input);

        let api_rules = count_rules_that_would_process(&api_input);
        println!(
            "Rules that would be processed: {} out of {}",
            api_rules.len(),
            total_rules
        );
        println!("  Rules: {:?}", api_rules);

        let api_secrets = detect_secrets(&api_input, None, false);
        println!("Secrets detected: {} (expected: 1)", api_secrets.len());
        assert!(!api_secrets.is_empty(), "Should detect at least 1 secrets");
        println!("✅ Test passed");

        // Test AWS keyword - should process aws-access-token rule
        // Use a realistic AWS key that matches the pattern [A-Z2-7]{16}
        let aws_input = format!("AWS_ACCESS_KEY_ID={}", fake_aws_access_key_alt());
        println!("\n--- AWS keyword - should process aws-access-token rule ---");
        println!("Input: {}", aws_input);

        let aws_rules = count_rules_that_would_process(&aws_input);
        println!(
            "Rules that would be processed: {} out of {}",
            aws_rules.len(),
            total_rules
        );
        println!("  Rules: {:?}", aws_rules);

        let aws_secrets = detect_secrets(&aws_input, None, false);
        println!("Secrets detected: {} (expected: 1)", aws_secrets.len());

        // Should detect AWS key
        assert!(!aws_secrets.is_empty(), "Should detect at least 1 secrets");
        println!("✅ Test passed");
    }

    #[test]
    fn test_debug_missing_secrets() {
        println!("=== DEBUGGING MISSING SECRETS ===");

        let test_cases = vec![
            format!("SECRET_TOKEN={}", fake_secret_token()),
            format!("PASSWORD={}", fake_password_secret()),
        ];

        for input in test_cases {
            println!("\nTesting: {}", input);

            // Check entropy first
            let parts: Vec<&str> = input.split('=').collect();
            if parts.len() == 2 {
                let secret_value = parts[1];
                let entropy = calculate_entropy(secret_value);
                println!("  Secret value: '{}'", secret_value);
                println!("  Entropy: {:.2} (threshold: 3.5)", entropy);

                if entropy >= 3.5 {
                    println!("  ✓ Entropy check PASSED");
                } else {
                    println!("  ✗ Entropy check FAILED - this is why it's not detected");
                }
            }

            // Test the fallback regex directly
            if let Ok(regex) = create_simple_api_key_regex() {
                println!("  Testing fallback regex:");
                if regex.is_match(&input) {
                    println!("    ✓ Fallback regex MATCHES");
                    for mat in regex.find_iter(&input) {
                        println!("    Match: '{}'", mat.as_str());
                        if let Some(captures) = regex.captures(mat.as_str()) {
                            for (i, cap) in captures.iter().enumerate() {
                                if let Some(cap) = cap {
                                    println!("      Capture {}: '{}'", i, cap.as_str());
                                }
                            }
                        }

                        // Test allowlist checking
                        let config = &*GITLEAKS_CONFIG;
                        let generic_rule = config
                            .rules
                            .iter()
                            .find(|r| r.id == "generic-api-key")
                            .unwrap();
                        let allowed = should_allow_match(
                            &input,
                            None,
                            mat.as_str(),
                            mat.start(),
                            mat.end(),
                            generic_rule,
                            &config.allowlist,
                        );
                        println!("      Allowed by allowlist: {}", allowed);
                        if allowed {
                            println!(
                                "      ✗ FILTERED OUT by allowlist - this is why it's not detected"
                            );
                        }
                    }
                } else {
                    println!("    ✗ Fallback regex does NOT match");
                }
            }

            // Test full detection
            let result = redact_secrets(&input, None, &HashMap::new(), false);
            println!(
                "  Full detection result: {} secrets",
                result.redaction_map.len()
            );
        }
    }

    #[test]
    fn test_debug_allowlist_filtering() {
        println!("=== DEBUGGING ALLOWLIST FILTERING ===");

        let test_cases = vec![
            format!("SECRET_TOKEN={}", fake_secret_token()),
            format!("PASSWORD={}", fake_password_secret()),
        ];

        let config = &*GITLEAKS_CONFIG;
        let generic_rule = config
            .rules
            .iter()
            .find(|r| r.id == "generic-api-key")
            .unwrap();

        for input in test_cases {
            println!("\nAnalyzing: {}", input);

            if let Ok(regex) = create_simple_api_key_regex() {
                for mat in regex.find_iter(&input) {
                    let match_text = mat.as_str();
                    println!("  Match: '{}'", match_text);

                    // Test global allowlist
                    if let Some(global_allowlist) = &config.allowlist {
                        println!("  Checking global allowlist:");

                        // Test global regex patterns
                        if let Some(regexes) = &global_allowlist.regexes {
                            for (i, pattern) in regexes.iter().enumerate() {
                                if let Ok(regex) = Regex::new(pattern)
                                    && regex.is_match(match_text)
                                {
                                    println!("    ✗ FILTERED by global regex {}: '{}'", i, pattern);
                                }
                            }
                        }

                        // Test global stopwords
                        if let Some(stopwords) = &global_allowlist.stopwords {
                            for stopword in stopwords {
                                if match_text.to_lowercase().contains(&stopword.to_lowercase()) {
                                    println!("    ✗ FILTERED by global stopword: '{}'", stopword);
                                }
                            }
                        }
                    }

                    // Test rule-specific allowlists
                    if let Some(rule_allowlists) = &generic_rule.allowlists {
                        for (rule_idx, allowlist) in rule_allowlists.iter().enumerate() {
                            println!("  Checking rule allowlist {}:", rule_idx);

                            // Test rule regex patterns
                            if let Some(regexes) = &allowlist.regexes {
                                for (i, pattern) in regexes.iter().enumerate() {
                                    if let Ok(regex) = Regex::new(pattern)
                                        && regex.is_match(match_text)
                                    {
                                        println!(
                                            "    ✗ FILTERED by rule regex {}: '{}'",
                                            i, pattern
                                        );
                                    }
                                }
                            }

                            // Test rule stopwords
                            if let Some(stopwords) = &allowlist.stopwords {
                                for stopword in stopwords {
                                    if match_text.to_lowercase().contains(&stopword.to_lowercase())
                                    {
                                        println!("    ✗ FILTERED by rule stopword: '{}'", stopword);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn test_debug_new_allowlist_logic() {
        println!("=== DEBUGGING NEW ALLOWLIST LOGIC ===");

        let test_cases = vec![
            format!("SECRET_TOKEN={}", fake_secret_token()),
            format!("PASSWORD={}", fake_password_secret()),
            "PASSWORD=password123".to_string(), // Should be filtered
            "API_KEY=example_key".to_string(),  // Should be filtered
        ];

        let config = &*GITLEAKS_CONFIG;
        let generic_rule = config
            .rules
            .iter()
            .find(|r| r.id == "generic-api-key")
            .unwrap();

        for input in test_cases {
            println!("\nTesting: {}", input);

            if let Ok(regex) = create_simple_api_key_regex() {
                for mat in regex.find_iter(&input) {
                    let match_text = mat.as_str();
                    println!("  Match: '{}'", match_text);

                    // Parse the KEY=VALUE
                    if let Some((_, value)) = match_text.split_once('=') {
                        println!("    Value: '{}'", value);

                        // Test specific stopwords
                        let test_stopwords = ["token", "password", "super", "word"];
                        for stopword in test_stopwords {
                            let value_lower = value.to_lowercase();
                            let stopword_lower = stopword.to_lowercase();

                            if value_lower == stopword_lower {
                                println!("    '{}' - Exact match: YES", stopword);
                            } else if value.len() < 15 && value_lower.contains(&stopword_lower) {
                                let without_stopword = value_lower.replace(&stopword_lower, "");
                                let is_simple = without_stopword.chars().all(|c| {
                                    c.is_ascii_digit() || "!@#$%^&*()_+-=[]{}|;:,.<>?".contains(c)
                                });
                                println!(
                                    "    '{}' - Short+contains: len={}, without='{}', simple={}",
                                    stopword,
                                    value.len(),
                                    without_stopword,
                                    is_simple
                                );
                            } else {
                                println!("    '{}' - No filter", stopword);
                            }
                        }
                    }

                    // Test the actual allowlist
                    if let Some(rule_allowlists) = &generic_rule.allowlists {
                        for (rule_idx, allowlist) in rule_allowlists.iter().enumerate() {
                            let allowed = is_allowed_by_rule_allowlist(
                                &input,
                                None,
                                match_text,
                                mat.start(),
                                mat.end(),
                                allowlist,
                            );
                            println!("  Rule allowlist {}: allowed = {}", rule_idx, allowed);
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn test_redact_password_basic() {
        let content = "User password is supersecret123 and should be hidden";
        let password = "supersecret123";
        let result = redact_password(content, password, &HashMap::new());

        // Should redact the password
        assert!(!result.redacted_string.contains(password));
        assert!(
            result
                .redacted_string
                .contains("[REDACTED_SECRET:password:")
        );
        assert_eq!(result.redaction_map.len(), 1);

        // The redaction map should contain our password
        let redacted_password = result.redaction_map.values().next().unwrap();
        assert_eq!(redacted_password, password);
    }

    #[test]
    fn test_redact_password_empty() {
        let content = "Some content without password";
        let password = "";
        let result = redact_password(content, password, &HashMap::new());

        // Should not change anything
        assert_eq!(result.redacted_string, content);
        assert!(result.redaction_map.is_empty());
    }

    #[test]
    fn test_redact_password_multiple_occurrences() {
        let content = "Password is mypass123 and again mypass123 appears here";
        let password = "mypass123";
        let result = redact_password(content, password, &HashMap::new());

        // Should redact both occurrences with the same key
        assert!(!result.redacted_string.contains(password));
        assert_eq!(result.redaction_map.len(), 1);

        // Count redaction keys in the result
        let redaction_key = result.redaction_map.keys().next().unwrap();
        let count = result.redacted_string.matches(redaction_key).count();
        assert_eq!(count, 2);
    }

    #[test]
    fn test_redact_password_reuse_existing_key() {
        // Start with an existing redaction map
        let mut existing_map = HashMap::new();
        existing_map.insert(
            "[REDACTED_SECRET:password:abc123]".to_string(),
            "mypassword".to_string(),
        );

        let content = "The password mypassword should use existing key";
        let password = "mypassword";
        let result = redact_password(content, password, &existing_map);

        // Should reuse the existing key
        assert_eq!(result.redaction_map.len(), 1);
        assert!(
            result
                .redaction_map
                .contains_key("[REDACTED_SECRET:password:abc123]")
        );
        assert!(
            result
                .redacted_string
                .contains("[REDACTED_SECRET:password:abc123]")
        );
    }

    #[test]
    fn test_redact_password_with_existing_different_secrets() {
        // Start with an existing redaction map containing different secrets
        let mut existing_map = HashMap::new();
        existing_map.insert(
            "[REDACTED_SECRET:api-key:xyz789]".to_string(),
            "some_api_key".to_string(),
        );

        let content = "API key is some_api_key and password is newpassword123";
        let password = "newpassword123";
        let result = redact_password(content, password, &existing_map);

        // Should preserve existing mapping and add new one
        assert_eq!(result.redaction_map.len(), 2);
        assert!(
            result
                .redaction_map
                .contains_key("[REDACTED_SECRET:api-key:xyz789]")
        );
        assert!(
            result
                .redaction_map
                .get("[REDACTED_SECRET:api-key:xyz789]")
                .unwrap()
                == "some_api_key"
        );

        // Should add new password mapping
        let new_keys: Vec<_> = result
            .redaction_map
            .keys()
            .filter(|k| k.contains("password"))
            .collect();
        assert_eq!(new_keys.len(), 1);
        let password_key = new_keys[0];
        assert_eq!(
            result.redaction_map.get(password_key).unwrap(),
            "newpassword123"
        );
    }

    #[test]
    fn test_redact_password_no_match() {
        let content = "This content has no matching password";
        let password = "notfound";
        let result = redact_password(content, password, &HashMap::new());

        // Should still create a redaction key but content unchanged
        assert_eq!(result.redacted_string, content);
        assert_eq!(result.redaction_map.len(), 1);
        assert_eq!(result.redaction_map.values().next().unwrap(), "notfound");
    }

    #[test]
    fn test_redact_password_integration_with_restore() {
        let content = "Login with username admin and password secret456";
        let password = "secret456";
        let result = redact_password(content, password, &HashMap::new());

        // Redact the password
        assert!(!result.redacted_string.contains(password));
        assert!(result.redacted_string.contains("username admin"));

        // Restore should bring back the original
        let restored = restore_secrets(&result.redacted_string, &result.redaction_map);
        assert_eq!(restored, content);
    }

    #[test]
    fn test_redact_secrets_with_existing_redaction_map() {
        // Test that secrets in the existing redaction map get redacted even if not detected by detect_secrets
        let content = "The secret value is mysecretvalue123 and another is anothersecret456";

        // First, test with empty map to prove the secret wouldn't normally be redacted
        let result_empty = redact_secrets(content, None, &HashMap::new(), false);

        // Verify that mysecretvalue123 is NOT redacted when using empty map
        assert!(result_empty.redacted_string.contains("mysecretvalue123"));
        // Now create an existing redaction map with one of the secrets
        let mut existing_redaction_map = HashMap::new();
        existing_redaction_map.insert(
            "[REDACTED_SECRET:manual:abc123]".to_string(),
            "mysecretvalue123".to_string(),
        );

        let result = redact_secrets(content, None, &existing_redaction_map, false);

        // The secret from the existing map should be redacted
        assert!(
            result
                .redacted_string
                .contains("[REDACTED_SECRET:manual:abc123]")
        );
        assert!(!result.redacted_string.contains("mysecretvalue123"));

        // The redaction map should contain the existing mapping
        assert!(
            result
                .redaction_map
                .contains_key("[REDACTED_SECRET:manual:abc123]")
        );
        assert_eq!(
            result
                .redaction_map
                .get("[REDACTED_SECRET:manual:abc123]")
                .unwrap(),
            "mysecretvalue123"
        );
    }

    #[test]
    fn test_redact_secrets_skip_already_redacted() {
        // Content that already contains redacted secrets should not be double-redacted
        let content = "The password is [REDACTED_SECRET:password:abc123] and API key is [REDACTED_SECRET:api-key:xyz789]";
        let result = redact_secrets(content, None, &HashMap::new(), false);

        // Should return content unchanged
        assert_eq!(result.redacted_string, content);
        // Should not add any new redactions
        assert!(result.redaction_map.is_empty());
    }

    #[test]
    fn test_redact_password_skip_already_redacted() {
        // Content that already contains redacted secrets should not be double-redacted
        let content = "[REDACTED_SECRET:password:existing123]";
        let password = "newpassword";
        let result = redact_password(content, password, &HashMap::new());

        // Should return content unchanged
        assert_eq!(result.redacted_string, content);
        // Should not add any new redactions
        assert!(result.redaction_map.is_empty());
    }

    #[test]
    fn test_redact_secrets_skip_nested_redaction() {
        // Simulate what happens when local_tools redacts and proxy tries to redact again
        let original_password = "MySecureP@ssw0rd!";

        // First redaction (simulating local_tools)
        let first_result = redact_password(original_password, original_password, &HashMap::new());
        assert!(
            first_result
                .redacted_string
                .contains("[REDACTED_SECRET:password:")
        );

        // Second redaction attempt (simulating proxy) - should be skipped
        let second_result =
            redact_secrets(&first_result.redacted_string, None, &HashMap::new(), false);

        // Should return the already-redacted content unchanged
        assert_eq!(second_result.redacted_string, first_result.redacted_string);
        assert!(second_result.redaction_map.is_empty());
    }

    #[test]
    fn test_huawei_cloud_credentials_detection() {
        // Test Huawei Cloud credentials in CSV format
        // Using obviously fake test values (TESTHUAWEI prefix) to avoid GitHub push protection
        let csv_content = r#"User Name,Access Key Id,Secret Access Key
terraform,TESTHUAWEIKEY1234567,TestHuaweiSecretKey1234567890abcdefghij"#;

        let result = redact_secrets(csv_content, None, &HashMap::new(), false);

        println!("Input: {}", csv_content);
        println!("Redacted: {}", result.redacted_string);
        println!("Mapping: {:?}", result.redaction_map);

        // Should detect both AK and SK
        assert!(
            !result.redaction_map.is_empty(),
            "Should detect Huawei credentials"
        );

        // Verify AK is redacted (20 char uppercase alphanumeric)
        assert!(
            !result.redacted_string.contains("TESTHUAWEIKEY1234567"),
            "AK should be redacted"
        );

        // Verify SK is redacted (40 char alphanumeric)
        assert!(
            !result
                .redacted_string
                .contains("TestHuaweiSecretKey1234567890abcdefghij"),
            "SK should be redacted"
        );

        // Verify redaction keys are present
        assert!(
            result.redacted_string.contains("[REDACTED_SECRET:huawei-"),
            "Should contain Huawei redaction markers"
        );
    }

    #[test]
    fn test_huawei_access_key_id_pattern() {
        // Test AK detection with "Access Key Id" keyword
        // Using obviously fake test value to avoid GitHub push protection
        // Must be exactly 20 chars to match the regex pattern
        let input = "Access Key Id: TESTHWCLOUD123456789";
        let result = redact_secrets(input, None, &HashMap::new(), false);

        println!("Input: {}", input);
        println!("Redacted: {}", result.redacted_string);

        assert!(
            !result.redaction_map.is_empty(),
            "Should detect Huawei AK with 'Access Key Id' keyword"
        );
        assert!(
            !result.redacted_string.contains("TESTHWCLOUD123456789"),
            "AK should be redacted"
        );
    }

    #[test]
    fn test_huawei_secret_access_key_pattern() {
        // Test SK detection with "Secret Access Key" keyword
        // Using obviously fake test value to avoid GitHub push protection
        let input = "Secret Access Key: TestHwCloudSecretKey12345678901234567890";
        let result = redact_secrets(input, None, &HashMap::new(), false);

        println!("Input: {}", input);
        println!("Redacted: {}", result.redacted_string);

        assert!(
            !result.redaction_map.is_empty(),
            "Should detect Huawei SK with 'Secret Access Key' keyword"
        );
        assert!(
            !result
                .redacted_string
                .contains("TestHwCloudSecretKey12345678901234567890"),
            "SK should be redacted"
        );
    }
}