selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
//! Security Scanner
//!
//! Security analysis capabilities:
//! - Secret detection (API keys, passwords, tokens)
//! - Vulnerability detection (SAST-style)
//! - Dependency auditing
//! - Compliance checking

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::RwLock;
use std::time::{SystemTime, UNIX_EPOCH};

/// Severity of a security finding
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum SecuritySeverity {
    /// Informational finding
    Info,
    /// Low severity
    Low,
    /// Medium severity
    Medium,
    /// High severity
    High,
    /// Critical severity
    Critical,
}

impl SecuritySeverity {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Critical => "critical",
        }
    }

    /// CVSS-like score
    pub fn score(&self) -> f32 {
        match self {
            Self::Info => 0.0,
            Self::Low => 3.0,
            Self::Medium => 5.5,
            Self::High => 7.5,
            Self::Critical => 9.5,
        }
    }
}

/// Category of security finding
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SecurityCategory {
    /// Hardcoded secrets
    HardcodedSecret,
    /// Injection vulnerability
    Injection,
    /// Authentication issue
    Authentication,
    /// Authorization issue
    Authorization,
    /// Data exposure
    DataExposure,
    /// Cryptographic weakness
    Cryptography,
    /// Configuration issue
    Configuration,
    /// Vulnerable dependency
    Dependency,
    /// Compliance violation
    Compliance,
    /// Code quality security issue
    CodeQuality,
    /// Custom category
    Custom(String),
}

impl SecurityCategory {
    pub fn as_str(&self) -> &str {
        match self {
            Self::HardcodedSecret => "hardcoded_secret",
            Self::Injection => "injection",
            Self::Authentication => "authentication",
            Self::Authorization => "authorization",
            Self::DataExposure => "data_exposure",
            Self::Cryptography => "cryptography",
            Self::Configuration => "configuration",
            Self::Dependency => "dependency",
            Self::Compliance => "compliance",
            Self::CodeQuality => "code_quality",
            Self::Custom(s) => s,
        }
    }
}

/// A security finding
#[derive(Debug, Clone)]
pub struct SecurityFinding {
    /// Finding ID
    pub id: String,
    /// Title
    pub title: String,
    /// Description
    pub description: String,
    /// Category
    pub category: SecurityCategory,
    /// Severity
    pub severity: SecuritySeverity,
    /// File path
    pub file: Option<PathBuf>,
    /// Line number
    pub line: Option<u32>,
    /// Code snippet
    pub snippet: Option<String>,
    /// Remediation advice
    pub remediation: Option<String>,
    /// CWE ID
    pub cwe: Option<String>,
    /// Timestamp
    pub timestamp: u64,
}

impl SecurityFinding {
    pub fn new(title: &str, category: SecurityCategory, severity: SecuritySeverity) -> Self {
        let id = format!(
            "SEC-{:x}",
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos() as u64
        );
        Self {
            id,
            title: title.to_string(),
            description: String::new(),
            category,
            severity,
            file: None,
            line: None,
            snippet: None,
            remediation: None,
            cwe: None,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        }
    }

    pub fn with_description(mut self, desc: &str) -> Self {
        self.description = desc.to_string();
        self
    }

    pub fn with_location(mut self, file: PathBuf, line: u32) -> Self {
        self.file = Some(file);
        self.line = Some(line);
        self
    }

    pub fn with_snippet(mut self, snippet: &str) -> Self {
        self.snippet = Some(snippet.to_string());
        self
    }

    pub fn with_remediation(mut self, remediation: &str) -> Self {
        self.remediation = Some(remediation.to_string());
        self
    }

    pub fn with_cwe(mut self, cwe: &str) -> Self {
        self.cwe = Some(cwe.to_string());
        self
    }
}

/// Pattern for detecting secrets
#[derive(Debug, Clone)]
pub struct SecretPattern {
    /// Pattern name
    pub name: String,
    /// Regex pattern
    pub pattern: String,
    /// Pre-compiled regex (avoids recompilation on every scan and enables size limits)
    pub compiled: Option<regex::Regex>,
    /// Severity
    pub severity: SecuritySeverity,
    /// Description
    pub description: String,
}

