rastray 0.15.0

Blazing-fast static analysis CLI for security, dependency, and performance audits.
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
use std::fs;
use std::sync::OnceLock;

use regex::Regex;

use crate::cli::Severity;
use crate::crawler::{CrawlSummary, FileKind};
use crate::reporter::{Category, Finding, Location};

use super::{Analyzer, AnalyzerError};

#[derive(Debug, Default)]
pub struct SecretsAnalyzer;

impl SecretsAnalyzer {
    pub fn new() -> Self {
        Self
    }
}

impl Analyzer for SecretsAnalyzer {
    fn name(&self) -> &'static str {
        "secrets"
    }

    fn analyze(&self, crawl: &CrawlSummary) -> Result<Vec<Finding>, AnalyzerError> {
        let patterns = compiled_patterns()?;
        let mut findings = Vec::new();
        for file in &crawl.files {
            if !is_scannable(file.kind) {
                continue;
            }
            let contents = match fs::read_to_string(&file.path) {
                Ok(c) => c,
                Err(_) => continue,
            };
            for pattern in patterns {
                for m in pattern.regex.find_iter(&contents) {
                    if let Some(threshold) = pattern.min_entropy {
                        if shannon_entropy(m.as_str()) < threshold {
                            continue;
                        }
                    }
                    let (line, column) = byte_offset_to_line_col(&contents, m.start());
                    let location = Location::file(file.path.clone())
                        .with_span(m.start(), m.len())
                        .with_line(line, column);
                    findings.push(
                        Finding::new(
                            pattern.code,
                            format!("possible {} detected", pattern.name),
                            pattern.severity,
                            Category::Secret,
                        )
                        .with_help(pattern.help)
                        .with_location(location),
                    );
                }
            }
        }
        Ok(findings)
    }
}

pub fn scan_text_for_secrets(
    contents: &str,
    synthetic_path: std::path::PathBuf,
) -> Result<Vec<Finding>, AnalyzerError> {
    let patterns = compiled_patterns()?;
    let mut findings = Vec::new();
    for pattern in patterns {
        for m in pattern.regex.find_iter(contents) {
            if let Some(threshold) = pattern.min_entropy {
                if shannon_entropy(m.as_str()) < threshold {
                    continue;
                }
            }
            let (line, column) = byte_offset_to_line_col(contents, m.start());
            let location = Location::file(synthetic_path.clone())
                .with_span(m.start(), m.len())
                .with_line(line, column);
            findings.push(
                Finding::new(
                    pattern.code,
                    format!("possible {} detected", pattern.name),
                    pattern.severity,
                    Category::Secret,
                )
                .with_help(pattern.help)
                .with_location(location),
            );
        }
    }
    Ok(findings)
}

fn is_scannable(kind: FileKind) -> bool {
    matches!(
        kind,
        FileKind::Manifest | FileKind::Source | FileKind::Config
    )
}

struct PatternSpec {
    code: &'static str,
    name: &'static str,
    severity: Severity,
    help: &'static str,
    pattern: &'static str,
    min_entropy: Option<f64>,
}

struct CompiledPattern {
    code: &'static str,
    name: &'static str,
    severity: Severity,
    help: &'static str,
    regex: Regex,
    min_entropy: Option<f64>,
}

const DEFAULT_MIN_ENTROPY: f64 = 3.0;

