raxit-core 0.1.2

Core security scanning engine for AI agent applications
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
//! Secret Detection Analyzer
//!
//! Detects exposed secrets, API keys, and credentials in source code.
//!
//! ## Detection Methods
//!
//! 1. **Regex Pattern Matching**: Detects 11 common secret types including:
//!    - OpenAI API keys (`sk-*` patterns)
//!    - Anthropic API keys (`sk-ant-*`)
//!    - AWS access keys (`AKIA*`)
//!    - GitHub tokens (`ghp_*`, `gho_*`)
//!    - JWT tokens
//!    - Private keys (PEM format)
//!    - Database connection strings
//!
//! 2. **Entropy Analysis**: Uses Shannon entropy to detect high-randomness strings
//!    that may be cryptographic keys or tokens
//!
//! 3. **Variable Name Analysis**: Flags assignments to sensitive variable names
//!    like `api_key`, `password`, `secret`, `token`
//!
//! 4. **False Positive Filtering**: Excludes common placeholder values and
//!    example strings
//!
//! ## Usage
//!
//! ```rust,no_run
//! use raxit_core::analyzers::secret_detection;
//! use raxit_core::schema::ScanResult;
//!
//! let mut result = ScanResult::new();
//! // ... populate result.manifest.files ...
//!
//! let findings = secret_detection::analyze(&result)?;
//!
//! for finding in findings {
//!     match finding.severity.as_str() {
//!         "critical" => println!("🔴 Critical: {}", finding.message),
//!         "high" => println!("🟠 High: {}", finding.message),
//!         _ => println!("â„šī¸  {}", finding.message),
//!     }
//! }
//! # Ok::<(), raxit_core::RaxitError>(())
//! ```
//!
//! ## Security Note
//!
//! All detected secrets are masked in output using the `mask_secret()` function
//! to prevent accidental exposure in logs or reports.

use crate::error::Result;
use crate::schema::{ScanResult, SecretFinding, SourceLocation};
use once_cell::sync::Lazy;
use regex::Regex;

