jsxbin-analyzer 1.0.0

Comprehensive code analyzer for JSX with dependency detection, API classification, and security scanning
Documentation
use crate::types::{SecurityIssue, SecurityIssueType, Severity};
use jsxbin_parser::types::Token;
use log::{debug, trace};
use regex::Regex;

/// Scans code for security vulnerabilities
pub struct SecurityScanner {
    eval_regex: Regex,
    exec_regex: Regex,
    credential_regex: Regex,
    sql_injection_regex: Regex,
}

impl SecurityScanner {
    /// Create a new security scanner
    pub fn new() -> Self {
        SecurityScanner {
            eval_regex: Regex::new(r"eval\s*\(").unwrap(),
            exec_regex: Regex::new(r"(exec|execute)\s*\(").unwrap(),
            credential_regex: Regex::new(
                r#"(password|api_key|api_secret|token|auth|credential)\s*[:=]\s*['"][\w\-]+['"]"#,
            )
            .unwrap(),
            sql_injection_regex: Regex::new(r"SELECT|INSERT|UPDATE|DELETE.*\+").unwrap(),
        }
    }

    /// Scan tokens for security issues
    pub fn scan_tokens(&self, tokens: &[Token]) -> Vec<SecurityIssue> {
        debug!("Scanning tokens for security issues");
        let mut issues = Vec::new();

        for token in tokens {
            self.scan_token(token, &mut issues);
        }

        debug!("Found {} security issues", issues.len());
        issues
    }

    fn scan_token(&self, token: &Token, issues: &mut Vec<SecurityIssue>) {
        match token {
            Token::Identifier(name) => {
                if name == "eval" {
                    trace!("Found eval() usage");
                    issues.push(SecurityIssue {
                        issue_type: SecurityIssueType::EvalUsage,
                        description: "Usage of eval() detected - highly risky for code injection".to_string(),
                        severity: Severity::Critical,
                        location: Some(name.clone()),
                    });
                }
            }

            Token::StringLiteral(s) => {
                // Check for hardcoded credentials
                if s.contains("password")
                    || s.contains("api_key")
                    || s.contains("secret")
                    || s.contains("token")
                {
                    trace!("Found potential hardcoded credential: {}", s);
                    issues.push(SecurityIssue {
                        issue_type: SecurityIssueType::HardcodedCredentials,
                        description: format!(
                            "Potential hardcoded credential detected: {}",
                            Self::redact_string(s)
                        ),
                        severity: Severity::High,
                        location: None,
                    });
                }

                // Check for SQL injection patterns
                if s.contains("SELECT ")
                    || s.contains("INSERT ")
                    || s.contains("UPDATE ")
                    || s.contains("DELETE ")
                {
                    if s.contains("+") || s.contains("concat") {
                        trace!("Found potential SQL injection: {}", s);
                        issues.push(SecurityIssue {
                            issue_type: SecurityIssueType::CommandInjection,
                            description:
                                "Potential SQL injection vulnerability detected".to_string(),
                            severity: Severity::High,
                            location: None,
                        });
                    }
                }
            }

            Token::FunctionCall { callee, .. } => {
                if let Token::Identifier(name) = &*callee.token {
                    if name == "eval" || name == "exec" {
                        trace!("Found dynamic code execution: {}", name);
                        issues.push(SecurityIssue {
                            issue_type: SecurityIssueType::DynamicCode,
                            description: format!(
                                "Dynamic code execution detected via {}()",
                                name
                            ),
                            severity: Severity::Critical,
                            location: Some(name.clone()),
                        });
                    }
                }
            }

            Token::MemberAccess { property, .. } => {
                if let Token::Identifier(prop) = &*property.token {
                    if prop == "eval" {
                        trace!("Found eval via member access");
                        issues.push(SecurityIssue {
                            issue_type: SecurityIssueType::DynamicCode,
                            description: "Dynamic code execution via eval detected".to_string(),
                            severity: Severity::Critical,
                            location: None,
                        });
                    }
                }
            }

            _ => {}
        }
    }

