repotoire 0.3.112

Graph-powered code analysis CLI. 114 detectors for security, architecture, and code quality.
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
//! Insecure Random Detector
//!
//! Graph-enhanced detection of insecure random:
//! - Trace random values through function calls to security contexts
//! - Check if random is used for IDs, tokens, or passwords
//! - Language-specific secure alternatives

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphStore;
use crate::models::{deterministic_finding_id, Finding, Severity};
use anyhow::Result;
use regex::Regex;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::OnceLock;
use tracing::info;

static INSECURE_RANDOM: OnceLock<Regex> = OnceLock::new();

fn insecure_random() -> &'static Regex {
    INSECURE_RANDOM.get_or_init(|| {
        Regex::new(r"(?i)(Math\.random\(\)|random\.random\(\)|random\.randint|rand\(\)|srand\(|mt_rand|lcg_value|uniqid)").expect("valid regex")
    })
}

/// Get secure alternative for each language
fn get_secure_alternative(ext: &str) -> &'static str {
    match ext {
        "py" => {
            "```python\n\
                 import secrets\n\
                 \n\
                 # For tokens/passwords\n\
                 token = secrets.token_urlsafe(32)\n\
                 \n\
                 # For random integers\n\
                 num = secrets.randbelow(100)\n\
                 \n\
                 # For random bytes\n\
                 data = secrets.token_bytes(16)\n\
                 ```"
        }
        "js" | "ts" => {
            "```javascript\n\
                        // Node.js\n\
                        const crypto = require('crypto');\n\
                        const token = crypto.randomBytes(32).toString('hex');\n\
                        \n\
                        // Browser\n\
                        const array = new Uint8Array(32);\n\
                        crypto.getRandomValues(array);\n\
                        ```"
        }
        "java" => {
            "```java\n\
                   import java.security.SecureRandom;\n\
                   \n\
                   SecureRandom random = new SecureRandom();\n\
                   byte[] bytes = new byte[32];\n\
                   random.nextBytes(bytes);\n\
                   ```"
        }
        "go" => {
            "```go\n\
                 import \"crypto/rand\"\n\
                 \n\
                 bytes := make([]byte, 32)\n\
                 rand.Read(bytes)\n\
                 ```"
        }
        "php" => {
            "```php\n\
                  // PHP 7+\n\
                  $bytes = random_bytes(32);\n\
                  $token = bin2hex($bytes);\n\
                  ```"
        }
        "rb" => {
            "```ruby\n\
                 require 'securerandom'\n\
                 \n\
                 token = SecureRandom.hex(32)\n\
                 ```"
        }
        "c" | "cpp" => {
            "```c\n\
                        // Linux\n\
                        #include <sys/random.h>\n\
                        getrandom(buffer, size, 0);\n\
                        \n\
                        // Or read from /dev/urandom\n\
                        ```"
        }
        _ => "Use your platform's cryptographic random number generator.",
    }
}

pub struct InsecureRandomDetector {
    repository_path: PathBuf,
    max_findings: usize,
}

impl InsecureRandomDetector {
    pub fn new(repository_path: impl Into<PathBuf>) -> Self {
        Self {
            repository_path: repository_path.into(),
            max_findings: 50,
        }
    }

