secfinding 0.3.0

Universal security finding types for vulnerability scanners.
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
//! Typed evidence attached to findings.
//!
//! Each variant carries structured proof. Consumers use the tag to
//! render evidence correctly (terminal, markdown, SARIF, etc.).

use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Concrete evidence proving a finding is real.
///
/// Extensible via `#[non_exhaustive]` — new evidence types can be added
/// for new tools (firmware, mobile, etc.) without breaking existing consumers.
///
/// # Examples
///
/// ```
/// use secfinding::Evidence;
///
/// let evidence = Evidence::http_status(403)?;
/// assert_eq!(evidence.to_string(), "http-response status=403 headers=0 body_excerpt=none");
/// # Ok::<(), &'static str>(())
/// ```
///
/// # Thread Safety
/// `Evidence` is `Send` and `Sync`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Evidence {
    /// HTTP response data (status, headers, body excerpt).
    HttpResponse {
        /// HTTP status code.
        #[serde(deserialize_with = "deserialize_http_status")]
        status: u16,
        /// Response headers as key-value pairs.
        headers: Vec<(Arc<str>, Arc<str>)>,
        /// First N bytes of the response body.
        body_excerpt: Option<Arc<str>>,
    },

    /// DNS record evidence.
    DnsRecord {
        /// Record type (A, AAAA, CNAME, MX, TXT, etc.).
        record_type: Arc<str>,
        /// Record value.
        value: Arc<str>,
    },

    /// Service banner captured during port scanning.
    Banner {
        /// Raw banner text.
        raw: Arc<str>,
    },

    /// JavaScript source snippet with context.
    JsSnippet {
        /// URL of the JS file.
        url: Arc<str>,
        /// Line number in the file.
        #[serde(deserialize_with = "deserialize_positive_usize")]
        line: usize,
        /// The matched code snippet.
        snippet: Arc<str>,
    },

    /// TLS certificate information.
    Certificate {
        /// Certificate subject (CN).
        subject: Arc<str>,
        /// Subject Alternative Names.
        san: Vec<Arc<str>>,
        /// Certificate issuer.
        issuer: Arc<str>,
        /// Expiration date.
        expires: Arc<str>,
    },

    /// Source code snippet (for SAST, malware detection).
    CodeSnippet {
        /// File path.
        file: Arc<str>,
        /// Line number.
        #[serde(deserialize_with = "deserialize_positive_usize")]
        line: usize,
        /// Column number (optional).
        #[serde(default, deserialize_with = "deserialize_optional_positive_usize")]
        column: Option<usize>,
        /// The matched code.
        snippet: Arc<str>,
        /// Programming language.
        language: Option<Arc<str>>,
    },

    /// HTTP request that triggered the finding (for template/vuln scanners).
    HttpRequest {
        /// HTTP method.
        method: Arc<str>,
        /// Full URL.
        url: Arc<str>,
        /// Request headers.
        headers: Vec<(Arc<str>, Arc<str>)>,
        /// Request body.
        body: Option<Arc<str>>,
    },

    /// Matched pattern or regex (for pattern-based scanners).
    PatternMatch {
        /// The pattern or regex that matched.
        pattern: Arc<str>,
        /// The matched content.
        matched: Arc<str>,
    },

    /// Unstructured evidence — fallback for anything that doesn't fit above.
    Raw(Arc<str>),
}

