use crate::model::{Location, Report, Severity};
use anyhow::Result;
use serde_json::{json, Value};
pub fn render(report: &Report) -> Result<String> {
let mut rule_ids: Vec<&str> = report.open_secrets().map(|s| s.rule.as_str()).collect();
if report.flagged_hosts().next().is_some() {
rule_ids.push("flagged-host");
}
rule_ids.sort_unstable();
rule_ids.dedup();
let secrets = report.open_secrets().map(|s| {
json!({
"ruleId": s.rule,
"level": match s.severity { Severity::High => "error", Severity::Medium => "warning", Severity::Low => "note" },
"message": { "text": format!("{} exposed in {} agent history: {}", s.rule, s.location.agent, s.preview) },
"locations": [location(&s.location)],
"partialFingerprints": { "egrix/v1": s.id },
})
});
let hosts = report.flagged_hosts().map(|h| {
json!({
"ruleId": "flagged-host",
"level": "warning",
"message": { "text": format!("{} ({}) contacted {} time(s)", h.host, h.reason, h.occurrences) },
"locations": h.locations.first().map(location).into_iter().collect::<Vec<Value>>(),
"partialFingerprints": { "egrix/v1": h.host },
})
});
let results: Vec<Value> = secrets.chain(hosts).collect();
Ok(serde_json::to_string_pretty(&json!({
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [{
"tool": { "driver": {
"name": "egrix",
"version": env!("CARGO_PKG_VERSION"),
"informationUri": env!("CARGO_PKG_REPOSITORY"),
"rules": rule_ids.iter().map(|id| json!({ "id": id })).collect::<Vec<Value>>(),
}},
"results": results,
}],
}))?)
}
fn location(loc: &Location) -> Value {
json!({ "physicalLocation": {
"artifactLocation": { "uri": loc.file.to_string_lossy() },
"region": { "startLine": loc.line.max(1) },
}})
}