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
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
//! Webhook notifications — `forge-guard notify`.
//!
//! Sends audit summaries to Slack and Discord webhooks. Payload builders are
//! pure functions (unit-testable without network); sending is a thin wrapper
//! over the blocking `reqwest` client.

use crate::core::{Finding, ProjectConfig, Severity};
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};

/// Notification platform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationKind {
    /// Slack incoming webhook (`hooks.slack.com/services/...`)
    Slack,
    /// Discord webhook (`discord.com/api/webhooks/...`)
    Discord,
}

impl NotificationKind {
    /// Parse a platform name (`slack` | `discord`).
    pub fn parse(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "slack" => Ok(Self::Slack),
            "discord" => Ok(Self::Discord),
            other => bail!(
                "Unknown notification platform: '{}'. Use 'slack' or 'discord'.",
                other
            ),
        }
    }

    /// Heuristically detect the platform from a webhook URL.
    pub fn detect(url: &str) -> Self {
        let lower = url.to_lowercase();
        if lower.contains("discord.com/api/webhooks")
            || lower.contains("discordapp.com/api/webhooks")
        {
            Self::Discord
        } else {
            Self::Slack
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Slack => "slack",
            Self::Discord => "discord",
        }
    }
}

/// Summary of an audit/deployment run to be notified about.
#[derive(Debug, Clone)]
pub struct AuditNotification {
    /// Message title (e.g. "Forge Guard Audit", "Deployment blocked").
    pub title: String,
    /// Project name.
    pub project: String,
    /// Target chain.
    pub chain: String,
    /// Overall security score (0–100), if known.
    pub overall_score: Option<u8>,
    /// Risk level label, if known.
    pub risk: Option<String>,
    /// Whether the run succeeded (deployment approved / audit complete).
    pub success: bool,
    /// Findings associated with the run.
    pub findings: Vec<Finding>,
}

impl AuditNotification {
    /// The highest severity present in the findings.
    pub fn max_severity(&self) -> Severity {
        max_severity(&self.findings)
    }
}

/// The highest severity across a set of findings.
pub fn max_severity(findings: &[Finding]) -> Severity {
    findings
        .iter()
        .map(|f| f.severity)
        .max()
        .unwrap_or(Severity::Informational)
}

/// Parse a severity label into a [`Severity`].
pub fn severity_from_str(s: &str) -> Option<Severity> {
    match s.to_lowercase().as_str() {
        "critical" | "crit" => Some(Severity::Critical),
        "high" => Some(Severity::High),
        "medium" | "med" => Some(Severity::Medium),
        "low" => Some(Severity::Low),
        "informational" | "info" => Some(Severity::Informational),
        _ => None,
    }
}

/// Whether the highest finding severity meets the given minimum gate.
pub fn meets_severity_gate(findings: &[Finding], min: Severity) -> bool {
    max_severity(findings) >= min
}

fn severity_color(sev: Severity) -> &'static str {
    match sev {
        Severity::Critical => "#e01e5a",
        Severity::High => "#eb4d4b",
        Severity::Medium => "#f39c12",
        Severity::Low => "#3498db",
        Severity::Informational => "#95a5a6",
    }
}

fn count_by_severity(findings: &[Finding], sev: Severity) -> usize {
    findings.iter().filter(|f| f.severity == sev).count()
}

// ─────────────────────────────────────────────────────────────────
// Payload builders (pure — unit tested)
// ─────────────────────────────────────────────────────────────────