    /// Check what the random value is used for
    fn analyze_usage(line: &str, surrounding: &str) -> (SecurityContext, String) {
        let combined = format!("{} {}", line, surrounding).to_lowercase();

        // Token/secret generation
        if combined.contains("token") || combined.contains("secret") || combined.contains("api_key")
        {
            return (
                SecurityContext::Token,
                "token/secret generation".to_string(),
            );
        }

        // Password/salt
        if combined.contains("password") || combined.contains("salt") || combined.contains("hash") {
            return (
                SecurityContext::Password,
                "password/salt generation".to_string(),
            );
        }

        // Session/auth
        if combined.contains("session") || combined.contains("auth") || combined.contains("login") {
            return (
                SecurityContext::Session,
                "session/authentication".to_string(),
            );
        }

        // ID generation — only flag security-sensitive IDs, not trace/metric/display IDs
        if combined.contains("uuid") || combined.contains("identifier") {
            return (SecurityContext::ID, "ID generation".to_string());
        }
        // Security-sensitive ID patterns
        if (combined.contains("session_id") || combined.contains("sessionid")
            || combined.contains("user_id") || combined.contains("userid")
            || combined.contains("auth_id") || combined.contains("api_id"))
            && !combined.contains("trace") && !combined.contains("metric")
            && !combined.contains("display") && !combined.contains("record")
            && !combined.contains("internal") && !combined.contains("log")
        {
            return (SecurityContext::ID, "ID generation".to_string());
        }

        // Crypto
        if combined.contains("crypto")
            || combined.contains("encrypt")
            || combined.contains("key")
            || combined.contains("iv")
            || combined.contains("nonce")
        {
            return (
                SecurityContext::Crypto,
                "cryptographic operation".to_string(),
            );
        }

        // OTP/verification
        if combined.contains("otp")
            || combined.contains("code")
            || combined.contains("verification")
            || combined.contains("pin")
        {
            return (SecurityContext::OTP, "OTP/verification code".to_string());
        }

        (SecurityContext::Unknown, "unknown".to_string())
    }

    /// Find functions that use insecure random and are called by security-related code
    fn find_security_callers(
        &self,
        graph: &dyn crate::graph::GraphQuery,
        func_name: &str,
    ) -> Vec<String> {
        let mut security_callers = Vec::new();

        if let Some(func) = graph
            .get_functions()
            .into_iter()
            .find(|f| f.name == func_name)
        {
            let callers = graph.get_callers(&func.qualified_name);

            for caller in callers {
                let caller_lower = caller.name.to_lowercase();
                if caller_lower.contains("auth")
                    || caller_lower.contains("login")
                    || caller_lower.contains("token")
                    || caller_lower.contains("session")
                    || caller_lower.contains("password")
                    || caller_lower.contains("secret")
                {
                    security_callers.push(caller.name.clone());
                }
            }
        }

        security_callers
    }

    /// Find containing function
    fn find_containing_function(
        graph: &dyn crate::graph::GraphQuery,
        file_path: &str,
        line: u32,
    ) -> Option<String> {
        graph
            .get_functions()
            .into_iter()
            .find(|f| f.file_path == file_path && f.line_start <= line && f.line_end >= line)
            .map(|f| f.name)
    }
}

#[derive(PartialEq)]
enum SecurityContext {
    Token,
    Password,
    Session,
    ID,
    Crypto,
    OTP,
    Unknown,
}

