rma-analyzer 0.11.0

Code analysis and security scanning for Rust Monorepo Analyzer
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! PMD provider for Java static analysis
//!
//! Integrates with [PMD](https://pmd.github.io/), a source code analyzer for
//! Java, JavaScript, and other languages with comprehensive security and
//! quality rules.
//!
//! This provider shells out to the PMD CLI and parses its XML output,
//! converting findings to RMA's unified Finding format.
//!
//! # PMD Priority to RMA Severity Mapping
//!
//! PMD uses priority levels 1-5 (1 = highest):
//! - Priority 1: Critical
//! - Priority 2: Error
//! - Priority 3: Warning
//! - Priority 4-5: Info

use super::AnalysisProvider;
use anyhow::{Context, Result};
use quick_xml::de::from_str;
use rma_common::{
    Confidence, Finding, FindingCategory, Language, Severity, SourceLocation,
    config::PmdProviderConfig,
};
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::Duration;
use tracing::{debug, info, warn};

/// PMD Java analysis provider
pub struct PmdProvider {
    config: PmdProviderConfig,
    available: bool,
    pmd_command: String,
}

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

impl PmdProvider {
    /// Create a new PMD provider with the given configuration
    pub fn new(config: PmdProviderConfig) -> Self {
        let (available, pmd_command) = Self::find_pmd(&config);

        if available {
            info!("PMD provider initialized: {}", pmd_command);
        } else {
            debug!("PMD not found - Java will use native rules only");
        }

        Self {
            config,
            available,
            pmd_command,
        }
    }

    /// Try to find PMD installation
    fn find_pmd(config: &PmdProviderConfig) -> (bool, String) {
        // If explicit path provided, use it
        if !config.pmd_path.is_empty() {
            let path = Path::new(&config.pmd_path);
            if path.exists() {
                // Check if it's a binary or a directory
                if path.is_file() {
                    return (
                        Self::check_pmd_binary(&config.pmd_path),
                        config.pmd_path.clone(),
                    );
                } else if path.is_dir() {
                    // Look for pmd binary in bin/ subdirectory
                    let pmd_bin = path.join("bin").join("pmd");
                    if pmd_bin.exists() {
                        let pmd_path = pmd_bin.to_string_lossy().to_string();
                        return (Self::check_pmd_binary(&pmd_path), pmd_path);
                    }
                    // Or it might be the lib directory with jar
                    let pmd_jar = path.join("lib").join("pmd-dist.jar");
                    if pmd_jar.exists() {
                        return (true, format!("java -jar {}", pmd_jar.display()));
                    }
                }
            }
        }

        // Try 'pmd' in PATH
        if Self::check_pmd_binary("pmd") {
            return (true, "pmd".to_string());
        }

        // Try common locations
        let common_paths = ["/usr/local/bin/pmd", "/opt/pmd/bin/pmd", "~/.local/bin/pmd"];

        for path in common_paths {
            let expanded = shellexpand::tilde(path).to_string();
            if Path::new(&expanded).exists() && Self::check_pmd_binary(&expanded) {
                return (true, expanded);
            }
        }

        (false, String::new())
    }