/// Build a Slack `blocks` payload for an audit notification.
pub fn build_slack_payload(n: &AuditNotification) -> Value {
    let critical = count_by_severity(&n.findings, Severity::Critical);
    let high = count_by_severity(&n.findings, Severity::High);
    let medium = count_by_severity(&n.findings, Severity::Medium);
    let low = count_by_severity(&n.findings, Severity::Low);
    let info = count_by_severity(&n.findings, Severity::Informational);

    let mut blocks = vec![
        json!({
            "type": "header",
            "text": {
                "type": "plain_text",
                "text": format!("{}{}", n.title, if n.success { "" } else { "" })
            }
        }),
        json!({
            "type": "section",
            "fields": [
                { "type": "mrkdwn", "text": format!("*Project:*\n{}", n.project) },
                { "type": "mrkdwn", "text": format!("*Chain:*\n{}", n.chain) }
            ]
        }),
    ];

    let mut score_text = String::new();
    if let Some(score) = n.overall_score {
        score_text.push_str(&format!("*Score:* {}/100\n", score));
    }
    if let Some(risk) = &n.risk {
        score_text.push_str(&format!("*Risk:* {}\n", risk));
    }
    if !score_text.is_empty() {
        blocks.push(json!({
            "type": "section",
            "text": { "type": "mrkdwn", "text": score_text.trim_end() }
        }));
    }

    blocks.push(json!({
        "type": "section",
        "fields": [
            { "type": "mrkdwn", "text": format!("🛑 Critical: {}\n🔴 High: {}\n🟡 Medium: {}", critical, high, medium) },
            { "type": "mrkdwn", "text": format!("🔵 Low: {}\n⚪ Info: {}\n*Total:* {}", low, info, n.findings.len()) }
        ]
    }));

    let top: Vec<&Finding> = n
        .findings
        .iter()
        .filter(|f| f.severity >= Severity::High)
        .take(5)
        .collect();
    if !top.is_empty() {
        let mut text = String::from("*Top findings:*\n");
        for f in &top {
            let location = match (&f.file, f.line) {
                (Some(file), Some(line)) => format!("{}:{}", file, line),
                (Some(file), None) => file.clone(),
                (None, _) => "unknown".into(),
            };
            text.push_str(&format!("• [{}] {} ({})\n", f.severity, f.title, location));
        }
        blocks.push(json!({
            "type": "section",
            "text": { "type": "mrkdwn", "text": text.trim_end() }
        }));
    }

    json!({ "blocks": blocks })
}

/// Build a Discord `embeds` payload for an audit notification.
pub fn build_discord_payload(n: &AuditNotification) -> Value {
    let max = n.max_severity();
    let critical = count_by_severity(&n.findings, Severity::Critical);
    let high = count_by_severity(&n.findings, Severity::High);
    let medium = count_by_severity(&n.findings, Severity::Medium);
    let low = count_by_severity(&n.findings, Severity::Low);

    let mut description = format!(
        "🛑 Critical: {} | 🔴 High: {} | 🟡 Medium: {} | 🔵 Low: {}\n*Total findings:* {}",
        critical,
        high,
        medium,
        low,
        n.findings.len()
    );
    if let Some(score) = n.overall_score {
        description.push_str(&format!("\n**Overall score:** {}/100", score));
    }
    if let Some(risk) = &n.risk {
        description.push_str(&format!("\n**Risk level:** {}", risk));
    }

    let top: Vec<&Finding> = n
        .findings
        .iter()
        .filter(|f| f.severity >= Severity::High)
        .take(5)
        .collect();
    if !top.is_empty() {
        let mut list = String::new();
        for f in &top {
            let location = match (&f.file, f.line) {
                (Some(file), Some(line)) => format!("{}:{}", file, line),
                (Some(file), None) => file.clone(),
                (None, _) => "unknown".into(),
            };
            list.push_str(&format!(
                "`[{}]` **{}** — {}\n",
                f.severity, f.title, location
            ));
        }
        description.push_str(&format!("\n\n**Top findings:**\n{}", list.trim_end()));
    }

    json!({
        "username": "Forge Guard",
        "content": format!("{} {}", n.title, if n.success { "" } else { "" }),
        "embeds": [{
            "title": format!("{}{}", n.project, n.chain),
            "description": description,
            "color": u32::from_str_radix(severity_color(max).trim_start_matches('#'), 16).unwrap_or(0x95a5a6)
        }]
    })
}

// ─────────────────────────────────────────────────────────────────
// Sending
// ─────────────────────────────────────────────────────────────────

