forge-guard 0.1.0

Pre-deployment smart contract auditing framework for Foundry
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
//! `forge audit` — the primary audit command.

use crate::ai::{
    consensus_to_core_finding, create_provider, AuditContext, ConsensusConfig, ConsensusEngine,
    GasAuditor, LlmProvider, LogicAuditor, SecurityAuditor,
};
use crate::chains::ChainRegistry;
use crate::core::{
    AuditResult, AuditSummary, OutputFormat, ProjectConfig, RiskLevel, SecurityScores,
};
use crate::exploit;
use crate::gas;
use crate::plugins::PluginRegistry;
use crate::reports;
use crate::security::SecurityEngine;
use crate::utils::Cache;

use super::AuditArgs;
use anyhow::Result;
use std::time::Instant;

/// Run a comprehensive security audit.
pub fn run(args: &AuditArgs) -> Result<()> {
    let start = Instant::now();

    // Load configuration
    let mut config = ProjectConfig::from_default_location();
    apply_args(&mut config, args);

    // Initialize systems
    let cache = Cache::new(&config)?;
    let chain_registry = ChainRegistry::default();
    let plugin_registry = PluginRegistry::new(&config)?;
    let security_engine = SecurityEngine::new(&config, &plugin_registry)?;

    // Discover Solidity source files
    let source_files = discover_sources(&config)?;
    if source_files.is_empty() {
        anyhow::bail!("No Solidity source files found in {:?}", config.src_dirs);
    }

    // Incremental file analysis: skip unchanged files using content hashing
    let changed_files = cache.filter_changed_files(&source_files);
    let skipped_count = source_files.len() - changed_files.len();
    let files_to_analyze = if changed_files.is_empty() && !source_files.is_empty() {
        // All files unchanged — still analyze them but log it
        source_files.clone()
    } else {
        changed_files
    };

    if skipped_count > 0 && !files_to_analyze.is_empty() {
        eprintln!(
            "⏭️  Skipping {} unchanged files (content hash matched)",
            skipped_count
        );
    }

    // Phase 1: Security analysis
    if args.quick {
        eprintln!(
            "⚡ Running quick audit on {} files (chain: {})...",
            files_to_analyze.len(),
            args.shared.chain
        );
    } else {
        eprintln!(
            "🔍 Running security audit on {} files (chain: {})...",
            files_to_analyze.len(),
            args.shared.chain
        );
    }

    let findings = if args.quick {
        security_engine.analyze_files_quick(&files_to_analyze, &chain_registry)?
    } else {
        security_engine.analyze_files(&files_to_analyze, &chain_registry)?
    };

    // Record file hashes for future incremental analysis
    if !args.quick {
        for file in &files_to_analyze {
            let _ = cache.record_file_hash(file);
        }
    }

    // Phase 2: Exploit analysis (optional — skipped in quick mode)
    let exploit_findings = if !args.quick && (args.exploit || args.full) {
        eprintln!("💥 Running exploit path analysis...");
        exploit::analyze_exploit_paths(&findings, &files_to_analyze)?
    } else {
        Vec::new()
    };

    // Phase 3: Gas analysis (optional — skipped in quick mode)
    let gas_findings = if !args.quick && (args.gas || args.full) {
        eprintln!("⛽ Running gas analysis...");
        gas::analyze_gas(&files_to_analyze, &config)?
    } else {
        Vec::new()
    };

    // Phase 4: AI-powered analysis (optional — skipped in quick mode)
    let ai_findings = if !args.quick && args.ai {
        run_ai_analysis(&files_to_analyze, args, &config)?
    } else {
        Vec::new()
    };

    // Combine all findings
    let mut all_findings = findings;
    all_findings.extend(exploit_findings);
    all_findings.extend(gas_findings);
    all_findings.extend(ai_findings);

    // Calculate scores
    let scores = security_engine.calculate_scores(&all_findings);
    let overall_score = calculate_overall(&scores);
    let risk_level = determine_risk_level(overall_score, &all_findings);
    let production_ready = overall_score >= config.min_deployment_score;
    let deployment_approved = !has_blocking_findings(&all_findings) && production_ready;

    let duration = start.elapsed().as_secs_f64();

    let result = AuditResult {
        project_name: config.project_root.to_string_lossy().to_string(),
        chain: args.shared.chain.clone(),
        timestamp: chrono::Utc::now().to_rfc3339(),
        duration_seconds: duration,
        findings: all_findings.clone(),
        scores,
        overall_score,
        risk_level,
        production_ready,
        deployment_approved,
        summary: build_summary(&all_findings, &source_files),
    };

    // Output
    match config.output {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&result)?);
        }
        OutputFormat::Markdown => {
            let md = reports::markdown::generate_report(&result)?;
            println!("{}", md);
        }
        OutputFormat::Terminal => {
            if args.quick || args.summary {
                // Show executive summary in quick mode or when --summary is set
                let summary = reports::generate_executive_summary(&result);
                println!("{}", summary);
            } else {
                print_terminal_report(&result, args);
            }
        }
    }

    // Write report files if requested
    if args.shared.report {
        let report_dir = std::path::PathBuf::from("reports");
        std::fs::create_dir_all(&report_dir)?;
        reports::json::write_report(&result, &report_dir.join("audit.json"))?;
        let md = reports::markdown::generate_report(&result)?;
        std::fs::write(report_dir.join("audit.md"), md)?;
        eprintln!("📄 Reports saved to reports/");
    }

    // Cache results
    cache.store("last_audit", &result)?;

    if args.shared.strict && all_findings.iter().any(|f| f.severity.score() >= 3) {
        anyhow::bail!("Strict mode: findings detected with severity MEDIUM or higher");
    }

    Ok(())
}

