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..dcd9f09 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, @@ -634,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)) => { @@ -1529,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)) => { @@ -1539,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 @@ -1602,6 +1622,7 @@ async fn ci_review( args: &CiReviewArgs, commit: &str, request: Option<&github_actions::ReviewRequest>, + summary_target: Option<&summary::SummaryTarget>, ) -> anyhow::Result { let started = tokio::time::Instant::now(); let deadline = poll_deadline(args.timeout)?; @@ -1628,9 +1649,23 @@ 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 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())?; } @@ -1642,7 +1677,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 +2198,7 @@ mod tests { commit: None, sarif: None, annotations: false, + summary: None, json: false, timeout: 3, fail_on: None, @@ -2175,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}"); @@ -2236,6 +2271,7 @@ mod tests { commit: None, sarif: None, annotations: false, + summary: None, json: false, timeout: 3, fail_on: None, @@ -2245,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 new file mode 100644 index 0000000..16f898b --- /dev/null +++ b/src/summary.rs @@ -0,0 +1,1121 @@ +//! 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, 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; +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::model::{Assessment, CodeAssessment, Finding, ReviewDetail}; +use crate::outcome::{self, Outcome}; +use crate::sarif; +use crate::severity::Severity; +use crate::text; + +/// 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 { + /// 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 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, +) -> anyhow::Result> { + let Some(explicit) = flag else { + return Ok(None); + }; + 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()); + 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)))) +} + +/// 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) => { + 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) + .append(true) + .open(path) + .await + .with_context(|| format!("could not open job summary at {}", 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() + ); + } + 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() + .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, + 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 _ = writeln!( + out, + "## Proofline review: {}{}\n", + subject_heading(review), + commit_suffix(review) + ); + + out.push_str(&status_line(review, state, gate)); + out.push('\n'); + if let Some(reason) = outcome::review_gap(review) { + let _ = writeln!(out, "- **Review gap:** `{}`", escape_heading_code(reason)); + } + let _ = writeln!(out, "- **Review page:** [View in Proofline]({url})"); + out +} + +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_to_budget(&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: 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, gate: GateVerdict) -> String { + match state { + Some(Outcome::Completed) => { + let counts = match &review.open_items { + Some(open) if open.open_findings == 0 && open.serious_findings == 0 => { + "no open findings".to_owned() + } + Some(open) => { + format!( + "{} open ({} serious)", + open.open_findings, open.serious_findings + ) + } + None => { + let unresolved = collect_unresolved(review).len(); + match unresolved { + 0 => "no unresolved findings recorded".to_owned(), + 1 => "1 unresolved finding recorded".to_owned(), + n => format!("{n} unresolved findings recorded"), + } + } + }; + let gate_note = match gate { + GateVerdict::ThresholdReached(threshold) => { + format!( + " — failed `--fail-on {}`", + threshold.as_str().to_lowercase() + ) + } + GateVerdict::Unmeasured(threshold) => format!( + " — `--fail-on {}` could not be measured (`open_items` absent)", + threshold.as_str().to_lowercase() + ), + GateVerdict::None | GateVerdict::Passed => String::new(), + }; + format!("- **Status:** **COMPLETED** — {counts}{gate_note}") + } + 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, 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 { + let notice = "\nNo environment assessment has been recorded yet.\n"; + if out.len() + notice.len() <= max_bytes { + out.push_str(notice); + } + } + return; + } + + let mut rows = Vec::with_capacity(review.assessments.len() + 1); + if let Some(code) = code { + rows.push(format_code_row(code)); + } else if code_unavail { + rows.push(format!( + "| Code-only | INCOMPLETE | — | {} |\n", + code_cell("CODE_ASSESSMENT_UNAVAILABLE") + )); + } + for assessment in &review.assessments { + 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 { + let notice = "\n_No environment assessment has been recorded yet._\n"; + if out.len() + notice.len() <= max_bytes { + out.push_str(notice); + } + } +} + +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()); + format!( + "| Code-only | {} | {open_count} | {gaps} |\n", + code.status.as_str() + ) +} + +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()); + format!( + "| {} | {} | {open_count} | {gaps} |\n", + escape_cell(&assessment.environment_display_name), + escape_cell(&assessment.status), + ) +} + +fn format_gaps(reasons: Option<&[String]>) -> String { + 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(", ") + } +} + +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(); + + 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); + } + return; + } + + out.push_str(heading); + out.push_str(table_header); + out.push_str(&first_row); + + 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 { + omitted_more(remaining_after).len() + }; + if out.len() + row.len() + reserve > max_bytes { + out.push_str(&omitted_more(remaining_including_this)); + 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}") + }; + code_cell(&coords) + }, + ); + let mut description = format!( + "{} — {}", + escape_cell(&finding.claim), + escape_cell(&finding.impact) + ); + if let Some(fix) = &finding.remediation + && !fix.trim().is_empty() + { + 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), + 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 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" + ) +} + +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()); + 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); + } + _ => escaped.push(ch), + } + } + 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('|', "|") +} + +/// 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 inside a backtick code span outside a GFM table. +fn escape_heading_code(raw: &str) -> String { + text::one_line(raw).replace('`', "'") +} + +/// 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::*; + 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 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, + 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![verified_ref(HEAD)], + } + } + + 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_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(), + 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"))) + ); + // 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()); + } + + #[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), + GateVerdict::Passed, + &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 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()); + 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, + 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), + 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("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_gfm_autolinks_formatting_pipes_and_bidi_controls() { + let mut hostile = finding( + Uuid::from_u128(2), + "SERIOUS", + "NEW", + "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, unlocated, resolved], + )]); + detail.open_items = Some(OpenItems { + open_findings: 2, + serious_findings: 1, + }); + + let md = render( + &detail, + Some(Outcome::Completed), + GateVerdict::ThresholdReached(Severity::Serious), + &url(), + MAX_SUMMARY_BYTES, + ); + assert!(md.contains("2 open (1 serious) — 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": [] }, + }], + })) + } + } + }), + ) + .fallback({ + let seen = Arc::clone(&seen); + move || { + let seen = Arc::clone(&seen); + async move { + seen.fetch_add(1, Ordering::Relaxed); + StatusCode::NOT_FOUND + } + } + }); + 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 auth, OIDC exchange, org resolution, or polling. + let mut missing_env = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + missing_env + .args([ + "--base-url", + &origin, + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--summary", + ]) + .env("PROOFLINE_TOKEN", TOKEN) + .env_remove("PROOFLINE_ORGANIZATION_ID") + .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 auth or polling" + ); + + // 2. --summary "" (clap usage error) and --summary " " (blank path) both + // reject empty explicit paths even when GITHUB_STEP_SUMMARY is set, + // making zero HTTP requests and leaving the step summary untouched. + let step_summary = directory.path().join("step-summary.md"); + let prior_summary = "## Earlier step\n\nAll unit tests passed."; + std::fs::write(&step_summary, prior_summary).unwrap(); + for (blank_arg, expected_err) in [("", "a value is required"), (" ", "must not be empty")] { + let mut blank_path = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + blank_path + .args([ + "--base-url", + &origin, + "--org", + ORG, + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--summary", + blank_arg, + ]) + .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 blank_output = tokio::time::timeout( + std::time::Duration::from_secs(15), + blank_path.kill_on_drop(true).output(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(blank_output.status.code(), Some(1), "{blank_arg:?}"); + assert!( + String::from_utf8_lossy(&blank_output.stderr).contains(expected_err), + "{blank_arg:?}: {}", + String::from_utf8_lossy(&blank_output.stderr) + ); + } + assert_eq!(requests.load(Ordering::Relaxed), 0); + assert_eq!( + std::fs::read_to_string(&step_summary).unwrap(), + prior_summary + ); + + // 3. --summary appends cleanly (with a blank-line separator even without a trailing newline), + // neutralizes untrusted HTML/Markdown/autolinks, and preserves exit 3 on --fail-on. + 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" + ), + "{content}" + ); + assert!(content.contains("1 open (1 serious) — failed `--fail-on serious`")); + assert!( + content.contains("<script>x</script> | !\\[p\\](https://evil.test)"), + "{content}" + ); + assert!(!content.contains("https://evil.test")); + assert!( + content.contains("src/app.rs:3-5"), + "{content}" + ); + assert!(!content.contains("Already fixed finding")); + let result: Value = serde_json::from_slice(&appended.stdout).unwrap(); + assert_eq!(result["outcome"], "COMPLETED"); + + // 4. --summary writes to an explicit path without needing or touching GITHUB_STEP_SUMMARY. + let sentinel_step = directory.path().join("sentinel-step.md"); + std::fs::write(&sentinel_step, "untouched").unwrap(); + let explicit_file = directory.path().join("custom-summary.md"); + let explicit_arg = explicit_file.to_str().unwrap(); + let mut explicit_cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + explicit_cmd + .args([ + "--base-url", + &origin, + "--org", + ORG, + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--summary", + explicit_arg, + ]) + .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", &sentinel_step) + .current_dir(directory.path()); + let explicit = tokio::time::timeout( + std::time::Duration::from_secs(15), + explicit_cmd.kill_on_drop(true).output(), + ) + .await + .unwrap() + .unwrap(); + 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 | — |")); + assert_eq!( + std::fs::read_to_string(&sentinel_step).unwrap(), + "untouched" + ); +} + +#[tokio::test] +async fn ci_review_summary_reports_incomplete_gaps_and_unmeasured_fail_on() { + let detail_body = Arc::new(Mutex::new(json!({}))); + let served = Arc::clone(&detail_body); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|| async { + Json(json!({ + "repositories": [{ + "id": CI_REPOSITORY, + "full_name": "acme/app", + }] + })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(|| async { + Json(json!({ + "items": [{ + "id": CI_REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "created_at": "2026-10-01T00:00:00Z", + "head_commit_sha": CI_HEAD, + "pull_request_number": 12, + "repository_id": CI_REPOSITORY, + "run_number": 1, + }], + "next_cursor": null, + "truncated": false, + "filters": { "repositories": [], "environments": [], "authors": [] }, + })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"), + get(move || { + let served = Arc::clone(&served); + async move { Json(served.lock().unwrap().clone()) } + }), + ); + 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. Incomplete assessment writes gaps honestly and preserves exit 2. + *detail_body.lock().unwrap() = json!({ + "id": CI_REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "head_commit_sha": CI_HEAD, + "repository_id": CI_REPOSITORY, + "repository_full_name": "acme/app", + "pull_request_number": 12, + "run_number": 1, + "assessment_count": 1, + "open_items": { "open_findings": 0, "serious_findings": 0, "accepted_risks": 0, "not_assessed": [] }, + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-0000000000f2", + "environment_display_name": "production", + "status": "INCOMPLETE", + "incompleteness_kind": "WORLD_UNAVAILABLE", + "findings": [], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + }], + }); + let incomplete_file = directory.path().join("incomplete.md"); + let incomplete = cli( + &origin, + &[ + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--summary", + incomplete_file.to_str().unwrap(), + ], + ) + .await; + assert_eq!(incomplete.status.code(), Some(2)); + let md = std::fs::read_to_string(&incomplete_file).unwrap(); + assert!( + md.contains("**INCOMPLETE** — result is not complete"), + "{md}" + ); + assert!(md.contains("WORLD\\_UNAVAILABLE"), "{md}"); + assert!(!md.contains("no open findings"), "{md}"); + + // 2. Completed review without `open_items` + `--fail-on` reports unmeasured and exits 4. + *detail_body.lock().unwrap() = json!({ + "id": CI_REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "head_commit_sha": CI_HEAD, + "repository_id": CI_REPOSITORY, + "repository_full_name": "acme/app", + "pull_request_number": 12, + "run_number": 1, + "assessment_count": 1, + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-0000000000f2", + "environment_display_name": "production", + "status": "COMPLETED", + "findings": [], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + }], + }); + let unmeasured_file = directory.path().join("unmeasured.md"); + let unmeasured = cli( + &origin, + &[ + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--fail-on", + "serious", + "--summary", + unmeasured_file.to_str().unwrap(), + ], + ) + .await; + assert_eq!(unmeasured.status.code(), Some(4)); + let md = std::fs::read_to_string(&unmeasured_file).unwrap(); + assert!( + md.contains("`--fail-on serious` could not be measured (`open_items` absent)"), + "{md}" + ); +} + #[tokio::test] async fn native_tools_keep_tenant_paths_and_reruns_make_one_attempt() { let requests = Arc::new(Mutex::new(Vec::new()));