tldr-cli 0.1.3

CLI binary for TLDR code analysis tool
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! Secure Command - Security Analysis Dashboard
//!
//! Aggregates security sub-analyses (taint, resources, bounds, contracts,
//! behavioral, mutability) into a severity-sorted security report.
//!
//! # Sub-analyses
//!
//! - `taint`: Detect data flow from untrusted sources to sensitive sinks
//! - `resources`: Detect resource leaks (files, connections)
//! - `bounds`: Detect potential buffer overflows and bounds issues
//! - `contracts`: Analyze pre/postconditions (full mode only)
//! - `behavioral`: Analyze exception handling and state transitions (full mode only)
//! - `mutability`: Detect mutable parameter issues (full mode only)
//!
//! # Quick Mode
//!
//! Quick mode (`--quick`) runs only the fast analyses:
//! - taint, resources, bounds
//!
//! Full mode adds:
//! - contracts, behavioral, mutability
//!
//! # Example
//!
//! ```bash
//! # Analyze a file
//! tldr secure src/app.py
//!
//! # Quick mode (faster)
//! tldr secure src/app.py --quick
//!
//! # Show detail for sub-analysis
//! tldr secure src/app.py --detail taint
//!
//! # Text output
//! tldr secure src/app.py -f text
//! ```

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;

use clap::Args;
use colored::Colorize;
use serde_json::Value;
use tree_sitter::Node;

use crate::output::OutputFormat;

use super::ast_cache::AstCache;
use super::error::{RemainingError, RemainingResult};
use super::types::{SecureFinding, SecureReport, SecureSummary};

// =============================================================================
// Security Analysis Types
// =============================================================================

/// Security sub-analysis types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecurityAnalysis {
    Taint,
    Resources,
    Bounds,
    Contracts,
    Behavioral,
    Mutability,
}

impl SecurityAnalysis {
    /// Get the analysis name
    pub fn name(&self) -> &'static str {
        match self {
            Self::Taint => "taint",
            Self::Resources => "resources",
            Self::Bounds => "bounds",
            Self::Contracts => "contracts",
            Self::Behavioral => "behavioral",
            Self::Mutability => "mutability",
        }
    }
}

/// Quick mode analyses (fast)
pub const QUICK_ANALYSES: &[SecurityAnalysis] = &[
    SecurityAnalysis::Taint,
    SecurityAnalysis::Resources,
    SecurityAnalysis::Bounds,
];

/// Full mode analyses (all)
pub const FULL_ANALYSES: &[SecurityAnalysis] = &[
    SecurityAnalysis::Taint,
    SecurityAnalysis::Resources,
    SecurityAnalysis::Bounds,
    SecurityAnalysis::Contracts,
    SecurityAnalysis::Behavioral,
    SecurityAnalysis::Mutability,
];

// =============================================================================
// CLI Arguments
// =============================================================================

/// Security analysis dashboard aggregating multiple security checks
#[derive(Debug, Args, Clone)]
pub struct SecureArgs {
    /// File path or directory to analyze
    pub path: PathBuf,

    /// Show details for specific sub-analysis
    #[arg(long)]
    pub detail: Option<String>,

    /// Run quick mode (taint, resources, bounds only)
    #[arg(long)]
    pub quick: bool,

    /// Write output to file instead of stdout
    #[arg(long, short = 'o')]
    pub output: Option<PathBuf>,
}

impl SecureArgs {
    /// Run the secure command with CLI-provided format
    pub fn run(&self, format: OutputFormat) -> anyhow::Result<()> {
        run(self.clone(), format)
    }
}

// =============================================================================
// Implementation
// =============================================================================