impl SecretPattern {
    pub fn new(name: &str, pattern: &str, severity: SecuritySeverity) -> Self {
        let compiled = regex::RegexBuilder::new(pattern)
            .size_limit(1 << 20) // 1 MB limit to mitigate ReDoS
            .build()
            .ok();
        Self {
            name: name.to_string(),
            pattern: pattern.to_string(),
            compiled,
            severity,
            description: format!("Potential {} detected", name),
        }
    }
}

/// Scanner for hardcoded secrets
pub struct SecretScanner {
    /// Secret patterns
    patterns: Vec<SecretPattern>,
    /// Files to skip
    _skip_files: Vec<String>,
    /// Findings
    findings: Vec<SecurityFinding>,
}

impl SecretScanner {
    pub fn new() -> Self {
        Self {
            patterns: Self::default_patterns(),
            _skip_files: vec![
                ".git".to_string(),
                "node_modules".to_string(),
                "target".to_string(),
                ".env.example".to_string(),
            ],
            findings: Vec::new(),
        }
    }

    fn default_patterns() -> Vec<SecretPattern> {
        vec![
            SecretPattern::new(
                "AWS Access Key",
                r"AKIA[0-9A-Z]{16}",
                SecuritySeverity::Critical,
            ),
            SecretPattern::new(
                "AWS Secret Key",
                r#"(?i)aws(.{0,20})?['"][0-9a-zA-Z/+]{40}['"]"#,
                SecuritySeverity::Critical,
            ),
            // GitHub classic tokens (ghp_, gho_, ghu_, ghs_, ghr_)
            SecretPattern::new(
                "GitHub Token",
                r"gh[pousr]_[A-Za-z0-9_]{36,}",
                SecuritySeverity::Critical,
            ),
            // GitHub fine-grained personal access tokens
            SecretPattern::new(
                "GitHub Fine-Grained Token",
                r"github_pat_[A-Za-z0-9_]{22,}",
                SecuritySeverity::Critical,
            ),
            // GitLab personal/project/group access tokens
            SecretPattern::new(
                "GitLab Token",
                r"glpat-[A-Za-z0-9_\-]{20,}",
                SecuritySeverity::Critical,
            ),
            SecretPattern::new(
                "Generic API Key",
                r#"(?i)(api[_-]?key|apikey)['"]?\s*[:=]\s*['"][a-zA-Z0-9]{20,}['"]"#,
                SecuritySeverity::High,
            ),
            SecretPattern::new(
                "Private Key",
                r"-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",
                SecuritySeverity::Critical,
            ),
            // Google API keys (AIza...)
            SecretPattern::new(
                "Google API Key",
                r"AIza[a-zA-Z0-9_\-]{35}",
                SecuritySeverity::High,
            ),
            // Stripe secret keys
            SecretPattern::new(
                "Stripe Key",
                r"(sk_live_|rk_live_|pk_live_)[a-zA-Z0-9]{24,}",
                SecuritySeverity::Critical,
            ),
            SecretPattern::new(
                "Password in Code",
                r#"(?i)(password|passwd|pwd)['"]?\s*[:=]\s*['"][^'"]{8,}['"]"#,
                SecuritySeverity::High,
            ),
            SecretPattern::new(
                "Bearer Token",
                r"(?i)bearer\s+[a-zA-Z0-9_\-\.]+",
                SecuritySeverity::High,
            ),
            SecretPattern::new(
                "JWT Token",
                r"eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*",
                SecuritySeverity::High,
            ),
            SecretPattern::new(
                "Database URL",
                r"(?i)(postgres|mysql|mongodb)://[^:]+:[^@]+@",
                SecuritySeverity::High,
            ),
            // Slack tokens: bot (xoxb-), user (xoxp-), app-level (xoxa-),
            // legacy (xoxs-), refresh (xoxr-)
            SecretPattern::new(
                "Slack Token",
                r"xox[bpsar]-[0-9A-Za-z\-]{10,}",
                SecuritySeverity::High,
            ),
            // Partial JWT / base64-encoded token starting with eyJ
            SecretPattern::new(
                "JWT Partial",
                r"eyJ[a-zA-Z0-9_/+\-]{30,}",
                SecuritySeverity::Medium,
            ),
            // Generic high-entropy base64 strings
            SecretPattern::new(
                "Base64 Secret",
                r#"(?i)(?:key|token|secret|password|credential|auth)\s*[:=]\s*['"]?[A-Za-z0-9+/=_\-]{40,}['"]?"#,
                SecuritySeverity::Medium,
            ),
        ]
    }

