forge-guard 0.3.4

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
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
//! `forge-guard plugins` — manage audit plugins.

use crate::core::ProjectConfig;
use crate::plugins::{register_default_plugins, PluginRegistry};

use super::{PluginAction, PluginArgs};
use anyhow::{Context, Result};
use colored::*;
use std::path::PathBuf;

/// Manage audit plugins.
pub fn run(args: &PluginArgs) -> Result<()> {
    let config = ProjectConfig::from_default_location();
    let mut registry =
        PluginRegistry::new(&config).context("Failed to initialize plugin registry")?;
    // Register built-in plugins
    register_default_plugins(&mut registry);

    match &args.action {
        Some(action) => match action {
            PluginAction::List => list_plugins(&registry),
            PluginAction::Install { name, source } => install_plugin(name, source.as_deref()),
            PluginAction::Remove { name } => remove_plugin(name),
            PluginAction::Enable { name } => enable_plugin(&mut registry, name),
            PluginAction::Disable { name } => disable_plugin(&mut registry, name),
            PluginAction::New { name } => create_plugin_scaffold(name),
        },
        None => list_plugins(&registry),
    }
}

fn list_plugins(registry: &PluginRegistry) -> Result<()> {
    let plugins = registry.list_plugins();

    println!("{}", "🔌 Installed Plugins".bold());
    println!("{}", "─────────────────────".dimmed());

    if plugins.is_empty() {
        println!("  No plugins installed.");
        println!("  Use `forge-guard plugins install <name>` to add one.");
        return Ok(());
    }

    println!(
        "  {} total ({} built-in, {} external)",
        plugins.len().to_string().bold(),
        plugins
            .iter()
            .filter(|p| matches!(p.plugin_type, crate::plugins::PluginType::Builtin))
            .count(),
        plugins
            .iter()
            .filter(|p| matches!(p.plugin_type, crate::plugins::PluginType::External))
            .count(),
    );
    println!();

    for plugin in &plugins {
        let status = if plugin.enabled {
            "✅ enabled".green()
        } else {
            "⛔ disabled".dimmed()
        };

        let kind = match plugin.plugin_type {
            crate::plugins::PluginType::Builtin => "[built-in]".dimmed(),
            crate::plugins::PluginType::External => "[external]".cyan(),
        };

        let path_display = plugin
            .path
            .as_ref()
            .map(|p| format!(" at {}", p.display()))
            .unwrap_or_default();

        println!(
            "  {} {:30} v{:<8} {} {}",
            status,
            plugin.name.bold(),
            plugin.version,
            kind,
            plugin.description,
        );
        if !path_display.is_empty() {
            println!("  {:>6}{}", "", path_display.dimmed());
        }
    }

    Ok(())
}

fn install_plugin(name: &str, source: Option<&str>) -> Result<()> {
    eprintln!("📦 Installing plugin: {}...", name.bold());

    let plugin_dir = PathBuf::from(".forge-guard").join("plugins").join(name);

    if plugin_dir.exists() {
        anyhow::bail!(
            "Plugin '{}' is already installed at {}",
            name,
            plugin_dir.display()
        );
    }

    std::fs::create_dir_all(&plugin_dir).with_context(|| {
        format!(
            "Failed to create plugin directory: {}",
            plugin_dir.display()
        )
    })?;

    if let Some(src) = source {
        eprintln!("   From: {}", src);
        // Try to clone from git source
        if src.ends_with(".git") || src.starts_with("https://") || src.starts_with("git@") {
            let status = std::process::Command::new("git")
                .args(["clone", src, &plugin_dir.to_string_lossy()])
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .context("Failed to run git clone — is git installed?")?;

            if !status.success() {
                anyhow::bail!("Failed to clone plugin from '{}'", src);
            }
            eprintln!("   ✅ Cloned from {}", src);
        } else {
            // Try to download from a URL
            let status = std::process::Command::new("curl")
                .args([
                    "-sSL",
                    "-o",
                    &plugin_dir.join("plugin.tar.gz").to_string_lossy(),
                    src,
                ])
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status();

            match status {
                Ok(s) if s.success() => {
                    eprintln!("   ✅ Downloaded from {}", src);
                }
                _ => {
                    anyhow::bail!(
                        "Could not install from '{}'. Provide a git URL or use `forge-guard plugins new {}` to create a scaffold.",
                        src, name
                    );
                }
            }
        }
    } else {
        // No source provided — create a basic plugin.toml
        let plugin_toml = format!(
            "[package]\nname = \"{}\"\nversion = \"0.1.0\"\ndescription = \"A forge-guard plugin\"\n\n# Binary to execute (relative to this directory)\nbinary = \"target/release/{}\"\n",
            name, name
        );
        std::fs::write(plugin_dir.join("plugin.toml"), &plugin_toml)
            .context("Failed to write plugin.toml")?;
        eprintln!("   ✅ Created plugin.toml scaffold");
    }

    eprintln!(
        "{} Plugin '{}' installed at {}.",
        "".green(),
        name,
        plugin_dir.display()
    );
    if source.is_none() {
        eprintln!(
            "   {}",
            "Edit plugin.toml and implement your plugin logic.".dimmed()
        );
        eprintln!(
            "   {}",
            "Plugins communicate via JSON IPC on stdin/stdout.".dimmed()
        );
        eprintln!(
            "   {}",
            "See forge-guard docs for the protocol specification.".dimmed()
        );
    }
    Ok(())
}

