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": uri(&loc.file) },
"region": { "startLine": loc.line.max(1) },
}})
}
fn uri(path: &std::path::Path) -> String {
let text = path.to_string_lossy().replace('\\', "/");
let encoded: String = text
.bytes()
.map(|b| {
let c = b as char;
if c.is_ascii_alphanumeric() || "/-._~:@!$&'()*+,;=".contains(c) {
c.to_string()
} else {
format!("%{b:02X}")
}
})
.collect();
if let Some(rest) = encoded.strip_prefix("//") {
format!("file://{rest}")
} else if encoded.starts_with('/') {
format!("file://{encoded}")
} else if text.len() >= 2 && text.as_bytes()[1] == b':' {
format!("file:///{encoded}")
} else {
encoded
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Agent;
use std::path::PathBuf;
#[test]
fn paths_become_valid_uris() {
assert_eq!(uri(std::path::Path::new(r"C:\Users\me\a b.jsonl")), "file:///C:/Users/me/a%20b.jsonl");
assert_eq!(uri(std::path::Path::new("/home/me/a#b.jsonl")), "file:///home/me/a%23b.jsonl");
assert_eq!(uri(std::path::Path::new("relative/a.jsonl")), "relative/a.jsonl");
}
#[test]
fn a_location_carries_its_uri_and_line() {
let loc = Location { agent: Agent::Claude, file: PathBuf::from(r"C:\x\a.jsonl"), line: 3, repo: None, branch: None, day: 0 };
let value = location(&loc);
assert_eq!(value["physicalLocation"]["artifactLocation"]["uri"].as_str(), Some("file:///C:/x/a.jsonl"));
assert_eq!(value["physicalLocation"]["region"]["startLine"].as_u64(), Some(3));
}
}