    /// Check if a PMD binary works
    fn check_pmd_binary(path: &str) -> bool {
        // Handle "java -jar ..." case
        if path.starts_with("java") {
            let parts: Vec<&str> = path.split_whitespace().collect();
            if parts.len() >= 3 {
                return Command::new(parts[0])
                    .args(&parts[1..])
                    .arg("--version")
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .status()
                    .map(|s| s.success())
                    .unwrap_or(false);
            }
        }

        Command::new(path)
            .arg("--version")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    /// Build the PMD command arguments
    fn build_command(&self, target_path: &Path) -> Vec<String> {
        let mut args = vec![
            "check".to_string(),
            "-d".to_string(),
            target_path.to_string_lossy().to_string(),
            "-f".to_string(),
            "xml".to_string(),
        ];

        // Add rulesets
        if !self.config.rulesets.is_empty() {
            args.push("-R".to_string());
            args.push(self.config.rulesets.join(","));
        }

        // Add minimum priority filter
        if self.config.min_priority < 5 {
            args.push("--minimum-priority".to_string());
            args.push(self.config.min_priority.to_string());
        }

        // Add extra arguments
        args.extend(self.config.extra_args.clone());

        args
    }

    /// Run PMD and return findings
    pub fn run_pmd(&self, path: &Path) -> Result<Vec<Finding>> {
        if !self.available {
            if self.config.fail_on_error {
                anyhow::bail!("PMD is not available");
            }
            warn!("PMD not available, returning empty results");
            return Ok(Vec::new());
        }

        let args = self.build_command(path);
        debug!("Running PMD: {} {:?}", self.pmd_command, args);

        // Parse command (might be "java -jar path" or just "pmd")
        let (program, full_args) = if self.pmd_command.starts_with("java") {
            let parts: Vec<&str> = self.pmd_command.split_whitespace().collect();
            let program = parts[0].to_string();
            let mut cmd_args: Vec<String> = parts[1..].iter().map(|s| s.to_string()).collect();
            cmd_args.extend(args);
            (program, cmd_args)
        } else {
            (self.pmd_command.clone(), args)
        };

        // Run with timeout
        let timeout = Duration::from_millis(self.config.timeout_ms);
        let (tx, rx) = mpsc::channel();

        let program_clone = program.clone();
        let args_clone = full_args.clone();

        let handle = std::thread::spawn(move || {
            let output = Command::new(&program_clone)
                .args(&args_clone)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .output();
            let _ = tx.send(output);
        });

        match rx.recv_timeout(timeout) {
            Ok(output_result) => {
                let _ = handle.join();
                let output = output_result.context("Failed to execute PMD")?;

                // PMD returns non-zero if it finds violations, so we check stderr for errors
                let stderr = String::from_utf8_lossy(&output.stderr);
                if !stderr.is_empty() && !stderr.contains("violations") {
                    debug!("PMD stderr: {}", stderr);
                }

                let stdout =
                    String::from_utf8(output.stdout).context("Invalid UTF-8 in PMD output")?;

                if stdout.trim().is_empty() {
                    return Ok(Vec::new());
                }

                self.parse_xml_output(&stdout, path)
            }
            Err(_) => {
                // Timeout - try to kill the process
                warn!("PMD execution timed out after {:?}", timeout);
                if self.config.fail_on_error {
                    anyhow::bail!("PMD execution timed out");
                }
                Ok(Vec::new())
            }
        }
    }

    /// Parse PMD XML output into RMA findings
    fn parse_xml_output(&self, xml: &str, base_path: &Path) -> Result<Vec<Finding>> {
        // Try to parse as PMD XML format
        let pmd_report: PmdReport = from_str(xml).context("Failed to parse PMD XML output")?;

        let mut findings = Vec::new();

        for file in pmd_report.files {
            for violation in file.violations {
                if let Some(finding) = self.convert_violation(&file.name, &violation, base_path) {
                    findings.push(finding);
                }
            }
        }

        info!("PMD found {} findings", findings.len());
        Ok(findings)
    }

    /// Convert a PMD violation to an RMA Finding
    fn convert_violation(
        &self,
        filename: &str,
        violation: &PmdViolation,
        _base_path: &Path,
    ) -> Option<Finding> {
        // Map priority to severity using config or defaults
        let priority_str = violation.priority.to_string();
        let severity = self
            .config
            .severity_map
            .get(&priority_str)
            .copied()
            .unwrap_or_else(|| Self::default_severity(violation.priority));

        // Determine confidence based on rule category
        let (confidence, category) = Self::categorize_rule(&violation.rule, &violation.ruleset);

        let rule_id = format!("pmd/java/{}", violation.rule);

        let location = SourceLocation::new(
            PathBuf::from(filename),
            violation.begin_line,
            violation.begin_column.unwrap_or(1),
            violation.end_line.unwrap_or(violation.begin_line),
            violation.end_column.unwrap_or(1),
        );

        let mut finding = Finding {
            id: format!("{}:{}:{}", rule_id, filename, violation.begin_line),
            rule_id,
            message: violation.message.trim().to_string(),
            severity,
            location,
            language: Language::Java,
            snippet: None, // PMD doesn't include snippet in XML
            suggestion: violation.external_info_url.clone(),
            confidence,
            category,
            fingerprint: None,
            properties: None,
        };

        finding.compute_fingerprint();
        Some(finding)
    }

    /// Default severity mapping for PMD priority
    fn default_severity(priority: u8) -> Severity {
        match priority {
            1 => Severity::Critical,
            2 => Severity::Error,
            3 => Severity::Warning,
            _ => Severity::Info,
        }
    }

    /// Categorize rule based on ruleset and rule name
    fn categorize_rule(rule: &str, ruleset: &str) -> (Confidence, FindingCategory) {
        let ruleset_lower = ruleset.to_lowercase();
        let rule_lower = rule.to_lowercase();

        // Security rules
        if ruleset_lower.contains("security")
            || rule_lower.contains("injection")
            || rule_lower.contains("xss")
            || rule_lower.contains("crypto")
            || rule_lower.contains("sensitive")
            || rule_lower.contains("hardcoded")
        {
            return (Confidence::High, FindingCategory::Security);
        }

        // Error-prone / correctness rules
        if ruleset_lower.contains("errorprone")
            || ruleset_lower.contains("error-prone")
            || rule_lower.contains("null")
            || rule_lower.contains("exception")
            || rule_lower.contains("resource")
        {
            return (Confidence::Medium, FindingCategory::Quality);
        }

        // Best practices
        if ruleset_lower.contains("bestpractices") || ruleset_lower.contains("best-practices") {
            return (Confidence::Medium, FindingCategory::Quality);
        }

        // Performance
        if ruleset_lower.contains("performance") || rule_lower.contains("performance") {
            return (Confidence::Medium, FindingCategory::Performance);
        }

        // Design / code style
        if ruleset_lower.contains("design")
            || ruleset_lower.contains("code")
            || ruleset_lower.contains("style")
        {
            return (Confidence::Low, FindingCategory::Style);
        }

        // Default
        (Confidence::Medium, FindingCategory::Quality)
    }

    /// Check if a file should be included based on patterns
    fn should_include_file(&self, path: &Path) -> bool {
        let path_str = path.to_string_lossy();

        // Check exclude patterns first
        for pattern in &self.config.exclude_patterns {
            if Self::matches_glob(&path_str, pattern) {
                return false;
            }
        }

        // Check include patterns
        for pattern in &self.config.include_patterns {
            if Self::matches_glob(&path_str, pattern) {
                return true;
            }
        }

        // Default: include .java files
        path.extension().map(|ext| ext == "java").unwrap_or(false)
    }

    /// Simple glob matching
    fn matches_glob(path: &str, pattern: &str) -> bool {
        let regex_pattern = pattern
            .replace("**", "§")
            .replace('*', "[^/]*")
            .replace('§', ".*");

        regex::Regex::new(&format!("^{}$", regex_pattern))
            .map(|re| re.is_match(path))
            .unwrap_or(false)
    }
}

impl AnalysisProvider for PmdProvider {
    fn name(&self) -> &'static str {
        "pmd"
    }