fn remove_plugin(name: &str) -> Result<()> {
    eprintln!("🗑️  Removing plugin: {}...", name.bold());

    let plugin_dir = PathBuf::from(".forge-guard").join("plugins").join(name);

    if !plugin_dir.exists() {
        anyhow::bail!(
            "Plugin '{}' is not installed at {}",
            name,
            plugin_dir.display()
        );
    }

    // Check if it's a built-in (cannot remove)
    if name.starts_with("forge-guard-") && name != "forge-guard-example" {
        anyhow::bail!(
            "Plugin '{}' is a built-in plugin and cannot be removed.",
            name
        );
    }

    std::fs::remove_dir_all(&plugin_dir).with_context(|| {
        format!(
            "Failed to remove plugin directory: {}",
            plugin_dir.display()
        )
    })?;

    eprintln!("{} Plugin '{}' removed.", "".green(), name);
    Ok(())
}

fn enable_plugin(registry: &mut PluginRegistry, name: &str) -> Result<()> {
    if registry.enable_plugin(name) {
        eprintln!("{} Plugin '{}' enabled.", "".green(), name);
    } else {
        anyhow::bail!(
            "Plugin '{}' not found. Use `forge-guard plugins list` to see all plugins.",
            name
        );
    }
    Ok(())
}

fn disable_plugin(registry: &mut PluginRegistry, name: &str) -> Result<()> {
    if registry.disable_plugin(name) {
        eprintln!("{} Plugin '{}' disabled.", "".yellow(), name);
    } else {
        anyhow::bail!(
            "Plugin '{}' not found. Use `forge-guard plugins list` to see all plugins.",
            name
        );
    }
    Ok(())
}

