token-analyzer 0.0.1

Fast, parallel token security analyzer - Detect exposed secrets, API keys, and sensitive tokens in your codebase
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
//! Token Security Analyzer - Fast, parallel token usage analysis
//!
//! This module provides a standalone security analyzer that scans codebases
//! for token usage patterns and identifies potential security risks like
//! plaintext exposure in logs, prints, or debug statements.
//!
//! # Features
//! - **Blazing fast**: Uses ripgrep's `ignore` crate for file walking
//! - **Parallel**: Leverages `rayon` for multi-threaded file scanning
//! - **Smart**: Respects `.gitignore` and common ignore patterns
//! - **Security-focused**: Detects dangerous patterns (print, log, echo)
//! - **Context-aware**: Prioritizes sensitive files (.env, configs)
//! - **Entropy detection**: Identifies high-entropy strings (real secrets)
//! - **Known prefixes**: Detects known token formats (AWS, GitHub, Slack...)
//!
//! # Example
//! ```no_run
//! use token_analyzer::{TokenSecurityAnalyzer, AnalyzerConfig};
//! use std::path::PathBuf;
//!
//! let analyzer = TokenSecurityAnalyzer::new(AnalyzerConfig::default());
//! let report = analyzer.analyze("API_KEY", &PathBuf::from(".")).unwrap();
//!
//! println!("Found {} calls in {} files", report.total_calls, report.files.len());
//! for file in &report.files {
//!     if file.has_exposure {
//!         println!("⚠️  {} - EXPOSED! (risk: {:?})", file.path.display(), file.risk_level);
//!     }
//! }
//! ```

use anyhow::Result;
use ignore::WalkBuilder;
use parking_lot::Mutex;
use rayon::prelude::*;
use regex::Regex;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

// ============================================================================
// Risk Classification
// ============================================================================

/// Risk level for a file based on its type and content
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
    /// Low risk - regular source code
    Low = 1,
    /// Medium risk - configuration files
    Medium = 2,
    /// High risk - sensitive config files
    High = 3,
    /// Critical risk - environment/secrets files
    Critical = 4,
}

impl RiskLevel {
    /// Returns the risk multiplier for scoring
    pub fn multiplier(&self) -> usize {
        match self {
            RiskLevel::Low => 1,
            RiskLevel::Medium => 2,
            RiskLevel::High => 3,
            RiskLevel::Critical => 4,
        }
    }
}

/// Known token prefixes from popular services
pub const KNOWN_TOKEN_PREFIXES: &[(&str, &str)] = &[
    // GitHub
    ("ghp_", "GitHub Personal Access Token"),
    ("gho_", "GitHub OAuth Token"),
    ("ghu_", "GitHub User-to-Server Token"),
    ("ghs_", "GitHub Server-to-Server Token"),
    ("ghr_", "GitHub Refresh Token"),
    // AWS
    ("AKIA", "AWS Access Key ID"),
    ("ABIA", "AWS STS Token"),
    ("ACCA", "AWS Context-specific Credential"),
    ("ASIA", "AWS Temporary Access Key"),
    // Slack
    ("xoxb-", "Slack Bot Token"),
    ("xoxp-", "Slack User Token"),
    ("xoxa-", "Slack App Token"),
    ("xoxr-", "Slack Refresh Token"),
    // Stripe
    ("sk_live_", "Stripe Live Secret Key"),
    ("sk_test_", "Stripe Test Secret Key"),
    ("pk_live_", "Stripe Live Publishable Key"),
    ("rk_live_", "Stripe Live Restricted Key"),
    // OpenAI
    ("sk-", "OpenAI API Key"),
    // Anthropic
    ("sk-ant-", "Anthropic API Key"),
    // Google
    ("AIza", "Google API Key"),
    // Hugging Face
    ("hf_", "Hugging Face Token"),
    // npm
    ("npm_", "npm Access Token"),
    // PyPI
    ("pypi-", "PyPI API Token"),
    // Discord
    ("NDc", "Discord Bot Token (Base64)"),
    ("MTk", "Discord Bot Token (Base64)"),
    // Telegram
    ("bot", "Telegram Bot Token"),
    // Twilio
    ("SK", "Twilio API Key"),
    // SendGrid
    ("SG.", "SendGrid API Key"),
    // Mailgun
    ("key-", "Mailgun API Key"),
    // DigitalOcean
    ("dop_v1_", "DigitalOcean Personal Access Token"),
    ("doo_v1_", "DigitalOcean OAuth Token"),
    // Vercel
    ("vercel_", "Vercel Token"),
    // Supabase
    ("sbp_", "Supabase Token"),
    // PlanetScale
    ("pscale_", "PlanetScale Token"),
    // Railway
    ("railway_", "Railway Token"),
    // Render
    ("rnd_", "Render Token"),
    // Netlify
    ("netlify_", "Netlify Token"),
];

