forge-guard 0.3.6

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
//! Historical trend tracking — M16.
//!
//! Persists audit results in a local SQLite database (default
//! `~/.forge-guard/history.db`) so teams can track their security posture
//! over time:
//!
//! * `forge-guard report --history` — score trends over time
//! * `forge-guard report --regression` — new findings since the last audit
//!
//! Recording is opt-in (`--enable-history` or `[history] enabled = true`) and
//! best-effort — a failed write is logged as a warning and never fails the
//! audit itself.

use crate::core::{AuditResult, Finding, ForgeGuardError, ProjectConfig};
use rusqlite::{params, Connection};
use std::path::PathBuf;

/// One stored audit record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryEntry {
    /// Row id in the database.
    pub id: i64,
    /// RFC3339 timestamp of the audit.
    pub timestamp: String,
    /// Project name (project root path as reported by the audit).
    pub project: String,
    /// Target chain (or "all" for `--all-chains` audits).
    pub chain: String,
    /// Overall security score (0-100).
    pub overall_score: u8,
    /// Risk level label.
    pub risk_level: String,
    /// Total number of findings.
    pub total_findings: usize,
    pub critical_count: usize,
    pub high_count: usize,
    pub medium_count: usize,
    pub low_count: usize,
    pub info_count: usize,
    /// Finding signatures present in this audit (for regression detection).
    pub finding_signatures: Vec<String>,
}

/// A stable signature identifying a finding across audits. Line numbers are
/// intentionally excluded so that code edits which shift lines don't turn a
/// pre-existing issue into a false "new finding".
pub fn finding_signature(f: &Finding) -> String {
    format!(
        "{}|{}|{}",
        f.severity.label(),
        f.file.as_deref().unwrap_or(""),
        f.title.to_lowercase()
    )
}

/// Result of comparing the current audit against the previous snapshot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Regression {
    /// Signatures of findings present now but not in the previous audit.
    pub new_signatures: Vec<String>,
    /// Signatures present in the previous audit but gone now.
    pub resolved_signatures: Vec<String>,
}

/// Compute new/resolved findings between two audits.
///
/// `previous` is the set of signatures from the earlier audit (e.g.
/// [`HistoryEntry::finding_signatures`]); `current` is the live findings of
/// the latest audit. Signatures are matched set-wise, so findings are stable
/// across line-number shifts.
pub fn regression(current: &[Finding], previous: &[String]) -> Regression {
    let current_set: std::collections::HashSet<String> =
        current.iter().map(finding_signature).collect();
    let previous_set: std::collections::HashSet<String> = previous.iter().cloned().collect();

    let mut new_signatures: Vec<String> = current_set.difference(&previous_set).cloned().collect();
    new_signatures.sort();

    let mut resolved_signatures: Vec<String> =
        previous_set.difference(&current_set).cloned().collect();
    resolved_signatures.sort();

    Regression {
        new_signatures,
        resolved_signatures,
    }
}

/// Handle to the local history SQLite database.
pub struct HistoryStore {
    conn: Connection,
}