/// Run the secure analysis
pub fn run(args: SecureArgs, format: OutputFormat) -> anyhow::Result<()> {
    let start = Instant::now();

    // Validate path exists
    if !args.path.exists() {
        return Err(RemainingError::file_not_found(&args.path).into());
    }

    // Create report
    let mut report = SecureReport::new(args.path.display().to_string());

    // Initialize AST cache for shared parsing
    let mut cache = AstCache::default();

    // Determine which analyses to run
    let analyses = if args.quick {
        QUICK_ANALYSES
    } else {
        FULL_ANALYSES
    };

    // Collect files to analyze (auto-detect Python files)
    let files = collect_files(&args.path)?;

    // Run sub-analyses and collect findings
    let mut all_findings = Vec::new();
    let mut sub_results: HashMap<String, Value> = HashMap::new();

    for analysis in analyses {
        let (findings, raw_result) = run_security_analysis(*analysis, &files, &mut cache)?;

        // Update summary
        update_summary(&mut report.summary, *analysis, &findings);

        // Collect findings
        all_findings.extend(findings);

        // Store raw result if requested
        if args.detail.as_deref() == Some(analysis.name()) {
            sub_results.insert(analysis.name().to_string(), raw_result);
        }
    }

    // Sort findings by severity (critical first)
    all_findings.sort_by(|a, b| severity_order(&a.severity).cmp(&severity_order(&b.severity)));

    report.findings = all_findings;
    report.sub_results = sub_results;
    report.total_elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;

    // Output
    let output_str = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&report)?,
        OutputFormat::Compact => serde_json::to_string(&report)?,
        OutputFormat::Text => format_text_report(&report),
        OutputFormat::Sarif | OutputFormat::Dot => {
            // SARIF/DOT not fully supported for secure, fall back to JSON
            serde_json::to_string_pretty(&report)?
        }
    };

    // Write output
    if let Some(output_path) = &args.output {
        fs::write(output_path, &output_str)?;
    } else {
        println!("{}", output_str);
    }

    Ok(())
}

/// Collect supported files to analyze.
fn collect_files(path: &Path) -> RemainingResult<Vec<PathBuf>> {
    let mut files = Vec::new();

    if path.is_file() {
        if is_supported_secure_file(path) {
            files.push(path.to_path_buf());
        }
    } else if path.is_dir() {
        // Walk directory and collect Python/Rust files.
        for entry in walkdir::WalkDir::new(path)
            .max_depth(10)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let p = entry.path();
            if p.is_file() && is_supported_secure_file(p) {
                files.push(p.to_path_buf());
            }
        }
    }

    // Return empty vec if no files found (like vuln.rs does)
    // The report will show 0 files scanned with no findings

    Ok(files)
}

fn is_supported_secure_file(path: &std::path::Path) -> bool {
    matches!(path.extension().and_then(|e| e.to_str()), Some("py" | "rs"))
}

fn is_rust_file(path: &std::path::Path) -> bool {
    matches!(path.extension().and_then(|e| e.to_str()), Some("rs"))
}

fn is_rust_test_file(path: &std::path::Path) -> bool {
    let p = path.to_string_lossy();
    p.contains("/tests/")
        || p.contains("\\tests\\")
        || p.ends_with("_test.rs")
        || p.ends_with("tests.rs")
}

/// Run a specific security analysis on files
fn run_security_analysis(
    analysis: SecurityAnalysis,
    files: &[PathBuf],
    cache: &mut AstCache,
) -> RemainingResult<(Vec<SecureFinding>, Value)> {
    let mut findings = Vec::new();

    for file in files {
        let source = fs::read_to_string(file)?;

        // Get or parse the AST
        let tree = cache.get_or_parse(file, &source)?;

        // Run analysis
        let file_findings = match analysis {
            SecurityAnalysis::Taint => analyze_taint(tree.root_node(), &source, file),
            SecurityAnalysis::Resources => analyze_resources(tree.root_node(), &source, file),
            SecurityAnalysis::Bounds => analyze_bounds(tree.root_node(), &source, file),
            SecurityAnalysis::Contracts => analyze_contracts(tree.root_node(), &source, file),
            SecurityAnalysis::Behavioral => analyze_behavioral(tree.root_node(), &source, file),
            SecurityAnalysis::Mutability => analyze_mutability(tree.root_node(), &source, file),
        };

        findings.extend(file_findings);
    }

    // Create raw result
    let raw_result = serde_json::to_value(&findings).unwrap_or(Value::Array(vec![]));

    Ok((findings, raw_result))
}