/// Critical file patterns (highest risk)
const CRITICAL_FILE_PATTERNS: &[&str] = &[
    ".env",
    ".env.local",
    ".env.development",
    ".env.production",
    ".env.staging",
    ".envrc",
    "secrets",
    "credentials",
    ".secrets",
    ".credentials",
    "id_rsa",
    "id_ed25519",
    ".pem",
    ".key",
    ".p12",
    ".pfx",
    ".htpasswd",
    ".netrc",
    ".npmrc",
    ".pypirc",
    ".dockerconfigjson",
    "service_account",
    "serviceaccount",
];

/// High risk file patterns
const HIGH_RISK_FILE_PATTERNS: &[&str] = &[
    "docker-compose",
    "dockerfile",
    "terraform.tfvars",
    "terraform.tfstate",
    ".tfvars",
    "ansible",
    "vault",
    "consul",
    "kubernetes",
    "k8s",
    "helm",
    "kustomize",
    "application.yml",
    "application.yaml",
    "application.properties",
    "appsettings.json",
    "config.yml",
    "config.yaml",
    "config.json",
    "settings.yml",
    "settings.yaml",
    "settings.json",
    "parameters.yml",
    "parameters.yaml",
    "database.yml",
];

/// Medium risk file extensions
const MEDIUM_RISK_EXTENSIONS: &[&str] = &[
    "yml",
    "yaml",
    "toml",
    "ini",
    "cfg",
    "conf",
    "config",
    "properties",
];

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for the token analyzer
#[derive(Debug, Clone)]
pub struct AnalyzerConfig {
    /// Maximum number of files to scan (0 = unlimited)
    pub max_files: usize,
    /// Maximum file size in bytes to scan (skip larger files)
    pub max_file_size: u64,
    /// Timeout for the entire analysis in milliseconds (0 = no timeout)
    pub timeout_ms: u64,
    /// Whether to follow symbolic links
    pub follow_symlinks: bool,
    /// Whether to include hidden files
    pub include_hidden: bool,
    /// File extensions to scan (empty = use defaults)
    pub extensions: Vec<String>,
    /// Additional directories to ignore
    pub ignore_dirs: Vec<String>,
    /// Number of threads to use (0 = auto)
    pub num_threads: usize,
}

impl Default for AnalyzerConfig {
    fn default() -> Self {
        Self {
            max_files: 10_000,
            max_file_size: 10 * 1024 * 1024, // 10 MB
            timeout_ms: 30_000,              // 30 seconds
            follow_symlinks: false,
            include_hidden: false,
            extensions: vec![],
            ignore_dirs: vec![
                "node_modules".into(),
                "target".into(),
                ".git".into(),
                "__pycache__".into(),
                "venv".into(),
                ".venv".into(),
                "dist".into(),
                "build".into(),
                ".cache".into(),
            ],
            num_threads: 0, // Auto-detect
        }
    }
}

impl AnalyzerConfig {
    /// Creates a fast config for quick scans
    pub fn fast() -> Self {
        Self {
            max_files: 1_000,
            max_file_size: 1024 * 1024, // 1 MB
            timeout_ms: 5_000,          // 5 seconds
            ..Default::default()
        }
    }

    /// Creates a thorough config for complete scans
    pub fn thorough() -> Self {
        Self {
            max_files: 0,                    // Unlimited
            max_file_size: 50 * 1024 * 1024, // 50 MB
            timeout_ms: 120_000,             // 2 minutes
            include_hidden: true,
            ..Default::default()
        }
    }

    /// Get default extensions for code files
    fn default_extensions() -> Vec<&'static str> {
        vec![
            "py", "js", "ts", "jsx", "tsx", "rs", "go", "rb", "java", "kt", "swift", "c", "cpp",
            "h", "hpp", "cs", "php", "sh", "bash", "zsh", "fish", "yaml", "yml", "json", "toml",
            "env", "conf", "cfg", "ini", "md", "txt", "sql", "graphql", "prisma",
        ]
    }
}

// ============================================================================
// Results
// ============================================================================

/// Exposure type detected
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExposureType {
    /// Hardcoded value in source code
    HardcodedValue,
    /// Logged or printed to output
    LoggedOutput,
    /// Found in environment file (.env)
    EnvironmentFile,
    /// Found in configuration file
    ConfigFile,
    /// High entropy string (likely real secret)
    HighEntropy,
    /// Known token prefix detected
    KnownTokenPrefix(String),
}