    fn description(&self) -> &'static str {
        "PMD Java static analysis for security and quality"
    }

    fn supports_language(&self, lang: Language) -> bool {
        // PMD primarily supports Java, but also JavaScript
        // We focus on Java here as that's the main use case
        matches!(lang, Language::Java)
    }

    fn is_available(&self) -> bool {
        self.available
    }

    fn version(&self) -> Option<String> {
        if !self.available {
            return None;
        }

        let (program, args) = if self.pmd_command.starts_with("java") {
            let parts: Vec<&str> = self.pmd_command.split_whitespace().collect();
            (
                parts[0].to_string(),
                parts[1..].iter().map(|s| s.to_string()).collect::<Vec<_>>(),
            )
        } else {
            (self.pmd_command.clone(), Vec::new())
        };

        let mut cmd = Command::new(&program);
        cmd.args(&args).arg("--version");

        cmd.output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim().to_string())
    }

    fn analyze_file(&self, path: &Path) -> Result<Vec<Finding>> {
        if !self.should_include_file(path) {
            return Ok(Vec::new());
        }
        self.run_pmd(path)
    }

    fn analyze_directory(&self, path: &Path) -> Result<Vec<Finding>> {
        self.run_pmd(path)
    }

    fn analyze_files(&self, files: &[&Path]) -> Result<Vec<Finding>> {
        // Filter to Java files only
        let java_files: Vec<_> = files
            .iter()
            .filter(|f| self.should_include_file(f))
            .collect();

        if java_files.is_empty() {
            return Ok(Vec::new());
        }

        // PMD can analyze multiple files, but for simplicity we use directory mode
        // A more efficient implementation would create a file list for PMD
        let mut all_findings = Vec::new();
        for file in java_files {
            let findings = self.run_pmd(file)?;
            all_findings.extend(findings);
        }
        Ok(all_findings)
    }
}