/// Update summary based on findings
fn update_summary(
    summary: &mut SecureSummary,
    analysis: SecurityAnalysis,
    findings: &[SecureFinding],
) {
    match analysis {
        SecurityAnalysis::Taint => {
            summary.taint_count = findings.len() as u32;
            summary.taint_critical =
                findings.iter().filter(|f| f.severity == "critical").count() as u32;
            summary.unsafe_blocks = findings
                .iter()
                .filter(|f| f.category == "unsafe_block")
                .count() as u32;
        }
        SecurityAnalysis::Resources => {
            summary.leak_count = findings
                .iter()
                .filter(|f| f.category == "resource_leak")
                .count() as u32;
            summary.raw_pointer_ops = findings
                .iter()
                .filter(|f| f.category == "raw_pointer")
                .count() as u32;
        }
        SecurityAnalysis::Bounds => {
            summary.bounds_warnings =
                findings.iter().filter(|f| f.category == "bounds").count() as u32;
            summary.unwrap_calls =
                findings.iter().filter(|f| f.category == "unwrap").count() as u32;
            summary.todo_markers = findings
                .iter()
                .filter(|f| f.category == "todo_marker")
                .count() as u32;
        }
        SecurityAnalysis::Contracts => {
            summary.missing_contracts = findings.len() as u32;
        }
        SecurityAnalysis::Behavioral => {
            // Not tracked in summary
        }
        SecurityAnalysis::Mutability => {
            summary.mutable_params = findings.len() as u32;
        }
    }
}

/// Get severity order (lower = more severe)
fn severity_order(severity: &str) -> u8 {
    match severity {
        "critical" => 0,
        "high" => 1,
        "medium" => 2,
        "low" => 3,
        "info" => 4,
        _ => 5,
    }
}

// =============================================================================
// Taint Analysis
// =============================================================================

/// Known taint sinks in Python
const TAINT_SINKS: &[(&str, &str, &str)] = &[
    // (pattern, vuln_type, severity)
    ("cursor.execute", "SQL Injection", "critical"),
    ("execute", "SQL Injection", "critical"),
    ("os.system", "Command Injection", "critical"),
    ("subprocess.call", "Command Injection", "critical"),
    ("subprocess.run", "Command Injection", "high"),
    ("subprocess.Popen", "Command Injection", "high"),
    ("eval", "Code Injection", "critical"),
    ("exec", "Code Injection", "critical"),
    ("pickle.loads", "Insecure Deserialization", "critical"),
    ("yaml.load", "Insecure Deserialization", "high"),
    ("open", "Path Traversal", "high"),
    ("render_template_string", "Template Injection", "high"),
];

/// Analyze taint flows in a file
fn analyze_taint(root: Node, source: &str, file: &Path) -> Vec<SecureFinding> {
    if is_rust_file(file) {
        return analyze_rust_unsafe_blocks(source, file);
    }

    let mut findings = Vec::new();
    let source_bytes = source.as_bytes();

    // Simple pattern matching for dangerous patterns
    // In a full implementation, this would do data flow analysis

    // Find f-strings and format strings used in dangerous contexts
    analyze_fstring_injection(root, source_bytes, file, &mut findings);

    // Find direct concatenation in dangerous sinks
    analyze_string_concat_in_sinks(root, source_bytes, file, &mut findings);

    findings
}

fn analyze_fstring_injection(
    root: Node,
    source: &[u8],
    file: &Path,
    findings: &mut Vec<SecureFinding>,
) {
    traverse_for_fstrings(root, source, file, findings);
}

fn traverse_for_fstrings(node: Node, source: &[u8], file: &Path, findings: &mut Vec<SecureFinding>) {
    // Check if this is a call to a dangerous function with an f-string
    if node.kind() == "call" {
        if let Some(func) = node.child_by_field_name("function") {
            let func_text = node_text(func, source);

            // Check if it's a dangerous sink
            for (pattern, vuln_type, severity) in TAINT_SINKS {
                if func_text.contains(pattern)
                    || func_text.ends_with(pattern.split('.').next_back().unwrap_or(pattern))
                {
                    // Check if arguments contain f-strings or format
                    if let Some(args) = node.child_by_field_name("arguments") {
                        let args_text = node_text(args, source);
                        if args_text.contains("f\"")
                            || args_text.contains("f'")
                            || args_text.contains(".format(")
                            || args_text.contains(" + ")
                        {
                            findings.push(SecureFinding::new(
                                "taint",
                                *severity,
                                format!("{}: Potential {} - user input may flow to dangerous function", 
                                    vuln_type, vuln_type.to_lowercase()),
                            ).with_location(file.display().to_string(), node.start_position().row as u32 + 1));
                        }
                    }
                }
            }
        }
    }

    // Recurse
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            traverse_for_fstrings(child, source, file, findings);
        }
    }
}