impl std::fmt::Display for ExposureType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExposureType::HardcodedValue => write!(f, "Hardcoded value"),
            ExposureType::LoggedOutput => write!(f, "Logged/printed"),
            ExposureType::EnvironmentFile => write!(f, "In .env file"),
            ExposureType::ConfigFile => write!(f, "In config file"),
            ExposureType::HighEntropy => write!(f, "High entropy (real secret)"),
            ExposureType::KnownTokenPrefix(prefix) => write!(f, "Known prefix: {}", prefix),
        }
    }
}

/// Detailed exposure information
#[derive(Debug, Clone)]
pub struct ExposureDetail {
    /// Line number where exposure was detected
    pub line: usize,
    /// Type of exposure
    pub exposure_type: ExposureType,
    /// The actual content that was matched (redacted if sensitive)
    pub context: String,
}

/// Analysis report for a single file
#[derive(Debug, Clone)]
pub struct FileAnalysis {
    /// Path to the file
    pub path: PathBuf,
    /// Number of token occurrences in this file
    pub call_count: usize,
    /// Whether the token appears to be exposed (print, log, etc.)
    pub has_exposure: bool,
    /// Risk level based on file type
    pub risk_level: RiskLevel,
    /// Computed risk score (call_count * risk_multiplier)
    pub risk_score: usize,
    /// Detailed exposure information
    pub exposures: Vec<ExposureDetail>,
    /// Line numbers where exposure was detected (legacy compatibility)
    pub exposure_lines: Vec<usize>,
    /// Line numbers of all occurrences
    pub occurrence_lines: Vec<usize>,
}

/// Complete analysis report
#[derive(Debug, Clone)]
pub struct AnalysisReport {
    /// Token that was analyzed
    pub token_name: String,
    /// Directory that was scanned
    pub search_dir: PathBuf,
    /// Total number of calls found
    pub total_calls: usize,
    /// Number of files with exposure warnings
    pub exposure_count: usize,
    /// Total risk score across all files
    pub total_risk_score: usize,
    /// Number of critical-risk files found
    pub critical_files: usize,
    /// Per-file analysis results
    pub files: Vec<FileAnalysis>,
    /// Time taken for the analysis
    pub duration: Duration,
    /// Number of files scanned
    pub files_scanned: usize,
    /// Whether the analysis was truncated due to limits
    pub truncated: bool,
    /// Error messages encountered during scan
    pub errors: Vec<String>,
}

impl AnalysisReport {
    /// Returns files sorted by risk score (highest first), then exposure, then call count
    pub fn files_sorted(&self) -> Vec<&FileAnalysis> {
        let mut sorted: Vec<_> = self.files.iter().collect();
        sorted.sort_by(|a, b| {
            // Risk score first, then exposure, then call count
            b.risk_score
                .cmp(&a.risk_score)
                .then_with(|| b.has_exposure.cmp(&a.has_exposure))
                .then_with(|| b.call_count.cmp(&a.call_count))
        });
        sorted
    }

    /// Returns only files with exposure warnings
    pub fn exposed_files(&self) -> Vec<&FileAnalysis> {
        self.files.iter().filter(|f| f.has_exposure).collect()
    }

    /// Returns files at critical or high risk level
    pub fn high_risk_files(&self) -> Vec<&FileAnalysis> {
        self.files
            .iter()
            .filter(|f| f.risk_level >= RiskLevel::High)
            .collect()
    }

    /// Check if any exposure was found
    pub fn has_security_issues(&self) -> bool {
        self.exposure_count > 0
    }

    /// Check if critical issues were found
    pub fn has_critical_issues(&self) -> bool {
        self.files
            .iter()
            .any(|f| f.has_exposure && f.risk_level == RiskLevel::Critical)
    }
}

// ============================================================================
// Analyzer
// ============================================================================

/// Token Security Analyzer
///
/// Scans directories for token usage and identifies security risks.
pub struct TokenSecurityAnalyzer {
    config: AnalyzerConfig,
}

impl TokenSecurityAnalyzer {
    /// Creates a new analyzer with the given configuration
    pub fn new(config: AnalyzerConfig) -> Self {
        Self { config }
    }

    /// Creates an analyzer with default configuration
    pub fn default_analyzer() -> Self {
        Self::new(AnalyzerConfig::default())
    }