// =============================================================================
// PMD XML Report Structures
// =============================================================================

/// Root element of PMD XML report
#[derive(Debug, Deserialize)]
#[serde(rename = "pmd")]
struct PmdReport {
    #[serde(default)]
    #[allow(dead_code)]
    version: Option<String>,

    #[serde(rename = "file", default)]
    files: Vec<PmdFile>,
}

/// File element containing violations
#[derive(Debug, Deserialize)]
struct PmdFile {
    #[serde(rename = "@name")]
    name: String,

    #[serde(rename = "violation", default)]
    violations: Vec<PmdViolation>,
}

/// Individual PMD violation
#[derive(Debug, Deserialize)]
struct PmdViolation {
    /// Beginning line number
    #[serde(rename = "@beginline")]
    begin_line: usize,

    /// Ending line number
    #[serde(rename = "@endline")]
    end_line: Option<usize>,

    /// Beginning column
    #[serde(rename = "@begincolumn")]
    begin_column: Option<usize>,

    /// Ending column
    #[serde(rename = "@endcolumn")]
    end_column: Option<usize>,

    /// Rule name
    #[serde(rename = "@rule")]
    rule: String,

    /// Ruleset name
    #[serde(rename = "@ruleset")]
    ruleset: String,

    /// Priority (1-5, 1 is highest)
    #[serde(rename = "@priority")]
    priority: u8,

    /// Optional external info URL
    #[serde(rename = "@externalInfoUrl")]
    external_info_url: Option<String>,