    /// Add a custom pattern
    pub fn add_pattern(&mut self, pattern: SecretPattern) {
        self.patterns.push(pattern);
    }

    /// Scan content for secrets
    pub fn scan_content(&mut self, content: &str, file: Option<&PathBuf>) -> Vec<SecurityFinding> {
        let mut findings = Vec::new();

        for (line_num, line) in content.lines().enumerate() {
            // Skip comments
            let trimmed = line.trim();
            if trimmed.starts_with("//") || trimmed.starts_with('#') || trimmed.starts_with("/*") {
                continue;
            }

            for pattern in &self.patterns {
                if let Some(ref re) = pattern.compiled {
                    for mat in re.find_iter(line) {
                        let mut finding = SecurityFinding::new(
                            &pattern.name,
                            SecurityCategory::HardcodedSecret,
                            pattern.severity,
                        )
                        .with_description(&pattern.description)
                        .with_cwe("CWE-798");

                        if let Some(f) = file {
                            finding = finding.with_location(f.clone(), (line_num + 1) as u32);
                        }

                        // Mask the secret in snippet
                        let masked = Self::mask_secret(mat.as_str());
                        finding = finding.with_snippet(&masked);
                        finding = finding.with_remediation(
                            "Remove hardcoded secret and use environment variables or a secrets manager"
                        );

                        findings.push(finding.clone());
                        self.findings.push(finding);
                    }
                }
            }
        }

        findings
    }

    /// Mask a secret for safe display
    fn mask_secret(secret: &str) -> String {
        if secret.len() <= 8 {
            "*".repeat(secret.len())
        } else {
            format!(
                "{}...{}",
                secret.chars().take(4).collect::<String>(),
                "*".repeat(secret.chars().count().saturating_sub(4))
            )
        }
    }

    /// Get all findings
    pub fn findings(&self) -> &[SecurityFinding] {
        &self.findings
    }

    /// Clear findings
    pub fn clear(&mut self) {
        self.findings.clear();
    }
}

impl Default for SecretScanner {
    fn default() -> Self {
        Self::new()
    }
}

/// SAST-style vulnerability pattern
#[derive(Debug, Clone)]
pub struct VulnerabilityPattern {
    /// Pattern ID
    pub id: String,
    /// Name
    pub name: String,
    /// Language
    pub language: String,
    /// Pattern to match
    pub pattern: String,
    /// Severity
    pub severity: SecuritySeverity,
    /// CWE ID
    pub cwe: String,
    /// Description
    pub description: String,
    /// Remediation
    pub remediation: String,
}

/// Detector for code vulnerabilities
pub struct VulnerabilityDetector {
    /// Vulnerability patterns
    patterns: Vec<VulnerabilityPattern>,
    /// Findings
    findings: Vec<SecurityFinding>,
}

impl VulnerabilityDetector {
    pub fn new() -> Self {
        Self {
            patterns: Self::default_patterns(),
            findings: Vec::new(),
        }
    }