    /// Analyzes token usage in the specified directory
    pub fn analyze(&self, token_name: &str, search_dir: &Path) -> Result<AnalysisReport> {
        let start = Instant::now();
        let timeout = if self.config.timeout_ms > 0 {
            Some(Duration::from_millis(self.config.timeout_ms))
        } else {
            None
        };

        // Validate inputs
        if token_name.is_empty() {
            anyhow::bail!("Token name cannot be empty");
        }
        if !search_dir.exists() {
            anyhow::bail!("Search directory does not exist: {}", search_dir.display());
        }

        // Build the file walker
        let files = self.collect_files(search_dir, &start, timeout)?;
        let files_scanned = files.len();
        let truncated = self.config.max_files > 0 && files_scanned >= self.config.max_files;

        // Check timeout before processing
        if let Some(t) = timeout {
            if start.elapsed() >= t {
                return Ok(self.timeout_report(token_name, search_dir, start));
            }
        }

        // Build regex patterns
        let patterns = self.build_patterns(token_name)?;

        // Parallel analysis
        let results = self.analyze_files_parallel(&files, &patterns, &start, timeout)?;

        // Build report
        let total_calls: usize = results.iter().map(|f| f.call_count).sum();
        let exposure_count = results.iter().filter(|f| f.has_exposure).count();
        let total_risk_score: usize = results.iter().map(|f| f.risk_score).sum();
        let critical_files = results
            .iter()
            .filter(|f| f.risk_level == RiskLevel::Critical)
            .count();

        Ok(AnalysisReport {
            token_name: token_name.to_string(),
            search_dir: search_dir.to_path_buf(),
            total_calls,
            exposure_count,
            total_risk_score,
            critical_files,
            files: results,
            duration: start.elapsed(),
            files_scanned,
            truncated,
            errors: vec![],
        })
    }

    /// Determines the risk level for a file based on its path and name
    fn get_file_risk_level(path: &Path) -> RiskLevel {
        let filename = path
            .file_name()
            .map(|n| n.to_string_lossy().to_lowercase())
            .unwrap_or_default();
        let path_str = path.to_string_lossy().to_lowercase();

        // Check for critical patterns
        for pattern in CRITICAL_FILE_PATTERNS {
            if filename.contains(pattern) || filename.starts_with(pattern) {
                return RiskLevel::Critical;
            }
        }

        // Check for high-risk patterns
        for pattern in HIGH_RISK_FILE_PATTERNS {
            if filename.contains(pattern) || path_str.contains(pattern) {
                return RiskLevel::High;
            }
        }

        // Check for medium-risk extensions
        if let Some(ext) = path.extension() {
            let ext_str = ext.to_string_lossy().to_lowercase();
            if MEDIUM_RISK_EXTENSIONS.contains(&ext_str.as_str()) {
                return RiskLevel::Medium;
            }
        }

        RiskLevel::Low
    }

    /// Calculates Shannon entropy of a string (higher = more random = more likely real secret)
    fn calculate_entropy(s: &str) -> f64 {
        if s.is_empty() {
            return 0.0;
        }

        let mut char_counts = std::collections::HashMap::new();
        for c in s.chars() {
            *char_counts.entry(c).or_insert(0) += 1;
        }

        let len = s.len() as f64;
        let mut entropy = 0.0;

        for count in char_counts.values() {
            let p = *count as f64 / len;
            entropy -= p * p.log2();
        }

        entropy
    }

    /// Checks if a string appears to be a high-entropy secret
    fn is_high_entropy_secret(value: &str) -> bool {
        // Minimum length for a real secret
        if value.len() < 8 {
            return false;
        }

        // Skip obvious placeholders
        let lower = value.to_lowercase();
        if lower.contains("example")
            || lower.contains("placeholder")
            || lower.contains("your_")
            || lower.contains("xxx")
            || lower.contains("todo")
            || lower.contains("replace")
            || lower == "test"
            || lower == "secret"
            || lower == "password"
        {
            return false;
        }

        // Calculate entropy - real secrets typically have entropy > 3.5
        let entropy = Self::calculate_entropy(value);
        entropy > 3.5
    }

