dalfox-rs 0.3.0

Type-safe asynchronous wrapper for the Dalfox XSS scanner (Dalfox ≥3) with JSON findings, stored XSS support, and multi-format result formatting
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
//! Strictly-typed structures for Dalfox scan results.
//!
//! Every field from Dalfox's JSON output is mapped to a concrete Rust type,
//! with enums for known-finite value sets and `Other`/`Unknown` fallbacks
//! for forward compatibility with newer Dalfox versions.

use serde::{Deserialize, Serialize};
use std::fmt;

/// The classification of a finding event.
///
/// Dalfox emits different event types depending on the confidence
/// and nature of the detection.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EventType {
    /// Verified XSS vulnerability with confirmed execution.
    #[serde(rename = "V")]
    Verified,
    /// Grep-based match (information disclosure, sensitive patterns).
    #[serde(rename = "G")]
    Grep,
    /// Informational finding (no direct vulnerability).
    #[serde(rename = "I")]
    Information,
    /// Reflected parameter detected but unverified.
    #[serde(rename = "R")]
    Reflected,
    /// AST-based DOM XSS detection.
    #[serde(rename = "A")]
    Ast,
    /// Unknown event type from a newer Dalfox version.
    #[serde(untagged)]
    Other(String),
}

impl fmt::Display for EventType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Verified => write!(f, "Verified"),
            Self::Grep => write!(f, "Grep"),
            Self::Information => write!(f, "Info"),
            Self::Reflected => write!(f, "Reflected"),
            Self::Ast => write!(f, "AST"),
            Self::Other(s) => write!(f, "{s}"),
        }
    }
}

/// Vulnerability severity as reported by Dalfox.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Severity {
    /// High severity (critical/high impact XSS).
    #[serde(rename = "High")]
    High,
    /// Medium severity.
    #[serde(rename = "Medium")]
    Medium,
    /// Low severity.
    #[serde(rename = "Low")]
    Low,
    /// Informational severity.
    #[serde(rename = "Information", alias = "Info")]
    Information,
    /// Unknown severity from a newer Dalfox version.
    #[serde(untagged)]
    Unknown(String),
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::High => write!(f, "High"),
            Self::Medium => write!(f, "Medium"),
            Self::Low => write!(f, "Low"),
            Self::Information => write!(f, "Info"),
            Self::Unknown(s) => write!(f, "{s}"),
        }
    }
}

/// HTTP method used in the finding.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Method {
    /// HTTP GET.
    #[serde(rename = "GET")]
    Get,
    /// HTTP POST.
    #[serde(rename = "POST")]
    Post,
    /// HTTP PUT.
    #[serde(rename = "PUT")]
    Put,
    /// HTTP DELETE.
    #[serde(rename = "DELETE")]
    Delete,
    /// HTTP HEAD.
    #[serde(rename = "HEAD")]
    Head,
    /// HTTP OPTIONS.
    #[serde(rename = "OPTIONS")]
    Options,
    /// HTTP PATCH.
    #[serde(rename = "PATCH")]
    Patch,
    /// Other or custom HTTP method.
    #[serde(untagged)]
    Other(String),
}

impl fmt::Display for Method {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Get => write!(f, "GET"),
            Self::Post => write!(f, "POST"),
            Self::Put => write!(f, "PUT"),
            Self::Delete => write!(f, "DELETE"),
            Self::Head => write!(f, "HEAD"),
            Self::Options => write!(f, "OPTIONS"),
            Self::Patch => write!(f, "PATCH"),
            Self::Other(s) => write!(f, "{s}"),
        }
    }
}