    fn default_patterns() -> Vec<VulnerabilityPattern> {
        vec![
            VulnerabilityPattern {
                id: "RUST001".to_string(),
                name: "Unsafe Block".to_string(),
                language: "rust".to_string(),
                pattern: r"unsafe\s*\{".to_string(),
                severity: SecuritySeverity::Medium,
                cwe: "CWE-242".to_string(),
                description: "Unsafe block found - requires careful review".to_string(),
                remediation: "Document safety invariants or use safe alternatives".to_string(),
            },
            VulnerabilityPattern {
                id: "RUST002".to_string(),
                name: "Unwrap on Result/Option".to_string(),
                language: "rust".to_string(),
                pattern: r"\.unwrap\(\)".to_string(),
                severity: SecuritySeverity::Low,
                cwe: "CWE-252".to_string(),
                description: "Unwrap can panic on None/Err".to_string(),
                remediation: "Use proper error handling with ? or match".to_string(),
            },
            VulnerabilityPattern {
                id: "RUST003".to_string(),
                name: "SQL Query String Building".to_string(),
                language: "rust".to_string(),
                pattern: r#"format!\s*\(\s*["']SELECT|format!\s*\(\s*["']INSERT|format!\s*\(\s*["']UPDATE|format!\s*\(\s*["']DELETE"#.to_string(),
                severity: SecuritySeverity::High,
                cwe: "CWE-89".to_string(),
                description: "Potential SQL injection vulnerability".to_string(),
                remediation: "Use parameterized queries instead of string formatting".to_string(),
            },
            VulnerabilityPattern {
                id: "RUST004".to_string(),
                name: "Command Injection".to_string(),
                language: "rust".to_string(),
                pattern: r"Command::new\s*\(\s*&?format!".to_string(),
                severity: SecuritySeverity::Critical,
                cwe: "CWE-78".to_string(),
                description: "Potential command injection vulnerability".to_string(),
                remediation: "Use static command strings or validate/sanitize input".to_string(),
            },
            VulnerabilityPattern {
                id: "RUST005".to_string(),
                name: "Path Traversal".to_string(),
                language: "rust".to_string(),
                pattern: r#"Path::new\s*\(\s*&?format!|PathBuf::from\s*\(\s*&?format!"#.to_string(),
                severity: SecuritySeverity::High,
                cwe: "CWE-22".to_string(),
                description: "Potential path traversal vulnerability".to_string(),
                remediation: "Validate paths and use canonicalize()".to_string(),
            },
            VulnerabilityPattern {
                id: "JS001".to_string(),
                name: "eval() Usage".to_string(),
                language: "javascript".to_string(),
                pattern: r"\beval\s*\(".to_string(),
                severity: SecuritySeverity::Critical,
                cwe: "CWE-95".to_string(),
                description: "eval() can execute arbitrary code".to_string(),
                remediation: "Avoid eval() - use safer alternatives".to_string(),
            },
            VulnerabilityPattern {
                id: "JS002".to_string(),
                name: "innerHTML Assignment".to_string(),
                language: "javascript".to_string(),
                pattern: r"\.innerHTML\s*=".to_string(),
                severity: SecuritySeverity::High,
                cwe: "CWE-79".to_string(),
                description: "Potential XSS via innerHTML".to_string(),
                remediation: "Use textContent or sanitize HTML".to_string(),
            },
            VulnerabilityPattern {
                id: "PY001".to_string(),
                name: "Python exec/eval".to_string(),
                language: "python".to_string(),
                pattern: r"\b(exec|eval)\s*\(".to_string(),
                severity: SecuritySeverity::Critical,
                cwe: "CWE-95".to_string(),
                description: "exec/eval can execute arbitrary code".to_string(),
                remediation: "Avoid exec/eval with untrusted input".to_string(),
            },
            VulnerabilityPattern {
                id: "PY002".to_string(),
                name: "Python pickle".to_string(),
                language: "python".to_string(),
                pattern: r"pickle\.(load|loads)\s*\(".to_string(),
                severity: SecuritySeverity::High,
                cwe: "CWE-502".to_string(),
                description: "pickle can deserialize malicious code".to_string(),
                remediation: "Use json or other safe serialization formats".to_string(),
            },
        ]
    }

    /// Add a custom pattern
    pub fn add_pattern(&mut self, pattern: VulnerabilityPattern) {
        self.patterns.push(pattern);
    }

