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
// src/analysis/usage_tracker.rs

use std::collections::HashMap;
use std::path::PathBuf;

use syn::visit::Visit;
use syn::{Expr, ExprPath, File};

/// Kind of usage for a constant
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UsageKind {
    /// Used in an equality comparison (==, !=)
    Comparison,
    /// Used in a function call argument
    FunctionArg { function: String, arg_position: usize },
    /// Used in a method call
    MethodCall { method: String },
    /// Used in an assignment
    Assignment,
    /// Used in a return statement
    Return,
    /// Used in a match pattern
    MatchPattern,
    /// Used in a field initialization
    FieldInit { struct_name: String, field: String },
    /// Other usage
    Other,
}

/// A usage of a constant
#[derive(Debug, Clone)]
pub struct ConstantUsage {
    /// Name of the constant
    pub constant_name: String,

    /// Kind of usage
    pub kind: UsageKind,

    /// Line number
    pub line: u32,

    /// Function where the usage occurs (if any)
    pub in_function: Option<String>,

    /// Whether in a test context
    pub in_test: bool,
}

/// Tracks usage of constants throughout a file
pub struct UsageTracker {
    /// Known constant names to track
    constants_to_track: Vec<String>,

    /// Collected usages
    usages: Vec<ConstantUsage>,

    /// Current function
    current_function: Option<String>,

    /// Whether in test context
    in_test: bool,

    /// File being analyzed
    file_path: PathBuf,
}

impl UsageTracker {
    pub fn new(file_path: PathBuf, constants_to_track: Vec<String>) -> Self {
        Self {
            constants_to_track,
            usages: Vec::new(),
            current_function: None,
            in_test: false,
            file_path,
        }
    }

    /// Track usages of specified constants in a file
    pub fn track(
        file_path: PathBuf,
        file: &File,
        constants_to_track: Vec<String>,
    ) -> Vec<ConstantUsage> {
        let mut tracker = Self::new(file_path, constants_to_track);
        tracker.visit_file(file);
        tracker.usages
    }

    /// Track all uppercase identifiers (potential constants)
    pub fn track_all(file_path: PathBuf, file: &File) -> Vec<ConstantUsage> {
        let mut tracker = Self::new(file_path, Vec::new());
        tracker.constants_to_track = Vec::new(); // Track all
        tracker.visit_file(file);
        tracker.usages
    }

    /// Check if a name is a constant we're tracking
    fn is_tracked(&self, name: &str) -> bool {
        if self.constants_to_track.is_empty() {
            // Track all uppercase identifiers
            name.chars()
                .all(|c| c.is_uppercase() || c == '_' || c.is_numeric())
                && !name.is_empty()
                && name.chars().next().map(|c| c.is_alphabetic()).unwrap_or(false)
        } else {
            self.constants_to_track.contains(&name.to_string())
        }
    }

    /// Record a usage
    fn record_usage(&mut self, name: String, kind: UsageKind, line: u32) {
        self.usages.push(ConstantUsage {
            constant_name: name,
            kind,
            line,
            in_function: self.current_function.clone(),
            in_test: self.in_test,
        });
    }

    /// Get usages grouped by constant name
    pub fn usages_by_constant(&self) -> HashMap<String, Vec<&ConstantUsage>> {
        let mut map: HashMap<String, Vec<&ConstantUsage>> = HashMap::new();
        for usage in &self.usages {
            map.entry(usage.constant_name.clone())
                .or_default()
                .push(usage);
        }
        map
    }

    /// Get the collected usages
    pub fn usages(&self) -> &[ConstantUsage] {
        &self.usages
    }

    /// Take ownership of results
    pub fn into_usages(self) -> Vec<ConstantUsage> {
        self.usages
    }
}

impl<'ast> Visit<'ast> for UsageTracker {
    fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
        // Check for comparisons
        if matches!(node.op, syn::BinOp::Eq(_) | syn::BinOp::Ne(_)) {
            // Check left side
            if let Expr::Path(path) = &*node.left {
                if let Some(name) = path.path.get_ident().map(|i| i.to_string()) {
                    if self.is_tracked(&name) {
                        self.record_usage(
                            name,
                            UsageKind::Comparison,
                            path.path.segments.first().map(|s| s.ident.span().start().line as u32).unwrap_or(0),
                        );
                    }
                }
            }

            // Check right side
            if let Expr::Path(path) = &*node.right {
                if let Some(name) = path.path.get_ident().map(|i| i.to_string()) {
                    if self.is_tracked(&name) {
                        self.record_usage(
                            name,
                            UsageKind::Comparison,
                            path.path.segments.first().map(|s| s.ident.span().start().line as u32).unwrap_or(0),
                        );
                    }
                }
            }
        }