fn analyze_string_concat_in_sinks(
    _root: Node,
    _source: &[u8],
    _file: &Path,
    _findings: &mut Vec<SecureFinding>,
) {
    // Placeholder for string concatenation analysis
    // In a full implementation, this would track string operations
}

// =============================================================================
// Resource Analysis
// =============================================================================

/// Known resource creators
const RESOURCE_CREATORS: &[&str] = &["open", "socket", "connect", "cursor", "urlopen"];

/// Analyze resource leaks in a file
fn analyze_resources(root: Node, source: &str, file: &Path) -> Vec<SecureFinding> {
    if is_rust_file(file) {
        return analyze_rust_raw_pointers(source, file);
    }

    let mut findings = Vec::new();
    let source_bytes = source.as_bytes();

    // Find resource assignments outside of `with` statements
    find_leaked_resources(root, source_bytes, file, &mut findings);

    findings
}

fn find_leaked_resources(
    node: Node,
    source: &[u8],
    file: &Path,
    findings: &mut Vec<SecureFinding>,
) {
    // Check if this is an assignment with a resource creator
    if node.kind() == "assignment" {
        if let Some(right) = node.child_by_field_name("right") {
            if right.kind() == "call" {
                if let Some(func) = right.child_by_field_name("function") {
                    let func_text = node_text(func, source);
                    let func_name = func_text.split('.').next_back().unwrap_or(func_text);

                    if RESOURCE_CREATORS.contains(&func_name) {
                        // Check if this is inside a with statement
                        if !is_inside_with(node) {
                            findings.push(
                                SecureFinding::new(
                                    "resource_leak",
                                    "high",
                                    format!(
                                        "Resource '{}' opened without context manager - may leak",
                                        func_name
                                    ),
                                )
                                .with_location(
                                    file.display().to_string(),
                                    node.start_position().row as u32 + 1,
                                ),
                            );
                        }
                    }
                }
            }
        }
    }

    // Recurse
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            find_leaked_resources(child, source, file, findings);
        }
    }
}

fn is_inside_with(node: Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "with_statement" {
            return true;
        }
        current = parent.parent();
    }
    false
}

// =============================================================================
// Bounds Analysis
// =============================================================================

/// Analyze bounds/overflow issues in a file
fn analyze_bounds(_root: Node, source: &str, file: &Path) -> Vec<SecureFinding> {
    if is_rust_file(file) {
        return analyze_rust_bounds(source, file);
    }

    // Placeholder for Python bounds analysis.
    Vec::new()
}

// =============================================================================
// Contracts Analysis
// =============================================================================

/// Analyze missing contracts in a file
fn analyze_contracts(_root: Node, _source: &str, _file: &Path) -> Vec<SecureFinding> {
    // Placeholder - would check for functions without type hints, docstrings, or assertions
    Vec::new()
}

// =============================================================================
// Behavioral Analysis
// =============================================================================

/// Analyze behavioral issues (exception handling, state) in a file
fn analyze_behavioral(root: Node, source: &str, file: &Path) -> Vec<SecureFinding> {
    let mut findings = Vec::new();
    let source_bytes = source.as_bytes();

    // Find bare except clauses
    find_bare_except(root, source_bytes, file, &mut findings);

    findings
}

fn find_bare_except(node: Node, source: &[u8], file: &Path, findings: &mut Vec<SecureFinding>) {
    // Check for except clauses without exception type
    if node.kind() == "except_clause" {
        let has_type = node.children(&mut node.walk()).any(|c| {
            c.kind() == "as_pattern"
                || (c.kind() == "identifier" && node_text(c, source) != "Exception")
        });

        if !has_type {
            let text = node_text(node, source);
            if text.starts_with("except:") || text.starts_with("except :") {
                findings.push(
                    SecureFinding::new(
                        "behavioral",
                        "medium",
                        "Bare except clause catches all exceptions including KeyboardInterrupt",
                    )
                    .with_location(
                        file.display().to_string(),
                        node.start_position().row as u32 + 1,
                    ),
                );
            }
        }
    }

    // Recurse
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            find_bare_except(child, source, file, findings);
        }
    }
}

// =============================================================================
// Mutability Analysis
// =============================================================================

/// Analyze mutability issues in a file
fn analyze_mutability(_root: Node, _source: &str, _file: &Path) -> Vec<SecureFinding> {
    // Placeholder - would check for mutable default arguments, etc.
    Vec::new()
}