    /// Scan content for vulnerabilities
    pub fn scan_content(
        &mut self,
        content: &str,
        file: Option<&PathBuf>,
        language: &str,
    ) -> Vec<SecurityFinding> {
        let mut findings = Vec::new();

        // Filter patterns for this language
        let applicable: Vec<_> = self
            .patterns
            .iter()
            .filter(|p| p.language == language || p.language == "*")
            .collect();

        for (line_num, line) in content.lines().enumerate() {
            for pattern in &applicable {
                if let Ok(re) = regex::Regex::new(&pattern.pattern) {
                    if re.is_match(line) {
                        let mut finding = SecurityFinding::new(
                            &pattern.name,
                            SecurityCategory::CodeQuality,
                            pattern.severity,
                        )
                        .with_description(&pattern.description)
                        .with_cwe(&pattern.cwe)
                        .with_remediation(&pattern.remediation)
                        .with_snippet(line.trim());

                        if let Some(f) = file {
                            finding = finding.with_location(f.clone(), (line_num + 1) as u32);
                        }

                        findings.push(finding.clone());
                        self.findings.push(finding);
                    }
                }
            }
        }

        findings
    }

    /// Get all findings
    pub fn findings(&self) -> &[SecurityFinding] {
        &self.findings
    }

    /// Clear findings
    pub fn clear(&mut self) {
        self.findings.clear();
    }
}

impl Default for VulnerabilityDetector {
    fn default() -> Self {
        Self::new()
    }
}

/// A dependency with security info
#[derive(Debug, Clone)]
pub struct Dependency {
    /// Package name
    pub name: String,
    /// Version
    pub version: String,
    /// Source (crates.io, npm, pypi, etc.)
    pub source: String,
    /// Known vulnerabilities
    pub vulnerabilities: Vec<KnownVulnerability>,
}

impl Dependency {
    pub fn new(name: &str, version: &str, source: &str) -> Self {
        Self {
            name: name.to_string(),
            version: version.to_string(),
            source: source.to_string(),
            vulnerabilities: Vec::new(),
        }
    }

    pub fn is_vulnerable(&self) -> bool {
        !self.vulnerabilities.is_empty()
    }

    pub fn max_severity(&self) -> Option<SecuritySeverity> {
        self.vulnerabilities.iter().map(|v| v.severity).max()
    }
}

/// A known vulnerability in a dependency
#[derive(Debug, Clone)]
pub struct KnownVulnerability {
    /// CVE or advisory ID
    pub id: String,
    /// Severity
    pub severity: SecuritySeverity,
    /// Description
    pub description: String,
    /// Fixed version
    pub fixed_version: Option<String>,
    /// URL for more info
    pub url: Option<String>,
}

impl KnownVulnerability {
    pub fn new(id: &str, severity: SecuritySeverity, description: &str) -> Self {
        Self {
            id: id.to_string(),
            severity,
            description: description.to_string(),
            fixed_version: None,
            url: None,
        }
    }

    pub fn with_fixed_version(mut self, version: &str) -> Self {
        self.fixed_version = Some(version.to_string());
        self
    }

    pub fn with_url(mut self, url: &str) -> Self {
        self.url = Some(url.to_string());
        self
    }
}

/// Auditor for dependencies
pub struct DependencyAuditor {
    /// Known vulnerable packages (simplified for demo)
    vulnerability_db: HashMap<String, Vec<KnownVulnerability>>,
    /// Scanned dependencies
    dependencies: Vec<Dependency>,
    /// Findings
    findings: Vec<SecurityFinding>,
}

impl DependencyAuditor {
    pub fn new() -> Self {
        Self {
            vulnerability_db: Self::default_db(),
            dependencies: Vec::new(),
            findings: Vec::new(),
        }
    }

    fn default_db() -> HashMap<String, Vec<KnownVulnerability>> {
        let mut db = HashMap::new();

        // Example known vulnerabilities (in practice, this would be populated from a real database)
        db.insert(
            "lodash".to_string(),
            vec![KnownVulnerability::new(
                "CVE-2021-23337",
                SecuritySeverity::High,
                "Command Injection in lodash",
            )
            .with_fixed_version("4.17.21")],
        );

        db.insert(
            "log4j".to_string(),
            vec![KnownVulnerability::new(
                "CVE-2021-44228",
                SecuritySeverity::Critical,
                "Log4Shell RCE vulnerability",
            )
            .with_fixed_version("2.17.0")],
        );

        db
    }

    /// Add a vulnerability to the database
    pub fn add_vulnerability(&mut self, package: &str, vuln: KnownVulnerability) {
        self.vulnerability_db
            .entry(package.to_string())
            .or_default()
            .push(vuln);
    }

