From 261beef6b100a16db842530b0edc007ab30bc60d Mon Sep 17 00:00:00 2001 From: arielonoriaga Date: Tue, 1 Dec 2026 09:59:57 -0300 Subject: [PATCH 1/2] feat(ci): add --summary to write GitHub Actions job summary Markdown --- README.md | 2 +- src/lib.rs | 24 +- src/summary.rs | 640 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/http.rs | 249 +++++++++++++++++++ 4 files changed, 913 insertions(+), 2 deletions(-) create mode 100644 src/summary.rs diff --git a/README.md b/README.md index 6a124c3..b93d0dd 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Repository commands use the checkout’s `origin` by default. Use `--remote NAME `proofline review --range BASE..HEAD --fail-on serious` exits 3 when a complete review has an unresolved finding at or above the threshold. PR reviews use the server’s effective open-item counts; other reviews count unresolved findings. Incomplete and unavailable results retain their nonzero exits. `--fail-on` cannot be combined with `--no-wait`. -In GitHub Actions, `proofline ci review --annotations` prints unresolved findings as workflow annotations at verified cited lines. Findings without a verified head location appear on the job. The review link contains the full result. +In GitHub Actions, `proofline ci review --annotations` prints unresolved findings as workflow annotations at verified cited lines. Findings without a verified head location appear on the job. Add `--summary` to append a Markdown job summary (assessment coverage, gaps, and escaped unresolved findings within GitHub's 1 MiB step summary limit) to `GITHUB_STEP_SUMMARY`, or `--summary FILE` to write it to a chosen path. The review link contains the full result. For a CodePipeline execution or Amplify job, run `proofline ci deploy --commit SHA --aws-run ID` in a later pipeline. Add `--environment-id UUID` to select its Proofline environment. The output names the AWS provider and run ID. Proofline records successful CodePipeline executions and failed, stopped or cancelled ones it ties to the ECS rollout that served the commit. A reader inside a still-running execution finds no matching deploy, waits until its timeout and exits 2. On a GitHub `workflow_run` event, an explicit `--aws-run` disables the default Actions run and attempt filters. diff --git a/src/lib.rs b/src/lib.rs index 8bf7a9e..4aa8ed7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,7 @@ mod sarif; mod scan; mod setup; mod severity; +mod summary; pub mod text; mod tls; pub mod update; @@ -233,6 +234,10 @@ struct CiReviewArgs { /// uploading `--sarif` to code scanning, this works on every GitHub plan. #[arg(long)] annotations: bool, + /// Also write the review as a Markdown job summary. Without a file path, + /// appends to `GITHUB_STEP_SUMMARY`; with a file path, writes that file. + #[arg(long, value_name = "FILE", num_args = 0..=1)] + summary: Option>, /// Print JSON instead of text. #[arg(long)] json: bool, @@ -1603,6 +1608,10 @@ async fn ci_review( commit: &str, request: Option<&github_actions::ReviewRequest>, ) -> anyhow::Result { + let summary_target = summary::resolve_target( + args.summary.as_ref().map(|path| path.as_deref()), + std::env::var_os(summary::GITHUB_STEP_SUMMARY_ENV), + )?; let started = tokio::time::Instant::now(); let deadline = poll_deadline(args.timeout)?; let (name, repository_id) = connected_repository(api, &args.repository).await?; @@ -1628,9 +1637,21 @@ async fn ci_review( return Ok(Verdict::Unavailable); }; confirm_ci_subject(&detail, commit, repository_id)?; + let verdict = ci_verdict(state, detail.open_items.as_ref(), args.fail_on); if let Some(path) = sarif_path { write_sarif(api, review_id, &detail, path).await?; } + if let Some(target) = &summary_target { + let markdown = summary::render( + &detail, + state, + verdict, + args.fail_on, + &api.review_url(review_id), + summary::MAX_SUMMARY_BYTES, + ); + summary::write_target(target, &markdown).await?; + } if args.annotations { annotations::write(&detail, &mut std::io::stderr().lock())?; } @@ -1642,7 +1663,6 @@ async fn ci_review( state, OutputFormat::from_json(args.json), )?; - let verdict = ci_verdict(state, detail.open_items.as_ref(), args.fail_on); say_ci_ending(api, review_id, &detail, state, verdict, args.timeout); Ok(verdict) } @@ -2164,6 +2184,7 @@ mod tests { commit: None, sarif: None, annotations: false, + summary: None, json: false, timeout: 3, fail_on: None, @@ -2236,6 +2257,7 @@ mod tests { commit: None, sarif: None, annotations: false, + summary: None, json: false, timeout: 3, fail_on: None, diff --git a/src/summary.rs b/src/summary.rs new file mode 100644 index 0000000..afaa4f8 --- /dev/null +++ b/src/summary.rs @@ -0,0 +1,640 @@ +//! GitHub Actions job summary (Markdown) for a pull-request review. Findings +//! quote model output and repository content, which are untrusted, so control +//! characters, Unicode bidirectional controls, raw HTML, Markdown links/images, +//! and table delimiters are escaped before writing. An incomplete review or +//! assessment always names its gaps and never renders as clean. + +use std::cmp::Reverse; +use std::ffi::OsString; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; + +use anyhow::{Context as _, bail}; +use tokio::io::AsyncWriteExt as _; +use url::Url; + +use crate::Verdict; +use crate::model::{Assessment, CodeAssessment, Finding, ReviewDetail}; +use crate::outcome::{self, Outcome}; +use crate::severity::Severity; +use crate::{sarif, text}; + +/// GitHub Actions drops job summaries larger than 1 MiB. +pub(crate) const MAX_SUMMARY_BYTES: usize = 1024 * 1024; + +/// Environment variable GitHub Actions sets to the current step's summary file. +pub(crate) const GITHUB_STEP_SUMMARY_ENV: &str = "GITHUB_STEP_SUMMARY"; + +/// Where a rendered job summary should be written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum SummaryTarget { + /// Append to a shared summary file such as `GITHUB_STEP_SUMMARY`. + Append(PathBuf), + /// Write (creating or replacing) an explicit caller-provided file path. + Write(PathBuf), +} + +/// Resolves `--summary [FILE]` before any network wait so a missing +/// `GITHUB_STEP_SUMMARY` fails immediately instead of after polling. +pub(crate) fn resolve_target( + flag: Option>, + step_summary_env: Option, +) -> anyhow::Result> { + let Some(explicit) = flag else { + return Ok(None); + }; + if let Some(path) = explicit.filter(|path| !path.as_os_str().is_empty()) { + return Ok(Some(SummaryTarget::Write(path.to_path_buf()))); + } + let env_path = step_summary_env.filter(|value| !value.to_string_lossy().trim().is_empty()); + let Some(env_path) = env_path else { + bail!( + "--summary without a file path requires {GITHUB_STEP_SUMMARY_ENV} to be set, or pass --summary " + ); + }; + Ok(Some(SummaryTarget::Append(PathBuf::from(env_path)))) +} + +/// Writes or appends `markdown` according to `target`. +pub(crate) async fn write_target(target: &SummaryTarget, markdown: &str) -> anyhow::Result<()> { + match target { + SummaryTarget::Write(path) => tokio::fs::write(path, markdown) + .await + .with_context(|| format!("could not write job summary to {}", path.display())), + SummaryTarget::Append(path) => { + let mut file = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .await + .with_context(|| format!("could not open job summary at {}", path.display()))?; + let existing_len = file + .metadata() + .await + .with_context(|| format!("could not inspect job summary at {}", path.display()))? + .len(); + if existing_len > 0 { + file.write_all(b"\n").await.with_context(|| { + format!("could not append job summary to {}", path.display()) + })?; + } + file.write_all(markdown.as_bytes()) + .await + .with_context(|| format!("could not append job summary to {}", path.display()))?; + file.flush() + .await + .with_context(|| format!("could not flush job summary at {}", path.display())) + } + } +} + +/// Renders a pull-request review as a GitHub-Flavored Markdown job summary +/// within `max_bytes`. +pub(crate) fn render( + review: &ReviewDetail, + state: Option, + verdict: Verdict, + fail_on: Option, + url: &Url, + max_bytes: usize, +) -> String { + let mut out = String::new(); + let heading = format!( + "## Proofline review: {}{}\n\n", + subject_heading(review), + commit_suffix(review) + ); + out.push_str(&heading); + + out.push_str(&status_line(review, state, verdict, fail_on)); + out.push('\n'); + if let Some(reason) = outcome::review_gap(review) { + let _ = writeln!(out, "- **Review gap:** `{reason}`"); + } + let _ = writeln!(out, "- **Review page:** [View in Proofline]({url})"); + + push_assessments(&mut out, review); + push_findings(&mut out, review, state, max_bytes); + + if out.len() > max_bytes { + truncate_utf8(&mut out, max_bytes); + } + out +} + +fn subject_heading(review: &ReviewDetail) -> String { + let base = match (&review.repository_full_name, review.pull_request_number) { + (Some(repo), Some(pr)) => format!("{} #{pr}", escape_inline(repo)), + (Some(repo), None) => escape_inline(repo), + _ => escape_inline(&review.kind), + }; + if let Some(run) = review.run_number { + format!("{base} (run {run})") + } else { + base + } +} + +fn commit_suffix(review: &ReviewDetail) -> String { + let Some(head) = review.head_commit_sha.as_deref() else { + return String::new(); + }; + let short = head.get(..12).unwrap_or(head); + format!(" at `{}`", escape_code_span(short)) +} + +fn status_line( + review: &ReviewDetail, + state: Option, + verdict: Verdict, + fail_on: Option, +) -> String { + match state { + Some(Outcome::Completed) => { + let counts = match &review.open_items { + Some(open) if open.open_findings == 0 => "no open findings".to_owned(), + Some(open) => { + let other = open.open_findings.saturating_sub(open.serious_findings); + format!( + "{} serious, {other} warning open ({} total)", + open.serious_findings, open.open_findings + ) + } + None => { + let unresolved = collect_unresolved(review).len(); + if unresolved == 0 { + "no unresolved findings recorded".to_owned() + } else { + format!("{unresolved} unresolved findings recorded") + } + } + }; + let gate = match (verdict, fail_on) { + (Verdict::ThresholdReached, Some(threshold)) => { + format!( + " — failed `--fail-on {}`", + threshold.as_str().to_lowercase() + ) + } + (Verdict::Unavailable, Some(threshold)) => format!( + " — `--fail-on {}` could not be measured (`open_items` absent)", + threshold.as_str().to_lowercase() + ), + _ => String::new(), + }; + format!("- **Status:** **COMPLETED** — {counts}{gate}") + } + Some(other) => { + format!( + "- **Status:** **{}** — result is not complete", + other.as_str() + ) + } + None => format!( + "- **Status:** **{}** — review did not finish before timeout", + escape_inline(&review.status) + ), + } +} + +fn push_assessments(out: &mut String, review: &ReviewDetail) { + let code = outcome::code_assessment(review); + let code_unavail = outcome::code_unavailable(review); + if code.is_none() && !code_unavail && review.assessments.is_empty() { + if review.assessment_count != 0 { + out.push_str("\nNo environment assessment has been recorded yet.\n"); + } + return; + } + + out.push_str("\n### Assessments\n\n"); + out.push_str("| Lane | Status | Unresolved | Gaps |\n"); + out.push_str("| --- | --- | ---: | --- |\n"); + + if let Some(code) = code { + push_code_row(out, code); + } else if code_unavail { + out.push_str("| Code-only | INCOMPLETE | — | `CODE_ASSESSMENT_UNAVAILABLE` |\n"); + } + + for assessment in &review.assessments { + push_env_row(out, assessment); + } + + if review.assessments.is_empty() && review.assessment_count != 0 { + out.push_str("\n_No environment assessment has been recorded yet._\n"); + } +} + +fn push_code_row(out: &mut String, code: &CodeAssessment) { + let open_count = code + .findings + .iter() + .filter(|item| !outcome::resolved(item)) + .count(); + let gaps = format_gaps(outcome::code_gap(code).as_deref()); + let _ = writeln!( + out, + "| Code-only | {} | {open_count} | {gaps} |", + code.status.as_str() + ); +} + +fn push_env_row(out: &mut String, assessment: &Assessment) { + let open_count = assessment + .findings + .iter() + .filter(|item| !outcome::resolved(item)) + .count(); + let gaps = format_gaps(outcome::gap(assessment).as_deref()); + let _ = writeln!( + out, + "| {} | {} | {open_count} | {gaps} |", + escape_cell(&assessment.environment_display_name), + escape_cell(&assessment.status), + ); +} + +fn format_gaps(reasons: Option<&[String]>) -> String { + match reasons { + Some(list) if !list.is_empty() => list + .iter() + .map(|code| format!("`{}`", escape_code_span(code))) + .collect::>() + .join(", "), + _ => "—".to_owned(), + } +} + +struct OpenFinding<'a> { + lane: &'a str, + finding: &'a Finding, +} + +fn collect_unresolved(review: &ReviewDetail) -> Vec> { + let mut items = Vec::new(); + if let Some(code) = outcome::code_assessment(review) { + for finding in &code.findings { + if !outcome::resolved(finding) { + items.push(OpenFinding { + lane: "code", + finding, + }); + } + } + } + for assessment in &review.assessments { + for finding in &assessment.findings { + if !outcome::resolved(finding) { + items.push(OpenFinding { + lane: &assessment.environment_display_name, + finding, + }); + } + } + } + // Most severe first; an unknown severity sorts last, matching `render.rs`. + items.sort_by_key(|item| Reverse(Severity::parse(&item.finding.severity))); + items +} + +fn push_findings( + out: &mut String, + review: &ReviewDetail, + state: Option, + max_bytes: usize, +) { + let findings = collect_unresolved(review); + if findings.is_empty() { + return; + } + + let heading = if state == Some(Outcome::Completed) { + "\n### Unresolved findings\n\n" + } else { + "\n### Findings so far (review is incomplete)\n\n" + }; + let table_header = "| Severity | Lane | Domain | Location | Finding | ID |\n| --- | --- | --- | --- | --- | --- |\n"; + + let head = review.head_commit_sha.as_deref().unwrap_or_default(); + let worst_footer = truncation_notice(findings.len()); + if out.len() + heading.len() + table_header.len() + worst_footer.len() > max_bytes { + let notice = truncation_notice(findings.len()); + if out.len() + notice.len() <= max_bytes { + out.push_str(¬ice); + } + return; + } + + out.push_str(heading); + out.push_str(table_header); + + let total = findings.len(); + for (index, item) in findings.iter().enumerate() { + let row = format_finding_row(item.lane, item.finding, head); + let remaining_after = total - index; + let reserve = if index + 1 == total { + 0 + } else { + truncation_notice(remaining_after).len() + }; + if out.len() + row.len() + reserve > max_bytes { + out.push_str(&truncation_notice(remaining_after)); + break; + } + out.push_str(&row); + } +} + +fn format_finding_row(lane: &str, finding: &Finding, head: &str) -> String { + let location = finding + .evidence_refs + .iter() + .find_map(|reference| sarif::location(reference, head)) + .map_or_else( + || "—".to_owned(), + |(path, start, end)| { + let coords = if end > start { + format!("{path}:{start}-{end}") + } else { + format!("{path}:{start}") + }; + format!("`{}`", escape_code_span(&coords)) + }, + ); + let mut description = format!( + "{} — {}", + escape_cell(&finding.claim), + escape_cell(&finding.impact) + ); + if let Some(fix) = &finding.remediation { + description.push_str(" Fix: "); + description.push_str(&escape_cell(fix)); + } + format!( + "| {} | {} | {} | {location} | {description} | `{}` |\n", + escape_cell(&finding.severity), + escape_cell(lane), + escape_cell(&finding.risk_domain), + finding.id + ) +} + +fn truncation_notice(omitted: usize) -> String { + let noun = if omitted == 1 { "finding" } else { "findings" }; + format!( + "\n_…and {omitted} more unresolved {noun} omitted to fit the job summary size limit. See the full review page above._\n" + ) +} + +/// Escapes untrusted text for inline Markdown outside code spans: strips +/// terminal/bidi controls, neutralizes raw HTML and Markdown link/image/code +/// syntax, and collapses everything onto a single line. +fn escape_inline(raw: &str) -> String { + let clean = text::one_line(raw); + let mut escaped = String::with_capacity(clean.len()); + for ch in clean.chars() { + match ch { + '&' => escaped.push_str("&"), + '<' => escaped.push_str("<"), + '>' => escaped.push_str(">"), + '\\' | '`' | '[' | ']' => { + escaped.push('\\'); + escaped.push(ch); + } + _ => escaped.push(ch), + } + } + escaped +} + +/// Escapes untrusted text for a GitHub-Flavored Markdown table cell. +fn escape_cell(raw: &str) -> String { + escape_inline(raw).replace('|', "\\|") +} + +/// Escapes untrusted text placed inside a single-backtick inline code span +/// inside a GFM table cell. +fn escape_code_span(raw: &str) -> String { + text::one_line(raw).replace('`', "'").replace('|', "\\|") +} + +fn truncate_utf8(text: &mut String, max_bytes: usize) { + let mut end = max_bytes.min(text.len()); + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{Checks, CodeAssessmentRead, CodeAssessmentStatus, EvidenceRef, OpenItems}; + use uuid::Uuid; + + const HEAD: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + fn url() -> Url { + Url::parse( + "https://app.proofline.sh/orgs/test/reviews/00000000-0000-0000-0000-000000000000", + ) + .unwrap() + } + + fn finding(id: Uuid, severity: &str, lifecycle_state: &str, claim: &str) -> Finding { + Finding { + id, + finding_fingerprint: None, + severity: severity.to_owned(), + risk_domain: "data_integrity".to_owned(), + claim: claim.to_owned(), + impact: "orders are lost".to_owned(), + lifecycle_state: lifecycle_state.to_owned(), + remediation: Some("use an idempotency key".to_owned()), + evidence_refs: vec![EvidenceRef { + kind: "repository_file".to_owned(), + label: "src/app.rs".to_owned(), + provenance_status: Some("VERIFIED_REPOSITORY_READ".to_owned()), + repository_path: Some("src/app.rs".to_owned()), + commit_sha: Some(HEAD.to_owned()), + start_line: Some(10), + end_line: Some(14), + file_sha256: None, + companion_repository: None, + }], + } + } + + fn assessment(name: &str, status: &str, findings: Vec) -> Assessment { + Assessment { + id: Uuid::nil(), + environment_display_name: name.to_owned(), + status: status.to_owned(), + findings, + checks: Checks { + receipt_recorded: true, + status: "READY".to_owned(), + families: Vec::new(), + }, + incompleteness_kind: None, + reason_codes: None, + release_evidence_gap: None, + } + } + + fn review(assessments: Vec) -> ReviewDetail { + ReviewDetail { + id: Uuid::nil(), + kind: "PULL_REQUEST".to_owned(), + status: "COMPLETED".to_owned(), + assessment_count: i64::try_from(assessments.len()).unwrap(), + assessments, + code_assessment: None, + subjects: Vec::new(), + base_commit_sha: Some("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_owned()), + head_commit_sha: Some(HEAD.to_owned()), + open_items: Some(OpenItems { + open_findings: 0, + serious_findings: 0, + }), + pull_request_number: Some(42), + repository_id: None, + repository_full_name: Some("acme/web".to_owned()), + run_number: Some(2), + local_reverifications: Vec::new(), + } + } + + #[test] + fn resolve_target_handles_explicit_path_env_and_missing_env() { + assert_eq!(resolve_target(None, None).unwrap(), None); + assert_eq!( + resolve_target(Some(Some(Path::new("report.md"))), None).unwrap(), + Some(SummaryTarget::Write(PathBuf::from("report.md"))) + ); + assert_eq!( + resolve_target(Some(None), Some(OsString::from("/tmp/step.md"))).unwrap(), + Some(SummaryTarget::Append(PathBuf::from("/tmp/step.md"))) + ); + assert!(resolve_target(Some(None), None).is_err()); + assert!(resolve_target(Some(None), Some(OsString::from(" "))).is_err()); + } + + #[test] + fn clean_completed_review_renders_compact_summary_without_findings_table() { + let detail = review(vec![assessment("production", "COMPLETED", Vec::new())]); + let md = render( + &detail, + Some(Outcome::Completed), + Verdict::Done, + Some(Severity::Serious), + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(md.contains("## Proofline review: acme/web #42 (run 2) at `aaaaaaaaaaaa`")); + assert!(md.contains("**Status:** **COMPLETED** — no open findings")); + assert!(md.contains("| production | COMPLETED | 0 | — |")); + assert!(!md.contains("### Unresolved findings")); + } + + #[test] + fn incomplete_review_never_claims_clean_and_lists_gaps() { + let mut prod = assessment("production", "INCOMPLETE", Vec::new()); + prod.incompleteness_kind = Some("WORLD_UNAVAILABLE".to_owned()); + let mut detail = review(vec![prod]); + detail.code_assessment = Some(CodeAssessmentRead::Recorded(CodeAssessment { + id: Uuid::nil(), + status: CodeAssessmentStatus::Incomplete, + head_commit_sha: HEAD.to_owned(), + base_commit_sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_owned(), + findings: vec![finding( + Uuid::from_u128(1), + "SERIOUS", + "NEW", + "missing timeout", + )], + incompleteness_kind: Some("TIMEOUT".to_owned()), + reason_codes: None, + })); + let md = render( + &detail, + Some(Outcome::Incomplete), + Verdict::NotComplete, + None, + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(md.contains("**Status:** **INCOMPLETE** — result is not complete")); + assert!(!md.contains("no open findings")); + assert!(md.contains("`WORLD_UNAVAILABLE`")); + assert!(md.contains("`TIMEOUT`")); + assert!(md.contains("### Findings so far (review is incomplete)")); + } + + #[test] + fn escapes_html_markdown_links_pipes_and_bidi_controls_in_findings() { + let hostile = finding( + Uuid::from_u128(2), + "SERIOUS", + "NEW", + "bad | ![img](https://evil.test) \u{202E}rtl `code` \\", + ); + let resolved = finding(Uuid::from_u128(3), "SERIOUS", "RESOLVED", "already fixed"); + let mut detail = review(vec![assessment( + "prod | eu", + "COMPLETED", + vec![hostile, resolved], + )]); + detail.open_items = Some(OpenItems { + open_findings: 1, + serious_findings: 1, + }); + + let md = render( + &detail, + Some(Outcome::Completed), + Verdict::ThresholdReached, + Some(Severity::Serious), + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(md.contains("failed `--fail-on serious`")); + assert!(!md.contains(" | ![p](https://evil.test)", + "impact": "orders are lost", + "lifecycle_state": "NEW", + "evidence_refs": [{ + "kind": "repository_file", + "label": "src/app.rs", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "src/app.rs", + "commit_sha": CI_HEAD, + "start_line": 3, + "end_line": 5, + }], + }, + { + "id": "0190f3a0-0000-7000-8000-0000000000a2", + "severity": "SERIOUS", + "risk_domain": "data_integrity", + "claim": "Already fixed finding", + "impact": "none", + "lifecycle_state": "RESOLVED", + "evidence_refs": [], + }, + ], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + }], + })) + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let directory = tempfile::tempdir().unwrap(); + + // 1. --summary without a file path and without GITHUB_STEP_SUMMARY fails fast before any HTTP call. + let mut missing_env = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + missing_env + .args([ + "--base-url", + &origin, + "--org", + ORG, + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--summary", + ]) + .env("PROOFLINE_TOKEN", TOKEN) + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/proofline-test-unavailable-bus", + ) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env_remove("GITHUB_STEP_SUMMARY") + .current_dir(directory.path()); + let output = tokio::time::timeout( + std::time::Duration::from_secs(15), + missing_env.kill_on_drop(true).output(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&output.stderr).contains("GITHUB_STEP_SUMMARY"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + requests.load(Ordering::Relaxed), + 0, + "must fail fast before polling" + ); + + // 2. --summary appends to GITHUB_STEP_SUMMARY without clobbering earlier steps, and preserves exit 3 on --fail-on. + let step_summary = directory.path().join("step-summary.md"); + std::fs::write(&step_summary, "## Earlier step\n\nAll unit tests passed.\n").unwrap(); + let mut append_cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + append_cmd + .args([ + "--base-url", + &origin, + "--org", + ORG, + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--fail-on", + "serious", + "--summary", + "--json", + ]) + .env("PROOFLINE_TOKEN", TOKEN) + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/proofline-test-unavailable-bus", + ) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("GITHUB_STEP_SUMMARY", &step_summary) + .current_dir(directory.path()); + let appended = tokio::time::timeout( + std::time::Duration::from_secs(15), + append_cmd.kill_on_drop(true).output(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + appended.status.code(), + Some(3), + "{}", + String::from_utf8_lossy(&appended.stderr) + ); + let content = std::fs::read_to_string(&step_summary).unwrap(); + assert!(content.starts_with( + "## Earlier step\n\nAll unit tests passed.\n\n## Proofline review: acme/app #12" + )); + assert!(content.contains("failed `--fail-on serious`")); + assert!(content.contains("<script>x</script> \\| !\\[p\\](https://evil.test)")); + assert!(content.contains("`src/app.rs:3-5`")); + assert!(!content.contains("Already fixed finding")); + let result: Value = serde_json::from_slice(&appended.stdout).unwrap(); + assert_eq!(result["outcome"], "COMPLETED"); + + // 3. --summary writes directly to an explicit path without needing GITHUB_STEP_SUMMARY. + let explicit_file = directory.path().join("custom-summary.md"); + let explicit_arg = explicit_file.to_str().unwrap(); + let explicit = cli( + &origin, + &[ + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--summary", + explicit_arg, + ], + ) + .await; + assert_eq!( + explicit.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&explicit.stderr) + ); + let written = std::fs::read_to_string(&explicit_file).unwrap(); + assert!(written.starts_with("## Proofline review: acme/app #12")); + assert!(written.contains("| production | COMPLETED | 1 | — |")); +} + #[tokio::test] async fn native_tools_keep_tenant_paths_and_reruns_make_one_attempt() { let requests = Arc::new(Mutex::new(Vec::new())); From 83a28ce8e0d6f6c44d712aa165c3f70ae05c7171 Mon Sep 17 00:00:00 2001 From: arielonoriaga Date: Tue, 1 Dec 2026 10:24:17 -0300 Subject: [PATCH 2/2] fix(ci): harden --summary GFM escaping, fail-fast, append budget and decouple module --- src/lib.rs | 60 ++-- src/summary.rs | 781 +++++++++++++++++++++++++++++++++++++++---------- tests/http.rs | 274 +++++++++++++++-- 3 files changed, 928 insertions(+), 187 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 4aa8ed7..dcd9f09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -639,10 +639,24 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { let commit = ci_commit(args.commit.as_deref())?; + let summary_target = summary::resolve_target( + args.summary.as_ref().map(|path| path.as_deref()), + std::env::var_os(summary::GITHUB_STEP_SUMMARY_ENV), + )?; let http = Http::new(origin)?; let event = std::env::var(github_actions::EVENT_NAME).unwrap_or_default(); let issuer = github_actions::Issuer::from_environment(); - let result = ci_job(http, token, issuer, &event, cli.org, &args, &commit).await; + let result = ci_job( + http, + token, + issuer, + &event, + cli.org, + &args, + &commit, + summary_target.as_ref(), + ) + .await; ci_ending(result) } Command::Ci(CiCommand::Deploy(mut args)) => { @@ -1534,6 +1548,7 @@ async fn ci_job( org: Option, args: &CiReviewArgs, commit: &str, + summary_target: Option<&summary::SummaryTarget>, ) -> anyhow::Result { let (api, request) = match (token, issuer) { (None, Some(issuer)) => { @@ -1544,7 +1559,7 @@ async fn ci_job( } (token, _) => (connect(http, token, org).await?, None), }; - ci_review(&api, args, commit, request.as_ref()).await + ci_review(&api, args, commit, request.as_ref(), summary_target).await } /// How long a pull-request job waits for the App's review of its head before @@ -1607,11 +1622,8 @@ async fn ci_review( args: &CiReviewArgs, commit: &str, request: Option<&github_actions::ReviewRequest>, + summary_target: Option<&summary::SummaryTarget>, ) -> anyhow::Result { - let summary_target = summary::resolve_target( - args.summary.as_ref().map(|path| path.as_deref()), - std::env::var_os(summary::GITHUB_STEP_SUMMARY_ENV), - )?; let started = tokio::time::Instant::now(); let deadline = poll_deadline(args.timeout)?; let (name, repository_id) = connected_repository(api, &args.repository).await?; @@ -1641,16 +1653,18 @@ async fn ci_review( if let Some(path) = sarif_path { write_sarif(api, review_id, &detail, path).await?; } - if let Some(target) = &summary_target { - let markdown = summary::render( - &detail, - state, - verdict, - args.fail_on, - &api.review_url(review_id), - summary::MAX_SUMMARY_BYTES, - ); - summary::write_target(target, &markdown).await?; + if let Some(target) = summary_target { + let gate = match (state, verdict, args.fail_on) { + (Some(Outcome::Completed), Verdict::ThresholdReached, Some(threshold)) => { + summary::GateVerdict::ThresholdReached(threshold) + } + (Some(Outcome::Completed), Verdict::Unavailable, Some(threshold)) => { + summary::GateVerdict::Unmeasured(threshold) + } + (Some(Outcome::Completed), Verdict::Done, Some(_)) => summary::GateVerdict::Passed, + _ => summary::GateVerdict::None, + }; + summary::write_summary(target, &detail, state, gate, &api.review_url(review_id)).await?; } if args.annotations { annotations::write(&detail, &mut std::io::stderr().lock())?; @@ -2196,7 +2210,7 @@ mod tests { }; let token = stored_token.then(|| SecretString::from("plp_stored")); let org = stored_token.then(|| ORG.parse().unwrap()); - let ended = ci_job(http, token, Some(issuer), event, org, &args, HEAD) + let ended = ci_job(http, token, Some(issuer), event, org, &args, HEAD, None) .await .unwrap(); assert_eq!(ended, verdict, "{case}"); @@ -2267,7 +2281,17 @@ mod tests { remote: "origin".to_owned(), }, }; - let verdict = ci_job(http, None, Some(issuer), "pull_request", None, &args, HEAD).await; + let verdict = ci_job( + http, + None, + Some(issuer), + "pull_request", + None, + &args, + HEAD, + None, + ) + .await; ticker.abort(); let received = received.lock().unwrap().clone(); (verdict, received) diff --git a/src/summary.rs b/src/summary.rs index afaa4f8..16f898b 100644 --- a/src/summary.rs +++ b/src/summary.rs @@ -1,8 +1,9 @@ //! GitHub Actions job summary (Markdown) for a pull-request review. Findings //! quote model output and repository content, which are untrusted, so control -//! characters, Unicode bidirectional controls, raw HTML, Markdown links/images, -//! and table delimiters are escaped before writing. An incomplete review or -//! assessment always names its gaps and never renders as clean. +//! characters, Unicode bidirectional controls, raw HTML, GFM extended +//! autolinks, Markdown formatting/links/images, and table delimiters are +//! neutralized before writing. An incomplete review or assessment always names +//! its gaps and never renders as clean. use std::cmp::Reverse; use std::ffi::OsString; @@ -13,18 +14,28 @@ use anyhow::{Context as _, bail}; use tokio::io::AsyncWriteExt as _; use url::Url; -use crate::Verdict; use crate::model::{Assessment, CodeAssessment, Finding, ReviewDetail}; use crate::outcome::{self, Outcome}; +use crate::sarif; use crate::severity::Severity; -use crate::{sarif, text}; +use crate::text; -/// GitHub Actions drops job summaries larger than 1 MiB. +/// GitHub Actions drops job summaries larger than 1 MiB for the whole step. pub(crate) const MAX_SUMMARY_BYTES: usize = 1024 * 1024; /// Environment variable GitHub Actions sets to the current step's summary file. pub(crate) const GITHUB_STEP_SUMMARY_ENV: &str = "GITHUB_STEP_SUMMARY"; +/// Outcome of `--fail-on` for a completed review, owned by this module so +/// summary rendering stays decoupled from CLI exit handling. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum GateVerdict { + None, + Passed, + ThresholdReached(Severity), + Unmeasured(Severity), +} + /// Where a rendered job summary should be written. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum SummaryTarget { @@ -34,8 +45,8 @@ pub(crate) enum SummaryTarget { Write(PathBuf), } -/// Resolves `--summary [FILE]` before any network wait so a missing -/// `GITHUB_STEP_SUMMARY` fails immediately instead of after polling. +/// Resolves `--summary [FILE]` before any network or credential I/O so a +/// missing `GITHUB_STEP_SUMMARY` or blank path fails immediately. pub(crate) fn resolve_target( flag: Option>, step_summary_env: Option, @@ -43,7 +54,10 @@ pub(crate) fn resolve_target( let Some(explicit) = flag else { return Ok(None); }; - if let Some(path) = explicit.filter(|path| !path.as_os_str().is_empty()) { + if let Some(path) = explicit { + if path.as_os_str().is_empty() || path.to_string_lossy().trim().is_empty() { + bail!("--summary file path must not be empty"); + } return Ok(Some(SummaryTarget::Write(path.to_path_buf()))); } let env_path = step_summary_env.filter(|value| !value.to_string_lossy().trim().is_empty()); @@ -55,12 +69,33 @@ pub(crate) fn resolve_target( Ok(Some(SummaryTarget::Append(PathBuf::from(env_path)))) } -/// Writes or appends `markdown` according to `target`. -pub(crate) async fn write_target(target: &SummaryTarget, markdown: &str) -> anyhow::Result<()> { +/// Renders and writes or appends a pull-request review summary respecting the +/// total `MAX_SUMMARY_BYTES` cap (including existing bytes when appending). +pub(crate) async fn write_summary( + target: &SummaryTarget, + review: &ReviewDetail, + state: Option, + gate: GateVerdict, + url: &Url, +) -> anyhow::Result<()> { + write_summary_with_limit(target, review, state, gate, url, MAX_SUMMARY_BYTES).await +} + +async fn write_summary_with_limit( + target: &SummaryTarget, + review: &ReviewDetail, + state: Option, + gate: GateVerdict, + url: &Url, + max_bytes: usize, +) -> anyhow::Result<()> { match target { - SummaryTarget::Write(path) => tokio::fs::write(path, markdown) - .await - .with_context(|| format!("could not write job summary to {}", path.display())), + SummaryTarget::Write(path) => { + let markdown = render(review, state, gate, url, max_bytes); + tokio::fs::write(path, markdown) + .await + .with_context(|| format!("could not write job summary to {}", path.display())) + } SummaryTarget::Append(path) => { let mut file = tokio::fs::OpenOptions::new() .create(true) @@ -68,17 +103,29 @@ pub(crate) async fn write_target(target: &SummaryTarget, markdown: &str) -> anyh .open(path) .await .with_context(|| format!("could not open job summary at {}", path.display()))?; - let existing_len = file - .metadata() - .await - .with_context(|| format!("could not inspect job summary at {}", path.display()))? - .len(); - if existing_len > 0 { - file.write_all(b"\n").await.with_context(|| { - format!("could not append job summary to {}", path.display()) - })?; + let existing_len = usize::try_from( + file.metadata() + .await + .with_context(|| { + format!("could not inspect job summary at {}", path.display()) + })? + .len(), + ) + .unwrap_or(usize::MAX); + let separator = if existing_len > 0 { "\n\n" } else { "" }; + let remaining = max_bytes.saturating_sub(existing_len.saturating_add(separator.len())); + let header = render_header(review, state, gate, url); + if remaining < header.len() { + bail!( + "could not append job summary to {}: file already reached the {max_bytes}-byte step summary limit", + path.display() + ); } - file.write_all(markdown.as_bytes()) + let markdown = render_with_header(header, review, state, remaining); + let mut payload = Vec::with_capacity(separator.len() + markdown.len()); + payload.extend_from_slice(separator.as_bytes()); + payload.extend_from_slice(markdown.as_bytes()); + file.write_all(&payload) .await .with_context(|| format!("could not append job summary to {}", path.display()))?; file.flush() @@ -93,31 +140,48 @@ pub(crate) async fn write_target(target: &SummaryTarget, markdown: &str) -> anyh pub(crate) fn render( review: &ReviewDetail, state: Option, - verdict: Verdict, - fail_on: Option, + gate: GateVerdict, url: &Url, max_bytes: usize, +) -> String { + let header = render_header(review, state, gate, url); + render_with_header(header, review, state, max_bytes) +} + +fn render_header( + review: &ReviewDetail, + state: Option, + gate: GateVerdict, + url: &Url, ) -> String { let mut out = String::new(); - let heading = format!( - "## Proofline review: {}{}\n\n", + let _ = writeln!( + out, + "## Proofline review: {}{}\n", subject_heading(review), commit_suffix(review) ); - out.push_str(&heading); - out.push_str(&status_line(review, state, verdict, fail_on)); + out.push_str(&status_line(review, state, gate)); out.push('\n'); if let Some(reason) = outcome::review_gap(review) { - let _ = writeln!(out, "- **Review gap:** `{reason}`"); + let _ = writeln!(out, "- **Review gap:** `{}`", escape_heading_code(reason)); } let _ = writeln!(out, "- **Review page:** [View in Proofline]({url})"); + out +} - push_assessments(&mut out, review); +fn render_with_header( + mut out: String, + review: &ReviewDetail, + state: Option, + max_bytes: usize, +) -> String { + push_assessments(&mut out, review, max_bytes); push_findings(&mut out, review, state, max_bytes); if out.len() > max_bytes { - truncate_utf8(&mut out, max_bytes); + truncate_to_budget(&mut out, max_bytes); } out } @@ -139,50 +203,49 @@ fn commit_suffix(review: &ReviewDetail) -> String { let Some(head) = review.head_commit_sha.as_deref() else { return String::new(); }; - let short = head.get(..12).unwrap_or(head); - format!(" at `{}`", escape_code_span(short)) + let short: String = text::one_line(head).trim().chars().take(12).collect(); + if short.is_empty() { + return String::new(); + } + format!(" at `{}`", escape_heading_code(&short)) } -fn status_line( - review: &ReviewDetail, - state: Option, - verdict: Verdict, - fail_on: Option, -) -> String { +fn status_line(review: &ReviewDetail, state: Option, gate: GateVerdict) -> String { match state { Some(Outcome::Completed) => { let counts = match &review.open_items { - Some(open) if open.open_findings == 0 => "no open findings".to_owned(), + Some(open) if open.open_findings == 0 && open.serious_findings == 0 => { + "no open findings".to_owned() + } Some(open) => { - let other = open.open_findings.saturating_sub(open.serious_findings); format!( - "{} serious, {other} warning open ({} total)", - open.serious_findings, open.open_findings + "{} open ({} serious)", + open.open_findings, open.serious_findings ) } None => { let unresolved = collect_unresolved(review).len(); - if unresolved == 0 { - "no unresolved findings recorded".to_owned() - } else { - format!("{unresolved} unresolved findings recorded") + match unresolved { + 0 => "no unresolved findings recorded".to_owned(), + 1 => "1 unresolved finding recorded".to_owned(), + n => format!("{n} unresolved findings recorded"), } } }; - let gate = match (verdict, fail_on) { - (Verdict::ThresholdReached, Some(threshold)) => { + let gate_note = match gate { + GateVerdict::ThresholdReached(threshold) => { format!( " — failed `--fail-on {}`", threshold.as_str().to_lowercase() ) } - (Verdict::Unavailable, Some(threshold)) => format!( + GateVerdict::Unmeasured(threshold) => format!( " — `--fail-on {}` could not be measured (`open_items` absent)", threshold.as_str().to_lowercase() ), - _ => String::new(), + GateVerdict::None | GateVerdict::Passed => String::new(), }; - format!("- **Status:** **COMPLETED** — {counts}{gate}") + format!("- **Status:** **COMPLETED** — {counts}{gate_note}") } Some(other) => { format!( @@ -197,72 +260,92 @@ fn status_line( } } -fn push_assessments(out: &mut String, review: &ReviewDetail) { +fn push_assessments(out: &mut String, review: &ReviewDetail, max_bytes: usize) { let code = outcome::code_assessment(review); let code_unavail = outcome::code_unavailable(review); if code.is_none() && !code_unavail && review.assessments.is_empty() { if review.assessment_count != 0 { - out.push_str("\nNo environment assessment has been recorded yet.\n"); + let notice = "\nNo environment assessment has been recorded yet.\n"; + if out.len() + notice.len() <= max_bytes { + out.push_str(notice); + } } return; } - out.push_str("\n### Assessments\n\n"); - out.push_str("| Lane | Status | Unresolved | Gaps |\n"); - out.push_str("| --- | --- | ---: | --- |\n"); - + let mut rows = Vec::with_capacity(review.assessments.len() + 1); if let Some(code) = code { - push_code_row(out, code); + rows.push(format_code_row(code)); } else if code_unavail { - out.push_str("| Code-only | INCOMPLETE | — | `CODE_ASSESSMENT_UNAVAILABLE` |\n"); + rows.push(format!( + "| Code-only | INCOMPLETE | — | {} |\n", + code_cell("CODE_ASSESSMENT_UNAVAILABLE") + )); } - for assessment in &review.assessments { - push_env_row(out, assessment); + rows.push(format_env_row(assessment)); } + append_table_rows( + out, + "\n### Assessments\n\n", + "| Lane | Status | Unresolved | Gaps |\n| --- | --- | ---: | --- |\n", + rows.len(), + |index| rows[index].clone(), + max_bytes, + omitted_more_assessments_notice, + omitted_all_assessments_notice, + ); + if review.assessments.is_empty() && review.assessment_count != 0 { - out.push_str("\n_No environment assessment has been recorded yet._\n"); + let notice = "\n_No environment assessment has been recorded yet._\n"; + if out.len() + notice.len() <= max_bytes { + out.push_str(notice); + } } } -fn push_code_row(out: &mut String, code: &CodeAssessment) { +fn format_code_row(code: &CodeAssessment) -> String { let open_count = code .findings .iter() .filter(|item| !outcome::resolved(item)) .count(); let gaps = format_gaps(outcome::code_gap(code).as_deref()); - let _ = writeln!( - out, - "| Code-only | {} | {open_count} | {gaps} |", + format!( + "| Code-only | {} | {open_count} | {gaps} |\n", code.status.as_str() - ); + ) } -fn push_env_row(out: &mut String, assessment: &Assessment) { +fn format_env_row(assessment: &Assessment) -> String { let open_count = assessment .findings .iter() .filter(|item| !outcome::resolved(item)) .count(); let gaps = format_gaps(outcome::gap(assessment).as_deref()); - let _ = writeln!( - out, - "| {} | {} | {open_count} | {gaps} |", + format!( + "| {} | {} | {open_count} | {gaps} |\n", escape_cell(&assessment.environment_display_name), escape_cell(&assessment.status), - ); + ) } fn format_gaps(reasons: Option<&[String]>) -> String { - match reasons { - Some(list) if !list.is_empty() => list - .iter() - .map(|code| format!("`{}`", escape_code_span(code))) - .collect::>() - .join(", "), - _ => "—".to_owned(), + let Some(reasons) = reasons else { + return "—".to_owned(); + }; + let formatted: Vec = reasons + .iter() + .map(|code| text::one_line(code)) + .filter(|code| !code.trim().is_empty()) + .map(|code| code_cell(&code)) + .collect(); + if formatted.is_empty() { + code_cell("ASSESSMENT_RESULT_UNAVAILABLE") + } else { + formatted.join(", ") } } @@ -315,11 +398,44 @@ fn push_findings( "\n### Findings so far (review is incomplete)\n\n" }; let table_header = "| Severity | Lane | Domain | Location | Finding | ID |\n| --- | --- | --- | --- | --- | --- |\n"; - let head = review.head_commit_sha.as_deref().unwrap_or_default(); - let worst_footer = truncation_notice(findings.len()); - if out.len() + heading.len() + table_header.len() + worst_footer.len() > max_bytes { - let notice = truncation_notice(findings.len()); + + append_table_rows( + out, + heading, + table_header, + findings.len(), + |index| format_finding_row(findings[index].lane, findings[index].finding, head), + max_bytes, + omitted_more_findings_notice, + omitted_all_findings_notice, + ); +} + +fn append_table_rows( + out: &mut String, + heading: &str, + table_header: &str, + total: usize, + row_at: impl Fn(usize) -> String, + max_bytes: usize, + omitted_more: impl Fn(usize) -> String, + omitted_all: impl Fn(usize) -> String, +) { + if total == 0 { + return; + } + let first_row = row_at(0); + let first_reserve = if total == 1 { + 0 + } else { + omitted_more(total - 1).len() + }; + + // Never emit a dangling empty table header if row 0 does not fit. + if out.len() + heading.len() + table_header.len() + first_row.len() + first_reserve > max_bytes + { + let notice = omitted_all(total); if out.len() + notice.len() <= max_bytes { out.push_str(¬ice); } @@ -328,18 +444,19 @@ fn push_findings( out.push_str(heading); out.push_str(table_header); + out.push_str(&first_row); - let total = findings.len(); - for (index, item) in findings.iter().enumerate() { - let row = format_finding_row(item.lane, item.finding, head); - let remaining_after = total - index; - let reserve = if index + 1 == total { + for index in 1..total { + let row = row_at(index); + let remaining_including_this = total - index; + let remaining_after = total - index - 1; + let reserve = if remaining_after == 0 { 0 } else { - truncation_notice(remaining_after).len() + omitted_more(remaining_after).len() }; if out.len() + row.len() + reserve > max_bytes { - out.push_str(&truncation_notice(remaining_after)); + out.push_str(&omitted_more(remaining_including_this)); break; } out.push_str(&row); @@ -359,7 +476,7 @@ fn format_finding_row(lane: &str, finding: &Finding, head: &str) -> String { } else { format!("{path}:{start}") }; - format!("`{}`", escape_code_span(&coords)) + code_cell(&coords) }, ); let mut description = format!( @@ -367,38 +484,76 @@ fn format_finding_row(lane: &str, finding: &Finding, head: &str) -> String { escape_cell(&finding.claim), escape_cell(&finding.impact) ); - if let Some(fix) = &finding.remediation { + if let Some(fix) = &finding.remediation + && !fix.trim().is_empty() + { description.push_str(" Fix: "); description.push_str(&escape_cell(fix)); } format!( - "| {} | {} | {} | {location} | {description} | `{}` |\n", + "| {} | {} | {} | {location} | {description} | {} |\n", escape_cell(&finding.severity), escape_cell(lane), escape_cell(&finding.risk_domain), - finding.id + code_cell(&finding.id.to_string()), + ) +} + +fn omitted_more_assessments_notice(omitted: usize) -> String { + let noun = if omitted == 1 { + "assessment" + } else { + "assessments" + }; + format!( + "\n_…and {omitted} more {noun} omitted to fit the job summary size limit. See the full review page above._\n" + ) +} + +fn omitted_all_assessments_notice(total: usize) -> String { + let noun = if total == 1 { + "assessment" + } else { + "assessments" + }; + format!( + "\n_All {total} {noun} omitted to fit the job summary size limit. See the full review page above._\n" ) } -fn truncation_notice(omitted: usize) -> String { +fn omitted_more_findings_notice(omitted: usize) -> String { let noun = if omitted == 1 { "finding" } else { "findings" }; format!( "\n_…and {omitted} more unresolved {noun} omitted to fit the job summary size limit. See the full review page above._\n" ) } -/// Escapes untrusted text for inline Markdown outside code spans: strips -/// terminal/bidi controls, neutralizes raw HTML and Markdown link/image/code -/// syntax, and collapses everything onto a single line. +fn omitted_all_findings_notice(total: usize) -> String { + let noun = if total == 1 { "finding" } else { "findings" }; + format!( + "\n_All {total} unresolved {noun} omitted to fit the job summary size limit. See the full review page above._\n" + ) +} + +/// Escapes untrusted text for inline Markdown: strips terminal/bidi controls, +/// neutralizes raw HTML, Markdown emphasis/links/images/code, GitHub `@` +/// mentions / `mailto:` autolinks and `$` math blocks (`@` / +/// `$` survive `cmark-gfm` entity decoding), and GFM extended +/// autolinks (`https://`, `www.`), while keeping rendered text readable. fn escape_inline(raw: &str) -> String { let clean = text::one_line(raw); let mut escaped = String::with_capacity(clean.len()); - for ch in clean.chars() { + let chars: Vec = clean.chars().collect(); + for (index, &ch) in chars.iter().enumerate() { match ch { '&' => escaped.push_str("&"), '<' => escaped.push_str("<"), '>' => escaped.push_str(">"), - '\\' | '`' | '[' | ']' => { + ':' => escaped.push_str(":"), + '@' => escaped.push_str("@"), + '$' => escaped.push_str("$"), + '.' if preceded_by_www(&chars, index) => escaped.push_str("."), + '\\' | '`' | '[' | ']' | '*' | '_' | '~' => { escaped.push('\\'); escaped.push(ch); } @@ -408,25 +563,92 @@ fn escape_inline(raw: &str) -> String { escaped } +fn preceded_by_www(chars: &[char], dot_index: usize) -> bool { + dot_index >= 3 + && chars[dot_index - 3].eq_ignore_ascii_case(&'w') + && chars[dot_index - 2].eq_ignore_ascii_case(&'w') + && chars[dot_index - 1].eq_ignore_ascii_case(&'w') +} + /// Escapes untrusted text for a GitHub-Flavored Markdown table cell. fn escape_cell(raw: &str) -> String { - escape_inline(raw).replace('|', "\\|") + escape_inline(raw).replace('|', "|") +} + +/// Renders untrusted inline code inside a GFM table cell using HTML `` +/// around fully escaped cell text. CommonMark/GFM still parses Markdown inside +/// inline `...` tags, so full cell escaping prevents link/image/ +/// autolink injection, paired backtick tag-swallowing, and `\|` corruption. +fn code_cell(raw: &str) -> String { + format!("{}", escape_cell(raw)) } -/// Escapes untrusted text placed inside a single-backtick inline code span -/// inside a GFM table cell. -fn escape_code_span(raw: &str) -> String { - text::one_line(raw).replace('`', "'").replace('|', "\\|") +/// Escapes untrusted text inside a backtick code span outside a GFM table. +fn escape_heading_code(raw: &str) -> String { + text::one_line(raw).replace('`', "'") } -fn truncate_utf8(text: &mut String, max_bytes: usize) { - let mut end = max_bytes.min(text.len()); +/// Enforces `max_bytes` cleanly on a UTF-8 boundary, preferring a newline +/// boundary and never slicing inside an HTML tag, character reference, +/// inline ``/`` pair, or backtick span. +fn truncate_to_budget(text: &mut String, max_bytes: usize) { + if text.len() <= max_bytes { + return; + } + let mut end = max_bytes; while end > 0 && !text.is_char_boundary(end) { end -= 1; } + let Some(prefix) = text.get(..end) else { + text.clear(); + return; + }; + if let Some(newline) = prefix.rfind('\n') { + text.truncate(newline + 1); + return; + } + loop { + let Some(slice) = text.get(..end) else { + text.clear(); + return; + }; + if let Some(lt) = slice.rfind('<') + && !slice.get(lt..).is_some_and(|tail| tail.contains('>')) + { + end = lt; + continue; + } + if let Some(amp) = slice.rfind('&') + && !slice.get(amp..).is_some_and(|tail| tail.contains(';')) + { + end = amp; + continue; + } + if let Some(open) = unclosed_inline_tag(slice, "") + .or_else(|| unclosed_inline_tag(slice, "")) + { + end = open; + continue; + } + if slice.bytes().filter(|&b| b == b'`').count() % 2 == 1 + && let Some(tick) = slice.rfind('`') + { + end = tick; + continue; + } + break; + } text.truncate(end); } +fn unclosed_inline_tag(slice: &str, open_tag: &str, close_tag: &str) -> Option { + if slice.matches(open_tag).count() > slice.matches(close_tag).count() { + slice.rfind(open_tag) + } else { + None + } +} + #[cfg(test)] mod tests { use super::*; @@ -442,6 +664,20 @@ mod tests { .unwrap() } + fn verified_ref(commit: &str) -> EvidenceRef { + EvidenceRef { + kind: "repository_file".to_owned(), + label: "src/app.rs".to_owned(), + provenance_status: Some("VERIFIED_REPOSITORY_READ".to_owned()), + repository_path: Some("src/app.rs".to_owned()), + commit_sha: Some(commit.to_owned()), + start_line: Some(10), + end_line: Some(14), + file_sha256: None, + companion_repository: None, + } + } + fn finding(id: Uuid, severity: &str, lifecycle_state: &str, claim: &str) -> Finding { Finding { id, @@ -452,17 +688,7 @@ mod tests { impact: "orders are lost".to_owned(), lifecycle_state: lifecycle_state.to_owned(), remediation: Some("use an idempotency key".to_owned()), - evidence_refs: vec![EvidenceRef { - kind: "repository_file".to_owned(), - label: "src/app.rs".to_owned(), - provenance_status: Some("VERIFIED_REPOSITORY_READ".to_owned()), - repository_path: Some("src/app.rs".to_owned()), - commit_sha: Some(HEAD.to_owned()), - start_line: Some(10), - end_line: Some(14), - file_sha256: None, - companion_repository: None, - }], + evidence_refs: vec![verified_ref(HEAD)], } } @@ -507,7 +733,7 @@ mod tests { } #[test] - fn resolve_target_handles_explicit_path_env_and_missing_env() { + fn resolve_target_handles_explicit_path_env_missing_env_and_empty_explicit_path() { assert_eq!(resolve_target(None, None).unwrap(), None); assert_eq!( resolve_target(Some(Some(Path::new("report.md"))), None).unwrap(), @@ -517,6 +743,15 @@ mod tests { resolve_target(Some(None), Some(OsString::from("/tmp/step.md"))).unwrap(), Some(SummaryTarget::Append(PathBuf::from("/tmp/step.md"))) ); + // An explicit empty or whitespace path must refuse rather than silently append to GITHUB_STEP_SUMMARY. + assert!( + resolve_target( + Some(Some(Path::new(""))), + Some(OsString::from("/tmp/step.md")) + ) + .is_err() + ); + assert!(resolve_target(Some(Some(Path::new(" "))), None).is_err()); assert!(resolve_target(Some(None), None).is_err()); assert!(resolve_target(Some(None), Some(OsString::from(" "))).is_err()); } @@ -527,8 +762,7 @@ mod tests { let md = render( &detail, Some(Outcome::Completed), - Verdict::Done, - Some(Severity::Serious), + GateVerdict::Passed, &url(), MAX_SUMMARY_BYTES, ); @@ -539,10 +773,72 @@ mod tests { } #[test] - fn incomplete_review_never_claims_clean_and_lists_gaps() { + fn inconsistent_open_items_and_unknown_severities_never_lie() { + let mut unknown = finding(Uuid::from_u128(10), "NOTE", "NEW", "unknown severity"); + unknown.remediation = Some(" ".to_owned()); + let serious = finding(Uuid::from_u128(11), "SERIOUS", "NEW", "serious finding"); + let mut detail = review(vec![assessment( + "production", + "COMPLETED", + vec![unknown, serious], + )]); + detail.open_items = Some(OpenItems { + open_findings: 0, + serious_findings: 1, + }); + let md = render( + &detail, + Some(Outcome::Completed), + GateVerdict::ThresholdReached(Severity::Serious), + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(!md.contains("no open findings"), "{md}"); + assert!(md.contains("0 open (1 serious) — failed `--fail-on serious`")); + // Unknown severity renders honestly and sorts after known severities. + let serious_pos = md.find("| SERIOUS |").unwrap(); + let unknown_pos = md.find("| NOTE |").unwrap(); + assert!(serious_pos < unknown_pos, "{md}"); + // Blank remediation does not emit a trailing " Fix: ". + assert!(!md.contains("Fix: |"), "{md}"); + + // Absent `open_items` with a single unresolved finding uses singular phrasing + // and reports `--fail-on` as unmeasured. + let mut single = review(vec![assessment( + "production", + "COMPLETED", + vec![finding(Uuid::from_u128(12), "WARNING", "NEW", "one open")], + )]); + single.open_items = None; + let unmeasured = render( + &single, + Some(Outcome::Completed), + GateVerdict::Unmeasured(Severity::Serious), + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(unmeasured.contains("1 unresolved finding recorded")); + assert!(unmeasured.contains("`--fail-on serious` could not be measured")); + } + + #[test] + fn incomplete_failed_stopped_timeout_and_gaps_never_claim_clean() { let mut prod = assessment("production", "INCOMPLETE", Vec::new()); prod.incompleteness_kind = Some("WORLD_UNAVAILABLE".to_owned()); - let mut detail = review(vec![prod]); + prod.reason_codes = Some(vec![ + String::new(), + "A\\|B".to_owned(), + "a`b".to_owned(), + "c`d".to_owned(), + "[click](https://evil.test)".to_owned(), + ]); + // A "COMPLETED" assessment whose reason_codes are only blank strings is + // still incomplete per `outcome::gap` and must never render `"—"`. + let mut blank_gap = assessment("staging", "COMPLETED", Vec::new()); + blank_gap.reason_codes = Some(vec![String::new(), " ".to_owned()]); + + let mut detail = review(vec![prod, blank_gap]); + detail.assessment_count = 3; detail.code_assessment = Some(CodeAssessmentRead::Recorded(CodeAssessment { id: Uuid::nil(), status: CodeAssessmentStatus::Incomplete, @@ -560,57 +856,136 @@ mod tests { let md = render( &detail, Some(Outcome::Incomplete), - Verdict::NotComplete, - None, + GateVerdict::None, &url(), MAX_SUMMARY_BYTES, ); assert!(md.contains("**Status:** **INCOMPLETE** — result is not complete")); + assert!(md.contains("- **Review gap:** `ASSESSMENT_HISTORY_UNAVAILABLE`")); assert!(!md.contains("no open findings")); - assert!(md.contains("`WORLD_UNAVAILABLE`")); - assert!(md.contains("`TIMEOUT`")); + assert!(md.contains("A\\\\|B"), "{md}"); + assert!( + md.contains("a\\`b, c\\`d"), + "{md}" + ); + assert!( + md.contains("\\[click\\](https://evil.test)"), + "{md}" + ); + assert!(md.contains("WORLD\\_UNAVAILABLE"), "{md}"); + assert!( + md.contains( + "| staging | COMPLETED | 0 | ASSESSMENT\\_RESULT\\_UNAVAILABLE |" + ), + "{md}" + ); + assert!(md.contains("TIMEOUT")); + assert!(!md.contains("")); assert!(md.contains("### Findings so far (review is incomplete)")); + + let mut timeout_detail = review(Vec::new()); + timeout_detail.status = "RUNNING**inject**".to_owned(); + timeout_detail.assessment_count = 0; + let timeout_md = render( + &timeout_detail, + None, + GateVerdict::None, + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(timeout_md.contains("RUNNING\\*\\*inject\\*\\*")); + assert!(timeout_md.contains("CODE\\_ASSESSMENT\\_UNAVAILABLE")); + + let failed_md = render( + &detail, + Some(Outcome::Failed), + GateVerdict::None, + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(failed_md.contains("**FAILED** — result is not complete")); + + let stopped_md = render( + &detail, + Some(Outcome::Stopped), + GateVerdict::None, + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(stopped_md.contains("**STOPPED** — result is not complete")); } #[test] - fn escapes_html_markdown_links_pipes_and_bidi_controls_in_findings() { - let hostile = finding( + fn escapes_html_gfm_autolinks_formatting_pipes_and_bidi_controls() { + let mut hostile = finding( Uuid::from_u128(2), "SERIOUS", "NEW", - "bad | ![img](https://evil.test) \u{202E}rtl `code` \\", + "bad | ![img](https://evil.test) www.evil.test a@b.test @octocat **bold** ~~strike~~ $x$ \u{202E}rtl `code` \\", ); + hostile.evidence_refs = vec![EvidenceRef { + repository_path: Some("![x](www.evil.test)/src/app.rs".to_owned()), + ..verified_ref(HEAD) + }]; + // Unverified / wrong-commit refs must not produce a file citation. + let mut unlocated = finding(Uuid::from_u128(4), "WARNING", "NEW", "unverified ref"); + unlocated.evidence_refs = vec![ + verified_ref("cccccccccccccccccccccccccccccccccccccccc"), + EvidenceRef { + provenance_status: Some("UNVERIFIED".to_owned()), + ..verified_ref(HEAD) + }, + ]; let resolved = finding(Uuid::from_u128(3), "SERIOUS", "RESOLVED", "already fixed"); + hostile.remediation = None; let mut detail = review(vec![assessment( "prod | eu", "COMPLETED", - vec![hostile, resolved], + vec![hostile, unlocated, resolved], )]); detail.open_items = Some(OpenItems { - open_findings: 1, + open_findings: 2, serious_findings: 1, }); let md = render( &detail, Some(Outcome::Completed), - Verdict::ThresholdReached, - Some(Severity::Serious), + GateVerdict::ThresholdReached(Severity::Serious), &url(), MAX_SUMMARY_BYTES, ); - assert!(md.contains("failed `--fail-on serious`")); + assert!(md.contains("2 open (1 serious) — failed `--fail-on serious`")); assert!(!md.contains("