fn apply_args(config: &mut ProjectConfig, args: &AuditArgs) {
    config.chain = args.shared.chain.clone();
    config.project_root = args.shared.project.clone();
    config.strict = args.shared.strict;
    config.offline = args.shared.offline;
    config.production = args.shared.production;
    config.parallelism = args.shared.parallelism;
    config.output = if args.shared.json {
        OutputFormat::Json
    } else if args.shared.markdown {
        OutputFormat::Markdown
    } else {
        OutputFormat::Terminal
    };

    if let Some(exclude) = &args.exclude {
        config.exclude = exclude.split(',').map(String::from).collect();
    }
}

fn discover_sources(config: &ProjectConfig) -> Result<Vec<std::path::PathBuf>> {
    let mut files = Vec::new();
    for dir in &config.src_dirs {
        let dir_path = if dir.is_absolute() {
            dir.clone()
        } else {
            config.project_root.join(dir)
        };
        if !dir_path.exists() {
            continue;
        }
        for entry in walkdir::WalkDir::new(&dir_path)
            .into_iter()
            .filter_entry(|e| {
                !config
                    .exclude
                    .iter()
                    .any(|p| e.file_name().to_string_lossy().contains(p))
            })
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.extension().is_some_and(|ext| ext == "sol") {
                files.push(path.to_path_buf());
            }
        }
    }
    Ok(files)
}

fn calculate_overall(scores: &SecurityScores) -> u8 {
    let vals = [
        scores.access_control,
        scores.security,
        scores.fuzzing,
        scores.gas,
        scores.architecture,
        scores.upgradeability,
        scores.dependencies,
        scores.deployment,
        scores.proxy_safety,
        scores.chain_compatibility,
        scores.production_readiness,
        scores.exploit_resistance,
    ];
    (vals.iter().copied().map(u16::from).sum::<u16>() / vals.len() as u16) as u8
}

fn determine_risk_level(score: u8, findings: &[crate::core::Finding]) -> RiskLevel {
    let has_critical = findings
        .iter()
        .any(|f| f.severity == crate::core::Severity::Critical);
    let has_high = findings
        .iter()
        .any(|f| f.severity == crate::core::Severity::High);

    if has_critical || score < 30 {
        RiskLevel::Critical
    } else if has_high || score < 50 {
        RiskLevel::High
    } else if score < 70 {
        RiskLevel::Medium
    } else if score < 85 {
        RiskLevel::Low
    } else {
        RiskLevel::Minimal
    }
}