    /// Audit a dependency
    pub fn audit_dependency(&mut self, name: &str, version: &str, source: &str) -> Dependency {
        let mut dep = Dependency::new(name, version, source);

        // Check vulnerability database
        if let Some(vulns) = self.vulnerability_db.get(name) {
            for vuln in vulns {
                // In practice, would check version ranges
                dep.vulnerabilities.push(vuln.clone());

                let finding = SecurityFinding::new(
                    &format!("Vulnerable dependency: {}", name),
                    SecurityCategory::Dependency,
                    vuln.severity,
                )
                .with_description(&vuln.description)
                .with_remediation(&format!(
                    "Update {} to version {}",
                    name,
                    vuln.fixed_version.as_deref().unwrap_or("latest")
                ));

                self.findings.push(finding);
            }
        }

        self.dependencies.push(dep.clone());
        dep
    }

    /// Get vulnerable dependencies
    pub fn vulnerable_dependencies(&self) -> Vec<&Dependency> {
        self.dependencies
            .iter()
            .filter(|d| d.is_vulnerable())
            .collect()
    }

    /// Get all findings
    pub fn findings(&self) -> &[SecurityFinding] {
        &self.findings
    }

    /// Clear
    pub fn clear(&mut self) {
        self.dependencies.clear();
        self.findings.clear();
    }
}

impl Default for DependencyAuditor {
    fn default() -> Self {
        Self::new()
    }
}

/// Compliance rule
#[derive(Debug, Clone)]
pub struct ComplianceRule {
    /// Rule ID
    pub id: String,
    /// Standard (OWASP, PCI-DSS, HIPAA, etc.)
    pub standard: String,
    /// Description
    pub description: String,
    /// Check function (simplified as pattern)
    pub pattern: Option<String>,
    /// Severity
    pub severity: SecuritySeverity,
}

impl ComplianceRule {
    pub fn new(id: &str, standard: &str, description: &str) -> Self {
        Self {
            id: id.to_string(),
            standard: standard.to_string(),
            description: description.to_string(),
            pattern: None,
            severity: SecuritySeverity::Medium,
        }
    }

    pub fn with_pattern(mut self, pattern: &str) -> Self {
        self.pattern = Some(pattern.to_string());
        self
    }

    pub fn with_severity(mut self, severity: SecuritySeverity) -> Self {
        self.severity = severity;
        self
    }
}

/// Checker for compliance rules
pub struct ComplianceChecker {
    /// Compliance rules
    rules: Vec<ComplianceRule>,
    /// Findings
    findings: Vec<SecurityFinding>,
}

impl ComplianceChecker {
    pub fn new() -> Self {
        Self {
            rules: Self::default_rules(),
            findings: Vec::new(),
        }
    }

    fn default_rules() -> Vec<ComplianceRule> {
        vec![
            ComplianceRule::new("OWASP-A01", "OWASP Top 10", "Broken Access Control")
                .with_severity(SecuritySeverity::High),
            ComplianceRule::new("OWASP-A02", "OWASP Top 10", "Cryptographic Failures")
                .with_pattern(r"(?i)(md5|sha1)\s*\(")
                .with_severity(SecuritySeverity::High),
            ComplianceRule::new("OWASP-A03", "OWASP Top 10", "Injection")
                .with_severity(SecuritySeverity::Critical),
            ComplianceRule::new("PCI-DSS-6.5.1", "PCI-DSS", "Address injection flaws")
                .with_severity(SecuritySeverity::High),
            ComplianceRule::new("HIPAA-164.312", "HIPAA", "Encryption of PHI at rest")
                .with_severity(SecuritySeverity::High),
        ]
    }

    /// Add a custom rule
    pub fn add_rule(&mut self, rule: ComplianceRule) {
        self.rules.push(rule);
    }