    /// Violation message (element text)
    #[serde(rename = "$text")]
    message: String,
}

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

    #[test]
    fn test_provider_creation() {
        let provider = PmdProvider::default();
        // Just test that it doesn't panic
        let _ = provider.is_available();
    }

    #[test]
    fn test_parse_pmd_xml() {
        let provider = PmdProvider::default();

        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<pmd version="6.55.0">
    <file name="/src/main/java/Example.java">
        <violation beginline="10" endline="10" begincolumn="5" endcolumn="20"
                   rule="UnusedLocalVariable" ruleset="Best Practices"
                   priority="3" externalInfoUrl="https://pmd.github.io/...">
            Avoid unused local variables such as 'temp'.
        </violation>
        <violation beginline="25" endline="30" begincolumn="1"
                   rule="AvoidReassigningParameters" ruleset="Best Practices"
                   priority="2">
            Avoid reassigning parameters such as 'input'.
        </violation>
    </file>
    <file name="/src/main/java/Security.java">
        <violation beginline="15" endline="15" begincolumn="10"
                   rule="HardcodedPassword" ruleset="Security"
                   priority="1">
            Hardcoded password detected.
        </violation>
    </file>
</pmd>"#;

        let findings = provider
            .parse_xml_output(xml, Path::new("/project"))
            .unwrap();

        assert_eq!(findings.len(), 3);

        // First finding - UnusedLocalVariable
        assert_eq!(findings[0].rule_id, "pmd/java/UnusedLocalVariable");
        assert_eq!(findings[0].severity, Severity::Warning); // priority 3
        assert_eq!(findings[0].location.start_line, 10);

        // Second finding - AvoidReassigningParameters
        assert_eq!(findings[1].rule_id, "pmd/java/AvoidReassigningParameters");
        assert_eq!(findings[1].severity, Severity::Error); // priority 2

        // Third finding - HardcodedPassword (security)
        assert_eq!(findings[2].rule_id, "pmd/java/HardcodedPassword");
        assert_eq!(findings[2].severity, Severity::Critical); // priority 1
        assert_eq!(findings[2].category, FindingCategory::Security);
        assert_eq!(findings[2].confidence, Confidence::High);
    }

    #[test]
    fn test_severity_mapping() {
        assert_eq!(PmdProvider::default_severity(1), Severity::Critical);
        assert_eq!(PmdProvider::default_severity(2), Severity::Error);
        assert_eq!(PmdProvider::default_severity(3), Severity::Warning);
        assert_eq!(PmdProvider::default_severity(4), Severity::Info);
        assert_eq!(PmdProvider::default_severity(5), Severity::Info);
    }

    #[test]
    fn test_rule_categorization() {
        // Security rules
        let (conf, cat) = PmdProvider::categorize_rule("HardcodedPassword", "Security");
        assert_eq!(conf, Confidence::High);
        assert_eq!(cat, FindingCategory::Security);

        // Error-prone rules
        let (conf, cat) = PmdProvider::categorize_rule("NullAssignment", "Error Prone");
        assert_eq!(conf, Confidence::Medium);
        assert_eq!(cat, FindingCategory::Quality);

        // Performance rules
        let (conf, cat) =
            PmdProvider::categorize_rule("UseStringBufferForStringAppends", "Performance");
        assert_eq!(conf, Confidence::Medium);
        assert_eq!(cat, FindingCategory::Performance);

        // Design rules
        let (conf, cat) = PmdProvider::categorize_rule("TooManyMethods", "Design");
        assert_eq!(conf, Confidence::Low);
        assert_eq!(cat, FindingCategory::Style);
    }

    #[test]
    fn test_glob_matching() {
        assert!(PmdProvider::matches_glob(
            "/src/main/java/Test.java",
            "**/*.java"
        ));
        assert!(PmdProvider::matches_glob(
            "/target/classes/Test.java",
            "**/target/**"
        ));
        assert!(!PmdProvider::matches_glob(
            "/src/main/java/Test.java",
            "**/target/**"
        ));
    }

    #[test]
    fn test_file_inclusion() {
        let provider = PmdProvider::default();

        // Should include .java files
        assert!(provider.should_include_file(Path::new("/src/Main.java")));

        // Should exclude target directory
        assert!(!provider.should_include_file(Path::new("/target/classes/Main.java")));

        // Should exclude non-Java files
        assert!(!provider.should_include_file(Path::new("/src/main.rs")));
    }

    #[test]
    fn test_empty_xml() {
        let provider = PmdProvider::default();

        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<pmd version="6.55.0">
</pmd>"#;

        let findings = provider
            .parse_xml_output(xml, Path::new("/project"))
            .unwrap();
        assert!(findings.is_empty());
    }

    #[test]
    fn test_command_building() {
        let config = PmdProviderConfig {
            rulesets: vec![
                "category/java/security.xml".to_string(),
                "category/java/bestpractices.xml".to_string(),
            ],
            ..Default::default()
        };

        let provider = PmdProvider::new(config);
        let args = provider.build_command(Path::new("/project"));

        assert!(args.contains(&"check".to_string()));
        assert!(args.contains(&"-d".to_string()));
        assert!(args.contains(&"/project".to_string()));
        assert!(args.contains(&"-f".to_string()));
        assert!(args.contains(&"xml".to_string()));
        assert!(args.contains(&"-R".to_string()));
    }
}