    /// Scan code string for security issues
    pub fn scan_code(&self, code: &str) -> Vec<SecurityIssue> {
        debug!("Scanning code string for security issues");
        let mut issues = Vec::new();

        // Check for eval usage
        if self.eval_regex.is_match(code) {
            trace!("Found eval() in code");
            issues.push(SecurityIssue {
                issue_type: SecurityIssueType::EvalUsage,
                description: "eval() function detected - major security risk".to_string(),
                severity: Severity::Critical,
                location: None,
            });
        }

        // Check for exec/execute usage
        if self.exec_regex.is_match(code) {
            trace!("Found exec/execute in code");
            issues.push(SecurityIssue {
                issue_type: SecurityIssueType::DynamicCode,
                description: "exec() or execute() detected - code can be dynamically executed".to_string(),
                severity: Severity::Critical,
                location: None,
            });
        }

        // Check for hardcoded credentials
        if self.credential_regex.is_match(code) {
            trace!("Found potential hardcoded credentials");
            issues.push(SecurityIssue {
                issue_type: SecurityIssueType::HardcodedCredentials,
                description: "Potential hardcoded credentials detected in code".to_string(),
                severity: Severity::High,
                location: None,
            });
        }

        // Check for SQL injection patterns
        if self.sql_injection_regex.is_match(code) {
            trace!("Found SQL injection pattern");
            issues.push(SecurityIssue {
                issue_type: SecurityIssueType::CommandInjection,
                description: "Potential SQL injection vulnerability detected".to_string(),
                severity: Severity::High,
                location: None,
            });
        }

        debug!("Found {} security issues", issues.len());
        issues
    }

    /// Check if code has critical security issues
    pub fn has_critical_issues(&self, tokens: &[Token]) -> bool {
        let issues = self.scan_tokens(tokens);
        issues.iter().any(|i| i.severity == Severity::Critical)
    }

    /// Redact sensitive information from strings
    fn redact_string(s: &str) -> String {
        if s.len() > 20 {
            format!("{}...", &s[..20])
        } else {
            s.to_string()
        }
    }

    /// Get security score (0-100, 100 is most secure)
    pub fn calculate_security_score(&self, tokens: &[Token]) -> u32 {
        let issues = self.scan_tokens(tokens);

        let critical_count = issues.iter().filter(|i| i.severity == Severity::Critical).count();
        let high_count = issues.iter().filter(|i| i.severity == Severity::High).count();
        let medium_count = issues.iter().filter(|i| i.severity == Severity::Medium).count();

        let penalty = critical_count * 30 + high_count * 15 + medium_count * 5;
        (100_i32 - penalty as i32).max(0) as u32
    }
}

impl Default for SecurityScanner {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_detect_eval() {
        let scanner = SecurityScanner::new();
        let code = "eval('alert(1)')";
        let issues = scanner.scan_code(code);
        assert!(issues.iter().any(|i| i.issue_type == SecurityIssueType::EvalUsage));
    }

    #[test]
    fn test_detect_hardcoded_creds() {
        let scanner = SecurityScanner::new();
        let code = r#"var password = "secret123";"#;
        let issues = scanner.scan_code(code);
        assert!(issues.iter().any(|i| i.issue_type == SecurityIssueType::HardcodedCredentials));
    }

    #[test]
    fn test_detect_sql_injection() {
        let scanner = SecurityScanner::new();
        let code = "SELECT * FROM users WHERE id = ' + userId";
        let issues = scanner.scan_code(code);
        assert!(issues.iter().any(|i| i.issue_type == SecurityIssueType::CommandInjection));
    }

    #[test]
    fn test_security_score() {
        let scanner = SecurityScanner::new();
        let clean_tokens = vec![
            Token::StringLiteral("hello".to_string()),
            Token::NumberLiteral(42.0),
        ];
        let score = scanner.calculate_security_score(&clean_tokens);
        assert_eq!(score, 100);
    }

    #[test]
    fn test_security_score_with_issues() {
        let scanner = SecurityScanner::new();
        let unsafe_tokens = vec![Token::Identifier("eval".to_string())];
        let score = scanner.calculate_security_score(&unsafe_tokens);
        assert!(score < 100);
    }
}