/// A structured finding reported by Dalfox via its JSON output.
///
/// Each finding represents a single detected XSS vector with full
/// contextual information about the injection point, payload, and evidence.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DalfoxFinding {
    /// The classification of this finding (verified, grep, info, reflected).
    #[serde(rename = "type")]
    pub event_type: EventType,

    /// The proof-of-concept URL demonstrating the vulnerability.
    pub poc: String,

    /// HTTP method used for the scan request.
    pub method: Method,

    /// Request body data (populated for POST, PUT, etc).
    #[serde(default)]
    pub data: String,

    /// The specific parameter that was injected.
    pub param: String,

    /// The actual XSS payload used.
    pub payload: String,

    /// The response snippet verifying payload reflection or execution.
    #[serde(default)]
    pub evidence: String,

    /// CWE classification identifier (e.g. "CWE-79").
    pub cwe: String,

    /// The vulnerability severity rating.
    pub severity: Severity,
}

impl fmt::Display for DalfoxFinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{sev}][{evt}] {cwe} on param '{param}' via {method}{poc}",
            sev = self.severity,
            evt = self.event_type,
            cwe = self.cwe,
            param = self.param,
            method = self.method,
            poc = self.poc,
        )
    }
}

/// Top-level JSON document emitted by Dalfox v3 with `--format json`.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct DalfoxJsonEnvelope {
    /// Parsed XSS findings from the scan.
    #[serde(default)]
    pub findings: Vec<DalfoxFinding>,
    /// Scan metadata (version, timing, counts). Ignored if absent or unparseable.
    #[serde(default)]
    pub meta: Option<serde_json::Value>,
}

/// Aggregate results from a Dalfox scan execution.
///
/// Contains the parsed findings, diagnostic metadata, and any parse errors
/// encountered while processing Dalfox's output stream.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct DalfoxResult {
    /// The detected XSS findings from the scan.
    pub findings: Vec<DalfoxFinding>,

    /// Lines from Dalfox output that failed to parse as valid findings.
    ///
    /// Non-empty values indicate a potential Dalfox schema change or
    /// corrupted output. Each entry contains `"parse_error: raw_line"`.
    pub parse_errors: Vec<String>,

    /// Captured stderr output from the Dalfox process.
    ///
    /// Contains warnings, progress information, and diagnostic messages
    /// emitted by the Dalfox binary during execution.
    pub stderr_output: String,

    /// The exit code of the Dalfox process, if available.
    pub exit_code: Option<i32>,

    /// Wall-clock duration of the scan.
    pub scan_duration: Option<std::time::Duration>,

    /// Optional metadata from Dalfox's JSON envelope (`meta` field).
    pub meta: Option<serde_json::Value>,
}

/// Supported output formats for scan results.
///
/// Use with [`DalfoxResult::format_as`] to convert findings into
/// the desired output representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OutputFormat {
    /// Compact single-line JSON array.
    Json,
    /// Pretty-printed JSON array.
    JsonPretty,
    /// Comma-separated values with header row.
    Csv,
    /// GitHub-flavored Markdown table.
    Markdown,
    /// Human-readable plain text report.
    Plain,
}

impl DalfoxResult {
    /// Format the scan results in the specified output format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use dalfox_rs::types::{DalfoxResult, OutputFormat};
    /// let result = DalfoxResult::default();
    /// let csv = result.format_as(OutputFormat::Csv);
    /// assert!(csv.starts_with("severity,"));
    /// ```
    pub fn format_as(&self, format: OutputFormat) -> String {
        match format {
            OutputFormat::Json => self.format_json(false),
            OutputFormat::JsonPretty => self.format_json(true),
            OutputFormat::Csv => self.format_csv(),
            OutputFormat::Markdown => self.format_markdown(),
            OutputFormat::Plain => self.format_plain(),
        }
    }

    fn format_json(&self, pretty: bool) -> String {
        let result = if pretty {
            serde_json::to_string_pretty(&self.findings)
        } else {
            serde_json::to_string(&self.findings)
        };
        // Vec<DalfoxFinding> serialization is infallible for well-formed types,
        // but we handle the impossible case gracefully.
        match result {
            Ok(json) => json,
            Err(err) => format!("{{\"error\": \"serialization failed: {err}\"}}"),
        }
    }

