vsec 0.0.1

Detect secrets and in Rust codebases
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
// src/filters/layer1_names.rs

use crate::models::{FactorCategory, ScoreFactor};
use crate::simd;

/// Configuration for benign name filtering
#[derive(Debug, Clone)]
pub struct BenignNameConfig {
    /// Terms that indicate a benign constant (case-insensitive)
    pub benign_terms: Vec<TermMatcher>,

    /// Terms that indicate a suspicious constant (raise score)
    pub suspicious_terms: Vec<TermMatcher>,

    /// Exact names to always ignore
    pub exact_ignore: Vec<String>,

    /// Regex patterns to ignore
    pub patterns_ignore: Vec<String>,
}

impl Default for BenignNameConfig {
    fn default() -> Self {
        Self {
            benign_terms: default_benign_terms(),
            suspicious_terms: default_suspicious_terms(),
            exact_ignore: vec![],
            patterns_ignore: vec![],
        }
    }
}

/// A term to match against names
#[derive(Debug, Clone)]
pub struct TermMatcher {
    /// The term to match
    pub term: String,

    /// Score modification when matched
    pub score_mod: i32,

    /// Human-readable reason
    pub reason: &'static str,

    /// Match mode
    pub mode: MatchMode,
}

#[derive(Debug, Clone, Copy)]
pub enum MatchMode {
    /// Name contains this term
    Contains,
    /// Name starts with this term
    Prefix,
    /// Name ends with this term
    Suffix,
    /// Exact match
    Exact,
}

fn default_benign_terms() -> Vec<TermMatcher> {
    vec![
        // Metadata - Always benign
        TermMatcher {
            term: "version".into(),
            score_mod: -100,
            reason: "Version identifiers are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "pkg_name".into(),
            score_mod: -100,
            reason: "Package names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "crate_name".into(),
            score_mod: -100,
            reason: "Crate names are not secrets",
            mode: MatchMode::Contains,
        },
        // Protocol/Format details
        TermMatcher {
            term: "mime".into(),
            score_mod: -100,
            reason: "MIME types are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "content_type".into(),
            score_mod: -100,
            reason: "Content types are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "encoding".into(),
            score_mod: -100,
            reason: "Encoding names are not secrets",
            mode: MatchMode::Contains,
        },
        // Config defaults
        TermMatcher {
            term: "default_".into(),
            score_mod: -50,
            reason: "Default values are often not secrets",
            mode: MatchMode::Prefix,
        },
        TermMatcher {
            term: "_default".into(),
            score_mod: -50,
            reason: "Default values are often not secrets",
            mode: MatchMode::Suffix,
        },
        // Paths and URLs (public)
        TermMatcher {
            term: "path".into(),
            score_mod: -60,
            reason: "Paths are typically not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "endpoint".into(),
            score_mod: -40,
            reason: "Endpoint names are often not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "route".into(),
            score_mod: -60,
            reason: "Routes are typically not secrets",
            mode: MatchMode::Contains,
        },
        // Parsing/Protocol magic
        TermMatcher {
            term: "magic".into(),
            score_mod: -100,
            reason: "Magic numbers/bytes are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "delimiter".into(),
            score_mod: -100,
            reason: "Delimiters are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "separator".into(),
            score_mod: -100,
            reason: "Separators are not secrets",
            mode: MatchMode::Contains,
        },
        // UI constants
        TermMatcher {
            term: "color".into(),
            score_mod: -100,
            reason: "Colors are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "theme".into(),
            score_mod: -100,
            reason: "Theme names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "font".into(),
            score_mod: -100,
            reason: "Font names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "style".into(),
            score_mod: -100,
            reason: "Style names are not secrets",
            mode: MatchMode::Contains,
        },
        // Error messages
        TermMatcher {
            term: "error_".into(),
            score_mod: -80,
            reason: "Error messages are typically not secrets",
            mode: MatchMode::Prefix,
        },
        TermMatcher {
            term: "_error".into(),
            score_mod: -80,
            reason: "Error messages are typically not secrets",
            mode: MatchMode::Suffix,
        },
        // Status/State names
        TermMatcher {
            term: "status".into(),
            score_mod: -60,
            reason: "Status names are typically not secrets",
            mode: MatchMode::Contains,
        },
        // Documentation
        TermMatcher {
            term: "description".into(),
            score_mod: -100,
            reason: "Descriptions are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "help".into(),
            score_mod: -100,
            reason: "Help text is not a secret",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "usage".into(),
            score_mod: -100,
            reason: "Usage text is not a secret",
            mode: MatchMode::Contains,
        },
        // Configuration/Protocol keys (used for map lookups, headers, etc.)
        TermMatcher {
            term: "topic".into(),
            score_mod: -100,
            reason: "Topic names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "checksum".into(),
            score_mod: -100,
            reason: "Checksum type names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "comment".into(),
            score_mod: -100,
            reason: "Comment field names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "broker".into(),
            score_mod: -50,
            reason: "Broker addresses are typically not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "acl".into(),
            score_mod: -50,
            reason: "ACL field names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "hash".into(),
            score_mod: -50,
            reason: "Hash type names are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "header".into(),
            score_mod: -80,
            reason: "Header names are typically not secrets",
            mode: MatchMode::Contains,
        },
        // Prefix/Suffix patterns (often used for string construction, not secrets)
        TermMatcher {
            term: "prefix".into(),
            score_mod: -100,
            reason: "Prefix strings are typically not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "suffix".into(),
            score_mod: -100,
            reason: "Suffix strings are typically not secrets",
            mode: MatchMode::Contains,
        },
        // URN/URI identifiers
        TermMatcher {
            term: "urn".into(),
            score_mod: -100,
            reason: "URN identifiers are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "namespace".into(),
            score_mod: -100,
            reason: "Namespace identifiers are not secrets",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "schema".into(),
            score_mod: -80,
            reason: "Schema names are typically not secrets",
            mode: MatchMode::Contains,
        },
    ]
}