impl Evidence {
    /// Create an HTTP response evidence with just a status code.
    ///
    /// # Errors
    ///
    /// Returns an error if the status code is not within the valid HTTP range (100-599).
    pub fn http_status(status: u16) -> Result<Self, &'static str> {
        if !(100..=599).contains(&status) {
            return Err(
                "HTTP status code must be between 100 and 599. Fix: pass a valid RFC HTTP status code.",
            );
        }
        Ok(Self::HttpResponse {
            status,
            headers: vec![],
            body_excerpt: None,
        })
    }

    /// Create a code snippet evidence.
    ///
    /// `line` and `column` are validated (1-based). Returns an error for invalid coordinates.
    ///
    /// # Errors
    ///
    /// Returns an error if `line` is 0 or if `column` is `Some(0)`.
    pub fn code(
        file: impl Into<String>,
        line: usize,
        snippet: impl Into<String>,
        column: Option<usize>,
        language: Option<String>,
    ) -> Result<Self, &'static str> {
        if line == 0 {
            return Err(
                "line values must be 1 or greater. Fix: pass a positive source line number.",
            );
        }
        if let Some(0) = column {
            return Err(
                "column values must be 1 or greater. Fix: pass a positive source column number.",
            );
        }

        Ok(Self::CodeSnippet {
            file: Arc::from(file.into()),
            line,
            column,
            snippet: Arc::from(snippet.into()),
            language: language.map(Arc::from),
        })
    }
}

fn deserialize_http_status<'de, D>(deserializer: D) -> Result<u16, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let status = u16::deserialize(deserializer)?;
    if !(100..=599).contains(&status) {
        return Err(serde::de::Error::custom(
            "HTTP status code must be between 100 and 599. Fix: pass a valid RFC HTTP status code.",
        ));
    }
    Ok(status)
}

fn deserialize_positive_usize<'de, D>(deserializer: D) -> Result<usize, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = usize::deserialize(deserializer)?;
    if value == 0 {
        return Err(serde::de::Error::custom(
            "line values must be 1 or greater. Fix: pass a positive source line number.",
        ));
    }
    Ok(value)
}

fn deserialize_optional_positive_usize<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<usize>::deserialize(deserializer)?;
    match value {
        Some(0) => Err(serde::de::Error::custom(
            "column values must be 1 or greater. Fix: pass a positive source column number.",
        )),
        _ => Ok(value),
    }
}

// Small helper formatters keep the main `fmt` implementation compact and
// easier to audit for correctness.
fn fmt_http_response(
    f: &mut std::fmt::Formatter<'_>,
    status: u16,
    headers: &[(Arc<str>, Arc<str>)],
    body_excerpt: Option<&Arc<str>>,
) -> std::fmt::Result {
    let excerpt = body_excerpt.as_ref().map_or_else(
        || "none".to_string(),
        |s| format!("<redacted,len={}>", s.len()),
    );
    write!(
        f,
        "http-response status={status} headers={} body_excerpt={excerpt}",
        headers.len()
    )
}

fn fmt_http_request(
    f: &mut std::fmt::Formatter<'_>,
    method: &str,
    url: &str,
    headers: &[(Arc<str>, Arc<str>)],
    body: Option<&Arc<str>>,
) -> std::fmt::Result {
    let body_info = body.as_ref().map_or_else(
        || "none".to_string(),
        |b| format!("<redacted,len={}>", b.len()),
    );
    write!(
        f,
        "http-request:{method} {url} headers={} body={body_info}",
        headers.len()
    )
}

fn fmt_code_snippet(
    f: &mut std::fmt::Formatter<'_>,
    file: &str,
    line: usize,
    language: Option<&Arc<str>>,
) -> std::fmt::Result {
    if let Some(lang) = language {
        write!(f, "code-snippet:{file}:{line} [{lang}]")
    } else {
        write!(f, "code-snippet:{file}:{line}")
    }
}