impl HistoryStore {
    /// Open (creating if needed) the history database configured for the
    /// given project. Creates the parent directory and the schema.
    pub fn open(config: &ProjectConfig) -> Result<Self, ForgeGuardError> {
        let path = db_path(config);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let conn = Connection::open(&path)?;
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS audit_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT NOT NULL,
                project TEXT NOT NULL,
                chain TEXT NOT NULL,
                overall_score INTEGER NOT NULL,
                risk_level TEXT NOT NULL,
                total_findings INTEGER NOT NULL,
                critical_count INTEGER NOT NULL,
                high_count INTEGER NOT NULL,
                medium_count INTEGER NOT NULL,
                low_count INTEGER NOT NULL,
                info_count INTEGER NOT NULL,
                finding_signatures TEXT NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_history_project
                ON audit_history(project, timestamp);",
        )?;
        Ok(Self { conn })
    }

    /// Persist an audit result as a history entry.
    pub fn record(&self, result: &AuditResult) -> Result<(), ForgeGuardError> {
        let signatures: Vec<String> = result.findings.iter().map(finding_signature).collect();
        self.conn.execute(
            "INSERT INTO audit_history (
                timestamp, project, chain, overall_score, risk_level,
                total_findings, critical_count, high_count, medium_count,
                low_count, info_count, finding_signatures
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
            params![
                result.timestamp,
                result.project_name,
                result.chain,
                i64::from(result.overall_score),
                result.risk_level.to_string(),
                result.summary.total_findings as i64,
                result.summary.critical_count as i64,
                result.summary.high_count as i64,
                result.summary.medium_count as i64,
                result.summary.low_count as i64,
                result.summary.info_count as i64,
                serde_json::to_string(&signatures).unwrap_or_else(|_| "[]".into()),
            ],
        )?;
        Ok(())
    }

    /// Most recent history entries for a project, newest first.
    pub fn trends(
        &self,
        project: &str,
        limit: usize,
    ) -> Result<Vec<HistoryEntry>, ForgeGuardError> {
        let limit = limit.max(1) as i64;
        let mut stmt = self.conn.prepare(
            "SELECT id, timestamp, project, chain, overall_score, risk_level,
                    total_findings, critical_count, high_count, medium_count,
                    low_count, info_count, finding_signatures
             FROM audit_history
             WHERE project = ?1
             ORDER BY timestamp DESC, id DESC
             LIMIT ?2",
        )?;
        let rows = stmt.query_map(params![project, limit], row_to_entry)?;
        let mut entries = Vec::new();
        for row in rows {
            entries.push(row?);
        }
        Ok(entries)
    }

    /// Latest history entry for a project + chain (used for regression).
    pub fn latest(
        &self,
        project: &str,
        chain: &str,
    ) -> Result<Option<HistoryEntry>, ForgeGuardError> {
        let mut stmt = self.conn.prepare(
            "SELECT id, timestamp, project, chain, overall_score, risk_level,
                    total_findings, critical_count, high_count, medium_count,
                    low_count, info_count, finding_signatures
             FROM audit_history
             WHERE project = ?1 AND chain = ?2
             ORDER BY timestamp DESC, id DESC
             LIMIT 1",
        )?;
        let mut rows = stmt.query_map(params![project, chain], row_to_entry)?;
        Ok(rows.next().transpose()?)
    }
}

fn row_to_entry(row: &rusqlite::Row<'_>) -> rusqlite::Result<HistoryEntry> {
    let signatures_json: String = row.get(12)?;
    let finding_signatures: Vec<String> =
        serde_json::from_str(&signatures_json).unwrap_or_default();
    Ok(HistoryEntry {
        id: row.get(0)?,
        timestamp: row.get(1)?,
        project: row.get(2)?,
        chain: row.get(3)?,
        overall_score: row.get::<_, i64>(4)? as u8,
        risk_level: row.get(5)?,
        total_findings: row.get::<_, i64>(6)? as usize,
        critical_count: row.get::<_, i64>(7)? as usize,
        high_count: row.get::<_, i64>(8)? as usize,
        medium_count: row.get::<_, i64>(9)? as usize,
        low_count: row.get::<_, i64>(10)? as usize,
        info_count: row.get::<_, i64>(11)? as usize,
        finding_signatures,
    })
}

/// Resolve the history database path from configuration.
///
/// * `[history] db_path` set and absolute → used directly
/// * `[history] db_path` set and relative → resolved against the project root
/// * `~` prefix → expanded to the user's home directory
/// * unset → `~/.forge-guard/history.db`
pub fn db_path(config: &ProjectConfig) -> PathBuf {
    if let Some(p) = &config.history.db_path {
        let expanded = expand_tilde(p);
        let path = PathBuf::from(expanded);
        if path.is_absolute() {
            path
        } else {
            config.project_root.join(path)
        }
    } else {
        default_db_path()
    }
}