    /// Check content against rules with patterns
    pub fn check_content(&mut self, content: &str, file: Option<&PathBuf>) -> Vec<SecurityFinding> {
        let mut findings = Vec::new();

        for (line_num, line) in content.lines().enumerate() {
            for rule in &self.rules {
                if let Some(pattern) = &rule.pattern {
                    if let Ok(re) = regex::Regex::new(pattern) {
                        if re.is_match(line) {
                            let mut finding = SecurityFinding::new(
                                &format!("{}: {}", rule.id, rule.description),
                                SecurityCategory::Compliance,
                                rule.severity,
                            )
                            .with_description(&format!("Potential {} violation", rule.standard))
                            .with_snippet(line.trim());

                            if let Some(f) = file {
                                finding = finding.with_location(f.clone(), (line_num + 1) as u32);
                            }

                            findings.push(finding.clone());
                            self.findings.push(finding);
                        }
                    }
                }
            }
        }

        findings
    }

    /// Get applicable standards
    pub fn standards(&self) -> Vec<String> {
        let mut standards: Vec<_> = self.rules.iter().map(|r| r.standard.clone()).collect();
        standards.sort();
        standards.dedup();
        standards
    }

    /// Get all findings
    pub fn findings(&self) -> &[SecurityFinding] {
        &self.findings
    }

    /// Clear
    pub fn clear(&mut self) {
        self.findings.clear();
    }
}

impl Default for ComplianceChecker {
    fn default() -> Self {
        Self::new()
    }
}

/// Security scan result
#[derive(Debug, Clone)]
pub struct ScanResult {
    /// All findings
    pub findings: Vec<SecurityFinding>,
    /// Summary by severity
    pub by_severity: HashMap<SecuritySeverity, usize>,
    /// Summary by category
    pub by_category: HashMap<String, usize>,
    /// Scan duration (ms)
    pub duration_ms: u64,
    /// Files scanned
    pub files_scanned: usize,
    /// Lines scanned
    pub lines_scanned: usize,
}

impl ScanResult {
    pub fn new() -> Self {
        Self {
            findings: Vec::new(),
            by_severity: HashMap::new(),
            by_category: HashMap::new(),
            duration_ms: 0,
            files_scanned: 0,
            lines_scanned: 0,
        }
    }

    /// Total finding count
    pub fn total_findings(&self) -> usize {
        self.findings.len()
    }

    /// Has critical findings?
    pub fn has_critical(&self) -> bool {
        self.by_severity
            .get(&SecuritySeverity::Critical)
            .is_some_and(|&c| c > 0)
    }

    /// Has high findings?
    pub fn has_high(&self) -> bool {
        self.by_severity
            .get(&SecuritySeverity::High)
            .is_some_and(|&c| c > 0)
    }

    /// Overall risk score
    pub fn risk_score(&self) -> f32 {
        self.findings.iter().map(|f| f.severity.score()).sum()
    }
}

impl Default for ScanResult {
    fn default() -> Self {
        Self::new()
    }
}

/// Main security scanner
pub struct SecurityScanner {
    /// Secret scanner
    secret_scanner: RwLock<SecretScanner>,
    /// Vulnerability detector
    vuln_detector: RwLock<VulnerabilityDetector>,
    /// Dependency auditor
    dep_auditor: RwLock<DependencyAuditor>,
    /// Compliance checker
    compliance_checker: RwLock<ComplianceChecker>,
    /// Scan history
    scan_history: RwLock<Vec<ScanResult>>,
}

impl SecurityScanner {
    pub fn new() -> Self {
        Self {
            secret_scanner: RwLock::new(SecretScanner::new()),
            vuln_detector: RwLock::new(VulnerabilityDetector::new()),
            dep_auditor: RwLock::new(DependencyAuditor::new()),
            compliance_checker: RwLock::new(ComplianceChecker::new()),
            scan_history: RwLock::new(Vec::new()),
        }
    }