const PATTERN_SPECS: &[PatternSpec] = &[
    PatternSpec {
        code: "RSTR-SEC-001",
        name: "AWS access key ID",
        severity: Severity::Critical,
        help: "rotate the credential immediately and purge it from git history",
        pattern: r"\bAKIA[0-9A-Z]{16}\b",
        min_entropy: Some(DEFAULT_MIN_ENTROPY),
    },
    PatternSpec {
        code: "RSTR-SEC-002",
        name: "GitHub personal access token",
        severity: Severity::High,
        help: "revoke the token at https://github.com/settings/tokens and rotate",
        pattern: r"\bghp_[0-9a-zA-Z]{36}\b",
        min_entropy: Some(DEFAULT_MIN_ENTROPY),
    },
    PatternSpec {
        code: "RSTR-SEC-003",
        name: "GitHub fine-grained personal access token",
        severity: Severity::High,
        help: "revoke the token at https://github.com/settings/tokens and rotate",
        pattern: r"\bgithub_pat_[0-9a-zA-Z_]{82}\b",
        min_entropy: Some(DEFAULT_MIN_ENTROPY),
    },
    PatternSpec {
        code: "RSTR-SEC-004",
        name: "Slack bot token",
        severity: Severity::High,
        help: "revoke at https://api.slack.com/apps and rotate",
        pattern: r"\bxoxb-[0-9]+-[0-9]+-[0-9a-zA-Z]+\b",
        min_entropy: Some(DEFAULT_MIN_ENTROPY),
    },
    PatternSpec {
        code: "RSTR-SEC-005",
        name: "Stripe live secret key",
        severity: Severity::Critical,
        help: "rotate the key in the Stripe dashboard and audit recent API usage",
        pattern: r"\bsk_live_[0-9a-zA-Z]{24,99}\b",
        min_entropy: Some(DEFAULT_MIN_ENTROPY),
    },
    PatternSpec {
        code: "RSTR-SEC-006",
        name: "Google API key",
        severity: Severity::High,
        help: "rotate the key in Google Cloud Console and audit recent usage",
        pattern: r"\bAIza[0-9A-Za-z_\-]{35}\b",
        min_entropy: Some(DEFAULT_MIN_ENTROPY),
    },
    PatternSpec {
        code: "RSTR-SEC-007",
        name: "PEM private key",
        severity: Severity::Critical,
        help: "remove the key from version control history and rotate immediately",
        pattern: r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY( BLOCK)?-----",
        min_entropy: None,
    },
    PatternSpec {
        code: "RSTR-SEC-008",
        name: "npm access token",
        severity: Severity::High,
        help: "revoke at https://www.npmjs.com/settings/<user>/tokens and rotate",
        pattern: r"\bnpm_[A-Za-z0-9]{36}\b",
        min_entropy: Some(DEFAULT_MIN_ENTROPY),
    },
];

static PATTERNS: OnceLock<Result<Vec<CompiledPattern>, regex::Error>> = OnceLock::new();

fn compiled_patterns() -> Result<&'static [CompiledPattern], AnalyzerError> {
    let cached = PATTERNS.get_or_init(|| {
        PATTERN_SPECS
            .iter()
            .map(|spec| {
                Regex::new(spec.pattern).map(|regex| CompiledPattern {
                    code: spec.code,
                    name: spec.name,
                    severity: spec.severity,
                    help: spec.help,
                    regex,
                    min_entropy: spec.min_entropy,
                })
            })
            .collect::<Result<Vec<_>, _>>()
    });
    match cached {
        Ok(v) => Ok(v.as_slice()),
        Err(e) => Err(AnalyzerError::Failed {
            name: "secrets",
            message: format!("failed to compile a builtin secret pattern: {e}"),
        }),
    }
}

fn byte_offset_to_line_col(text: &str, offset: usize) -> (usize, usize) {
    let mut line = 1usize;
    let mut col = 1usize;
    for (i, ch) in text.char_indices() {
        if i >= offset {
            break;
        }
        if ch == '\n' {
            line += 1;
            col = 1;
        } else {
            col += 1;
        }
    }
    (line, col)
}

