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
//! Integration tests for quick mode, incremental analysis, and cache features.
//! These tests create temporary Solidity files with known vulnerabilities,
//! run the security engine in both quick and full modes, and validate that
//! the results are correct.

use forge_guard::chains::ChainRegistry;
use forge_guard::core::ProjectConfig;
use forge_guard::plugins::PluginRegistry;
use forge_guard::security::SecurityEngine;
use forge_guard::utils::Cache;
use std::path::Path;

/// A vulnerable Solidity contract with multiple finding types (delegatecall, tx.origin, selfdestruct).
const VULNERABLE_CONTRACT: &str = r#"
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract VulnerableToken {
    address public owner;
    mapping(address => uint256) public balances;

    constructor() {
        owner = msg.sender;
    }

    // Reentrancy: state write after external call
    function withdraw(uint256 amount) external {
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
        balances[msg.sender] -= amount;
    }

    // Access control: no modifier on sensitive function
    function mint(address to, uint256 amount) external {
        balances[to] += amount;
    }

    // tx.origin usage
    function transfer(address to, uint256 amount) external {
        require(tx.origin == owner);
        balances[to] += amount;
    }

    // Unchecked external call to user-supplied address
    function execute(address target, bytes calldata data) external {
        (bool ok, ) = target.call(data);
        require(ok, "call failed");
    }
}
"#;

/// A simple clean contract that should produce no findings.
/// Uses proper NatSpec, storage-optimal types, and no vulnerabilities.
const CLEAN_CONTRACT: &str = r#"
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/// @title Counter
/// @notice A minimal counter without vulnerabilities
contract Counter {
    uint64 private countValue;

    /// @notice Increment the counter
    function increment() external {
        countValue += 1;
    }

    /// @notice Get the current count
    /// @return The current count value
    function getCount() external view returns (uint64) {
        return countValue;
    }
}
"#;

/// Create a temporary .sol file and return its path.
fn create_temp_sol_file(dir: &Path, name: &str, content: &str) -> std::path::PathBuf {
    let path = dir.join(name);
    std::fs::write(&path, content).expect("Failed to write temp file");
    path
}

/// Create a minimal ProjectConfig with caching disabled (to avoid side effects).
fn test_config(temp_dir: &Path) -> ProjectConfig {
    let mut config = ProjectConfig::from_default_location();
    config.project_root = temp_dir.to_path_buf();
    config.cache.enabled = false;
    config.src_dirs = vec![temp_dir.to_path_buf()];
    config
}

/// Create a minimal ProjectConfig with caching enabled.
fn test_config_with_cache(temp_dir: &Path) -> ProjectConfig {
    let mut config = test_config(temp_dir);
    config.cache.enabled = true;
    config.cache.directory = ".test-cache".into();
    config.cache.ttl_seconds = 3600;
    config
}

#[test]
fn test_quick_mode_detects_vulnerabilities() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config(temp.path());
    let plugin_reg = PluginRegistry::new(&config).unwrap();
    let engine = SecurityEngine::new(&config, &plugin_reg).unwrap();
    let chain_reg = ChainRegistry::default();

    let file = create_temp_sol_file(temp.path(), "VulnerableToken.sol", VULNERABLE_CONTRACT);
    let files = vec![file];

    let findings = engine
        .analyze_files_quick(&files, &chain_reg)
        .expect("Quick analysis should succeed");

    // Quick mode should detect pattern-based HIGH/CRITICAL issues
    // (delegatecall, tx.origin, selfdestruct — but NOT reentrancy or access control)
    assert!(
        !findings.is_empty(),
        "Quick mode should find vulnerabilities"
    );

    // Should have findings related to unsafe call patterns
    let tx_origin_findings: Vec<_> = findings
        .iter()
        .filter(|f| f.title.to_lowercase().contains("origin"))
        .collect();
    assert!(
        !tx_origin_findings.is_empty(),
        "Quick mode should detect tx.origin usage"
    );

    // Should NOT contain reentrancy findings (parser-heavy check skipped in quick mode)
    let reentrancy_findings: Vec<_> = findings
        .iter()
        .filter(|f| f.title.to_lowercase().contains("reentrancy"))
        .collect();
    assert!(
        reentrancy_findings.is_empty(),
        "Quick mode should skip parser-heavy reentrancy checks"
    );

    // Should NOT contain access control findings (parser-heavy check skipped)
    let ac_findings: Vec<_> = findings
        .iter()
        .filter(|f| f.title.to_lowercase().contains("access control"))
        .collect();
    assert!(
        ac_findings.is_empty(),
        "Quick mode should skip parser-heavy access control checks"
    );
}