/// Send a JSON payload to a webhook.
pub fn send(webhook: &str, payload: &Value) -> Result<()> {
    let client = reqwest::blocking::Client::new();
    let response = client
        .post(webhook)
        .json(payload)
        .send()
        .with_context(|| format!("Failed to reach webhook {}", webhook))?;
    if !response.status().is_success() {
        let status = response.status();
        bail!("Webhook returned HTTP {} for {}", status, webhook);
    }
    Ok(())
}

/// Resolve the webhook URL for a platform from CLI override or config.
pub fn resolve_webhook(
    kind: NotificationKind,
    cli_webhook: Option<&str>,
    config: &ProjectConfig,
) -> Option<String> {
    if let Some(url) = cli_webhook {
        return Some(url.to_string());
    }
    let endpoint = match kind {
        NotificationKind::Slack => &config.notifications.slack,
        NotificationKind::Discord => &config.notifications.discord,
    };
    endpoint.webhook.clone()
}

/// Minimum configured severity for a platform (default: high).
pub fn configured_min_severity(kind: NotificationKind, config: &ProjectConfig) -> Severity {
    let endpoint = match kind {
        NotificationKind::Slack => &config.notifications.slack,
        NotificationKind::Discord => &config.notifications.discord,
    };
    severity_from_str(&endpoint.min_severity).unwrap_or(Severity::High)
}