fn has_blocking_findings(findings: &[crate::core::Finding]) -> bool {
    findings.iter().any(|f| f.blocks_deployment)
}

fn build_summary(
    findings: &[crate::core::Finding],
    sources: &[std::path::PathBuf],
) -> AuditSummary {
    let mut summary = AuditSummary {
        total_findings: findings.len(),
        critical_count: 0,
        high_count: 0,
        medium_count: 0,
        low_count: 0,
        info_count: 0,
        files_analyzed: sources.len(),
        lines_analyzed: 0,
        contracts_analyzed: sources.len(),
    };

    for f in findings {
        match f.severity {
            crate::core::Severity::Critical => summary.critical_count += 1,
            crate::core::Severity::High => summary.high_count += 1,
            crate::core::Severity::Medium => summary.medium_count += 1,
            crate::core::Severity::Low => summary.low_count += 1,
            crate::core::Severity::Informational => summary.info_count += 1,
        }
    }

    // Estimate lines analyzed
    for src in sources {
        if let Ok(content) = std::fs::read_to_string(src) {
            summary.lines_analyzed += content.lines().count();
        }
    }

    summary
}

fn print_terminal_report(result: &AuditResult, _args: &AuditArgs) {
    use colored::*;

    println!(
        "\n{}",
        "═══════════════════════════════════════════════".bright_blue()
    );
    println!(
        "{}",
        "           FORGE AUDIT — SECURITY REPORT       "
            .bright_blue()
            .bold()
    );
    println!(
        "{}",
        "═══════════════════════════════════════════════".bright_blue()
    );

    println!("\n📋 Project:  {}", result.project_name);
    println!("⛓️  Chain:    {}", result.chain);
    println!("🕐 Duration:  {:.2}s", result.duration_seconds);
    println!("📁 Files:     {}", result.summary.files_analyzed);

    println!("\n{}", "── Findings ──".bold());
    println!(
        "  🛑 Critical:  {}",
        result.summary.critical_count.to_string().red().bold()
    );
    println!(
        "  🔴 High:     {}",
        result.summary.high_count.to_string().red()
    );
    println!(
        "  🟡 Medium:   {}",
        result.summary.medium_count.to_string().yellow()
    );
    println!(
        "  🔵 Low:      {}",
        result.summary.low_count.to_string().blue()
    );
    println!(
        "  ⚪ Info:     {}",
        result.summary.info_count.to_string().dimmed()
    );

    println!("\n{}", "── Scores ──".bold());
    println!(
        "  🔐 Access Control:      {:>3}/100",
        result.scores.access_control
    );
    println!(
        "  🛡️  Security:           {:>3}/100",
        result.scores.security
    );
    println!("  🎯 Fuzzing:             {:>3}/100", result.scores.fuzzing);
    println!("  ⛽ Gas:                 {:>3}/100", result.scores.gas);
    println!(
        "  🏗️  Architecture:       {:>3}/100",
        result.scores.architecture
    );
    println!(
        "  ⬆️  Upgradeability:     {:>3}/100",
        result.scores.upgradeability
    );
    println!(
        "  📦 Dependencies:        {:>3}/100",
        result.scores.dependencies
    );
    println!(
        "  🚀 Deployment:          {:>3}/100",
        result.scores.deployment
    );
    println!(
        "  🔗 Proxy Safety:        {:>3}/100",
        result.scores.proxy_safety
    );
    println!(
        "  ⛓️  Chain Compat:       {:>3}/100",
        result.scores.chain_compatibility
    );
    println!(
        "  ✅ Production Ready:    {:>3}/100",
        result.scores.production_readiness
    );
    println!(
        "  💥 Exploit Resistance:  {:>3}/100",
        result.scores.exploit_resistance
    );

    let overall_color = if result.overall_score >= 85 {
        "green"
    } else if result.overall_score >= 70 {
        "yellow"
    } else {
        "red"
    };
    println!(
        "\n{} {}",
        "Overall Score:".bold(),
        result.overall_score.to_string().color(overall_color).bold()
    );
    println!(
        "{} {}",
        "Risk Level:".bold(),
        format!("{}", result.risk_level)
            .color(match result.risk_level {
                RiskLevel::Critical => "red",
                RiskLevel::High => "red",
                RiskLevel::Medium => "yellow",
                RiskLevel::Low => "green",
                RiskLevel::Minimal => "green",
            })
            .bold()
    );
    println!(
        "{} {}",
        "Production Ready:".bold(),
        if result.production_ready {
            "✅ YES".green().bold()
        } else {
            "❌ NO".red().bold()
        }
    );
    println!(
        "{} {}",
        "Deployment:".bold(),
        if result.deployment_approved {
            "✅ APPROVED".green().bold()
        } else {
            "❌ BLOCKED".red().bold()
        }
    );

    // Show top findings
    let critical_high: Vec<_> = result
        .findings
        .iter()
        .filter(|f| {
            f.severity == crate::core::Severity::Critical
                || f.severity == crate::core::Severity::High
        })
        .collect();
    if !critical_high.is_empty() {
        println!("\n{}", "── Top Findings ──".bold().red());
        for f in critical_high.iter().take(5) {
            println!(
                "\n  [{}] {}",
                f.severity.to_string().red().bold(),
                f.title.bold()
            );
            println!(
                "       📄 {}:{}",
                f.file.as_deref().unwrap_or("?"),
                f.line.map_or("?".into(), |l| l.to_string())
            );
            println!("       💡 {}", f.recommendation);
        }
        if critical_high.len() > 5 {
            println!(
                "\n  ... and {} more critical/high findings",
                critical_high.len() - 5
            );
        }
    }

    println!(
        "\n{}",
        "═══════════════════════════════════════════════".bright_blue()
    );
}