impl std::fmt::Display for Evidence {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::HttpResponse {
                status,
                headers,
                body_excerpt,
            } => fmt_http_response(f, *status, headers, body_excerpt.as_ref()),
            Self::DnsRecord { record_type, .. } => write!(f, "dns:{record_type}"),
            Self::Banner { raw } => write!(f, "banner<len={}>", raw.len()),
            Self::JsSnippet { url, line, .. } => write!(f, "js-snippet:{url}:{line}"),
            Self::Certificate {
                subject,
                issuer,
                san,
                ..
            } => write!(
                f,
                "certificate:{subject} issuer={issuer} san_count={}",
                san.len()
            ),
            Self::CodeSnippet {
                file,
                line,
                language,
                ..
            } => fmt_code_snippet(f, file, *line, language.as_ref()),
            Self::HttpRequest {
                method,
                url,
                headers,
                body,
            } => fmt_http_request(f, method, url, headers, body.as_ref()),
            Self::PatternMatch { pattern, matched } => write!(
                f,
                "pattern-match:{pattern} => <redacted,len={}>",
                matched.len()
            ),
            Self::Raw(value) => write!(f, "raw:<redacted,len={}>", value.len()),
        }
    }
}

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

    #[test]
    fn serde_tagged() {
        let ev = Evidence::HttpResponse {
            status: 403,
            headers: vec![("server".into(), "cloudflare".into())],
            body_excerpt: Some("blocked".into()),
        };
        let json = serde_json::to_value(&ev).unwrap();
        assert_eq!(json["type"], "http_response");
        assert_eq!(json["status"], 403);
    }

    #[test]
    fn code_snippet_roundtrip() {
        let ev = Evidence::code("src/main.rs", 42, "let key = \"AKIA...\";", None, None).unwrap();
        let json = serde_json::to_string(&ev).unwrap();
        let back: Evidence = serde_json::from_str(&json).unwrap();
        if let Evidence::CodeSnippet {
            file,
            line,
            snippet,
            ..
        } = back
        {
            assert_eq!(file.as_ref(), "src/main.rs");
            assert_eq!(line, 42);
            assert_eq!(snippet.as_ref(), "let key = \"AKIA...\";");
        } else {
            panic!("wrong variant");
        }
    }

    #[test]
    fn helper_constructors_roundtrip() {
        let ev = Evidence::http_status(201).unwrap();
        let json = serde_json::to_string(&ev).unwrap();
        let back: Evidence = serde_json::from_str(&json).unwrap();
        if let Evidence::HttpResponse {
            status,
            headers,
            body_excerpt,
        } = back
        {
            assert_eq!(status, 201);
            assert!(headers.is_empty());
            assert!(body_excerpt.is_none());
        } else {
            panic!("wrong variant");
        }

        let snippet = Evidence::code("lib.rs", 10, "secret = 'x'", None, None).unwrap();
        let json = serde_json::to_string(&snippet).unwrap();
        let back: Evidence = serde_json::from_str(&json).unwrap();
        if let Evidence::CodeSnippet { line, snippet, .. } = back {
            assert_eq!(line, 10);
            assert!(snippet.contains("secret"));
        } else {
            panic!("wrong variant");
        }
    }

    #[test]
    fn serde_multiple_evidence_variants() {
        let samples = vec![
            Evidence::HttpRequest {
                method: "GET".into(),
                url: "https://example.com/login".into(),
                headers: vec![("host".into(), "example.com".into())],
                body: Some("a=1".into()),
            },
            Evidence::Certificate {
                subject: "CN=example".into(),
                san: vec!["DNS:example.com".into()],
                issuer: "Let's Encrypt".into(),
                expires: "2028-01-01".into(),
            },
            Evidence::PatternMatch {
                pattern: "api_key=[A-Za-z]+".into(),
                matched: "api_key=abc".into(),
            },
        ];

        for sample in samples {
            let json = serde_json::to_string(&sample).unwrap();
            let back: Evidence = serde_json::from_str(&json).unwrap();
            match (sample, back) {
                (
                    Evidence::HttpRequest { method: m1, .. },
                    Evidence::HttpRequest { method: m2, .. },
                ) => {
                    assert_eq!(m1, m2);
                }
                (
                    Evidence::Certificate { subject: s1, .. },
                    Evidence::Certificate { subject: s2, .. },
                ) => {
                    assert_eq!(s1, s2);
                }
                (
                    Evidence::PatternMatch { pattern: p1, .. },
                    Evidence::PatternMatch { pattern: p2, .. },
                ) => {
                    assert_eq!(p1, p2);
                }
                _ => panic!("roundtrip mismatch"),
            }
        }
    }
}