    fn format_csv(&self) -> String {
        let mut buf = String::from("severity,type,method,param,cwe,poc,payload,evidence\n");
        for finding in &self.findings {
            buf.push_str(&format!(
                "{},{},{},{},{},{},{},{}\n",
                csv_escape(&finding.severity.to_string()),
                csv_escape(&finding.event_type.to_string()),
                csv_escape(&finding.method.to_string()),
                csv_escape(&finding.param),
                csv_escape(&finding.cwe),
                csv_escape(&finding.poc),
                csv_escape(&finding.payload),
                csv_escape(&finding.evidence),
            ));
        }
        buf
    }

    fn format_markdown(&self) -> String {
        if self.findings.is_empty() {
            return "No findings.\n".to_string();
        }
        let mut buf =
            String::from("| Severity | Type | Method | Param | CWE | PoC | Payload |\n");
        buf.push_str("|----------|------|--------|-------|-----|-----|----------|\n");
        for finding in &self.findings {
            buf.push_str(&format!(
                "| {} | {} | {} | `{}` | {} | [link]({}) | `{}` |\n",
                finding.severity,
                finding.event_type,
                finding.method,
                finding.param,
                finding.cwe,
                finding.poc,
                md_escape(&finding.payload),
            ));
        }
        buf
    }

    fn format_plain(&self) -> String {
        if self.findings.is_empty() {
            return "No XSS findings detected.\n".to_string();
        }
        let mut buf = format!("=== {} Finding(s) ===\n\n", self.findings.len());
        for (i, finding) in self.findings.iter().enumerate() {
            let evidence_display = if finding.evidence.is_empty() {
                "(none)"
            } else {
                &finding.evidence
            };
            buf.push_str(&format!(
                "#{} [{}] {} ({})\n  Parameter: {}\n  Method:    {}\n  PoC:       {}\n  Payload:   {}\n  Evidence:  {}\n\n",
                i + 1,
                finding.severity,
                finding.cwe,
                finding.event_type,
                finding.param,
                finding.method,
                finding.poc,
                finding.payload,
                evidence_display,
            ));
        }
        if !self.parse_errors.is_empty() {
            buf.push_str(&format!(
                "--- {} Parse Error(s) ---\n",
                self.parse_errors.len()
            ));
            for err in &self.parse_errors {
                buf.push_str(&format!("{err}\n"));
            }
        }
        buf
    }
}

/// Escape a value for CSV output.
fn csv_escape(value: &str) -> String {
    if value.contains(',') || value.contains('"') || value.contains('\n') {
        format!("\"{}\"", value.replace('"', "\"\""))
    } else {
        value.to_string()
    }
}