        syn::visit::visit_expr_binary(self, node);
    }

    fn visit_expr_call(&mut self, node: &'ast syn::ExprCall) {
        // Get function name
        let function = quote::quote!(#node.func).to_string();

        // Check arguments
        for (pos, arg) in node.args.iter().enumerate() {
            if let Expr::Path(path) = arg {
                if let Some(name) = path.path.get_ident().map(|i| i.to_string()) {
                    if self.is_tracked(&name) {
                        self.record_usage(
                            name,
                            UsageKind::FunctionArg {
                                function: function.clone(),
                                arg_position: pos,
                            },
                            path.path.segments.first().map(|s| s.ident.span().start().line as u32).unwrap_or(0),
                        );
                    }
                }
            }
        }

        syn::visit::visit_expr_call(self, node);
    }

    fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
        let method = node.method.to_string();

        // Check receiver
        if let Expr::Path(path) = &*node.receiver {
            if let Some(name) = path.path.get_ident().map(|i| i.to_string()) {
                if self.is_tracked(&name) {
                    self.record_usage(
                        name,
                        UsageKind::MethodCall {
                            method: method.clone(),
                        },
                        path.path.segments.first().map(|s| s.ident.span().start().line as u32).unwrap_or(0),
                    );
                }
            }
        }

        // Check arguments
        for arg in &node.args {
            if let Expr::Path(path) = arg {
                if let Some(name) = path.path.get_ident().map(|i| i.to_string()) {
                    if self.is_tracked(&name) {
                        self.record_usage(
                            name,
                            UsageKind::FunctionArg {
                                function: format!(".{}", method),
                                arg_position: 0,
                            },
                            path.path.segments.first().map(|s| s.ident.span().start().line as u32).unwrap_or(0),
                        );
                    }
                }
            }
        }

        syn::visit::visit_expr_method_call(self, node);
    }

    fn visit_expr_return(&mut self, node: &'ast syn::ExprReturn) {
        if let Some(Expr::Path(path)) = &node.expr.as_deref() {
            if let Some(name) = path.path.get_ident().map(|i| i.to_string()) {
                if self.is_tracked(&name) {
                    self.record_usage(
                        name,
                        UsageKind::Return,
                        path.path.segments.first().map(|s| s.ident.span().start().line as u32).unwrap_or(0),
                    );
                }
            }
        }

        syn::visit::visit_expr_return(self, node);
    }

    fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
        let struct_name = quote::quote!(#node.path).to_string();

        for field in &node.fields {
            if let syn::Member::Named(field_name) = &field.member {
                if let Expr::Path(path) = &field.expr {
                    if let Some(name) = path.path.get_ident().map(|i| i.to_string()) {
                        if self.is_tracked(&name) {
                            self.record_usage(
                                name,
                                UsageKind::FieldInit {
                                    struct_name: struct_name.clone(),
                                    field: field_name.to_string(),
                                },
                                path.path.segments.first().map(|s| s.ident.span().start().line as u32).unwrap_or(0),
                            );
                        }
                    }
                }
            }
        }

        syn::visit::visit_expr_struct(self, node);
    }

    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        let old_function = self.current_function.take();
        let old_test = self.in_test;

        self.current_function = Some(node.sig.ident.to_string());

        // Check if this is a test function
        let is_test = node.attrs.iter().any(|attr| {
            attr.path().is_ident("test")
                || attr
                    .path()
                    .segments
                    .last()
                    .map(|s| s.ident == "test")
                    .unwrap_or(false)
        });

        if is_test {
            self.in_test = true;
        }

        syn::visit::visit_item_fn(self, node);

        self.current_function = old_function;
        self.in_test = old_test;
    }

    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
        let old_test = self.in_test;

        // Check if this is a test module
        let is_test_mod = node.ident == "tests"
            || node.ident == "test"
            || node.attrs.iter().any(|attr| {
                if attr.path().is_ident("cfg") {
                    if let Ok(meta) = attr.meta.require_list() {
                        return meta.tokens.to_string().contains("test");
                    }
                }
                false
            });

        if is_test_mod {
            self.in_test = true;
        }

        syn::visit::visit_item_mod(self, node);

        self.in_test = old_test;
    }
}

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

    #[test]
    fn test_track_comparison_usage() {
        let code = r#"
            const TOKEN: &str = "secret";
            fn check(input: &str) -> bool {
                input == TOKEN
            }
        "#;

        let file: syn::File = syn::parse_str(code).unwrap();
        let usages = UsageTracker::track(
            PathBuf::from("test.rs"),
            &file,
            vec!["TOKEN".to_string()],
        );

        assert_eq!(usages.len(), 1);
        assert_eq!(usages[0].constant_name, "TOKEN");
        assert!(matches!(usages[0].kind, UsageKind::Comparison));
    }

    #[test]
    fn test_track_function_arg() {
        let code = r#"
            const API_KEY: &str = "key";
            fn main() {
                authenticate(API_KEY);
            }
        "#;

        let file: syn::File = syn::parse_str(code).unwrap();
        let usages = UsageTracker::track(
            PathBuf::from("test.rs"),
            &file,
            vec!["API_KEY".to_string()],
        );

        assert_eq!(usages.len(), 1);
        assert!(matches!(
            &usages[0].kind,
            UsageKind::FunctionArg { function, arg_position: 0 } if function.contains("authenticate")
        ));
    }

    #[test]
    fn test_track_all_uppercase() {
        let code = r#"
            fn main() {
                if x == TOKEN {}
                call(SECRET);
            }
        "#;

        let file: syn::File = syn::parse_str(code).unwrap();
        let usages = UsageTracker::track_all(PathBuf::from("test.rs"), &file);

        assert_eq!(usages.len(), 2);
        assert!(usages.iter().any(|u| u.constant_name == "TOKEN"));
        assert!(usages.iter().any(|u| u.constant_name == "SECRET"));
    }

    #[test]
    fn test_function_context() {
        let code = r#"
            fn authenticate() {
                check(TOKEN);
            }
        "#;

        let file: syn::File = syn::parse_str(code).unwrap();
        let usages = UsageTracker::track_all(PathBuf::from("test.rs"), &file);

        assert_eq!(usages.len(), 1);
        assert_eq!(usages[0].in_function, Some("authenticate".to_string()));
    }

    #[test]
    fn test_test_context() {
        let code = r#"
            #[test]
            fn test_auth() {
                assert!(x == TOKEN);
            }
        "#;

        let file: syn::File = syn::parse_str(code).unwrap();
        let usages = UsageTracker::track_all(PathBuf::from("test.rs"), &file);

        assert!(usages.iter().all(|u| u.in_test));
    }
}