impl Detector for InsecureRandomDetector {
    fn name(&self) -> &'static str {
        "insecure-random"
    }
    fn description(&self) -> &'static str {
        "Detects insecure random for security purposes"
    }

    fn detect(&self, graph: &dyn crate::graph::GraphQuery) -> Result<Vec<Finding>> {
        let mut findings = vec![];
        let walker = ignore::WalkBuilder::new(&self.repository_path)
            .hidden(false)
            .git_ignore(true)
            .build();

        for entry in walker.filter_map(|e| e.ok()) {
            if findings.len() >= self.max_findings {
                break;
            }
            let path = entry.path();
            if !path.is_file() {
                continue;
            }

            let path_str = path.to_string_lossy().to_string();

            // Skip test files
            if crate::detectors::base::is_test_path(&path_str) {
                continue;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if !matches!(
                ext,
                "py" | "js" | "ts" | "java" | "go" | "rb" | "php" | "c" | "cpp"
            ) {
                continue;
            }

            if let Some(content) = crate::cache::global_cache().get_content(path) {
                let lines: Vec<&str> = content.lines().collect();

                for (i, line) in lines.iter().enumerate() {
                    if insecure_random().is_match(line) {
                        let start = i.saturating_sub(5);
                        let end = (i + 5).min(lines.len());
                        let surrounding = lines[start..end].join(" ");

                        let (context, usage) = Self::analyze_usage(line, &surrounding);
                        let containing_func =
                            Self::find_containing_function(graph, &path_str, (i + 1) as u32);

                        // Check if function is called by security code
                        let security_callers = if let Some(ref func) = containing_func {
                            self.find_security_callers(graph, func)
                        } else {
                            vec![]
                        };

                        // Only flag if in security context
                        if context == SecurityContext::Unknown && security_callers.is_empty() {
                            continue;
                        }

                        // For ID context: only flag if it looks like a *security-critical* ID
                        // (session ID, CSRF token, auth token). Skip trace IDs, metric IDs,
                        // display IDs, record IDs, game logic IDs — these don't need crypto-secure random.
                        if context == SecurityContext::ID && security_callers.is_empty() {
                            let line_lower = line.to_lowercase();
                            let is_safe_id = line_lower.contains("traceid")
                                || line_lower.contains("trace_id")
                                || line_lower.contains("metricid")
                                || line_lower.contains("metric_id")
                                || line_lower.contains("displayid")
                                || line_lower.contains("display_id")
                                || line_lower.contains("recordid")
                                || line_lower.contains("record_id")
                                || line_lower.contains("requestid")
                                || line_lower.contains("request_id")
                                || line_lower.contains("gameid")
                                || line_lower.contains("game_id")
                                || line_lower.contains("itemid")
                                || line_lower.contains("item_id")
                                // session and auth IDs are security-critical; keep flagging those
                                ;
                            // Also skip if it's clearly a non-security random use:
                            // e.g. Math.random() for game logic, UI jitter, test data
                            let is_game_or_ui = line_lower.contains("game")
                                || line_lower.contains("jitter")
                                || line_lower.contains("color")
                                || line_lower.contains("animation")
                                || line_lower.contains("position")
                                || line_lower.contains("offset")
                                || line_lower.contains("delay");
                            if is_safe_id || is_game_or_ui {
                                continue;
                            }
                        }

                        // Calculate severity
                        let severity = match context {
                            SecurityContext::Crypto | SecurityContext::Password => {
                                Severity::Critical
                            }
                            SecurityContext::Token
                            | SecurityContext::Session
                            | SecurityContext::OTP => Severity::High,
                            SecurityContext::ID => Severity::Medium,
                            SecurityContext::Unknown if !security_callers.is_empty() => {
                                Severity::High
                            }
                            _ => Severity::Medium,
                        };

                        // Build notes
                        let mut notes = Vec::new();
                        notes.push(format!("🎯 Used for: {}", usage));
                        if let Some(func) = &containing_func {
                            notes.push(format!("📦 In function: `{}`", func));
                        }
                        if !security_callers.is_empty() {
                            notes.push(format!(
                                "⚠️ Called by security functions: {}",
                                security_callers.join(", ")
                            ));
                        }

                        let context_notes = format!("\n\n**Analysis:**\n{}", notes.join("\n"));

                        let random_func = insecure_random()
                            .find(line)
                            .map(|m| m.as_str())
                            .unwrap_or("random");

                        findings.push(Finding {
                            id: String::new(),
                            detector: "InsecureRandomDetector".to_string(),
                            severity,
                            title: format!("Insecure `{}` used for {}", random_func, usage),
                            description: format!(
                                "`{}` is not cryptographically secure and can be predicted by attackers.{}",
                                random_func, context_notes
                            ),
                            affected_files: vec![path.to_path_buf()],
                            line_start: Some((i + 1) as u32),
                            line_end: Some((i + 1) as u32),
                            suggested_fix: Some(format!(
                                "Use a cryptographically secure random number generator:\n\n{}",
                                get_secure_alternative(ext)
                            )),
                            estimated_effort: Some("15 minutes".to_string()),
                            category: Some("security".to_string()),
                            cwe_id: Some("CWE-330".to_string()),
                            why_it_matters: Some(
                                "Insecure random number generators (like Math.random or random.random) \
                                 use predictable algorithms. Attackers can often guess the output and \
                                 forge tokens, guess passwords, or bypass authentication.".to_string()
                            ),
                            ..Default::default()
                        });
                    }
                }
            }
        }

        info!(
            "InsecureRandomDetector found {} findings (graph-aware)",
            findings.len()
        );
        Ok(findings)
    }
}