/// Send an audit notification to every configured webhook (best-effort).
///
/// * If no webhook is configured, prints a hint and returns `Ok`.
/// * Skips sending when the highest finding severity is below the
///   configured minimum, unless `force` is set (used for failures).
/// * Send errors are logged as warnings rather than failing the caller.
pub fn notify_from_config(
    config: &ProjectConfig,
    n: &AuditNotification,
    force: bool,
) -> Result<()> {
    for kind in [NotificationKind::Slack, NotificationKind::Discord] {
        let Some(webhook) = resolve_webhook(kind, None, config) else {
            continue;
        };
        let min = configured_min_severity(kind, config);
        if !force && !meets_severity_gate(&n.findings, min) {
            eprintln!(
                "🔕 {} webhook configured but findings are below the {} threshold — skipping",
                kind.as_str(),
                min.label()
            );
            continue;
        }
        let payload = match kind {
            NotificationKind::Slack => build_slack_payload(n),
            NotificationKind::Discord => build_discord_payload(n),
        };
        match send(&webhook, &payload) {
            Ok(()) => eprintln!("📢 {} notification sent", kind.as_str()),
            Err(e) => eprintln!("⚠️  Could not send {} notification: {}", kind.as_str(), e),
        }
    }
    Ok(())
}

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

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

    fn notification() -> AuditNotification {
        AuditNotification {
            title: "Forge Guard Audit".into(),
            project: "demo".into(),
            chain: "ethereum".into(),
            overall_score: Some(62),
            risk: Some("HIGH".into()),
            success: false,
            findings: vec![
                finding(Severity::Critical, "Reentrancy", "Vault.sol", 42),
                finding(Severity::High, "TX Origin", "Vault.sol", 60),
                finding(Severity::Medium, "Unchecked send", "Vault.sol", 80),
            ],
        }
    }

    #[test]
    fn test_kind_detect() {
        assert_eq!(
            NotificationKind::detect("https://hooks.slack.com/services/T000/B000/xxx"),
            NotificationKind::Slack
        );
        assert_eq!(
            NotificationKind::detect("https://discord.com/api/webhooks/123/abc"),
            NotificationKind::Discord
        );
        assert_eq!(
            NotificationKind::detect("https://discordapp.com/api/webhooks/123/abc"),
            NotificationKind::Discord
        );
    }

    #[test]
    fn test_kind_from_str() {
        assert_eq!(
            NotificationKind::parse("slack").unwrap(),
            NotificationKind::Slack
        );
        assert_eq!(
            NotificationKind::parse("Discord").unwrap(),
            NotificationKind::Discord
        );
        assert!(NotificationKind::parse("teams").is_err());
    }

    #[test]
    fn test_severity_gate() {
        let n = notification();
        assert!(meets_severity_gate(&n.findings, Severity::High));
        assert!(meets_severity_gate(&n.findings, Severity::Critical));
        assert!(!meets_severity_gate(&[], Severity::High));
        assert!(meets_severity_gate(&[], Severity::Informational));
    }

    #[test]
    fn test_severity_from_str() {
        assert_eq!(severity_from_str("critical"), Some(Severity::Critical));
        assert_eq!(severity_from_str("HIGH"), Some(Severity::High));
        assert_eq!(severity_from_str("info"), Some(Severity::Informational));
        assert_eq!(severity_from_str("bogus"), None);
    }

    #[test]
    fn test_slack_payload_structure() {
        let payload = build_slack_payload(&notification());
        let blocks = payload["blocks"].as_array().unwrap();
        assert!(blocks.iter().any(|b| b["type"] == "header"));
        assert!(payload.to_string().contains("Forge Guard Audit"));
        assert!(payload.to_string().contains("Vault.sol:42"));
    }

    #[test]
    fn test_discord_payload_structure() {
        let payload = build_discord_payload(&notification());
        assert_eq!(payload["username"], "Forge Guard");
        let embed = &payload["embeds"][0];
        assert!(embed["description"]
            .as_str()
            .unwrap()
            .contains("Critical: 1"));
        // JSON escapes newlines, so match on the score text itself
        assert!(embed["description"].as_str().unwrap().contains("62/100"));
        // Critical severity → red-ish color
        assert_eq!(embed["color"], u32::from_str_radix("e01e5a", 16).unwrap());
    }

    #[test]
    fn test_discord_payload_clean_run_color() {
        let mut n = notification();
        n.success = true;
        n.findings = vec![finding(Severity::Low, "Naming", "Vault.sol", 1)];
        let payload = build_discord_payload(&n);
        assert_eq!(
            payload["embeds"][0]["color"],
            u32::from_str_radix("3498db", 16).unwrap()
        );
    }

    #[test]
    fn test_slack_payload_no_findings() {
        let n = AuditNotification {
            title: "All clear".into(),
            project: "demo".into(),
            chain: "ethereum".into(),
            overall_score: Some(95),
            risk: None,
            success: true,
            findings: vec![],
        };
        let payload = build_slack_payload(&n);
        assert!(payload["blocks"].as_array().unwrap().len() >= 3);
        let body = payload.to_string();
        // NOTE: full needle "Score: 95/100" hits a str::find defect in some
        // rustc builds, so match the field and value separately.
        assert!(body.contains("Score:") && body.contains("95/100"));
        assert!(body.contains("*Total:*"));
    }

    #[test]
    fn test_notify_from_config_no_webhook_is_ok() {
        let config = ProjectConfig::default();
        assert!(notify_from_config(&config, &notification(), false).is_ok());
    }

    #[test]
    fn test_resolve_webhook_cli_overrides_config() {
        let mut config = ProjectConfig::default();
        config.notifications.slack.webhook = Some("https://hooks.slack.com/services/AAA".into());
        assert_eq!(
            resolve_webhook(
                NotificationKind::Slack,
                Some("https://cli.example/webhook"),
                &config
            ),
            Some("https://cli.example/webhook".into())
        );
        assert_eq!(
            resolve_webhook(NotificationKind::Slack, None, &config),
            Some("https://hooks.slack.com/services/AAA".into())
        );
        assert_eq!(
            resolve_webhook(NotificationKind::Discord, None, &config),
            None
        );
    }

    #[test]
    fn test_config_roundtrip() {
        let toml_str = r#"
[notifications.slack]
webhook = "https://hooks.slack.com/services/T/B/X"
min_severity = "critical"
"#;
        let config: ProjectConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(
            config.notifications.slack.webhook.as_deref(),
            Some("https://hooks.slack.com/services/T/B/X")
        );
        assert_eq!(config.notifications.slack.min_severity, "critical");
        assert_eq!(config.notifications.discord.webhook, None);
        // Defaults apply elsewhere
        assert_eq!(config.notifications.discord.min_severity, "high");
    }
}