fn shannon_entropy(s: &str) -> f64 {
    if s.is_empty() {
        return 0.0;
    }
    let len = s.len() as f64;
    let mut counts = [0u32; 256];
    for byte in s.bytes() {
        counts[byte as usize] = counts[byte as usize].saturating_add(1);
    }
    -counts
        .iter()
        .filter(|&&c| c > 0)
        .map(|&c| {
            let p = f64::from(c) / len;
            p * p.log2()
        })
        .sum::<f64>()
}

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

    #[test]
    fn byte_offset_at_start_is_line_1_col_1() {
        assert_eq!(byte_offset_to_line_col("hello", 0), (1, 1));
    }

    #[test]
    fn byte_offset_advances_column_within_line() {
        assert_eq!(byte_offset_to_line_col("hello", 3), (1, 4));
    }

    #[test]
    fn byte_offset_after_newline_advances_line_resets_column() {
        let text = "ab\ncd";
        assert_eq!(byte_offset_to_line_col(text, 3), (2, 1));
        assert_eq!(byte_offset_to_line_col(text, 4), (2, 2));
    }

    #[test]
    fn byte_offset_handles_multiple_newlines() {
        let text = "a\nb\nc";
        assert_eq!(byte_offset_to_line_col(text, 4), (3, 1));
    }

    #[test]
    fn all_builtin_patterns_compile() {
        let result = compiled_patterns();
        assert!(result.is_ok());
        if let Ok(patterns) = result {
            assert_eq!(patterns.len(), PATTERN_SPECS.len());
            assert!(patterns.len() >= 8);
        }
    }

    #[test]
    fn aws_pattern_matches_canonical_example() {
        let patterns = match compiled_patterns() {
            Ok(p) => p,
            Err(_) => return,
        };
        let aws = patterns.iter().find(|p| p.code == "RSTR-SEC-001");
        assert!(aws.is_some());
        if let Some(p) = aws {
            assert!(p.regex.is_match("AKIAIOSFODNN7EXAMPLE"));
            assert!(!p.regex.is_match("AKIA"));
            assert!(!p.regex.is_match("akiaiosfodnn7example"));
        }
    }

    #[test]
    fn github_pat_pattern_distinguishes_classic_and_fine_grained() {
        let patterns = match compiled_patterns() {
            Ok(p) => p,
            Err(_) => return,
        };
        let classic = patterns.iter().find(|p| p.code == "RSTR-SEC-002");
        let fine = patterns.iter().find(|p| p.code == "RSTR-SEC-003");
        assert!(classic.is_some());
        assert!(fine.is_some());
        if let (Some(c), Some(f)) = (classic, fine) {
            let classic_token = "ghp_1234567890abcdefghijklmnopqrstuvwxyz";
            assert!(c.regex.is_match(classic_token));
            assert!(!f.regex.is_match(classic_token));
        }
    }

    #[test]
    fn pem_private_key_marker_matches_common_variants() {
        let patterns = match compiled_patterns() {
            Ok(p) => p,
            Err(_) => return,
        };
        let pem = patterns.iter().find(|p| p.code == "RSTR-SEC-007");
        assert!(pem.is_some());
        if let Some(p) = pem {
            assert!(p.regex.is_match("-----BEGIN RSA PRIVATE KEY-----"));
            assert!(p.regex.is_match("-----BEGIN PRIVATE KEY-----"));
            assert!(p.regex.is_match("-----BEGIN EC PRIVATE KEY-----"));
            assert!(p.regex.is_match("-----BEGIN OPENSSH PRIVATE KEY-----"));
        }
    }

    #[test]
    fn is_scannable_includes_manifest_source_config() {
        assert!(is_scannable(FileKind::Manifest));
        assert!(is_scannable(FileKind::Source));
        assert!(is_scannable(FileKind::Config));
        assert!(!is_scannable(FileKind::Other));
    }

    #[test]
    fn shannon_entropy_of_empty_string_is_zero() {
        assert_eq!(shannon_entropy(""), 0.0);
    }

    #[test]
    fn shannon_entropy_of_uniform_string_is_zero() {
        assert_eq!(shannon_entropy("AAAAAAAA"), 0.0);
    }

    #[test]
    fn shannon_entropy_of_two_balanced_chars_is_one_bit() {
        let h = shannon_entropy("ABABABAB");
        assert!((h - 1.0).abs() < 1e-9);
    }

    #[test]
    fn shannon_entropy_of_canonical_aws_example_clears_default_threshold() {
        let h = shannon_entropy("AKIAIOSFODNN7EXAMPLE");
        assert!(h >= DEFAULT_MIN_ENTROPY);
    }

    #[test]
    fn shannon_entropy_of_low_entropy_aws_placeholder_is_below_threshold() {
        let h = shannon_entropy("AKIAAAAAAAAAAAAAAAAA");
        assert!(h < DEFAULT_MIN_ENTROPY);
    }

    #[test]
    fn entropy_filter_rejects_uniform_aws_match() {
        let patterns = match compiled_patterns() {
            Ok(p) => p,
            Err(_) => return,
        };
        let aws = patterns.iter().find(|p| p.code == "RSTR-SEC-001");
        assert!(aws.is_some());
        if let Some(p) = aws {
            let placeholder = "AKIAAAAAAAAAAAAAAAAA";
            let captured = p.regex.find(placeholder);
            assert!(captured.is_some());
            if let Some(m) = captured {
                assert!(shannon_entropy(m.as_str()) < DEFAULT_MIN_ENTROPY);
            }
        }
    }

    #[test]
    fn pem_private_key_marker_has_no_entropy_threshold() {
        let patterns = match compiled_patterns() {
            Ok(p) => p,
            Err(_) => return,
        };
        let pem = patterns.iter().find(|p| p.code == "RSTR-SEC-007");
        assert!(pem.is_some());
        if let Some(p) = pem {
            assert!(p.min_entropy.is_none());
        }
    }

    #[test]
    fn token_patterns_have_default_entropy_threshold() {
        let patterns = match compiled_patterns() {
            Ok(p) => p,
            Err(_) => return,
        };
        for p in patterns.iter().filter(|p| p.code != "RSTR-SEC-007") {
            assert_eq!(p.min_entropy, Some(DEFAULT_MIN_ENTROPY));
        }
    }
}