aptu-core 0.5.0

Core library for Aptu - OSS issue triage with AI assistance
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
// SPDX-License-Identifier: Apache-2.0

//! SARIF (Static Analysis Results Interchange Format) output support.
//!
//! Converts security findings to SARIF 2.1.0 format for integration with
//! GitHub Code Scanning and other security tools.

use hex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::types::{Finding, PatternDefinition};

/// SARIF report structure (SARIF 2.1.0).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifReport {
    /// SARIF schema version.
    pub version: String,
    /// SARIF schema URI.
    #[serde(rename = "$schema")]
    pub schema: String,
    /// List of runs (one per tool invocation).
    pub runs: Vec<SarifRun>,
}

/// A single run of a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifRun {
    /// Tool information.
    pub tool: SarifTool,
    /// List of results (findings).
    pub results: Vec<SarifResult>,
}

/// Tool information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifTool {
    /// Driver (the tool itself).
    pub driver: SarifDriver,
}

/// Tool driver information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifDriver {
    /// Tool name.
    pub name: String,
    /// Tool version.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Information URI.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "informationUri")]
    pub information_uri: Option<String>,
    /// Rule definitions (pattern metadata).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub rules: Vec<SarifRule>,
}

/// A single result (finding).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifResult {
    /// Rule ID that triggered this result.
    #[serde(rename = "ruleId")]
    pub rule_id: String,
    /// Result level (note, warning, error).
    pub level: String,
    /// Human-readable message.
    pub message: SarifMessage,
    /// Locations where the issue was found.
    pub locations: Vec<SarifLocation>,
    /// Stable fingerprint for deduplication.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fingerprints: Option<SarifFingerprints>,
}

/// Message structure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifMessage {
    /// Message text.
    pub text: String,
}

/// Help text for a rule, supporting plain text and markdown.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SarifHelp {
    /// Plain-text remediation guidance.
    pub text: String,
    /// Markdown-formatted remediation guidance.
    pub markdown: String,
}

/// A rule definition (pattern metadata) embedded in the SARIF driver.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SarifRule {
    /// Rule identifier (matches ruleId in results).
    pub id: String,
    /// Short, one-line description.
    pub short_description: SarifMessage,
    /// Longer description with more detail.
    pub full_description: SarifMessage,
    /// Remediation help text.
    pub help: SarifHelp,
    /// Authoritative reference URL (CWE, OWASP, etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub help_uri: Option<String>,
}

/// Location information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifLocation {
    /// Physical location in source code.
    #[serde(rename = "physicalLocation")]
    pub physical_location: SarifPhysicalLocation,
}

/// Physical location in source code.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifPhysicalLocation {
    /// Artifact (file) location.
    #[serde(rename = "artifactLocation")]
    pub artifact_location: SarifArtifactLocation,
    /// Region (line/column) information.
    pub region: SarifRegion,
}

/// Artifact location (file path).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifArtifactLocation {
    /// File URI or path.
    pub uri: String,
}

/// Region (line/column) information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifRegion {
    /// Start line (1-indexed).
    #[serde(rename = "startLine")]
    pub start_line: usize,
}

/// Fingerprints for deduplication.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SarifFingerprints {
    /// Primary fingerprint (SHA-256 hash).
    #[serde(rename = "primaryLocationLineHash")]
    pub primary_location_line_hash: String,
}

impl From<Vec<Finding>> for SarifReport {
    fn from(findings: Vec<Finding>) -> Self {
        let results: Vec<SarifResult> = findings.into_iter().map(SarifResult::from).collect();

        SarifReport {
            version: "2.1.0".to_string(),
            schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json".to_string(),
            runs: vec![SarifRun {
                tool: SarifTool {
                    driver: SarifDriver {
                        name: "aptu-security-scanner".to_string(),
                        version: Some(env!("CARGO_PKG_VERSION").to_string()),
                        information_uri: Some("https://github.com/clouatre-labs/aptu".to_string()),
                        rules: Vec::new(),
                    },
                },
                results,
            }],
        }
    }
}

impl SarifReport {
    /// Build a SARIF report with rule metadata embedded in the driver.
    ///
    /// Rule objects are built from `patterns`; result objects are built from `findings`.
    /// Use this constructor when you have pattern metadata available (e.g. from the CLI
    /// `scan-security` subcommand). Prefer `From<Vec<Finding>>` for lightweight usage.
    pub fn with_rules(findings: Vec<Finding>, patterns: &[PatternDefinition]) -> Self {
        let rules: Vec<SarifRule> = patterns
            .iter()
            .map(|p| {
                let help_text = p.remediation.clone().unwrap_or_default();
                SarifRule {
                    id: p.id.clone(),
                    short_description: SarifMessage {
                        text: p.description.clone(),
                    },
                    full_description: SarifMessage {
                        text: p.description.clone(),
                    },
                    help: SarifHelp {
                        text: help_text.clone(),
                        markdown: help_text,
                    },
                    help_uri: p.authority_url.clone(),
                }
            })
            .collect();

        let results: Vec<SarifResult> = findings.into_iter().map(SarifResult::from).collect();

        SarifReport {
            version: "2.1.0".to_string(),
            schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json".to_string(),
            runs: vec![SarifRun {
                tool: SarifTool {
                    driver: SarifDriver {
                        name: "aptu-security-scanner".to_string(),
                        version: Some(env!("CARGO_PKG_VERSION").to_string()),
                        information_uri: Some("https://github.com/clouatre-labs/aptu".to_string()),
                        rules,
                    },
                },
                results,
            }],
        }
    }
}