    /// Scan content for all security issues
    pub fn scan_content(
        &self,
        content: &str,
        file: Option<&PathBuf>,
        language: &str,
    ) -> ScanResult {
        let start = std::time::Instant::now();
        let mut result = ScanResult::new();

        // Scan for secrets
        if let Ok(mut scanner) = self.secret_scanner.write() {
            result.findings.extend(scanner.scan_content(content, file));
        }

        // Scan for vulnerabilities
        if let Ok(mut detector) = self.vuln_detector.write() {
            result
                .findings
                .extend(detector.scan_content(content, file, language));
        }

        // Check compliance
        if let Ok(mut checker) = self.compliance_checker.write() {
            result.findings.extend(checker.check_content(content, file));
        }

        // Calculate summaries
        for finding in &result.findings {
            *result.by_severity.entry(finding.severity).or_insert(0) += 1;
            *result
                .by_category
                .entry(finding.category.as_str().to_string())
                .or_insert(0) += 1;
        }

        result.duration_ms = start.elapsed().as_millis() as u64;
        result.files_scanned = 1;
        result.lines_scanned = content.lines().count();

        // Save to history
        if let Ok(mut history) = self.scan_history.write() {
            history.push(result.clone());
            if history.len() > 100 {
                history.remove(0);
            }
        }

        result
    }

    /// Audit a dependency
    pub fn audit_dependency(&self, name: &str, version: &str, source: &str) -> Dependency {
        if let Ok(mut auditor) = self.dep_auditor.write() {
            auditor.audit_dependency(name, version, source)
        } else {
            Dependency::new(name, version, source)
        }
    }

    /// Get scan statistics
    pub fn get_stats(&self) -> ScannerStats {
        let history = self.scan_history.read().ok();
        let total_scans = history.as_ref().map_or(0, |h| h.len());
        let total_findings: usize = history
            .as_ref()
            .map_or(0, |h| h.iter().map(|r| r.total_findings()).sum());

        ScannerStats {
            total_scans,
            total_findings,
            critical_findings: history.as_ref().map_or(0, |h| {
                h.iter()
                    .map(|r| {
                        r.by_severity
                            .get(&SecuritySeverity::Critical)
                            .copied()
                            .unwrap_or(0)
                    })
                    .sum()
            }),
            high_findings: history.as_ref().map_or(0, |h| {
                h.iter()
                    .map(|r| {
                        r.by_severity
                            .get(&SecuritySeverity::High)
                            .copied()
                            .unwrap_or(0)
                    })
                    .sum()
            }),
        }
    }

    /// Generate security report
    pub fn generate_report(&self, result: &ScanResult) -> String {
        let mut report = String::new();
        report.push_str("# Security Scan Report\n\n");

        report.push_str(&format!("- Files scanned: {}\n", result.files_scanned));
        report.push_str(&format!("- Lines scanned: {}\n", result.lines_scanned));
        report.push_str(&format!("- Scan duration: {}ms\n", result.duration_ms));
        report.push_str(&format!("- Total findings: {}\n", result.total_findings()));
        report.push_str(&format!("- Risk score: {:.1}\n\n", result.risk_score()));

        if result.has_critical() {
            report.push_str("## CRITICAL Findings\n");
            for finding in result
                .findings
                .iter()
                .filter(|f| f.severity == SecuritySeverity::Critical)
            {
                report.push_str(&format!(
                    "- **{}**: {}\n",
                    finding.title, finding.description
                ));
                if let Some(file) = &finding.file {
                    report.push_str(&format!(
                        "  Location: {}:{}\n",
                        file.display(),
                        finding.line.unwrap_or(0)
                    ));
                }
            }
            report.push('\n');
        }

        if result.has_high() {
            report.push_str("## HIGH Findings\n");
            for finding in result
                .findings
                .iter()
                .filter(|f| f.severity == SecuritySeverity::High)
            {
                report.push_str(&format!(
                    "- **{}**: {}\n",
                    finding.title, finding.description
                ));
            }
            report.push('\n');
        }

        report.push_str("## Summary by Category\n");
        for (cat, count) in &result.by_category {
            report.push_str(&format!("- {}: {}\n", cat, count));
        }

        report
    }
}

impl Default for SecurityScanner {
    fn default() -> Self {
        Self::new()
    }
}

/// Scanner statistics
#[derive(Debug, Clone)]
pub struct ScannerStats {
    pub total_scans: usize,
    pub total_findings: usize,
    pub critical_findings: usize,
    pub high_findings: usize,
}

#[cfg(test)]
#[path = "../../tests/unit/safety/scanner/scanner_test.rs"]
mod tests;