/// Escape pipe and backtick characters for Markdown table cells.
fn md_escape(value: &str) -> String {
    value.replace('|', "\\|").replace('`', "\\`")
}

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

    #[test]
    fn finding_deserialize() {
        let json = r#"{"type":"V","poc":"http://example.com?q=%3Cscript%3Ealert(1)%3C/script%3E","method":"GET","data":"","param":"q","payload":"<script>alert(1)</script>","evidence":"<script>alert(1)</script>","cwe":"CWE-79","severity":"High"}"#;
        let finding: DalfoxFinding = serde_json::from_str(json).expect("valid finding JSON");
        assert_eq!(finding.event_type, EventType::Verified);
        assert_eq!(finding.param, "q");
        assert_eq!(finding.severity, Severity::High);
        assert_eq!(finding.cwe, "CWE-79");
        assert_eq!(finding.method, Method::Get);
    }

    #[test]
    fn event_type_variants() {
        assert_eq!(
            serde_json::from_str::<EventType>("\"V\"").expect("verified"),
            EventType::Verified
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"G\"").expect("grep"),
            EventType::Grep
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"I\"").expect("info"),
            EventType::Information
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"R\"").expect("reflected"),
            EventType::Reflected
        );
        assert_eq!(
            serde_json::from_str::<EventType>("\"XNEW\"").expect("unknown"),
            EventType::Other("XNEW".to_string())
        );
    }

    #[test]
    fn severity_aliases() {
        assert_eq!(
            serde_json::from_str::<Severity>("\"Info\"").expect("info alias"),
            Severity::Information
        );
        assert_eq!(
            serde_json::from_str::<Severity>("\"Information\"").expect("info full"),
            Severity::Information
        );
        assert_eq!(
            serde_json::from_str::<Severity>("\"POTENTIAL\"").expect("unknown"),
            Severity::Unknown("POTENTIAL".to_string())
        );
    }

    #[test]
    fn method_patch_variant() {
        assert_eq!(
            serde_json::from_str::<Method>("\"PATCH\"").expect("patch"),
            Method::Patch
        );
        assert_eq!(
            serde_json::from_str::<Method>("\"CUSTOM\"").expect("custom"),
            Method::Other("CUSTOM".to_string())
        );
    }

    #[test]
    fn result_default_is_empty() {
        let result = DalfoxResult::default();
        assert!(result.findings.is_empty());
        assert!(result.parse_errors.is_empty());
        assert!(result.stderr_output.is_empty());
        assert!(result.exit_code.is_none());
        assert!(result.scan_duration.is_none());
        assert!(result.meta.is_none());
    }

    #[test]
    fn json_envelope_deserialize_with_meta() {
        let json = r#"{"findings":[],"meta":{"dalfox_version":"3.1.2","targets_input":1}}"#;
        let envelope: DalfoxJsonEnvelope =
            serde_json::from_str(json).expect("valid v3 JSON envelope");
        assert!(envelope.findings.is_empty());
        let meta = envelope.meta.expect("meta present");
        assert_eq!(meta["dalfox_version"], "3.1.2");
    }

    #[test]
    fn json_envelope_deserialize_findings_and_meta() {
        let json = r#"{
            "findings":[{"type":"V","poc":"http://example.com","method":"GET","param":"q","payload":"x","cwe":"CWE-79","severity":"High"}],
            "meta":{"dalfox_version":"3.1.2"}
        }"#;
        let envelope: DalfoxJsonEnvelope =
            serde_json::from_str(json).expect("valid envelope with findings");
        assert_eq!(envelope.findings.len(), 1);
        assert_eq!(envelope.findings[0].event_type, EventType::Verified);
    }

    #[test]
    fn event_type_ast_variant() {
        assert_eq!(
            serde_json::from_str::<EventType>("\"A\"").expect("ast"),
            EventType::Ast
        );
        assert_eq!(EventType::Ast.to_string(), "AST");
    }

    #[test]
    fn format_csv_header() {
        let result = DalfoxResult::default();
        let csv = result.format_as(OutputFormat::Csv);
        assert!(csv.starts_with("severity,type,method,param,cwe,poc,payload,evidence\n"));
    }

    #[test]
    fn format_plain_empty() {
        let result = DalfoxResult::default();
        let plain = result.format_as(OutputFormat::Plain);
        assert_eq!(plain, "No XSS findings detected.\n");
    }

    #[test]
    fn format_markdown_empty() {
        let result = DalfoxResult::default();
        let md = result.format_as(OutputFormat::Markdown);
        assert_eq!(md, "No findings.\n");
    }

    #[test]
    fn csv_escape_handles_commas_and_quotes() {
        assert_eq!(csv_escape("hello,world"), "\"hello,world\"");
        assert_eq!(csv_escape("say \"hi\""), "\"say \"\"hi\"\"\"");
        assert_eq!(csv_escape("simple"), "simple");
    }

    #[test]
    fn display_impls_are_readable() {
        assert_eq!(EventType::Verified.to_string(), "Verified");
        assert_eq!(Severity::High.to_string(), "High");
        assert_eq!(Method::Get.to_string(), "GET");
    }
}