/// Common secret patterns with regex
static SECRET_PATTERNS: Lazy<Vec<(&str, Regex)>> = Lazy::new(|| {
    vec![
        // OpenAI API keys (flexible pattern for sk- prefix keys)
        ("openai_key", Regex::new(r#"sk-[a-zA-Z0-9-]{20,}"#).unwrap()),
        // Anthropic API keys
        (
            "anthropic_key",
            Regex::new(r#"sk-ant-[a-zA-Z0-9-]{50,}"#).unwrap(),
        ),
        // AWS Access Keys
        (
            "aws_access_key",
            Regex::new(r#"\bAKIA[0-9A-Z]{16}\b"#).unwrap(),
        ),
        // GitHub Personal Access Tokens
        (
            "github_token",
            Regex::new(r#"\bghp_[a-zA-Z0-9]{36}\b"#).unwrap(),
        ),
        // GitHub OAuth Tokens
        (
            "github_oauth",
            Regex::new(r#"\bgho_[a-zA-Z0-9]{36}\b"#).unwrap(),
        ),
        // Stripe API keys
        (
            "stripe_key",
            Regex::new(r#"sk_live_[a-zA-Z0-9]{24,}"#).unwrap(),
        ),
        // JWT tokens
        (
            "jwt_token",
            Regex::new(r#"eyJ[a-zA-Z0-9_-]+\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+"#).unwrap(),
        ),
        // Google OAuth
        (
            "google_oauth",
            Regex::new(r#"ya29\.[0-9A-Za-z_-]+"#).unwrap(),
        ),
        // Slack tokens
        (
            "slack_token",
            Regex::new(r#"xox[baprs]-[0-9]{10,12}-[0-9]{10,12}-[a-zA-Z0-9]{24,}"#).unwrap(),
        ),
        // Connection strings
        (
            "connection_string",
            Regex::new(r#"(?i)(postgresql|mysql|mongodb|redis)://[^\s'"]+:[^\s'"]+@[^\s'"]+"#)
                .unwrap(),
        ),
        // Private keys (PEM format)
        (
            "private_key",
            Regex::new(r#"-----BEGIN [A-Z ]+PRIVATE KEY-----"#).unwrap(),
        ),
    ]
});

/// Sensitive variable name patterns
static SENSITIVE_VAR_NAMES: &[&str] = &[
    "api_key",
    "apikey",
    "api_secret",
    "secret_key",
    "secret",
    "password",
    "passwd",
    "pwd",
    "token",
    "access_token",
    "refresh_token",
    "auth_token",
    "bearer_token",
    "credential",
    "credentials",
    "private_key",
    "privatekey",
    "aws_access_key_id",
    "aws_secret_access_key",
    "database_password",
    "db_password",
    "encryption_key",
    "master_key",
    "client_secret",
];

/// False positive patterns to exclude (case-insensitive)
/// Only used for hardcoded passwords and sensitive variables
static FALSE_POSITIVE_PATTERNS: &[&str] = &[
    "your_key_here",
    "insert_key_here",
    "replace_with",
    "placeholder",
    "changeme",
    "secret_goes_here",
    "example_password",
    "test_password",
];

/// Analyze scan results for exposed secrets
pub fn analyze(result: &ScanResult) -> Result<Vec<SecretFinding>> {
    let mut findings = Vec::new();

    // Scan all files in the manifest
    for file_path in &result.manifest.files {
        if let Ok(content) = std::fs::read_to_string(file_path) {
            let file_findings = scan_file(file_path, &content)?;
            findings.extend(file_findings);
        }
    }

    Ok(findings)
}

/// Scan a single file for secrets
fn scan_file(file_path: &str, content: &str) -> Result<Vec<SecretFinding>> {
    let mut findings = Vec::new();

    for (line_num, line) in content.lines().enumerate() {
        let line_number = (line_num + 1) as u32;

        // Check regex patterns
        for (secret_type, pattern) in SECRET_PATTERNS.iter() {
            if let Some(captures) = pattern.find(line) {
                let matched_value = captures.as_str();

                #[cfg(test)]
                eprintln!("Found {secret_type} pattern: {matched_value} in line: {line}");

                // Skip false positives
                if is_false_positive(matched_value) {
                    #[cfg(test)]
                    eprintln!("  Skipped as false positive");
                    continue;
                }

                findings.push(SecretFinding {
                    id: format!(
                        "secret_{}_{}",
                        file_path.replace(['/', '.'], "_"),
                        line_number
                    ),
                    secret_type: secret_type.to_string(),
                    location: SourceLocation {
                        file: file_path.to_string(),
                        line: line_number,
                        end_line: Some(line_number),
                        function: None,
                    },
                    severity: determine_severity(secret_type),
                    message: format!(
                        "Potential {} detected in source code",
                        secret_type.replace('_', " ")
                    ),
                    matched_pattern: Some(mask_secret(matched_value)),
                });
            }
        }

        // Check sensitive variable names
        findings.extend(check_sensitive_variables(file_path, line, line_number)?);
    }

    Ok(findings)
}

/// Check for sensitive variable assignments
fn check_sensitive_variables(
    file_path: &str,
    line: &str,
    line_number: u32,
) -> Result<Vec<SecretFinding>> {
    let mut findings = Vec::new();

    // Look for variable assignments
    let assignment_pattern = Regex::new(r#"(\w+)\s*=\s*["']([^"']+)["']"#).unwrap();

    if let Some(captures) = assignment_pattern.captures(line) {
        let var_name = captures.get(1).map(|m| m.as_str()).unwrap_or("");
        let var_value = captures.get(2).map(|m| m.as_str()).unwrap_or("");

        // Check if variable name is sensitive
        let var_name_lower = var_name.to_lowercase();
        if SENSITIVE_VAR_NAMES
            .iter()
            .any(|sensitive| var_name_lower.contains(sensitive))
        {
            // Skip if value is clearly a placeholder
            if is_false_positive(var_value) {
                return Ok(findings);
            }

            // Check entropy
            let entropy = calculate_shannon_entropy(var_value);
            if entropy > 3.5 {
                findings.push(SecretFinding {
                    id: format!(
                        "secret_var_{}_{}",
                        file_path.replace(['/', '.'], "_"),
                        line_number
                    ),
                    secret_type: "sensitive_variable".to_string(),
                    location: SourceLocation {
                        file: file_path.to_string(),
                        line: line_number,
                        end_line: Some(line_number),
                        function: None,
                    },
                    severity: "high".to_string(),
                    message: format!(
                        "Sensitive variable '{var_name}' assigned with hardcoded value"
                    ),
                    matched_pattern: Some(format!("{} = {}", var_name, mask_secret(var_value))),
                });
            }
        }
    }

    Ok(findings)
}

/// Calculate Shannon entropy of a string
fn calculate_shannon_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;
    char_counts
        .values()
        .map(|&count| {
            let p = count as f64 / len;
            -p * p.log2()
        })
        .sum()
}

/// Check if a string matches false positive patterns
fn is_false_positive(s: &str) -> bool {
    let s_lower = s.to_lowercase();

    // Only filter very obvious placeholders
    FALSE_POSITIVE_PATTERNS
        .iter()
        .any(|pattern| s_lower == *pattern || s_lower.contains(pattern))
}

/// Mask a secret string for display
fn mask_secret(s: &str) -> String {
    if s.len() <= 8 {
        "*".repeat(s.len())
    } else {
        let visible_chars = 4.min(s.len() / 4);
        format!(
            "{}...{}",
            &s[..visible_chars],
            "*".repeat(s.len() - visible_chars)
        )
    }
}

/// Determine severity based on secret type
fn determine_severity(secret_type: &str) -> String {
    match secret_type {
        "openai_key" | "anthropic_key" | "aws_access_key" | "private_key" => "critical".to_string(),
        "github_token" | "stripe_key" | "connection_string" => "high".to_string(),
        "jwt_token" | "slack_token" | "azure_token" => "medium".to_string(),
        _ => "low".to_string(),
    }
}

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

    #[test]
    fn test_shannon_entropy() {
        // Low entropy (repeated chars)
        assert!(calculate_shannon_entropy("aaaaaaa") < 1.0);

        // High entropy (random-looking)
        assert!(calculate_shannon_entropy("sk-1234567890abcdef") > 3.0);

        // Very high entropy
        let entropy = calculate_shannon_entropy("xK9$mP2!qL7#vN4@");
        assert!(entropy > 3.5); // Mixed alphanumeric with symbols
    }

    #[test]
    fn test_openai_key_pattern() {
        let code = r#"api_key = "sk-proj-1234567890abcdefghijklmnopqrstuvwxyz123456""#;
        let findings = scan_file("test.py", code).unwrap();

        eprintln!("Findings: {findings:?}");
        assert!(!findings.is_empty(), "Expected to find openai_key pattern");
        assert!(findings.iter().any(|f| f.secret_type == "openai_key"));
    }

    #[test]
    fn test_anthropic_key_pattern() {
        let code = r#"client = Anthropic(api_key="sk-ant-api03-1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdef")"#;
        let findings = scan_file("test.py", code).unwrap();

        assert!(!findings.is_empty());
        assert!(findings.iter().any(|f| f.secret_type == "anthropic_key"));
    }

    #[test]
    fn test_aws_access_key_pattern() {
        let code = r#"AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE""#;
        let findings = scan_file("test.py", code).unwrap();

        assert!(!findings.is_empty());
        assert!(findings.iter().any(|f| f.secret_type == "aws_access_key"));
    }

    #[test]
    fn test_github_token_pattern() {
        // GitHub tokens are exactly 40 chars: ghp_ (4) + 36 chars
        let code = r#"token = "ghp_1234567890abcdefghijklmnopqrstuvwxyz""#;
        let findings = scan_file("test.py", code).unwrap();

        assert!(!findings.is_empty());
        assert!(findings.iter().any(|f| f.secret_type == "github_token"));
    }

    #[test]
    fn test_connection_string_pattern() {
        let code = r#"db_url = "postgresql://user:password@localhost:5432/mydb""#;
        let findings = scan_file("test.py", code).unwrap();

        assert!(!findings.is_empty());
        assert!(findings
            .iter()
            .any(|f| f.secret_type == "connection_string"));
    }

    #[test]
    fn test_sensitive_variable_detection() {
        let code = r#"api_key = "sk9mP2qL7vN4xK1wR8tY3""#;
        let findings = scan_file("test.py", code).unwrap();

        // Should match both pattern and variable name
        assert!(!findings.is_empty());
    }

    #[test]
    fn test_false_positive_filtering() {
        let code = r#"api_key = "your_key_here""#;
        let findings = scan_file("test.py", code).unwrap();

        // Should be filtered as false positive
        assert!(findings.is_empty());
    }

    #[test]
    fn test_example_values_filtered() {
        let code = r#"password = "example_password""#;
        let findings = scan_file("test.py", code).unwrap();

        // Should be filtered as example
        assert!(findings.is_empty());
    }

    #[test]
    fn test_jwt_token_pattern() {
        let code = r#"token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c""#;
        let findings = scan_file("test.py", code).unwrap();

        assert!(!findings.is_empty());
        assert!(findings.iter().any(|f| f.secret_type == "jwt_token"));
    }

    #[test]
    fn test_private_key_pattern() {
        let code = r#"key = """-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----""""#;
        let findings = scan_file("test.py", code).unwrap();

        assert!(!findings.is_empty());
        assert!(findings.iter().any(|f| f.secret_type == "private_key"));
        assert!(findings.iter().any(|f| f.severity == "critical"));
    }

    #[test]
    fn test_severity_levels() {
        assert_eq!(determine_severity("openai_key"), "critical");
        assert_eq!(determine_severity("github_token"), "high");
        assert_eq!(determine_severity("jwt_token"), "medium");
        assert_eq!(determine_severity("generic_api_key"), "low");
    }

    #[test]
    fn test_secret_masking() {
        // sk-1234567890abcdef is 18 chars, so visible_chars = min(4, 18/4) = 4
        // mask_secret shows first 4 chars + "..." + asterisks for remaining 14
        assert_eq!(mask_secret("sk-1234567890abcdef"), "sk-1...***************");
        assert_eq!(mask_secret("short"), "*****");
    }
}