/// Run AI-powered analysis on all source files.
fn run_ai_analysis(
    files: &[std::path::PathBuf],
    args: &AuditArgs,
    config: &ProjectConfig,
) -> Result<Vec<crate::core::Finding>> {
    use std::sync::Arc;

    eprintln!(
        "🤖 Running AI analysis (provider: {}, model: {})...",
        args.ai_provider, args.ai_model
    );

    // Create the LLM provider
    let boxed: Box<dyn LlmProvider> = create_provider(
        &args.ai_provider,
        &args.ai_model,
        config.ai.temperature,
        config.ai.max_tokens,
        args.ai_api_key.clone(),
        args.ollama_endpoint.clone(),
    )?;
    let provider: Arc<dyn LlmProvider> = Arc::from(boxed);

    // Build consensus engine with auditors
    let mut engine = ConsensusEngine::new(ConsensusConfig {
        min_confidence: config.ai.min_confidence,
        ..Default::default()
    });

    // Always add the security auditor
    engine.register(Box::new(SecurityAuditor::new(Arc::clone(&provider))));

    // Optionally add gas and logic auditors
    if args.ai_full || args.full {
        engine.register(Box::new(GasAuditor::new(Arc::clone(&provider))));
        engine.register(Box::new(LogicAuditor::new(Arc::clone(&provider))));
    }

    // Process each file
    let mut all_ai_findings = Vec::new();
    for file_path in files {
        let source_code = match std::fs::read_to_string(file_path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("  ⚠️  Could not read {}: {e}", file_path.display());
                continue;
            }
        };

        let file_name = file_path.to_string_lossy();
        let ctx = AuditContext::new(&source_code, &file_name, &config.chain);

        let report = engine.analyze(&ctx);

        if report.auditor_count > 0 {
            eprintln!(
                "  🤖 {}: {} findings ({} consensus, {} filtered)",
                file_name,
                report.findings.len(),
                report.deduplicated_count,
                report.filtered_count
            );
        }

        // Convert consensus findings to core Findings
        for cf in &report.findings {
            all_ai_findings.push(consensus_to_core_finding(cf, &file_name));
        }
    }

    eprintln!(
        "🤖 AI analysis complete — {} findings reported",
        all_ai_findings.len()
    );

    Ok(all_ai_findings)
}