fn create_plugin_scaffold(name: &str) -> Result<()> {
    let dir = PathBuf::from(".forge-guard").join("plugins").join(name);

    if dir.exists() {
        anyhow::bail!("Plugin directory already exists: {}", dir.display());
    }

    std::fs::create_dir_all(&dir)?;

    // Create plugin.toml metadata
    let plugin_toml = format!(
        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\ndescription = \"A custom forge-guard plugin\"\n\n# Binary to execute (relative to this directory)\nbinary = \"target/release/{}\"\n\n# Protocol version\nprotocol-version = \"1.0\"\n",
        name, name
    );
    std::fs::write(dir.join("plugin.toml"), &plugin_toml)?;

    // Create a Rust plugin scaffold
    let _name_camel: String = name
        .split('-')
        .map(|s| {
            let mut c = s.chars();
            match c.next() {
                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                None => String::new(),
            }
        })
        .collect();

    let plugin_rs = format!(
        r#"//! {} — Forge Guard plugin
//!
//! Generated by `forge-guard plugins new {}`
//!
//! This plugin communicates with forge-guard via JSON IPC:
//! - Reads PluginIpcInput from stdin
//! - Writes PluginIpcOutput to stdout
//!
//! Run `cargo build --release` to compile, then the plugin
//! will be automatically discovered by forge-guard.

use serde::{{Deserialize, Serialize}};
use std::io::{{self, Read, Write}};

/// Input received from forge-guard.
#[derive(Debug, Deserialize)]
struct PluginInput {{
    protocol_version: String,
    plugin_name: String,
    context: serde_json::Value,
}}

/// Output sent back to forge-guard.
#[derive(Debug, Serialize)]
struct PluginOutput {{
    success: bool,
    #[serde(default)]
    findings: Vec<PluginFinding>,
    #[serde(default)]
    error: Option<String>,
    #[serde(default)]
    stats: PluginStats,
}}

#[derive(Debug, Serialize)]
struct PluginFinding {{
    title: String,
    description: String,
    severity: String,
    #[serde(default)]
    file: Option<String>,
    #[serde(default)]
    line: Option<usize>,
    #[serde(default)]
    column: Option<usize>,
    #[serde(default)]
    code_snippet: Option<String>,
    #[serde(default)]
    recommendation: Option<String>,
    #[serde(default)]
    category: Option<String>,
    #[serde(default)]
    blocks_deployment: bool,
    #[serde(default)]
    references: Vec<String>,
}}

#[derive(Debug, Serialize, Default)]
struct PluginStats {{
    files_analyzed: u32,
    duration_ms: u64,
}}

fn main() {{
    // Read the JSON input from stdin
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).expect("Failed to read stdin");

    let _input: PluginInput = match serde_json::from_str(&input) {{
        Ok(i) => i,
        Err(e) => {{
            let output = PluginOutput {{
                success: false,
                findings: Vec::new(),
                error: Some(format!("Failed to parse input: {{}}", e)),
                stats: PluginStats::default(),
            }};
            let json = serde_json::to_string(&output).unwrap();
            println!("{{}}", json);
            return;
        }}
    }};

    // TODO: Implement your analysis logic here
    // The `input.context` field contains project configuration and file paths

    let output = PluginOutput {{
        success: true,
        findings: Vec::new(),
        error: None,
        stats: PluginStats {{
            files_analyzed: 0,
            duration_ms: 0,
        }},
    }};

    let json = serde_json::to_string(&output).unwrap();
    println!("{{}}", json);
}}
"#,
        name, name
    );
    std::fs::write(dir.join("main.rs"), &plugin_rs)?;

    // Create Cargo.toml
    let cargo_toml = format!(
        "[package]\nname = \"forge-guard-plugin-{}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[[bin]]\nname = \"{}\"\npath = \"main.rs\"\n\n[dependencies]\nserde = {{ version = \"1\", features = [\"derive\"] }}\nserde_json = \"1\"\n",
        name, name
    );
    std::fs::write(dir.join("Cargo.toml"), &cargo_toml)?;

    eprintln!(
        "{} Plugin scaffold created at {}",
        "".green(),
        dir.display()
    );
    eprintln!("   📄 plugin.toml  — Plugin metadata");
    eprintln!("   📄 Cargo.toml   — Rust project configuration");
    eprintln!("   📄 main.rs      — Plugin implementation");
    eprintln!();
    eprintln!("   Next steps:");
    eprintln!("     cd {}", dir.display());
    eprintln!("     cargo build --release");
    eprintln!("     forge-guard plugins list  (should show your plugin)");
    Ok(())
}

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

    #[test]
    fn test_plugins_arg_defaults() {
        let args = PluginArgs {
            shared: super::super::SharedFlags {
                chain: "ethereum".into(),
                project: std::path::PathBuf::from("."),
                json: false,
                markdown: false,
                html: false,
                strict: false,
                offline: false,
                production: false,
                report: false,
                parallelism: 4,
            },
            action: None,
        };
        assert!(args.action.is_none());
    }

    #[test]
    fn test_plugin_action_list() {
        let action = PluginAction::List;
        assert!(matches!(action, PluginAction::List));
    }

    #[test]
    fn test_plugin_action_install() {
        let action = PluginAction::Install {
            name: "my-plugin".into(),
            source: None,
        };
        assert!(matches!(action, PluginAction::Install { .. }));
        if let PluginAction::Install { name, .. } = &action {
            assert_eq!(name, "my-plugin");
        }
    }

    #[test]
    fn test_plugin_action_install_with_source() {
        let action = PluginAction::Install {
            name: "external-plugin".into(),
            source: Some("https://github.com/user/plugin".into()),
        };
        if let PluginAction::Install { name, source } = &action {
            assert_eq!(name, "external-plugin");
            assert_eq!(source.as_deref(), Some("https://github.com/user/plugin"));
        } else {
            panic!("Expected Install action");
        }
    }

    #[test]
    fn test_plugin_action_remove() {
        let action = PluginAction::Remove {
            name: "old-plugin".into(),
        };
        if let PluginAction::Remove { name } = &action {
            assert_eq!(name, "old-plugin");
        } else {
            panic!("Expected Remove action");
        }
    }

    #[test]
    fn test_plugin_action_enable() {
        let action = PluginAction::Enable {
            name: "security-plus".into(),
        };
        if let PluginAction::Enable { name } = &action {
            assert_eq!(name, "security-plus");
        } else {
            panic!("Expected Enable action");
        }
    }

    #[test]
    fn test_plugin_action_disable() {
        let action = PluginAction::Disable {
            name: "noisy-plugin".into(),
        };
        if let PluginAction::Disable { name } = &action {
            assert_eq!(name, "noisy-plugin");
        } else {
            panic!("Expected Disable action");
        }
    }

    #[test]
    fn test_plugin_action_new() {
        let action = PluginAction::New {
            name: "my-awesome-plugin".into(),
        };
        if let PluginAction::New { name } = &action {
            assert_eq!(name, "my-awesome-plugin");
        } else {
            panic!("Expected New action");
        }
    }

    #[test]
    fn test_list_plugins_empty_registry() {
        let config = ProjectConfig::default();
        let registry = PluginRegistry::new(&config).unwrap();
        let plugins = registry.list_plugins();
        assert!(plugins.is_empty());
    }

    #[test]
    fn test_list_plugins_with_builtins() {
        let config = ProjectConfig::default();
        let mut registry = PluginRegistry::new(&config).unwrap();
        register_default_plugins(&mut registry);
        let plugins = registry.list_plugins();
        assert_eq!(plugins.len(), 2);
        assert!(plugins.iter().any(|p| p.name == "forge-guard-example"));
        assert!(plugins
            .iter()
            .any(|p| p.name == "forge-guard-offline-guard"));
    }

    #[test]
    fn test_plugin_enable_and_disable_roundtrip() {
        let config = ProjectConfig::default();
        let mut registry = PluginRegistry::new(&config).unwrap();
        register_default_plugins(&mut registry);

        assert!(registry.disable_plugin("forge-guard-example"));
        let plugins = registry.list_plugins();
        let example = plugins
            .iter()
            .find(|p| p.name == "forge-guard-example")
            .unwrap();
        assert!(!example.enabled);

        assert!(registry.enable_plugin("forge-guard-example"));
        let plugins = registry.list_plugins();
        let example = plugins
            .iter()
            .find(|p| p.name == "forge-guard-example")
            .unwrap();
        assert!(example.enabled);
    }

    #[test]
    fn test_plugin_enable_nonexistent_returns_false() {
        let config = ProjectConfig::default();
        let mut registry = PluginRegistry::new(&config).unwrap();
        assert!(!registry.enable_plugin("nonexistent"));
        assert!(!registry.disable_plugin("nonexistent"));
    }

    #[test]
    fn test_install_plugin_dir_does_not_exist_initially() {
        let plugin_dir = std::path::PathBuf::from(".forge-guard")
            .join("plugins")
            .join("test-plugin");
        assert!(!plugin_dir.exists());
    }

    #[test]
    fn test_create_plugin_scaffold_creates_files() {
        // Use a temp directory to avoid polluting the project
        let dir = std::path::PathBuf::from("/tmp/forge-guard-test-plugin-scaffold");
        let _ = std::fs::remove_dir_all(&dir);

        // Create plugin scaffold in temp dir
        let plugin_dir = dir.join(".forge-guard").join("plugins").join("integ-test");
        std::fs::create_dir_all(&plugin_dir).unwrap();

        // Write a plugin.toml similar to what create_plugin_scaffold does
        let plugin_toml = format!(
            "[package]\nname = \"integ-test\"\nversion = \"0.1.0\"\ndescription = \"A custom forge-guard plugin\"\n\n# Binary to execute (relative to this directory)\nbinary = \"target/release/integ-test\"\n\n# Protocol version\nprotocol-version = \"1.0\"\n"
        );
        std::fs::write(plugin_dir.join("plugin.toml"), &plugin_toml).unwrap();

        // Verify files exist
        assert!(plugin_dir.join("plugin.toml").exists());
        let content = std::fs::read_to_string(plugin_dir.join("plugin.toml")).unwrap();
        assert!(content.contains("integ-test"));
        assert!(content.contains("protocol-version"));

        // Cleanup
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_scaffold_name_conversion() {
        // Test the camelCase conversion logic used in create_plugin_scaffold
        let name = "my-custom-plugin";
        let camel: String = name
            .split('-')
            .map(|s| {
                let mut c = s.chars();
                match c.next() {
                    Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                    None => String::new(),
                }
            })
            .collect();
        assert_eq!(camel, "MyCustomPlugin");
    }

    #[test]
    fn test_scaffold_name_conversion_single_word() {
        let name = "plugin";
        let camel: String = name
            .split('-')
            .map(|s| {
                let mut c = s.chars();
                match c.next() {
                    Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                    None => String::new(),
                }
            })
            .collect();
        assert_eq!(camel, "Plugin");
    }

    #[test]
    fn test_remove_nonexistent_bails() {
        let name = "nonexistent-plugin";
        let plugin_dir = std::path::PathBuf::from(".forge-guard")
            .join("plugins")
            .join(name);
        assert!(!plugin_dir.exists());
    }
}