fn default_suspicious_terms() -> Vec<TermMatcher> {
    vec![
        // Authentication
        TermMatcher {
            term: "token".into(),
            score_mod: 25,
            reason: "Tokens are often sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "secret".into(),
            score_mod: 35,
            reason: "Named 'secret' suggests sensitivity",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "key".into(),
            score_mod: 20,
            reason: "Keys are often sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "password".into(),
            score_mod: 40,
            reason: "Passwords are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "passwd".into(),
            score_mod: 40,
            reason: "Passwords are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "auth".into(),
            score_mod: 25,
            reason: "Authentication-related values are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "credential".into(),
            score_mod: 35,
            reason: "Credentials are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "private".into(),
            score_mod: 30,
            reason: "Private values are sensitive",
            mode: MatchMode::Contains,
        },
        // API keys
        TermMatcher {
            term: "api_key".into(),
            score_mod: 35,
            reason: "API keys are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "apikey".into(),
            score_mod: 35,
            reason: "API keys are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "access_key".into(),
            score_mod: 35,
            reason: "Access keys are sensitive",
            mode: MatchMode::Contains,
        },
        // Cryptographic
        TermMatcher {
            term: "signing".into(),
            score_mod: 25,
            reason: "Signing keys are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "hmac".into(),
            score_mod: 25,
            reason: "HMAC secrets are sensitive",
            mode: MatchMode::Contains,
        },
        // Database
        TermMatcher {
            term: "db_pass".into(),
            score_mod: 40,
            reason: "Database passwords are sensitive",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "connection_string".into(),
            score_mod: 30,
            reason: "Connection strings may contain credentials",
            mode: MatchMode::Contains,
        },
        // Admin/Backdoor
        TermMatcher {
            term: "admin".into(),
            score_mod: 15,
            reason: "Admin-related constants need scrutiny",
            mode: MatchMode::Contains,
        },
        TermMatcher {
            term: "backdoor".into(),
            score_mod: 50,
            reason: "Backdoor terminology is highly suspicious",
            mode: MatchMode::Contains,
        },
    ]
}

/// The benign name filter
pub struct BenignNameFilter {
    config: BenignNameConfig,
    compiled_patterns: Vec<regex::Regex>,
}