    /// Checks if a value matches a known token prefix
    fn detect_known_prefix(value: &str) -> Option<&'static str> {
        for (prefix, description) in KNOWN_TOKEN_PREFIXES {
            if value.starts_with(prefix) {
                return Some(*description);
            }
        }
        None
    }

    /// Collects files to analyze
    fn collect_files(
        &self,
        search_dir: &Path,
        start: &Instant,
        timeout: Option<Duration>,
    ) -> Result<Vec<PathBuf>> {
        let mut files = Vec::new();
        let extensions: Vec<&str> = if self.config.extensions.is_empty() {
            AnalyzerConfig::default_extensions()
        } else {
            self.config.extensions.iter().map(|s| s.as_str()).collect()
        };

        let mut builder = WalkBuilder::new(search_dir);
        builder
            .hidden(!self.config.include_hidden)
            .follow_links(self.config.follow_symlinks)
            .git_ignore(true)
            .git_global(true)
            .git_exclude(true);

        // Set thread count for parallel walking
        if self.config.num_threads > 0 {
            builder.threads(self.config.num_threads);
        }

        for result in builder.build() {
            // Check timeout
            if let Some(t) = timeout {
                if start.elapsed() >= t {
                    break;
                }
            }

            // Check file limit
            if self.config.max_files > 0 && files.len() >= self.config.max_files {
                break;
            }

            let entry = match result {
                Ok(e) => e,
                Err(_) => continue,
            };

            let path = entry.path();

            // Skip directories
            if path.is_dir() {
                continue;
            }

            // Check ignored directories
            if self.is_ignored_dir(path) {
                continue;
            }

            // Check if file should be included based on extension or critical pattern
            let filename = path
                .file_name()
                .map(|n| n.to_string_lossy().to_lowercase())
                .unwrap_or_default();

            // Always include critical files (like .env) regardless of extension
            let is_critical = CRITICAL_FILE_PATTERNS
                .iter()
                .any(|p| filename.contains(p) || filename.starts_with(p));

            if !is_critical {
                // Check extension for non-critical files
                if let Some(ext) = path.extension() {
                    let ext_str = ext.to_string_lossy().to_lowercase();
                    if !extensions.contains(&ext_str.as_str()) {
                        continue;
                    }
                } else {
                    // No extension and not critical - skip
                    continue;
                }
            }

            // Check file size
            if let Ok(metadata) = path.metadata() {
                if metadata.len() > self.config.max_file_size {
                    continue;
                }
            }

            files.push(path.to_path_buf());
        }

        Ok(files)
    }

    /// Checks if a path is in an ignored directory
    fn is_ignored_dir(&self, path: &Path) -> bool {
        for component in path.components() {
            if let std::path::Component::Normal(name) = component {
                let name_str = name.to_string_lossy();
                if self
                    .config
                    .ignore_dirs
                    .iter()
                    .any(|d| d == name_str.as_ref())
                {
                    return true;
                }
            }
        }
        false
    }

    /// Builds regex patterns for token detection
    fn build_patterns(&self, token_name: &str) -> Result<AnalysisPatterns> {
        // Escape special regex characters in token name
        let escaped = regex::escape(token_name);

        // Main pattern: exact token match (word boundary)
        let token_pattern = format!(r"\b{}\b", escaped);
        let token_regex = Regex::new(&token_pattern)
            .map_err(|e| anyhow::anyhow!("Failed to build token regex: {}", e))?;

        // Exposure patterns: detect dangerous usage
        // These patterns match lines that could expose the token value
        // Note: We explicitly match string literals with quotes to avoid false positives
        // from safe patterns like os.environ.get("TOKEN") or process.env.TOKEN
        let exposure_patterns = [
            // === HARDCODED VALUES (most critical) ===
            // Direct assignment with string value: TOKEN="value", TOKEN='value', TOKEN = "value"
            // This catches hardcoded secrets but NOT environment variable reads
            format!(r#"\b{}\b\s*=\s*["'][^"']+["']"#, escaped),
            // Dict/object literal with hardcoded value: "TOKEN": "value", 'TOKEN': 'value'
            format!(r#"["']{}\s*["']\s*:\s*["'][^"']+["']"#, escaped),
            // === LOGGING/PRINT STATEMENTS ===
            // Print statements
            format!(
                r"(?i)(print|println!?|printf|echo|puts)\s*[\(\[].*\b{}\b",
                escaped
            ),
            // Console logging (JS/TS)
            format!(
                r"(?i)console\.(log|info|warn|error|debug)\s*\(.*\b{}\b",
                escaped
            ),
            // Python logging
            format!(
                r"(?i)(logging\.|logger\.)(info|debug|warning|error|critical)\s*\(.*\b{}\b",
                escaped
            ),
            // Rust logging
            format!(
                r"(?i)(log::)?(info!|debug!|warn!|error!|trace!)\s*\(.*\b{}\b",
                escaped
            ),
            // Generic log calls
            format!(r"(?i)\blog\s*[\(\[].*\b{}\b", escaped),
            // Write to stdout/stderr
            format!(
                r"(?i)(stdout|stderr|write|writeln!?)\s*[\(\[].*\b{}\b",
                escaped
            ),
            // Format strings with the token (f-strings, format!)
            format!(r#"(?i)f["'].*\b{}\b"#, escaped),
            format!(r"(?i)format!\s*\(.*\b{}\b", escaped),
        ];

        let exposure_regex = Regex::new(&exposure_patterns.join("|"))
            .map_err(|e| anyhow::anyhow!("Failed to build exposure regex: {}", e))?;

        Ok(AnalysisPatterns {
            token_regex,
            exposure_regex,
        })
    }

    /// Analyzes files in parallel
    fn analyze_files_parallel(
        &self,
        files: &[PathBuf],
        patterns: &AnalysisPatterns,
        start: &Instant,
        timeout: Option<Duration>,
    ) -> Result<Vec<FileAnalysis>> {
        let results: Arc<Mutex<Vec<FileAnalysis>>> = Arc::new(Mutex::new(Vec::new()));
        let timed_out = Arc::new(Mutex::new(false));

        files.par_iter().for_each(|file| {
            // Check timeout
            if let Some(t) = timeout {
                if start.elapsed() >= t {
                    *timed_out.lock() = true;
                    return;
                }
            }

            if *timed_out.lock() {
                return;
            }

            if let Ok(analysis) = self.analyze_file(file, patterns) {
                if analysis.call_count > 0 {
                    results.lock().push(analysis);
                }
            }
        });

        let inner = Arc::try_unwrap(results)
            .map(|m| m.into_inner())
            .unwrap_or_else(|arc| arc.lock().clone());

        Ok(inner)
    }

    /// Analyzes a single file with advanced detection
    fn analyze_file(&self, path: &Path, patterns: &AnalysisPatterns) -> Result<FileAnalysis> {
        let content = fs::read_to_string(path)?;
        let risk_level = Self::get_file_risk_level(path);
        let is_env_file = path
            .file_name()
            .map(|n| n.to_string_lossy().to_lowercase().contains(".env"))
            .unwrap_or(false);
        let is_config_file = risk_level >= RiskLevel::Medium;

        let mut call_count = 0;
        let mut occurrence_lines = Vec::new();
        let mut exposures: Vec<ExposureDetail> = Vec::new();

        // Regex to extract values from assignments
        let value_pattern =
            Regex::new(r#"[=:]\s*["']([^"']+)["']|[=:]\s*([a-zA-Z0-9_\-./+]{8,})"#).ok();

        for (line_num, line) in content.lines().enumerate() {
            let line_number = line_num + 1; // 1-indexed

            // Skip comments
            let trimmed = line.trim();
            if trimmed.starts_with('#')
                || trimmed.starts_with("//")
                || trimmed.starts_with("/*")
                || trimmed.starts_with('*')
            {
                continue;
            }

            // Count occurrences of the token in this line
            let matches: Vec<_> = patterns.token_regex.find_iter(line).collect();
            if matches.is_empty() {
                continue;
            }

            call_count += matches.len();
            occurrence_lines.push(line_number);

            // === Advanced exposure detection ===

            // 1. Check for .env file exposure (any assignment is dangerous)
            if is_env_file {
                if let Some(ref vp) = value_pattern {
                    if let Some(caps) = vp.captures(line) {
                        let value = caps.get(1).or(caps.get(2)).map(|m| m.as_str());
                        if let Some(v) = value {
                            // Check for known token prefix
                            if let Some(prefix_desc) = Self::detect_known_prefix(v) {
                                exposures.push(ExposureDetail {
                                    line: line_number,
                                    exposure_type: ExposureType::KnownTokenPrefix(
                                        prefix_desc.to_string(),
                                    ),
                                    context: Self::redact_value(v),
                                });
                            } else if Self::is_high_entropy_secret(v) {
                                exposures.push(ExposureDetail {
                                    line: line_number,
                                    exposure_type: ExposureType::HighEntropy,
                                    context: Self::redact_value(v),
                                });
                            } else {
                                exposures.push(ExposureDetail {
                                    line: line_number,
                                    exposure_type: ExposureType::EnvironmentFile,
                                    context: format!("{}=***", patterns.token_regex.as_str()),
                                });
                            }
                        }
                    }
                }
                continue;
            }

            // 2. Check for hardcoded values in config files
            if is_config_file {
                if let Some(ref vp) = value_pattern {
                    if let Some(caps) = vp.captures(line) {
                        let value = caps.get(1).or(caps.get(2)).map(|m| m.as_str());
                        if let Some(v) = value {
                            // Skip environment variable references
                            if v.starts_with('$')
                                || v.contains("env.")
                                || v.contains("ENV[")
                                || v.contains("getenv")
                            {
                                continue;
                            }

                            if let Some(prefix_desc) = Self::detect_known_prefix(v) {
                                exposures.push(ExposureDetail {
                                    line: line_number,
                                    exposure_type: ExposureType::KnownTokenPrefix(
                                        prefix_desc.to_string(),
                                    ),
                                    context: Self::redact_value(v),
                                });
                            } else if Self::is_high_entropy_secret(v) {
                                exposures.push(ExposureDetail {
                                    line: line_number,
                                    exposure_type: ExposureType::HighEntropy,
                                    context: Self::redact_value(v),
                                });
                            } else {
                                exposures.push(ExposureDetail {
                                    line: line_number,
                                    exposure_type: ExposureType::ConfigFile,
                                    context: format!(
                                        "Hardcoded in {}",
                                        risk_level_name(risk_level)
                                    ),
                                });
                            }
                        }
                    }
                }
            }

            // 3. Standard exposure pattern check (logging, hardcoded values)
            if patterns.exposure_regex.is_match(line) {
                // Determine exposure type
                let exposure_type = if line.to_lowercase().contains("log")
                    || line.to_lowercase().contains("print")
                    || line.to_lowercase().contains("console")
                    || line.to_lowercase().contains("echo")
                {
                    ExposureType::LoggedOutput
                } else {
                    ExposureType::HardcodedValue
                };

                // Avoid duplicates
                if !exposures.iter().any(|e| e.line == line_number) {
                    exposures.push(ExposureDetail {
                        line: line_number,
                        exposure_type,
                        context: Self::truncate_line(line),
                    });
                }
            }
        }

        let exposure_lines: Vec<usize> = exposures.iter().map(|e| e.line).collect();
        let risk_score = call_count * risk_level.multiplier();

        Ok(FileAnalysis {
            path: path.to_path_buf(),
            call_count,
            has_exposure: !exposures.is_empty(),
            risk_level,
            risk_score,
            exposures,
            exposure_lines,
            occurrence_lines,
        })
    }

    /// Redacts a secret value for safe display
    fn redact_value(value: &str) -> String {
        if value.len() <= 8 {
            return "***".to_string();
        }
        let prefix = &value[..4];
        let suffix = &value[value.len() - 4..];
        format!("{}...{}", prefix, suffix)
    }

    /// Truncates a line for display
    fn truncate_line(line: &str) -> String {
        let trimmed = line.trim();
        if trimmed.len() <= 50 {
            trimmed.to_string()
        } else {
            format!("{}...", &trimmed[..47])
        }
    }

    /// Creates a timeout report
    fn timeout_report(
        &self,
        token_name: &str,
        search_dir: &Path,
        start: Instant,
    ) -> AnalysisReport {
        AnalysisReport {
            token_name: token_name.to_string(),
            search_dir: search_dir.to_path_buf(),
            total_calls: 0,
            exposure_count: 0,
            total_risk_score: 0,
            critical_files: 0,
            files: vec![],
            duration: start.elapsed(),
            files_scanned: 0,
            truncated: true,
            errors: vec!["Analysis timed out".to_string()],
        }
    }
}

/// Helper to get a readable name for risk level
fn risk_level_name(level: RiskLevel) -> &'static str {
    match level {
        RiskLevel::Low => "source file",
        RiskLevel::Medium => "config file",
        RiskLevel::High => "sensitive config",
        RiskLevel::Critical => "secrets file",
    }
}

/// Internal struct for regex patterns
struct AnalysisPatterns {
    token_regex: Regex,
    exposure_regex: Regex,
}

// ============================================================================
// Tests
// ============================================================================

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

    fn setup_test_dir() -> TempDir {
        let dir = TempDir::new().unwrap();

        // Create test files
        fs::write(
            dir.path().join("config.py"),
            r#"
import os
API_KEY = os.getenv("API_KEY")
db_url = f"postgres://{API_KEY}@localhost/db"
"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("main.js"),
            r#"
const API_KEY = process.env.API_KEY;
console.log("API Key:", API_KEY);
fetch(url, { headers: { "Authorization": API_KEY } });
"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("safe.rs"),
            r#"
let api_key = std::env::var("API_KEY")?;
client.set_header("Authorization", &api_key);
"#,
        )
        .unwrap();

        fs::write(
            dir.path().join("debug.py"),
            r#"
import logging
logger = logging.getLogger(__name__)
logger.debug(f"Using API_KEY: {API_KEY}")
print(f"Debug: API_KEY = {API_KEY}")
"#,
        )
        .unwrap();

        // Create a subdirectory with more files
        let subdir = dir.path().join("src");
        fs::create_dir(&subdir).unwrap();
        fs::write(
            subdir.join("api.ts"),
            r#"
export const API_KEY = process.env.API_KEY;
export function getHeaders() {
    return { "X-API-Key": API_KEY };
}
"#,
        )
        .unwrap();

        dir
    }

    #[test]
    fn test_analyzer_finds_token_occurrences() {
        let dir = setup_test_dir();
        let analyzer = TokenSecurityAnalyzer::default_analyzer();

        let report = analyzer.analyze("API_KEY", dir.path()).unwrap();

        assert!(report.total_calls > 0, "Should find token occurrences");
        assert!(!report.files.is_empty(), "Should have files with matches");
    }

    #[test]
    fn test_analyzer_detects_exposure() {
        let dir = setup_test_dir();
        let analyzer = TokenSecurityAnalyzer::default_analyzer();

        let report = analyzer.analyze("API_KEY", dir.path()).unwrap();

        assert!(report.exposure_count > 0, "Should detect exposure");
        assert!(report.has_security_issues(), "Should have security issues");

        // Check specific exposure files
        let exposed = report.exposed_files();
        let exposed_paths: Vec<_> = exposed
            .iter()
            .map(|f| f.path.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        assert!(
            exposed_paths.iter().any(|p| p == "main.js"),
            "main.js should be exposed (console.log)"
        );
        assert!(
            exposed_paths.iter().any(|p| p == "debug.py"),
            "debug.py should be exposed (logger.debug, print)"
        );
    }

    #[test]
    fn test_analyzer_respects_word_boundaries() {
        let dir = TempDir::new().unwrap();

        fs::write(
            dir.path().join("test.py"),
            r#"
API_KEY_NAME = "test"
MY_API_KEY = "value"
API_KEY = "secret"
"#,
        )
        .unwrap();

        let analyzer = TokenSecurityAnalyzer::default_analyzer();
        let report = analyzer.analyze("API_KEY", dir.path()).unwrap();

        // Should only find exact "API_KEY", not "API_KEY_NAME" or "MY_API_KEY"
        assert_eq!(report.total_calls, 1, "Should match exact token only");
    }

    #[test]
    fn test_analyzer_config_fast() {
        let config = AnalyzerConfig::fast();
        assert_eq!(config.max_files, 1_000);
        assert_eq!(config.timeout_ms, 5_000);
    }

    #[test]
    fn test_analyzer_config_thorough() {
        let config = AnalyzerConfig::thorough();
        assert_eq!(config.max_files, 0);
        assert!(config.include_hidden);
    }

    #[test]
    fn test_analyzer_empty_token() {
        let dir = TempDir::new().unwrap();
        let analyzer = TokenSecurityAnalyzer::default_analyzer();

        let result = analyzer.analyze("", dir.path());
        assert!(result.is_err(), "Should reject empty token");
    }

    #[test]
    fn test_analyzer_nonexistent_dir() {
        let analyzer = TokenSecurityAnalyzer::default_analyzer();

        let result = analyzer.analyze("TOKEN", Path::new("/nonexistent/path"));
        assert!(result.is_err(), "Should reject nonexistent directory");
    }

    #[test]
    fn test_analyzer_report_sorting() {
        let dir = setup_test_dir();
        let analyzer = TokenSecurityAnalyzer::default_analyzer();
        let report = analyzer.analyze("API_KEY", dir.path()).unwrap();

        let sorted = report.files_sorted();

        // First files should have exposure
        if !sorted.is_empty() && sorted[0].has_exposure {
            assert!(
                sorted.iter().take_while(|f| f.has_exposure).count() > 0,
                "Exposed files should come first"
            );
        }
    }

    #[test]
    fn test_analyzer_ignores_node_modules() {
        let dir = TempDir::new().unwrap();

        // Create node_modules directory with matching file
        let nm = dir.path().join("node_modules");
        fs::create_dir(&nm).unwrap();
        fs::write(nm.join("test.js"), "const API_KEY = 'test';").unwrap();

        // Create regular file
        fs::write(dir.path().join("main.js"), "const API_KEY = 'test';").unwrap();

        let analyzer = TokenSecurityAnalyzer::default_analyzer();
        let report = analyzer.analyze("API_KEY", dir.path()).unwrap();

        // Should only find in main.js, not node_modules
        assert_eq!(report.files.len(), 1);
        assert!(report.files[0].path.file_name().unwrap() == "main.js");
    }

    #[test]
    fn test_analyzer_performance_metrics() {
        let dir = setup_test_dir();
        let analyzer = TokenSecurityAnalyzer::default_analyzer();

        let report = analyzer.analyze("API_KEY", dir.path()).unwrap();

        assert!(
            report.duration.as_millis() < 5000,
            "Analysis should complete quickly (< 5s)"
        );
        assert!(report.files_scanned > 0, "Should report files scanned");
    }

    #[test]
    fn test_analyzer_multiple_occurrences_per_line() {
        let dir = TempDir::new().unwrap();

        fs::write(
            dir.path().join("test.py"),
            "x = API_KEY + API_KEY + API_KEY\n",
        )
        .unwrap();

        let analyzer = TokenSecurityAnalyzer::default_analyzer();
        let report = analyzer.analyze("API_KEY", dir.path()).unwrap();

        assert_eq!(
            report.total_calls, 3,
            "Should count all occurrences on same line"
        );
        assert_eq!(
            report.files[0].occurrence_lines.len(),
            1,
            "Should only have 1 line"
        );
    }
}