#[test]
fn test_full_mode_finds_more_than_quick_mode() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config(temp.path());
    let plugin_reg = PluginRegistry::new(&config).unwrap();
    let engine = SecurityEngine::new(&config, &plugin_reg).unwrap();
    let chain_reg = ChainRegistry::default();

    let file = create_temp_sol_file(temp.path(), "VulnerableToken.sol", VULNERABLE_CONTRACT);
    let files = vec![file];

    let quick_findings = engine
        .analyze_files_quick(&files, &chain_reg)
        .expect("Quick analysis should succeed");
    let full_findings = engine
        .analyze_files(&files, &chain_reg)
        .expect("Full analysis should succeed");

    // Full mode should find strictly more findings than quick mode
    assert!(
        full_findings.len() >= quick_findings.len(),
        "Full mode ({}) should find at least as many findings as quick mode ({})",
        full_findings.len(),
        quick_findings.len()
    );

    // Full mode should include reentrancy findings
    let reentrancy_in_full: Vec<_> = full_findings
        .iter()
        .filter(|f| f.title.to_lowercase().contains("reentrancy"))
        .collect();
    assert!(
        !reentrancy_in_full.is_empty(),
        "Full mode should detect reentrancy issues"
    );

    // Full mode should include access control findings
    let ac_in_full: Vec<_> = full_findings
        .iter()
        .filter(|f| f.title.to_lowercase().contains("access control"))
        .collect();
    assert!(
        !ac_in_full.is_empty(),
        "Full mode should detect access control issues"
    );
}

#[test]
fn test_clean_contract_no_findings() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config(temp.path());
    let plugin_reg = PluginRegistry::new(&config).unwrap();
    let engine = SecurityEngine::new(&config, &plugin_reg).unwrap();
    let chain_reg = ChainRegistry::default();

    let file = create_temp_sol_file(temp.path(), "Counter.sol", CLEAN_CONTRACT);
    let files = vec![file];

    let quick_findings = engine
        .analyze_files_quick(&files, &chain_reg)
        .expect("Quick analysis should succeed");
    let full_findings = engine
        .analyze_files(&files, &chain_reg)
        .expect("Full analysis should succeed");

    // Clean contract should have zero findings in both modes
    assert!(
        quick_findings.is_empty(),
        "Clean contract should have 0 quick findings, got {}",
        quick_findings.len()
    );
    assert!(
        full_findings.is_empty(),
        "Clean contract should have 0 full findings, got {}",
        full_findings.len()
    );
}

#[test]
fn test_incremental_file_analysis_unchanged() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config_with_cache(temp.path());
    let cache = Cache::new(&config).expect("Cache creation should succeed");

    let file = create_temp_sol_file(temp.path(), "test.sol", CLEAN_CONTRACT);

    // First run: file should be flagged as changed (not cached yet)
    assert!(
        !cache.is_file_unchanged(&file),
        "New file should not be unchanged"
    );

    // Record the hash
    cache
        .record_file_hash(&file)
        .expect("Recording file hash should succeed");

    // Immediately after recording, file should be unchanged
    assert!(
        cache.is_file_unchanged(&file),
        "File should be unchanged after recording hash"
    );
}

#[test]
fn test_incremental_file_analysis_modified() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config_with_cache(temp.path());
    let cache = Cache::new(&config).expect("Cache creation should succeed");

    let file = create_temp_sol_file(temp.path(), "test.sol", CLEAN_CONTRACT);

    // Record the initial hash
    cache
        .record_file_hash(&file)
        .expect("Recording initial hash should succeed");

    // File should be unchanged initially
    assert!(cache.is_file_unchanged(&file));

    // Now modify the file
    const MODIFIED_CONTRACT: &str = r#"
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Modified {
    uint256 public value;
    function set(uint256 v) external { value = v; }
}
"#;
    std::fs::write(&file, MODIFIED_CONTRACT).expect("Failed to modify file");

    // After modification, file should be flagged as changed
    assert!(
        !cache.is_file_unchanged(&file),
        "Modified file should be detected as changed"
    );
}

#[test]
fn test_filter_changed_files() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config_with_cache(temp.path());
    let cache = Cache::new(&config).expect("Cache creation should succeed");

    let file1 = create_temp_sol_file(temp.path(), "unchanged.sol", CLEAN_CONTRACT);
    let file2 = create_temp_sol_file(temp.path(), "changed.sol", CLEAN_CONTRACT);

    // Record both file hashes
    cache.record_file_hash(&file1).expect("Should record hash");
    cache.record_file_hash(&file2).expect("Should record hash");

    // Modify file2
    std::fs::write(&file2, VULNERABLE_CONTRACT).expect("Failed to modify file2");

    let files = vec![file1.clone(), file2.clone()];
    let changed = cache.filter_changed_files(&files);

    // Only file2 should be in the changed list
    assert_eq!(changed.len(), 1, "Only one file should be changed");
    assert_eq!(
        changed[0], file2,
        "The modified file should be the only changed file"
    );
}