/// `~/.forge-guard/history.db`, falling back to `$USERPROFILE` on Windows and
/// finally to `.forge-guard/history.db` relative to the current directory.
pub fn default_db_path() -> PathBuf {
    if let Some(home) = home_dir() {
        PathBuf::from(home).join(".forge-guard").join("history.db")
    } else {
        PathBuf::from(".forge-guard").join("history.db")
    }
}

fn expand_tilde(path: &str) -> String {
    if let Some(rest) = path.strip_prefix("~/") {
        if let Some(home) = home_dir() {
            return format!("{}/{}", home, rest);
        }
    }
    path.to_string()
}

fn home_dir() -> Option<String> {
    std::env::var("HOME")
        .ok()
        .or_else(|| std::env::var("USERPROFILE").ok())
}

/// Truncate an RFC3339 timestamp to second precision for display.
pub fn format_timestamp(ts: &str) -> &str {
    &ts[..ts.len().min(19)]
}

/// Format a history entry for the `report --history` table:
/// `date, chain, score, risk, findings summary`.
pub fn format_trend_row(entry: &HistoryEntry) -> String {
    format!(
        "  {:<19} {:<12} {:>9} {:<9} {} (🛑{} 🔴{} 🟡{} 🔵{}{})",
        format_timestamp(&entry.timestamp),
        entry.chain,
        format!("{}/100", entry.overall_score),
        entry.risk_level,
        entry.total_findings,
        entry.critical_count,
        entry.high_count,
        entry.medium_count,
        entry.low_count,
        entry.info_count,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{AuditSummary, RiskLevel, SecurityScores, Severity};

    fn finding(sev: Severity, title: &str, file: &str) -> Finding {
        Finding::builder()
            .id(&format!("FA-{}-1", sev.label()))
            .title(title)
            .description("desc")
            .severity(sev)
            .file(file)
            .location(1, 0)
            .recommendation("fix")
            .category("Security")
            .build()
    }

    fn sample_result(score: u8, findings: Vec<Finding>) -> AuditResult {
        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: 1,
            lines_analyzed: 10,
            contracts_analyzed: 1,
        };
        for f in &findings {
            match f.severity {
                Severity::Critical => summary.critical_count += 1,
                Severity::High => summary.high_count += 1,
                Severity::Medium => summary.medium_count += 1,
                Severity::Low => summary.low_count += 1,
                Severity::Informational => summary.info_count += 1,
            }
        }
        AuditResult {
            project_name: "demo".into(),
            chain: "ethereum".into(),
            chains: vec!["ethereum".into()],
            timestamp: "2026-08-17T10:00:00Z".into(),
            duration_seconds: 1.0,
            findings,
            scores: SecurityScores::perfect(),
            overall_score: score,
            risk_level: RiskLevel::Low,
            production_ready: true,
            deployment_approved: true,
            summary,
        }
    }

    #[test]
    fn test_finding_signature_is_stable_across_lines() {
        let a = finding(Severity::High, "Reentrancy", "Vault.sol");
        let mut b = finding(Severity::High, "Reentrancy", "Vault.sol");
        b.line = Some(999);
        assert_eq!(finding_signature(&a), finding_signature(&b));

        let c = finding(Severity::High, "Access Control", "Vault.sol");
        assert_ne!(finding_signature(&a), finding_signature(&c));
        assert_eq!(
            finding_signature(&a),
            "HIGH|Vault.sol|reentrancy".to_string()
        );
    }

    #[test]
    fn test_regression_detects_new_and_resolved() {
        let current = vec![
            finding(Severity::High, "Reentrancy", "Vault.sol"),
            finding(Severity::Medium, "Gas", "Vault.sol"),
        ];
        let previous = vec![finding_signature(&finding(
            Severity::High,
            "Reentrancy",
            "Vault.sol",
        ))];

        let diff = regression(&current, &previous);
        assert_eq!(diff.new_signatures, vec!["MEDIUM|Vault.sol|gas"]);
        assert!(diff.resolved_signatures.is_empty());

        // A finding fixed in the current audit shows up as resolved
        let diff2 = regression(&[], &previous);
        assert!(diff2.new_signatures.is_empty());
        assert_eq!(diff2.resolved_signatures, previous);
    }

    #[test]
    fn test_regression_ignores_line_shifts() {
        let mut before = finding(Severity::High, "Reentrancy", "Vault.sol");
        before.line = Some(10);
        let after = finding(Severity::High, "Reentrancy", "Vault.sol");
        let diff = regression(&[after], &[finding_signature(&before)]);
        assert!(
            diff.new_signatures.is_empty(),
            "line shifts must not regress"
        );
    }

    #[test]
    fn test_record_and_trends_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let config = ProjectConfig {
            history: crate::core::config::HistoryConfig {
                enabled: true,
                db_path: Some(dir.path().join("history.db").to_string_lossy().into()),
            },
            ..ProjectConfig::default()
        };

        let store = HistoryStore::open(&config).unwrap();
        let mut result = sample_result(80, vec![finding(Severity::High, "Reentrancy", "V.sol")]);
        result.timestamp = "2026-08-17T10:00:00Z".into();
        store.record(&result).unwrap();
        let mut result2 = sample_result(90, vec![]);
        result2.timestamp = "2026-08-18T10:00:00Z".into();
        store.record(&result2).unwrap();

        let trends = store.trends("demo", 10).unwrap();
        assert_eq!(trends.len(), 2);
        // Newest first
        assert_eq!(trends[0].overall_score, 90);
        assert_eq!(trends[0].finding_signatures.len(), 0);
        assert_eq!(trends[1].overall_score, 80);
        assert_eq!(
            trends[1].finding_signatures,
            vec!["HIGH|V.sol|reentrancy".to_string()]
        );

        let latest = store.latest("demo", "ethereum").unwrap().unwrap();
        assert_eq!(latest.overall_score, 90);
    }

    #[test]
    fn test_latest_filters_by_chain_and_project() {
        let dir = tempfile::tempdir().unwrap();
        let config = ProjectConfig {
            history: crate::core::config::HistoryConfig {
                enabled: true,
                db_path: Some(dir.path().join("history.db").to_string_lossy().into()),
            },
            ..ProjectConfig::default()
        };
        let store = HistoryStore::open(&config).unwrap();
        store.record(&sample_result(80, vec![])).unwrap();
        assert!(store.latest("other-project", "ethereum").unwrap().is_none());
        assert!(store.latest("demo", "base").unwrap().is_none());
        assert!(store.latest("demo", "ethereum").unwrap().is_some());
    }

    #[test]
    fn test_db_path_resolution() {
        // Explicit absolute path is used directly
        let config = ProjectConfig {
            history: crate::core::config::HistoryConfig {
                enabled: true,
                db_path: Some("/tmp/custom/history.db".into()),
            },
            ..ProjectConfig::default()
        };
        assert_eq!(db_path(&config), PathBuf::from("/tmp/custom/history.db"));

        // Relative path resolves against the project root
        let config = ProjectConfig {
            project_root: "/home/user/proj".into(),
            history: crate::core::config::HistoryConfig {
                enabled: true,
                db_path: Some("history.db".into()),
            },
            ..ProjectConfig::default()
        };
        assert_eq!(
            db_path(&config),
            PathBuf::from("/home/user/proj/history.db")
        );

        // Tilde expands to the home directory
        let config = ProjectConfig {
            history: crate::core::config::HistoryConfig {
                enabled: true,
                db_path: Some("~/.forge-guard/history.db".into()),
            },
            ..ProjectConfig::default()
        };
        let path = db_path(&config);
        assert!(path.is_absolute());

        // Default resolves to ~/.forge-guard/history.db
        let config = ProjectConfig::default();
        let path = default_db_path();
        assert!(path.to_string_lossy().contains(".forge-guard"));
        let _ = &config;
    }
}