impl BenignNameFilter {
    pub fn new(config: BenignNameConfig) -> Result<Self, regex::Error> {
        let compiled_patterns = config
            .patterns_ignore
            .iter()
            .map(|p| regex::Regex::new(p))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(Self {
            config,
            compiled_patterns,
        })
    }

    /// Analyze a name and return scoring factors
    pub fn analyze(&self, name: &str) -> Vec<ScoreFactor> {
        let mut factors = Vec::new();
        // Use SIMD-accelerated lowercase conversion
        let lower_name = simd::to_ascii_lowercase(name);

        // Check exact ignore list
        if self
            .config
            .exact_ignore
            .iter()
            .any(|n| n.eq_ignore_ascii_case(name))
        {
            factors.push(ScoreFactor::kill(
                "exact_ignore",
                format!("Name '{}' is in the ignore list", name),
            ));
            return factors;
        }

        // Check regex patterns
        for pattern in &self.compiled_patterns {
            if pattern.is_match(name) {
                factors.push(ScoreFactor::kill(
                    "pattern_ignore",
                    format!(
                        "Name '{}' matches ignore pattern '{}'",
                        name,
                        pattern.as_str()
                    ),
                ));
                return factors;
            }
        }

        // Check benign terms
        for term in &self.config.benign_terms {
            if self.term_matches(&lower_name, term) {
                factors.push(
                    ScoreFactor::new(
                        format!("benign_term:{}", term.term),
                        FactorCategory::Name,
                        term.score_mod,
                        term.reason,
                    )
                    .with_evidence(format!("Name '{}' contains '{}'", name, term.term)),
                );
            }
        }

        // Check suspicious terms (only if not killed by benign)
        let killed = factors.iter().any(|f| f.contribution <= -100);
        if !killed {
            for term in &self.config.suspicious_terms {
                if self.term_matches(&lower_name, term) {
                    factors.push(
                        ScoreFactor::new(
                            format!("suspicious_term:{}", term.term),
                            FactorCategory::Name,
                            term.score_mod,
                            term.reason,
                        )
                        .with_evidence(format!("Name '{}' contains '{}'", name, term.term)),
                    );
                }
            }
        }

        factors
    }

    fn term_matches(&self, name: &str, term: &TermMatcher) -> bool {
        // Use SIMD-accelerated lowercase for term
        let term_lower = simd::to_ascii_lowercase(&term.term);
        match term.mode {
            MatchMode::Contains => name.contains(&term_lower),
            MatchMode::Prefix => name.starts_with(&term_lower),
            MatchMode::Suffix => name.ends_with(&term_lower),
            MatchMode::Exact => name == term_lower,
        }
    }

    /// Quick check if a name is definitely benign (for early filtering)
    pub fn is_definitely_benign(&self, name: &str) -> bool {
        // Use SIMD-accelerated lowercase conversion
        let lower_name = simd::to_ascii_lowercase(name);

        // Check for kill-level benign terms
        self.config
            .benign_terms
            .iter()
            .filter(|t| t.score_mod <= -100)
            .any(|t| self.term_matches(&lower_name, t))
    }
}

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

    #[test]
    fn test_version_is_benign() {
        let filter = BenignNameFilter::new(BenignNameConfig::default()).unwrap();
        assert!(filter.is_definitely_benign("VERSION"));
        assert!(filter.is_definitely_benign("PROTOCOL_VERSION"));
        assert!(filter.is_definitely_benign("api_version"));
    }

    #[test]
    fn test_secret_is_suspicious() {
        let filter = BenignNameFilter::new(BenignNameConfig::default()).unwrap();
        let factors = filter.analyze("API_SECRET");
        let total: i32 = factors.iter().map(|f| f.contribution).sum();
        assert!(total > 0, "API_SECRET should have positive score");
    }

    #[test]
    fn test_auth_token_is_very_suspicious() {
        let filter = BenignNameFilter::new(BenignNameConfig::default()).unwrap();
        let factors = filter.analyze("GRPC_AUTH_TOKEN");
        let total: i32 = factors.iter().map(|f| f.contribution).sum();
        assert!(total >= 40, "GRPC_AUTH_TOKEN should have high score");
    }
}