diff --git a/src/hooks.rs b/src/hooks.rs index 7d5550a..d1528bf 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -21,7 +21,7 @@ use crate::model::{ }; use crate::origin::Origin; use crate::outcome::{self, Outcome}; -use crate::render::location; +use crate::render::{CommitPair, location}; use crate::severity::Severity; use crate::text::one_line; use crate::{RepositoryArgs, Verdict, connect, connected_repository, preflight, read_review, say}; @@ -531,12 +531,14 @@ fn first_sentence(text: &str) -> String { .to_owned() } -fn print_findings(findings: &[Finding]) { +fn print_findings(findings: &[Finding], commits: CommitPair<'_>) { for finding in findings { say(&format!( " {:<8} {} {}", one_line(&finding.severity), - location(finding).first().map_or("", String::as_str), + location(finding, commits) + .first() + .map_or("", String::as_str), first_sentence(&finding.claim) )); } @@ -597,13 +599,13 @@ fn print_read( } if let Some(code) = outcome::code_assessment(detail) { say(&code_line(code, complete)); - print_findings(&code.findings); + print_findings(&code.findings, CommitPair::code(code)); } else if outcome::code_unavailable(detail) { say(" Code-only: incomplete (CODE_ASSESSMENT_UNAVAILABLE)"); } for assessment in &detail.assessments { say(&assessment_line(assessment, complete)); - print_findings(&assessment.findings); + print_findings(&assessment.findings, CommitPair::review(detail)); } } diff --git a/src/render.rs b/src/render.rs index 44befb1..8354a20 100644 --- a/src/render.rs +++ b/src/render.rs @@ -6,35 +6,98 @@ use std::cmp::Reverse; use url::Url; use crate::model::{ - Assessment, CodeAssessment, Finding, LocalReverification, ReviewDetail, StoredCheck, + Assessment, CodeAssessment, EvidenceRef, Finding, LocalReverification, ReviewDetail, + StoredCheck, }; use crate::outcome::{self, Outcome}; +use crate::sarif::{self, LocationStatus}; use crate::severity::Severity; use crate::text::{one_line, terminal_safe}; -pub(crate) fn location(finding: &Finding) -> Vec { +/// The base and head a finding was reviewed at: a code assessment's own, or +/// else the review's, which a patch review leaves without a head. +#[derive(Clone, Copy)] +pub(crate) struct CommitPair<'a> { + base: Option<&'a str>, + head: Option<&'a str>, +} + +impl<'a> CommitPair<'a> { + pub(crate) fn review(review: &'a ReviewDetail) -> Self { + Self { + base: review.base_commit_sha.as_deref(), + head: review.head_commit_sha.as_deref(), + } + } + + pub(crate) fn code(code: &'a CodeAssessment) -> Self { + Self { + base: Some(&code.base_commit_sha), + head: Some(&code.head_commit_sha), + } + } +} + +/// Each cited file as `path:lines`. A citation SARIF would not place at the +/// reviewed head also says where it was read, so it never reads as head code. +pub(crate) fn location(finding: &Finding, commits: CommitPair<'_>) -> Vec { finding .evidence_refs .iter() .filter_map(|evidence| { let path = one_line(evidence.repository_path.as_deref()?); - Some(match (evidence.start_line, evidence.end_line) { + let place = match (evidence.start_line, evidence.end_line) { (Some(start), Some(end)) if end > start => format!("{path}:{start}-{end}"), (Some(start), _) => format!("{path}:{start}"), (None, _) => path, + }; + Some(match read_elsewhere(evidence, commits) { + Some(source) => format!("{place} ({source})"), + None => place, }) }) .collect() } -fn finding(out: &mut Vec, finding: &Finding) { +/// Where `evidence` was read, when SARIF's rules say it was not a verified +/// read of the reviewed head. A blank companion name counts as none. +fn read_elsewhere(evidence: &EvidenceRef, commits: CommitPair<'_>) -> Option { + let head = commits.head.unwrap_or_default(); + match sarif::code_location(evidence, head).err()? { + LocationStatus::CompanionRepository => Some( + evidence + .companion_repository + .as_deref() + .filter(|name| !name.trim().is_empty()) + .map_or_else( + || "in a companion repository".to_owned(), + |name| format!("in {}", one_line(name)), + ), + ), + LocationStatus::DifferentCommit => { + let commit = evidence.commit_sha.as_deref()?; + let side = match commits.base { + Some(base) if base.eq_ignore_ascii_case(commit) => "base", + _ => "commit", + }; + Some(format!( + "{side} {}", + one_line(commit.get(..12).unwrap_or(commit)) + )) + } + LocationStatus::UnverifiedProvenance => Some("unverified".to_owned()), + _ => None, + } +} + +fn finding(out: &mut Vec, finding: &Finding, commits: CommitPair<'_>) { out.push(format!( " {:<8} {} {}", one_line(&finding.severity), one_line(&finding.risk_domain), one_line(&finding.claim) )); - for place in location(finding) { + for place in location(finding, commits) { out.push(format!(" at {place}")); } out.push(format!(" impact: {}", one_line(&finding.impact))); @@ -45,7 +108,7 @@ fn finding(out: &mut Vec, finding: &Finding) { out.push(format!(" id: {}", finding.id)); } -fn assessment(out: &mut Vec, assessment: &Assessment) { +fn assessment(out: &mut Vec, assessment: &Assessment, review: &ReviewDetail) { let name = one_line(&assessment.environment_display_name); let mut findings: Vec<&Finding> = assessment.findings.iter().collect(); // Most severe first; a severity this CLI does not know prints last. @@ -69,7 +132,7 @@ fn assessment(out: &mut Vec, assessment: &Assessment) { } } for item in findings { - finding(out, item); + finding(out, item, CommitPair::review(review)); } } @@ -91,7 +154,7 @@ fn code_assessment(out: &mut Vec, code: &CodeAssessment) { None => out.push(format!("Code-only: COMPLETED, {} findings", findings.len())), } for item in findings { - finding(out, item); + finding(out, item, CommitPair::code(code)); } } @@ -228,7 +291,7 @@ pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> Strin } for item in &review.assessments { out.push(String::new()); - assessment(&mut out, item); + assessment(&mut out, item, review); } reverifications(&mut out, &review.local_reverifications); out.push(String::new()); @@ -238,7 +301,7 @@ pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> Strin #[cfg(test)] mod tests { use super::*; - use crate::model::{Checks, EvidenceRef}; + use crate::model::Checks; fn sample(status: &str, findings: Vec) -> ReviewDetail { ReviewDetail { @@ -356,6 +419,98 @@ mod tests { ); } + #[test] + fn a_citation_off_the_reviewed_head_says_where_it_was_read() { + let head = "0123456789abcdef0123456789abcdef01234567"; + let base = "a".repeat(40); + let cited = |commit: Option<&str>, companion: Option<&str>, provenance: &str| { + let mut reference = finding("SERIOUS", "x").evidence_refs.remove(0); + reference.kind = "repository_file".to_owned(); + reference.provenance_status = Some(provenance.to_owned()); + reference.commit_sha = commit.map(str::to_owned); + reference.companion_repository = companion.map(str::to_owned); + reference + }; + let verified = "VERIFIED_REPOSITORY_READ"; + let mut unnamed = cited(Some(head), None, verified); + unnamed.kind = "companion_repository_file".to_owned(); + let mut item = finding("SERIOUS", "lost order"); + item.evidence_refs = vec![ + cited(Some(head), None, verified), + cited(Some(&head.to_ascii_uppercase()), None, verified), + cited(None, None, verified), + cited(Some(&base), None, verified), + cited(Some(&"f".repeat(40)), None, verified), + cited(Some(head), Some("acme/\u{1b}[2Jcontracts"), verified), + unnamed, + cited(Some(head), Some(""), verified), + cited(Some(head), Some(" \t"), verified), + cited(Some(head), None, "LEGACY_UNSTRUCTURED"), + ]; + let mut detail = sample("COMPLETED", vec![item]); + detail.base_commit_sha = Some(base); + let text = review(&detail, None, &url()); + let places: Vec<&str> = text + .lines() + .filter_map(|line| line.trim_start().strip_prefix("at ")) + .collect(); + assert_eq!( + places, + [ + "src/orders.rs:10-14", + "src/orders.rs:10-14", + "src/orders.rs:10-14", + "src/orders.rs:10-14 (base aaaaaaaaaaaa)", + "src/orders.rs:10-14 (commit ffffffffffff)", + "src/orders.rs:10-14 (in acme/\u{FFFD}[2Jcontracts)", + "src/orders.rs:10-14 (in a companion repository)", + "src/orders.rs:10-14 (in a companion repository)", + "src/orders.rs:10-14 (in a companion repository)", + "src/orders.rs:10-14 (unverified)", + ], + "{text}" + ); + } + + #[test] + fn a_code_finding_is_read_against_its_assessments_commits() { + let head = "0123456789abcdef0123456789abcdef01234567"; + let base = "a".repeat(40); + let cited = |commit: &str| { + let mut item = finding("SERIOUS", "lost order"); + let reference = &mut item.evidence_refs[0]; + reference.kind = "repository_file".to_owned(); + reference.provenance_status = Some("VERIFIED_REPOSITORY_READ".to_owned()); + reference.commit_sha = Some(commit.to_owned()); + item + }; + // A patch review records no head of its own; its code assessment does. + let mut detail = sample("COMPLETED", Vec::new()); + detail.head_commit_sha = None; + detail.code_assessment = Some(crate::model::CodeAssessmentRead::Recorded(CodeAssessment { + id: uuid::Uuid::nil(), + status: crate::model::CodeAssessmentStatus::Completed, + base_commit_sha: base.clone(), + head_commit_sha: head.to_owned(), + findings: vec![cited(head), cited(&base)], + incompleteness_kind: None, + reason_codes: None, + })); + let text = review(&detail, None, &url()); + let places: Vec<&str> = text + .lines() + .filter_map(|line| line.trim_start().strip_prefix("at ")) + .collect(); + assert_eq!( + places, + [ + "src/orders.rs:10-14", + "src/orders.rs:10-14 (base aaaaaaaaaaaa)" + ], + "{text}" + ); + } + #[test] fn model_text_cannot_drive_the_terminal() { let detail = sample("COMPLETED", vec![finding("SERIOUS", "x\u{1b}[2J\ny")]); diff --git a/src/sarif.rs b/src/sarif.rs index 5134174..7782001 100644 --- a/src/sarif.rs +++ b/src/sarif.rs @@ -232,7 +232,7 @@ struct EvidenceProperties<'a> { #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] -enum LocationStatus { +pub(super) enum LocationStatus { Located, NoVerifiedReviewedLocation, NonCodeReference, @@ -608,7 +608,7 @@ pub(super) fn location<'a>(reference: &'a EvidenceRef, head: &str) -> Option<(&' code_location(reference, head).ok() } -fn code_location<'a>( +pub(super) fn code_location<'a>( reference: &'a EvidenceRef, head: &str, ) -> Result<(&'a str, u32, u32), LocationStatus> { diff --git a/tests/hooks.rs b/tests/hooks.rs index bc910b0..a577a82 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -17,6 +17,10 @@ const ORG: &str = "0190f3a0-0000-7000-8000-000000000001"; const REPOSITORY: &str = "0190f3a0-0000-7000-8000-000000000022"; const REVIEW: &str = "0190f3a0-0000-7000-8000-000000000033"; const TOKEN: &str = "hook-test-token"; +/// The commit every patch review in these tests is based on. +const PATCH_BASE: &str = "0123456789abcdef0123456789abcdef01234567"; +/// The head every CODE record in these tests was read at. +const CODE_HEAD: &str = "89abcdef0123456789abcdef0123456789abcdef"; type Uploads = Arc>>; /// Hook settings, the console's origin, the expected exit code and the @@ -127,6 +131,7 @@ async fn serve_reads( "id": REVIEW, "kind": "PATCH", "status": status, + "base_commit_sha": PATCH_BASE, "assessment_count": assessment_count, "assessments": [{ "id": "0190f3a0-0000-7000-8000-000000000044", @@ -140,8 +145,8 @@ async fn serve_reads( document["code_assessment"] = json!({ "id": "0190f3a0-0000-7000-8000-000000000066", "status": code_status, - "base_commit_sha": "0123456789abcdef0123456789abcdef01234567", - "head_commit_sha": "89abcdef0123456789abcdef0123456789abcdef", + "base_commit_sha": PATCH_BASE, + "head_commit_sha": CODE_HEAD, "findings": document["assessments"][0]["findings"], }); if assessment_count == 0 { @@ -655,6 +660,75 @@ async fn the_timeout_keeps_the_latest_read() { ); } +#[tokio::test] +async fn a_finding_cited_off_the_reviewed_head_says_where_it_was_read() { + let checkout = Checkout::new().await; + tokio::fs::write(checkout.root().join("orders.rs"), "fn main() { retry() }\n") + .await + .unwrap(); + checkout.git(&["add", "orders.rs"]).await; + let mut cited = findings("SERIOUS", false, "ACTIVE"); + cited[0]["evidence_refs"] = json!([{ + "kind": "repository_file", + "label": "orders.rs:1", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "orders.rs", + "start_line": 1, + "commit_sha": PATCH_BASE, + }]); + let origin = serve_review(Uploads::default(), "COMPLETED", 1, cited, None).await; + let output = checkout + .proofline(&origin, &["hook", "run", "pre-commit"], "") + .await; + let text = stderr(&output); + assert_eq!(output.status.code(), Some(0), "{text}"); + assert!( + text.contains("SERIOUS orders.rs:1 (base 0123456789ab) Orders are dropped on retry."), + "{text}" + ); +} + +#[tokio::test] +async fn a_code_finding_in_the_hook_line_is_read_against_its_assessments_commits() { + let checkout = Checkout::new().await; + tokio::fs::write(checkout.root().join("orders.rs"), "fn main() { retry() }\n") + .await + .unwrap(); + checkout.git(&["add", "orders.rs"]).await; + let cite = |commit: &str| { + json!([{ + "kind": "repository_file", + "label": "orders.rs:1", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "orders.rs", + "start_line": 1, + "commit_sha": commit, + }]) + }; + let mut cited = findings("SERIOUS", true, "ACTIVE"); + cited[0]["evidence_refs"] = cite(CODE_HEAD); + let mut at_base = cited[0].clone(); + at_base["id"] = json!("0190f3a0-0000-7000-8000-000000000056"); + at_base["claim"] = json!("Refunds skip the ledger."); + at_base["evidence_refs"] = cite(PATCH_BASE); + cited.as_array_mut().unwrap().push(at_base); + // The patch review records no head; its CODE record does. + let origin = serve_review(Uploads::default(), "COMPLETED", 0, cited, Some("COMPLETED")).await; + let output = checkout + .proofline(&origin, &["hook", "run", "pre-commit"], "") + .await; + let text = stderr(&output); + assert_eq!(output.status.code(), Some(0), "{text}"); + assert!( + text.contains("SERIOUS orders.rs:1 Orders are dropped on retry."), + "{text}" + ); + assert!( + text.contains("SERIOUS orders.rs:1 (base 0123456789ab) Refunds skip the ledger."), + "{text}" + ); +} + #[tokio::test] async fn only_a_complete_review_prints_no_findings() { let checkout = Checkout::new().await; diff --git a/tests/sarif.rs b/tests/sarif.rs index 77fa843..a7f9dc9 100644 --- a/tests/sarif.rs +++ b/tests/sarif.rs @@ -597,6 +597,46 @@ async fn code_results_keep_their_identity_and_cannot_complete_environment_assess } } +#[tokio::test] +async fn text_output_says_where_each_citation_sarif_does_not_place_was_read() { + let at = |commit: &str| { + let mut reference = code("src/orders.rs", 10, Some(14)); + reference["commit_sha"] = json!(commit); + reference + }; + let mut companion = at(HEAD); + companion["kind"] = json!("companion_repository_file"); + companion["companion_repository"] = json!("acme/contracts"); + let mut unverified = at(HEAD); + unverified["provenance_status"] = json!("LEGACY_UNSTRUCTURED"); + let references = vec![at(HEAD), at(BASE), at(OTHER_COMMIT), companion, unverified]; + let mut document = review(vec![finding(1, "SERIOUS", references)]); + document["base_commit_sha"] = json!(BASE); + let origin = serve(Console::new(document)).await; + let output = cli(&origin, ORG, TOKEN, &["findings", "--review", REVIEW]).await; + let text = String::from_utf8(output.stdout).unwrap(); + assert_eq!(output.status.code(), Some(0), "{text}"); + let places: Vec<&str> = text + .lines() + .filter_map(|line| line.trim_start().strip_prefix("at ")) + .collect(); + assert_eq!( + places, + [ + "src/orders.rs:10-14", + "src/orders.rs:10-14 (base 89abcdef0123)", + "src/orders.rs:10-14 (commit fedcba987654)", + "src/orders.rs:10-14 (in acme/contracts)", + "src/orders.rs:10-14 (unverified)", + ], + "{text}" + ); + // The same review's SARIF places only the read at the head. + let sarif = report(&export(&origin).await, &schema()); + let locations = &sarif["runs"][0]["results"][0]["locations"]; + assert_eq!(locations.as_array().unwrap().len(), 1, "{sarif}"); +} + #[tokio::test] async fn sarif_retains_identity_and_filters_locations_at_the_recorded_head() { let mut references = vec![