impl From<Finding> for SarifResult {
    fn from(finding: Finding) -> Self {
        // Map severity to SARIF level
        let level = match finding.severity {
            super::types::Severity::Critical | super::types::Severity::High => "error",
            super::types::Severity::Medium => "warning",
            super::types::Severity::Low => "note",
        };

        // Generate stable fingerprint: hash of (file_path + line_number + pattern_id)
        let fingerprint_input = format!(
            "{}:{}:{}",
            finding.file_path, finding.line_number, finding.pattern_id
        );
        let mut hasher = Sha256::new();
        hasher.update(fingerprint_input.as_bytes());
        let fingerprint = hex::encode(hasher.finalize());

        SarifResult {
            rule_id: finding.pattern_id,
            level: level.to_string(),
            message: SarifMessage {
                text: finding.description,
            },
            locations: vec![SarifLocation {
                physical_location: SarifPhysicalLocation {
                    artifact_location: SarifArtifactLocation {
                        uri: finding.file_path,
                    },
                    region: SarifRegion {
                        start_line: finding.line_number,
                    },
                },
            }],
            fingerprints: Some(SarifFingerprints {
                primary_location_line_hash: fingerprint,
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::security::types::{Confidence, Severity};

    #[test]
    fn test_sarif_report_structure() {
        let findings = vec![Finding {
            pattern_id: "hardcoded-secret".to_string(),
            description: "Hardcoded API key detected".to_string(),
            severity: Severity::Critical,
            confidence: Confidence::High,
            file_path: "src/config.rs".to_string(),
            line_number: 42,
            matched_text: "api_key = \"sk-1234567890\"".to_string(),
            cwe: Some("CWE-798".to_string()),
        }];

        let report = SarifReport::from(findings);

        assert_eq!(report.version, "2.1.0");
        assert_eq!(report.runs.len(), 1);
        assert_eq!(report.runs[0].results.len(), 1);
        assert_eq!(report.runs[0].tool.driver.name, "aptu-security-scanner");
    }

    #[test]
    fn test_severity_mapping() {
        let critical = Finding {
            pattern_id: "test".to_string(),
            description: "Test".to_string(),
            severity: Severity::Critical,
            confidence: Confidence::High,
            file_path: "test.rs".to_string(),
            line_number: 1,
            matched_text: "test".to_string(),
            cwe: None,
        };

        let result = SarifResult::from(critical.clone());
        assert_eq!(result.level, "error");

        let medium = Finding {
            severity: Severity::Medium,
            ..critical.clone()
        };
        let result = SarifResult::from(medium);
        assert_eq!(result.level, "warning");

        let low = Finding {
            severity: Severity::Low,
            ..critical
        };
        let result = SarifResult::from(low);
        assert_eq!(result.level, "note");
    }

    #[test]
    fn test_fingerprint_stability() {
        let finding = Finding {
            pattern_id: "test-pattern".to_string(),
            description: "Test finding".to_string(),
            severity: Severity::High,
            confidence: Confidence::Medium,
            file_path: "src/main.rs".to_string(),
            line_number: 10,
            matched_text: "test code".to_string(),
            cwe: None,
        };

        let result1 = SarifResult::from(finding.clone());
        let result2 = SarifResult::from(finding);

        assert_eq!(
            result1
                .fingerprints
                .as_ref()
                .unwrap()
                .primary_location_line_hash,
            result2
                .fingerprints
                .as_ref()
                .unwrap()
                .primary_location_line_hash
        );
    }

    #[test]
    fn test_fingerprint_uniqueness() {
        let finding1 = Finding {
            pattern_id: "pattern1".to_string(),
            description: "Test".to_string(),
            severity: Severity::High,
            confidence: Confidence::High,
            file_path: "src/main.rs".to_string(),
            line_number: 10,
            matched_text: "test".to_string(),
            cwe: None,
        };

        let finding2 = Finding {
            pattern_id: "pattern2".to_string(),
            ..finding1.clone()
        };

        let result1 = SarifResult::from(finding1);
        let result2 = SarifResult::from(finding2);

        assert_ne!(
            result1
                .fingerprints
                .as_ref()
                .unwrap()
                .primary_location_line_hash,
            result2
                .fingerprints
                .as_ref()
                .unwrap()
                .primary_location_line_hash
        );
    }

    #[test]
    fn test_sarif_serialization() {
        let findings = vec![Finding {
            pattern_id: "test-pattern".to_string(),
            description: "Test finding".to_string(),
            severity: Severity::High,
            confidence: Confidence::Medium,
            file_path: "src/test.rs".to_string(),
            line_number: 5,
            matched_text: "test".to_string(),
            cwe: Some("CWE-123".to_string()),
        }];

        let report = SarifReport::from(findings);
        let json = serde_json::to_string(&report).unwrap();

        assert!(json.contains("\"version\":\"2.1.0\""));
        assert!(json.contains("\"ruleId\":\"test-pattern\""));
        assert!(json.contains("\"level\":\"error\""));
    }
}