// =============================================================================
// Utilities
// =============================================================================

fn node_text<'a>(node: Node, source: &'a [u8]) -> &'a str {
    std::str::from_utf8(&source[node.start_byte()..node.end_byte()]).unwrap_or("")
}

fn analyze_rust_unsafe_blocks(source: &str, file: &Path) -> Vec<SecureFinding> {
    let mut findings = Vec::new();
    for (idx, line) in source.lines().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("//") {
            continue;
        }
        if trimmed.contains("unsafe {") || trimmed.starts_with("unsafe{") {
            findings.push(
                SecureFinding::new(
                    "unsafe_block",
                    "high",
                    "unsafe block detected; verify invariants and safety rationale",
                )
                .with_location(file.display().to_string(), (idx + 1) as u32),
            );
        }
    }
    findings
}

fn analyze_rust_raw_pointers(source: &str, file: &Path) -> Vec<SecureFinding> {
    let mut findings = Vec::new();
    for (idx, line) in source.lines().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("//") {
            continue;
        }
        if trimmed.contains("std::ptr::")
            || trimmed.contains("core::ptr::")
            || trimmed.contains("ptr::read(")
            || trimmed.contains("ptr::write(")
        {
            findings.push(
                SecureFinding::new(
                    "raw_pointer",
                    "high",
                    "raw pointer operation detected; audit aliasing, lifetime, and bounds assumptions",
                )
                .with_location(file.display().to_string(), (idx + 1) as u32),
            );
        }
    }
    findings
}

fn analyze_rust_bounds(source: &str, file: &Path) -> Vec<SecureFinding> {
    let mut findings = Vec::new();
    let skip_test_only = is_rust_test_file(file);

    for (idx, line) in source.lines().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("//") {
            continue;
        }

        if !skip_test_only && trimmed.contains(".unwrap()") {
            findings.push(
                SecureFinding::new(
                    "unwrap",
                    "medium",
                    "unwrap() call in non-test code may panic at runtime",
                )
                .with_location(file.display().to_string(), (idx + 1) as u32),
            );
        }

        if !skip_test_only && (trimmed.contains("todo!(") || trimmed.contains("unimplemented!(")) {
            findings.push(
                SecureFinding::new(
                    "todo_marker",
                    "low",
                    "todo!/unimplemented! marker found in non-test Rust code",
                )
                .with_location(file.display().to_string(), (idx + 1) as u32),
            );
        }
    }

    findings
}

// =============================================================================
// Text Output
// =============================================================================

fn format_text_report(report: &SecureReport) -> String {
    let mut output = String::new();

    output.push_str(&"=".repeat(60));
    output.push('\n');
    output.push_str(&format!(
        "{}\n",
        "SECURE - Security Analysis Dashboard".bold()
    ));
    output.push_str(&"=".repeat(60));
    output.push_str("\n\n");
    output.push_str(&format!("Path: {}\n\n", report.path));

    if report.findings.is_empty() {
        output.push_str(&format!("{}\n", "No security issues found.".green()));
    } else {
        output.push_str(&format!(
            "{}\n",
            "Severity | Category       | Description".bold()
        ));
        output.push_str(&format!("{}\n", "-".repeat(60)));

        for finding in &report.findings {
            let severity_colored = match finding.severity.as_str() {
                "critical" => finding.severity.red().bold().to_string(),
                "high" => finding.severity.red().to_string(),
                "medium" => finding.severity.yellow().to_string(),
                "low" => finding.severity.blue().to_string(),
                _ => finding.severity.clone(),
            };
            output.push_str(&format!(
                "{:>8} | {:<14} | {}\n",
                severity_colored, finding.category, finding.description
            ));
            if !finding.file.is_empty() {
                output.push_str(&format!(
                    "         |                | {}:{}\n",
                    finding.file, finding.line
                ));
            }
        }
    }

    output.push('\n');
    output.push_str(&format!("{}\n", "Summary:".bold()));
    output.push_str(&format!(
        "  Taint issues:      {} ({} critical)\n",
        report.summary.taint_count, report.summary.taint_critical
    ));
    output.push_str(&format!(
        "  Resource leaks:    {}\n",
        report.summary.leak_count
    ));
    output.push_str(&format!(
        "  Bounds warnings:   {}\n",
        report.summary.bounds_warnings
    ));
    output.push_str(&format!(
        "  Missing contracts: {}\n",
        report.summary.missing_contracts
    ));
    output.push_str(&format!(
        "  Mutable params:    {}\n",
        report.summary.mutable_params
    ));
    output.push_str(&format!(
        "  Unsafe blocks:     {}\n",
        report.summary.unsafe_blocks
    ));
    output.push_str(&format!(
        "  Raw pointer ops:   {}\n",
        report.summary.raw_pointer_ops
    ));
    output.push_str(&format!(
        "  Unwrap calls:      {}\n",
        report.summary.unwrap_calls
    ));
    output.push_str(&format!(
        "  Todo markers:      {}\n",
        report.summary.todo_markers
    ));
    output.push('\n');
    output.push_str(&format!("Elapsed: {:.2}ms\n", report.total_elapsed_ms));

    output
}