#[test]
fn test_quick_mode_with_vulnerable_token_detects_relevant_issues() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config(temp.path());
    let plugin_reg = PluginRegistry::new(&config).unwrap();
    let engine = SecurityEngine::new(&config, &plugin_reg).unwrap();
    let chain_reg = ChainRegistry::default();

    // Create a contract with only delegatecall-related vulnerability patterns
    let delegatecall_contract = r#"
pragma solidity ^0.8.20;
contract Proxy {
    address public implementation;
    function delegate(address target, bytes calldata data) external {
        (bool ok, ) = target.delegatecall(data);
        require(ok);
    }
}
"#;

    let file = create_temp_sol_file(temp.path(), "Proxy.sol", delegatecall_contract);
    let files = vec![file];

    let quick_findings = engine
        .analyze_files_quick(&files, &chain_reg)
        .expect("Quick analysis should succeed");

    // Quick mode should find delegatecall (line-based HIGH check)
    let dc_findings: Vec<_> = quick_findings
        .iter()
        .filter(|f| f.title.to_lowercase().contains("delegatecall"))
        .collect();
    assert!(
        !dc_findings.is_empty(),
        "Quick mode should detect delegatecall usage"
    );
}

#[test]
fn test_cache_file_hash_consistency() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");

    let file = create_temp_sol_file(temp.path(), "test.sol", CLEAN_CONTRACT);

    // Same file should always produce the same hash
    let hash1 = Cache::file_hash(&file).expect("First hash should succeed");
    let hash2 = Cache::file_hash(&file).expect("Second hash should succeed");

    assert_eq!(hash1, hash2, "File hash should be consistent");

    // Different content should produce different hash
    let other_file = create_temp_sol_file(temp.path(), "other.sol", VULNERABLE_CONTRACT);
    let hash3 = Cache::file_hash(&other_file).expect("Third hash should succeed");

    assert_ne!(hash1, hash3, "Different files should have different hashes");
}

#[test]
fn test_quick_mode_capped_findings() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let config = test_config(temp.path());
    let plugin_reg = PluginRegistry::new(&config).unwrap();
    let engine = SecurityEngine::new(&config, &plugin_reg).unwrap();
    let chain_reg = ChainRegistry::default();

    // Create a file with many vulnerability patterns
    let mut content = String::from("pragma solidity ^0.8.20;\ncontract ManyIssues {\n");
    for i in 0..10 {
        content.push_str(&format!(
            "    function issue{}() external {{ (bool ok, ) = address(0x{}).delegatecall(\"\"); require(ok); }}\n",
            i,
            format!("{:040x}", i)
        ));
    }
    content.push_str("}\n");

    let file = create_temp_sol_file(temp.path(), "ManyIssues.sol", &content);
    let files = vec![file];

    let quick_findings = engine
        .analyze_files_quick(&files, &chain_reg)
        .expect("Quick analysis should succeed");

    // Should find delegatecall issues but capped per check
    assert!(
        !quick_findings.is_empty(),
        "Quick mode should find some issues"
    );

    // All findings should be delegatecall-related (the quick checks running)
    let all_delegatecall = quick_findings
        .iter()
        .all(|f| f.title.to_lowercase().contains("delegatecall"));
    assert!(
        all_delegatecall,
        "Quick mode should only find delegatecall issues, found: {:?}",
        quick_findings.iter().map(|f| &f.title).collect::<Vec<_>>()
    );
}

#[test]
fn test_cache_disabled_no_effect() {
    let temp = tempfile::tempdir().expect("Failed to create temp dir");
    let mut config = test_config_with_cache(temp.path());
    config.cache.enabled = false;
    let cache = Cache::new(&config).expect("Cache creation should succeed");

    let file = create_temp_sol_file(temp.path(), "test.sol", CLEAN_CONTRACT);

    // With cache disabled, is_file_unchanged should always return false
    assert!(
        !cache.is_file_unchanged(&file),
        "Disabled cache should report file as changed"
    );

    // Recording should not error but should have no effect
    cache
        .record_file_hash(&file)
        .expect("Recording with disabled cache should not error");

    // Still unchanged should be false
    assert!(
        !cache.is_file_unchanged(&file),
        "Disabled cache should still report file as changed after recorded"
    );

    // filter_changed_files should return all files
    let files = vec![file];
    let changed = cache.filter_changed_files(&files);
    assert_eq!(
        changed.len(),
        1,
        "Disabled cache should return all files as changed"
    );
}