#[cfg(test)]
mod tests {
    use super::*;
    use tree_sitter::Parser;
    use tempfile::TempDir;

    fn create_test_file(dir: &TempDir, name: &str, content: &str) -> PathBuf {
        let path = dir.path().join(name);
        fs::write(&path, content).unwrap();
        path
    }

    #[test]
    fn test_secure_args_default() {
        // Test that default values are set correctly
        let args = SecureArgs {
            path: PathBuf::from("test.py"),
            detail: None,
            quick: false,
            output: None,
        };
        assert!(!args.quick);
    }

    #[test]
    fn test_severity_order() {
        assert!(severity_order("critical") < severity_order("high"));
        assert!(severity_order("high") < severity_order("medium"));
        assert!(severity_order("medium") < severity_order("low"));
        assert!(severity_order("low") < severity_order("info"));
    }

    #[test]
    fn test_taint_analysis_finds_sql_injection() {
        let source = r#"
def query(user_input):
    cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")
"#;

        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let findings = analyze_taint(tree.root_node(), source, &PathBuf::from("test.py"));
        assert!(!findings.is_empty(), "Should detect SQL injection");
        assert!(findings.iter().any(|f| f.severity == "critical"));
    }

    #[test]
    fn test_resource_analysis_finds_leak() {
        let source = r#"
def read_file():
    f = open("test.txt")
    data = f.read()
    return data
"#;

        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let findings = analyze_resources(tree.root_node(), source, &PathBuf::from("test.py"));
        assert!(!findings.is_empty(), "Should detect resource leak");
    }

    #[test]
    fn test_resource_analysis_no_leak_with_context() {
        let source = r#"
def read_file():
    with open("test.txt") as f:
        data = f.read()
    return data
"#;

        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let findings = analyze_resources(tree.root_node(), source, &PathBuf::from("test.py"));
        assert!(
            findings.is_empty(),
            "Should not detect leak with context manager"
        );
    }

    #[test]
    fn test_collect_files_includes_rust() {
        let temp = TempDir::new().unwrap();
        create_test_file(&temp, "sample.py", "print('ok')");
        create_test_file(&temp, "lib.rs", "fn main() {}");
        create_test_file(&temp, "notes.txt", "ignore");

        let files = collect_files(temp.path()).unwrap();
        assert!(files.iter().any(|f| f.ends_with("sample.py")));
        assert!(files.iter().any(|f| f.ends_with("lib.rs")));
        assert!(!files.iter().any(|f| f.ends_with("notes.txt")));
    }

    #[test]
    fn test_rust_secure_metrics_detected() {
        let source = r#"
use std::ptr;

fn risky(user: &str) {
    unsafe { ptr::write(user.as_ptr() as *mut u8, b'x'); }
    let _v = Some(user).unwrap();
    todo!("finish hardening");
}
"#;
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();
        let file = PathBuf::from("src/lib.rs");

        let taint_findings = analyze_taint(tree.root_node(), source, &file);
        let resource_findings = analyze_resources(tree.root_node(), source, &file);
        let bounds_findings = analyze_bounds(tree.root_node(), source, &file);

        assert!(!taint_findings.is_empty(), "Should count unsafe blocks");
        assert!(
            !resource_findings.is_empty(),
            "Should count raw pointer ops"
        );
        assert!(
            bounds_findings.iter().any(|f| f.category == "unwrap"),
            "Should count unwrap calls"
        );
        assert!(
            bounds_findings.iter().any(|f| f.category == "todo_marker"),
            "Should count todo markers"
        );
    }
}