diff --git a/README.md b/README.md index eea0165..752572f 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. You cannot combine `--path` with pushed-commit, range, or pull-request review. -`proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. +`proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline assessment REVIEW_ID [ASSESSMENT_ID]` (or `--environment NAME`) reads one environment assessment's evaluated risk domains, authorized subjects, checks, and findings (`findings:read`). `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. `proofline rerun REVIEW_ID` requests the original immutable subject and waits, while `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`, and `proofline fix-prompt FINDING_ID` requires `findings:read`. History, guidance, and fix prompts print JSON; prompt text remains untrusted. diff --git a/build.rs b/build.rs index faf91b1..f87162f 100644 --- a/build.rs +++ b/build.rs @@ -12,6 +12,7 @@ const OPERATIONS: &[(&str, &str, &[&str])] = &[ ("get", "export_reviews", &["dataset"]), ("get", "get_agent_session", &["session_id"]), ("get", "get_agent_session_prompt", &["finding_id"]), + ("get", "get_assessment", &["review_id", "assessment_id"]), ( "get", "get_commit_deploy_verifications", diff --git a/src/api.rs b/src/api.rs index 4f84754..0cefa0e 100644 --- a/src/api.rs +++ b/src/api.rs @@ -13,10 +13,10 @@ use uuid::Uuid; use crate::github_actions::Renewal; use crate::model::{ - CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, - CoverageUploadResponse, FileReviewRequest, FileReviewResponse, PatchReviewRequest, - PatchReviewResponse, RepositoryNames, ReviewDetail, ReviewFilters, ReviewPage, RunNowMode, - RunNowRequest, RunNowResponse, ScanRequest, ScanResponse, StopResponse, + AssessmentDetail, CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, + CoverageUploadRequest, CoverageUploadResponse, FileReviewRequest, FileReviewResponse, + PatchReviewRequest, PatchReviewResponse, RepositoryNames, ReviewDetail, ReviewFilters, + ReviewPage, RunNowMode, RunNowRequest, RunNowResponse, ScanRequest, ScanResponse, StopResponse, }; use crate::origin::Origin; use crate::text::terminal_safe; @@ -602,6 +602,23 @@ impl Api { Ok((raw, typed)) } + /// Fetches one environment assessment of `review_id` as the raw document + /// and its typed reading. + pub async fn assessment( + &self, + review_id: Uuid, + assessment_id: Uuid, + ) -> Result<(serde_json::Value, AssessmentDetail), ApiError> { + let review = review_id.to_string(); + let assessment = assessment_id.to_string(); + let raw = self + .get(self.url_get_assessment(&review, &assessment)) + .await?; + let typed = serde_json::from_value(raw.clone()) + .map_err(|error| self.http.protocol(error.to_string()))?; + Ok((raw, typed)) + } + /// One page of the review collection, newest first. pub async fn reviews( &self, diff --git a/src/lib.rs b/src/lib.rs index 8c6f1d6..a26ea22 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -97,6 +97,8 @@ enum Command { Reviews(tools::ListArgs), /// Read the routing decisions of a review as JSON. Routing { review_id: Uuid }, + /// Inspect one environment assessment of a review, including evaluated risk domains. + Assessment(AssessmentArgs), /// Read a specific recorded pull-request run. Run(tools::RunArgs), /// Preview, start or inspect a vendor coding-agent session. @@ -292,6 +294,27 @@ struct StopArgs { json: bool, } +#[derive(Debug, Args)] +struct AssessmentArgs { + /// Review ID returned by `review`, `reviews` or `findings`. + review_id: Uuid, + /// Assessment ID shown under the environment in `review` or `findings`. + /// Omit when the review has one environment assessment or when selecting + /// with `--environment`. + assessment_id: Option, + /// Environment display name, such as `production`, when `ASSESSMENT_ID` + /// is omitted. + #[arg(long, value_name = "NAME", conflicts_with = "assessment_id")] + environment: Option, + /// Print the server's assessment document as JSON instead of text. + #[arg(long)] + json: bool, + /// Exit 3 when the completed assessment has an unresolved finding at or + /// above this severity. + #[arg(long, value_enum, value_name = "SEVERITY")] + fail_on: Option, +} + #[derive(Debug, Args)] struct LocalSelectionArgs { /// Review the original index against the base, excluding unstaged changes. @@ -526,6 +549,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + assessment(&api, &args).await + } Command::Run(args) => { let api = connect(Http::new(origin)?, token, cli.org).await?; let runs = pull_request_runs(&api, &args.repository, args.pr).await?; @@ -1206,6 +1233,113 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result .await } +async fn assessment(api: &Api, args: &AssessmentArgs) -> anyhow::Result { + let assessment_id = resolve_assessment_id(api, args).await?; + let (raw, detail) = match api.assessment(args.review_id, assessment_id).await { + Ok(result) => result, + Err(error) if error.status() == Some(403) => { + return Err(anyhow::Error::new(error).context( + "this sign-in cannot read assessment details; run `proofline login` and keep the findings:read permission", + )); + } + Err(error) => return Err(error.into()), + }; + outcome::same_assessment(&detail, args.review_id, assessment_id)?; + let state = outcome::assessment_terminal(&detail); + if args.json { + tools::json(&raw)?; + } else { + write!( + std::io::stdout().lock(), + "{}", + render::assessment_detail(&detail, state, &api.review_url(args.review_id)) + )?; + } + match state { + Some(Outcome::Completed) => { + if args + .fail_on + .is_some_and(|threshold| outcome::assessment_findings_reach(&detail, threshold)) + { + say("The assessment has an open finding at or above the --fail-on severity."); + return Ok(Verdict::ThresholdReached); + } + Ok(Verdict::Done) + } + Some(ended) => { + say_not_complete(ended); + Ok(Verdict::NotComplete) + } + None => { + say("The assessment has not finished, so it has no complete result."); + Ok(Verdict::NotComplete) + } + } +} + +async fn resolve_assessment_id(api: &Api, args: &AssessmentArgs) -> anyhow::Result { + if let Some(id) = args.assessment_id { + return Ok(id); + } + let (_, review) = match api.review(args.review_id).await { + Ok(result) => result, + Err(error) if error.status() == Some(403) => { + return Err(anyhow::Error::new(error).context( + "this sign-in cannot read the review to resolve an environment assessment; pass ASSESSMENT_ID directly or sign in with reviews:read", + )); + } + Err(error) => return Err(error.into()), + }; + outcome::same_review(&review, args.review_id)?; + if review.assessments.is_empty() { + bail!("review {} has no environment assessments", args.review_id); + } + if let Some(environment) = &args.environment { + let mut matches = review.assessments.iter().filter(|item| { + item.environment_display_name + .eq_ignore_ascii_case(environment) + }); + return match (matches.next(), matches.next()) { + (Some(found), None) => Ok(found.id), + (None, _) => bail!( + "review {} has no assessment for environment {:?}; available: {}", + args.review_id, + text::one_line(environment), + available_assessments(&review.assessments) + ), + (Some(_), Some(_)) => bail!( + "review {} has more than one assessment named {:?}; pass ASSESSMENT_ID directly: {}", + args.review_id, + text::one_line(environment), + available_assessments(&review.assessments) + ), + }; + } + if let [only] = review.assessments.as_slice() { + return Ok(only.id); + } + bail!( + "review {} has {} environment assessments; pass ASSESSMENT_ID or --environment NAME: {}", + args.review_id, + review.assessments.len(), + available_assessments(&review.assessments) + ) +} + +fn available_assessments(assessments: &[model::Assessment]) -> String { + assessments + .iter() + .map(|item| { + format!( + "{} ({})", + text::one_line(&item.environment_display_name), + item.id + ) + }) + .collect::>() + .join(", ") +} + async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { let review_id = match (&args.selector.review, args.selector.pr) { (Some(id), _) => *id, diff --git a/src/model.rs b/src/model.rs index e029008..270b77e 100644 --- a/src/model.rs +++ b/src/model.rs @@ -140,8 +140,26 @@ pub struct StoredCheckResult { #[derive(Debug, Deserialize, Serialize)] pub struct ReviewSubject { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, pub kind: String, pub role: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub repository_full_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub commit_sha: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub artifact_digest: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workflow_run_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workflow_attempt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deployment_external_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub patch_digest: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, pub file_scope: Option, } @@ -230,6 +248,33 @@ pub struct Assessment { pub release_evidence_gap: Option, } +/// One risk domain evaluated (or skipped) for an environment assessment. +#[derive(Debug, Deserialize, Serialize)] +pub struct AssessmentDomain { + pub domain: String, + pub status: String, + pub reason: String, +} + +/// Detailed view of one environment assessment, including evaluated risk domains +/// and authorized review subjects. +#[derive(Debug, Deserialize, Serialize)] +pub struct AssessmentDetail { + pub review_id: Uuid, + pub id: Uuid, + pub environment_display_name: String, + pub status: String, + pub started_at: Option, + pub completed_at: Option, + pub domains: Vec, + pub findings: Vec, + pub checks: Checks, + pub subjects: Vec, + pub incompleteness_kind: Option, + pub reason_codes: Option>, + pub release_evidence_gap: Option, +} + #[derive(Debug, Deserialize, Serialize)] pub struct Checks { pub receipt_recorded: bool, diff --git a/src/outcome.rs b/src/outcome.rs index 5bc661b..803cd35 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -5,7 +5,8 @@ use uuid::Uuid; use crate::model::{ - Assessment, CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, Finding, ReviewDetail, + Assessment, AssessmentDetail, Checks, CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, + Finding, ReviewDetail, }; use crate::severity::Severity; @@ -33,6 +34,37 @@ pub(crate) fn same_review(detail: &ReviewDetail, requested: Uuid) -> Result<(), } } +/// An assessment-reading endpoint is keyed by review id and assessment id, so +/// its response must echo both requested identifiers. +#[derive(Debug, thiserror::Error)] +#[error( + "requested assessment {requested_assessment} of review {requested_review}, but the server returned assessment {returned_assessment} of review {returned_review}" +)] +pub(crate) struct WrongAssessment { + pub(crate) requested_review: Uuid, + pub(crate) requested_assessment: Uuid, + pub(crate) returned_review: Uuid, + pub(crate) returned_assessment: Uuid, +} + +/// Confirms `detail` is the assessment `assessment_id` of `review_id`. +pub(crate) fn same_assessment( + detail: &AssessmentDetail, + review_id: Uuid, + assessment_id: Uuid, +) -> Result<(), WrongAssessment> { + if detail.review_id == review_id && detail.id == assessment_id { + Ok(()) + } else { + Err(WrongAssessment { + requested_review: review_id, + requested_assessment: assessment_id, + returned_review: detail.review_id, + returned_assessment: detail.id, + }) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Outcome { Completed, @@ -175,14 +207,46 @@ pub(crate) fn resolved(finding: &Finding) -> bool { /// Whether an unresolved finding of a review without finding decisions /// reaches `threshold`. pub(crate) fn findings_reach(review: &ReviewDetail, threshold: Severity) -> bool { - let environment = review.assessments.iter().any(|assessment| { - assessment.findings.iter().any(|finding| { - finding.lifecycle_state != "RESOLVED" && threshold.reached_by(&finding.severity) - }) - }); + let environment = review + .assessments + .iter() + .any(|assessment| unresolved_reaches(&assessment.findings, threshold)); environment || code_assessment(review).is_some_and(|code| code_reaches(code, threshold)) } +/// Whether an unresolved finding of `detail` reaches `threshold`. +pub(crate) fn assessment_findings_reach(detail: &AssessmentDetail, threshold: Severity) -> bool { + unresolved_reaches(&detail.findings, threshold) +} + +fn unresolved_reaches(findings: &[Finding], threshold: Severity) -> bool { + findings + .iter() + .any(|finding| !resolved(finding) && threshold.reached_by(&finding.severity)) +} + +/// `None` while the assessment is still running. +pub fn assessment_terminal(detail: &AssessmentDetail) -> Option { + match detail.status.as_str() { + "PENDING" | "RUNNING" => None, + "FAILED" => Some(Outcome::Failed), + "STOPPED" | "SUPERSEDED" => Some(Outcome::Stopped), + "COMPLETED" if assessment_detail_gap(detail).is_none() => Some(Outcome::Completed), + _ => Some(Outcome::Incomplete), + } +} + +/// Why `detail`'s result is incomplete, or `None` when it is complete. +pub fn assessment_detail_gap(detail: &AssessmentDetail) -> Option> { + evaluate_gap( + &detail.status, + &detail.checks, + detail.reason_codes.as_deref(), + detail.incompleteness_kind.as_deref(), + detail.release_evidence_gap.as_deref(), + ) +} + /// CODE has no World receipts or environment checks. Its recorded status, /// public reason codes and incompleteness are the only completion evidence for /// the code lane. Reason codes come first, as for an environment assessment. @@ -201,28 +265,43 @@ pub(crate) fn code_gap(code: &CodeAssessment) -> Option> { /// Why an assessment's result is incomplete, or `None` when it is complete. pub fn gap(assessment: &Assessment) -> Option> { - let checks = &assessment.checks; + evaluate_gap( + &assessment.status, + &assessment.checks, + assessment.reason_codes.as_deref(), + assessment.incompleteness_kind.as_deref(), + assessment.release_evidence_gap.as_deref(), + ) +} + +fn evaluate_gap( + status: &str, + checks: &Checks, + reason_codes: Option<&[String]>, + incompleteness_kind: Option<&str>, + release_evidence_gap: Option<&str>, +) -> Option> { let check_gap = !checks.receipt_recorded || !COMPLETE_CHECKS.contains(&checks.status.as_str()) || checks.families.iter().any(|check| { !COMPLETE_CHECKS.contains(&check.outcome.as_str()) || !COMPLETE_LIFECYCLES.contains(&check.lifecycle.as_str()) }); - let reasons = assessment.reason_codes.clone().unwrap_or_default(); - let complete = assessment.status == "COMPLETED" + let reasons = reason_codes.unwrap_or_default().to_vec(); + let complete = status == "COMPLETED" && !check_gap && reasons.is_empty() - && assessment.release_evidence_gap.is_none() - && assessment.incompleteness_kind.is_none(); + && release_evidence_gap.is_none() + && incompleteness_kind.is_none(); if complete { return None; } let mut why = reasons; - if let Some(kind) = &assessment.incompleteness_kind { - why.push(kind.clone()); + if let Some(kind) = incompleteness_kind { + why.push(kind.to_owned()); } - if let Some(release) = &assessment.release_evidence_gap { - why.push(release.clone()); + if let Some(release) = release_evidence_gap { + why.push(release.to_owned()); } if check_gap { why.push(if checks.receipt_recorded { @@ -232,7 +311,7 @@ pub fn gap(assessment: &Assessment) -> Option> { }); } if why.is_empty() { - why.push(if KNOWN_ASSESSMENTS.contains(&assessment.status.as_str()) { + why.push(if KNOWN_ASSESSMENTS.contains(&status) { "ASSESSMENT_RESULT_UNAVAILABLE".to_owned() } else { "UNKNOWN_ASSESSMENT_STATUS".to_owned() @@ -244,7 +323,6 @@ pub fn gap(assessment: &Assessment) -> Option> { #[cfg(test)] mod tests { use super::*; - use crate::model::Checks; #[test] fn shared_outcome_contract() { @@ -431,4 +509,62 @@ mod tests { ); assert_eq!(gap(&assessment("COMPLETED")), None); } + + fn assessment_detail(status: &str) -> AssessmentDetail { + AssessmentDetail { + review_id: Uuid::from_u128(1), + id: Uuid::from_u128(2), + environment_display_name: "production".to_owned(), + status: status.to_owned(), + started_at: None, + completed_at: None, + domains: Vec::new(), + findings: Vec::new(), + checks: Checks { + receipt_recorded: true, + status: "READY".to_owned(), + families: Vec::new(), + }, + subjects: Vec::new(), + incompleteness_kind: None, + reason_codes: None, + release_evidence_gap: None, + } + } + + #[test] + fn assessment_detail_terminal_and_identity_hold_to_fail_closed_rules() { + let complete = assessment_detail("COMPLETED"); + assert_eq!(assessment_terminal(&complete), Some(Outcome::Completed)); + assert!(same_assessment(&complete, complete.review_id, complete.id).is_ok()); + assert!(same_assessment(&complete, Uuid::nil(), complete.id).is_err()); + assert!(same_assessment(&complete, complete.review_id, Uuid::nil()).is_err()); + + assert_eq!(assessment_terminal(&assessment_detail("RUNNING")), None); + assert_eq!(assessment_terminal(&assessment_detail("PENDING")), None); + assert_eq!( + assessment_terminal(&assessment_detail("FAILED")), + Some(Outcome::Failed) + ); + assert_eq!( + assessment_terminal(&assessment_detail("STOPPED")), + Some(Outcome::Stopped) + ); + assert_eq!( + assessment_terminal(&assessment_detail("SURPRISE")), + Some(Outcome::Incomplete) + ); + + let mut gapped = assessment_detail("COMPLETED"); + gapped.checks.receipt_recorded = false; + assert_eq!(assessment_terminal(&gapped), Some(Outcome::Incomplete)); + } + + #[test] + fn assessment_detail_fail_on_ignores_resolved_findings() { + let mut detail = assessment_detail("COMPLETED"); + detail.findings = vec![finding("WARNING", "OPEN"), finding("SERIOUS", "RESOLVED")]; + assert!(assessment_findings_reach(&detail, Severity::Warning)); + assert!(!assessment_findings_reach(&detail, Severity::Serious)); + } } diff --git a/src/render.rs b/src/render.rs index 782b09f..ba45a18 100644 --- a/src/render.rs +++ b/src/render.rs @@ -6,7 +6,8 @@ use std::cmp::Reverse; use url::Url; use crate::model::{ - Assessment, CodeAssessment, Finding, LocalReverification, ReviewDetail, StoredCheck, + Assessment, AssessmentDetail, CodeAssessment, Finding, LocalReverification, ReviewDetail, + ReviewSubject, StoredCheck, }; use crate::outcome::{self, Outcome}; use crate::severity::Severity; @@ -68,6 +69,8 @@ fn assessment(out: &mut Vec, assessment: &Assessment) { out.push(format!("{name}: COMPLETED, {} findings", findings.len())); } } + // `proofline assessment` takes this ID, so text output must not need --json. + out.push(format!(" id: {}", assessment.id)); for item in findings { finding(out, item); } @@ -235,6 +238,160 @@ pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> Strin out.join("\n") } +/// Renders one environment assessment in detail: status, completeness gaps, +/// authorized subjects, evaluated risk domains, deterministic checks, and +/// findings (most severe first). +pub fn assessment_detail(detail: &AssessmentDetail, state: Option, url: &Url) -> String { + let name = one_line(&detail.environment_display_name); + let status = state.map_or_else( + || terminal_safe(&detail.status), + |outcome| outcome.as_str().to_owned(), + ); + let mut out = vec![ + format!("{name} (review {}): {status}", detail.review_id), + format!("id: {}", detail.id), + url.to_string(), + ]; + if let Some(started_at) = &detail.started_at { + out.push(format!("started: {}", one_line(started_at))); + } + if let Some(completed_at) = &detail.completed_at { + out.push(format!("completed: {}", one_line(completed_at))); + } + + let mut findings: Vec<&Finding> = detail.findings.iter().collect(); + findings.sort_by_key(|item| Reverse(Severity::parse(&item.severity))); + match outcome::assessment_detail_gap(detail) { + Some(reasons) => { + out.push(format!( + "Assessment incomplete: {} ({})", + one_line(&detail.status), + one_line(&reasons.join(", ")) + )); + } + None if findings.is_empty() => { + out.push("Result: COMPLETED, no findings".to_owned()); + } + None => { + out.push(format!("Result: COMPLETED, {} findings", findings.len())); + } + } + + if !detail.subjects.is_empty() { + out.push(String::new()); + out.push(format!("Subjects ({}):", detail.subjects.len())); + for subject in &detail.subjects { + out.push(format!(" {}", subject_summary(subject))); + } + } + + out.push(String::new()); + if detail.domains.is_empty() { + out.push("Domains: none recorded".to_owned()); + } else { + let considered = detail + .domains + .iter() + .filter(|entry| entry.status == "CONSIDERED") + .count(); + let skipped = detail.domains.len().saturating_sub(considered); + out.push(format!( + "Domains ({} evaluated: {considered} considered, {skipped} skipped):", + detail.domains.len() + )); + for entry in &detail.domains { + out.push(format!( + " {:<10} {} {}", + one_line(&entry.status), + one_line(&entry.domain), + one_line(&entry.reason), + )); + } + } + + if detail.checks.receipt_recorded + || !detail.checks.families.is_empty() + || detail.checks.status != "NOT_APPLICABLE" + { + out.push(String::new()); + let receipt = if detail.checks.receipt_recorded { + "recorded" + } else { + "not recorded" + }; + out.push(format!( + "Checks: {} (receipt {receipt})", + one_line(&detail.checks.status) + )); + for check in &detail.checks.families { + let reason = check + .unresolved_reason + .as_deref() + .map_or_else(String::new, |value| format!(" ({})", one_line(value))); + let check_detail = check + .detail + .as_deref() + .map_or_else(String::new, |value| format!(": {}", one_line(value))); + out.push(format!( + " {:<14} {:<11} {}{reason}{check_detail}", + one_line(&check.outcome), + one_line(&check.lifecycle), + one_line(&check.name), + )); + } + } + + if !findings.is_empty() { + out.push(String::new()); + if outcome::assessment_detail_gap(detail).is_some() { + out.push("Findings so far (not a complete result):".to_owned()); + } else { + out.push(format!("Findings ({}):", findings.len())); + } + for item in findings { + finding(&mut out, item); + } + } + + out.push(String::new()); + out.join("\n") +} + +fn subject_summary(subject: &ReviewSubject) -> String { + let mut parts = vec![format!( + "{:<9} {}", + one_line(&subject.role), + one_line(&subject.kind) + )]; + if let Some(repo) = &subject.repository_full_name { + parts.push(one_line(repo)); + } + if let Some(sha) = &subject.commit_sha { + let short = sha.get(..12).unwrap_or(sha); + parts.push(format!("at {}", one_line(short))); + } + if let Some(digest) = &subject.artifact_digest { + parts.push(one_line(digest)); + } + if let Some(digest) = &subject.patch_digest { + let short = digest.get(..12).unwrap_or(digest); + parts.push(format!("patch {}", one_line(short))); + } + if let Some(run_id) = subject.workflow_run_id { + let attempt = subject + .workflow_attempt + .map_or_else(String::new, |attempt| format!(" attempt {attempt}")); + parts.push(format!("run {run_id}{attempt}")); + } + if let Some(scope) = &subject.file_scope { + parts.push(format!("{} files", scope.paths.len())); + } + if let Some(url) = &subject.url { + parts.push(one_line(url)); + } + parts.join(" ") +} + #[cfg(test)] mod tests { use super::*; @@ -344,4 +501,107 @@ mod tests { assert!(!text.contains('\u{1b}')); assert!(text.contains("x\u{FFFD}[2J y")); } + + #[test] + fn review_text_prints_each_assessment_id_for_follow_up_inspection() { + let mut detail = sample("COMPLETED", Vec::new()); + detail.assessments[0].id = uuid::Uuid::from_u128(0x0190_f3a0_0000_7000_8000_0000_0000_00bb); + let text = review(&detail, outcome::terminal(&detail), &url()); + assert!( + text.contains(" id: 0190f3a0-0000-7000-8000-0000000000bb\n"), + "{text}" + ); + } + + #[test] + fn assessment_detail_renders_domains_subjects_sanitized_text_and_never_false_clean() { + use crate::model::{AssessmentDomain, Check, ReviewSubject}; + + let review_id = uuid::Uuid::from_u128(0x0190_f3a0_0000_7000_8000_0000_0000_00aa); + let assessment_id = uuid::Uuid::from_u128(0x0190_f3a0_0000_7000_8000_0000_0000_00bb); + let detail = AssessmentDetail { + review_id, + id: assessment_id, + environment_display_name: "prod\u{1b}[31m".to_owned(), + status: "INCOMPLETE".to_owned(), + started_at: Some("2026-11-28T10:00:00Z".to_owned()), + completed_at: None, + domains: vec![ + AssessmentDomain { + domain: "iam_permissions".to_owned(), + status: "CONSIDERED".to_owned(), + reason: "IAM policy changed".to_owned(), + }, + AssessmentDomain { + domain: "datastore_compatibility".to_owned(), + status: "SKIPPED".to_owned(), + reason: "no schema\u{202E}changes".to_owned(), + }, + ], + findings: vec![finding("WARNING", "unused role")], + checks: Checks { + receipt_recorded: true, + status: "BLOCKED".to_owned(), + families: vec![Check { + name: "IAM diff".to_owned(), + outcome: "BLOCKED".to_owned(), + lifecycle: "GATING".to_owned(), + detail: Some("wildcard action".to_owned()), + unresolved_reason: None, + }], + }, + subjects: vec![ReviewSubject { + id: None, + kind: "GIT_REVISION".to_owned(), + role: "PRIMARY".to_owned(), + repository_full_name: Some("acme/web".to_owned()), + commit_sha: Some("0123456789abcdef0123456789abcdef01234567".to_owned()), + artifact_digest: None, + workflow_run_id: None, + workflow_attempt: None, + deployment_external_id: None, + patch_digest: None, + url: None, + file_scope: None, + }], + incompleteness_kind: Some("EVIDENCE_UNAVAILABLE".to_owned()), + reason_codes: Some(vec!["WORLD_UNAVAILABLE".to_owned()]), + release_evidence_gap: None, + }; + let text = assessment_detail(&detail, outcome::assessment_terminal(&detail), &url()); + assert!(!text.contains('\u{1b}')); + assert!(!text.contains('\u{202E}')); + assert!(!text.contains("no findings")); + assert!( + text.contains( + "Assessment incomplete: INCOMPLETE (WORLD_UNAVAILABLE, EVIDENCE_UNAVAILABLE)" + ), + "{text}" + ); + assert!( + text.contains("Domains (2 evaluated: 1 considered, 1 skipped):"), + "{text}" + ); + assert!( + text.contains("CONSIDERED iam_permissions IAM policy changed"), + "{text}" + ); + assert!( + text.contains("SKIPPED datastore_compatibility no schema\u{FFFD}changes"), + "{text}" + ); + assert!(text.contains("Subjects (1):"), "{text}"); + assert!( + text.contains("PRIMARY GIT_REVISION acme/web at 0123456789ab"), + "{text}" + ); + assert!( + text.contains("Checks: BLOCKED (receipt recorded)"), + "{text}" + ); + assert!( + text.contains("Findings so far (not a complete result):"), + "{text}" + ); + } } diff --git a/tests/contract.rs b/tests/contract.rs index cf7ae44..c517f51 100644 --- a/tests/contract.rs +++ b/tests/contract.rs @@ -3,12 +3,12 @@ use std::process::Command; use proofline_cli::model::{ - Assessment, Check, Checks, CodeAssessment, CommitDeploy, CommitDeployVerifications, - CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, - DeployCheckpoint, EvidenceRef, FileReviewRequest, FileReviewResponse, FileScope, FilterChoice, - Finding, OpenItems, PatchReviewRequest, PatchReviewResponse, RepositoryName, RepositoryNames, - ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, - RunNowRequest, RunNowResponse, StopResponse, UploadedReport, + Assessment, AssessmentDetail, AssessmentDomain, Check, Checks, CodeAssessment, CommitDeploy, + CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, + CoverageUploadResponse, DeployCheckpoint, EvidenceRef, FileReviewRequest, FileReviewResponse, + FileScope, FilterChoice, Finding, OpenItems, PatchReviewRequest, PatchReviewResponse, + RepositoryName, RepositoryNames, ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, + ReviewSummary, RunNowMode, RunNowRequest, RunNowResponse, StopResponse, UploadedReport, }; use serde::Serialize; use serde::de::DeserializeOwned; @@ -157,6 +157,8 @@ fn types_match_the_public_contract() { holds::("CustomerReviewDetail"); holds::("OpenItemsView"); holds::("CustomerAssessment"); + holds::("CustomerAssessmentDetail"); + holds::("DomainView"); holds::("CustomerCodeAssessment"); holds::("CustomerChecks"); holds::("CustomerCheck"); @@ -234,6 +236,10 @@ fn operations_the_cli_calls_exist() { for (method, path) in [ ("get", "/api/v1/organizations/{org_id}/reviews"), ("get", "/api/v1/organizations/{org_id}/reviews/{review_id}"), + ( + "get", + "/api/v1/organizations/{org_id}/reviews/{review_id}/assessments/{assessment_id}", + ), ("get", "/api/v1/organizations/{org_id}/repository-names"), ( "get", diff --git a/tests/http.rs b/tests/http.rs index 940dc12..f77a11f 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -3647,3 +3647,226 @@ async fn config_proposal_targets_must_match_the_selected_organization() { assert_eq!(server.requests()[0]["arguments"]["organization_id"], ORG); assert_eq!(server.frames.load(Ordering::SeqCst), 3); } + +#[tokio::test] +async fn assessment_inspects_domains_resolves_environments_and_enforces_verdicts() { + let review_id = SELECTED_REVIEW; + let prod_id = "0190f3a0-0000-7000-8000-000000000044"; + let staging_id = "0190f3a0-0000-7000-8000-000000000055"; + let wrong_id = "0190f3a0-0000-7000-8000-000000000066"; + let finding_id = "0190f3a0-0000-7000-8000-000000000077"; + let requests = Arc::new(Mutex::new(Vec::::new())); + let observed = Arc::clone(&requests); + let review_count = Arc::new(AtomicUsize::new(1)); + let review_count_route = Arc::clone(&review_count); + + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{review_id}"), + get(move || { + let observed = Arc::clone(&observed); + let count = review_count_route.load(Ordering::SeqCst); + async move { + observed.lock().unwrap().push("get_review".to_owned()); + let mut assessments = vec![json!({ + "id": prod_id, + "environment_display_name": "Production", + "status": "COMPLETED", + "findings": [], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + })]; + if count > 1 { + assessments.push(json!({ + "id": staging_id, + "environment_display_name": "Staging", + "status": "INCOMPLETE", + "incompleteness_kind": "WORLD_UNAVAILABLE", + "findings": [], + "checks": { "receipt_recorded": false, "status": "UNAVAILABLE", "families": [] }, + })); + } + Json(json!({ + "id": review_id, + "kind": "PULL_REQUEST", + "status": if count > 1 { "INCOMPLETE" } else { "COMPLETED" }, + "assessment_count": assessments.len(), + "assessments": assessments, + "repository_full_name": "acme/web", + "pull_request_number": 9, + })) + } + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{review_id}/assessments/{{assessment_id}}"), + get(move |headers: HeaderMap, Path(assessment_id): Path| { + async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + if assessment_id == wrong_id { + return ( + StatusCode::OK, + Json(json!({ + "review_id": review_id, + "id": prod_id, + "environment_display_name": "Production", + "status": "COMPLETED", + "domains": [], + "findings": [], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + "subjects": [], + })), + ) + .into_response(); + } + if assessment_id == staging_id { + return ( + StatusCode::OK, + Json(json!({ + "review_id": review_id, + "id": staging_id, + "environment_display_name": "Staging", + "status": "INCOMPLETE", + "incompleteness_kind": "WORLD_UNAVAILABLE", + "reason_codes": ["WORLD_UNAVAILABLE"], + "domains": [ + { + "domain": "network_reachability", + "status": "SKIPPED", + "reason": "snapshot unavailable" + } + ], + "findings": [], + "checks": { "receipt_recorded": false, "status": "UNAVAILABLE", "families": [] }, + "subjects": [], + })), + ) + .into_response(); + } + Json(json!({ + "review_id": review_id, + "id": prod_id, + "environment_display_name": "Production", + "status": "COMPLETED", + "started_at": "2026-11-28T10:00:00Z", + "completed_at": "2026-11-28T10:01:00Z", + "domains": [ + { + "domain": "iam_permissions", + "status": "CONSIDERED", + "reason": "policy diff touched role permissions" + }, + { + "domain": "datastore_compatibility", + "status": "SKIPPED", + "reason": "no migrations changed" + } + ], + "findings": [{ + "id": finding_id, + "finding_fingerprint": null, + "severity": "SERIOUS", + "risk_domain": "iam_permissions", + "claim": "Role grants wildcard S3 write.", + "impact": "Any service can overwrite artifacts.", + "lifecycle_state": "NEW", + "remediation": "Restrict to the deployment prefix.", + "evidence_refs": [], + }], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + "subjects": [{ + "id": "0190f3a0-0000-7000-8000-000000000088", + "kind": "GIT_REVISION", + "role": "PRIMARY", + "repository_full_name": "acme/web", + "commit_sha": "0123456789abcdef0123456789abcdef01234567", + "release_authorizations": [], + }], + })) + .into_response() + } + }), + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + // 1. Direct lookup makes no extra review request and renders domains, subjects, and findings. + let direct = cli(&origin, &["assessment", review_id, prod_id]).await; + assert!( + direct.status.success(), + "{}", + String::from_utf8_lossy(&direct.stderr) + ); + let stdout = String::from_utf8(direct.stdout).unwrap(); + assert!(stdout.contains("Production (review"), "{stdout}"); + assert!( + stdout.contains("Domains (2 evaluated: 1 considered, 1 skipped):"), + "{stdout}" + ); + assert!( + stdout.contains("CONSIDERED iam_permissions policy diff touched role permissions"), + "{stdout}" + ); + assert!( + stdout.contains("SKIPPED datastore_compatibility no migrations changed"), + "{stdout}" + ); + assert!( + stdout.contains("PRIMARY GIT_REVISION acme/web at 0123456789ab"), + "{stdout}" + ); + assert!( + stdout.contains("Role grants wildcard S3 write."), + "{stdout}" + ); + assert!(requests.lock().unwrap().is_empty()); + + // 2. `--fail-on serious` exits 3 on an open SERIOUS finding. + let gated = cli( + &origin, + &["assessment", review_id, prod_id, "--fail-on", "serious"], + ) + .await; + assert_eq!(gated.status.code(), Some(3)); + + // 3. `--json` preserves the raw API payload. + let json_out = cli(&origin, &["assessment", review_id, prod_id, "--json"]).await; + assert!(json_out.status.success()); + let decoded: Value = serde_json::from_slice(&json_out.stdout).unwrap(); + assert_eq!(decoded["id"], prod_id); + assert_eq!(decoded["domains"].as_array().unwrap().len(), 2); + + // 4. Omitting ASSESSMENT_ID auto-selects when exactly one assessment exists. + let auto = cli(&origin, &["assessment", review_id]).await; + assert!(auto.status.success()); + assert_eq!(requests.lock().unwrap().len(), 1); + + // 5. Multiple assessments require ASSESSMENT_ID or `--environment`; `--environment` resolves + // case-insensitively and incomplete assessments exit 2. + review_count.store(2, Ordering::SeqCst); + let ambiguous = cli(&origin, &["assessment", review_id]).await; + assert_eq!(ambiguous.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&ambiguous.stderr); + assert!( + stderr.contains(prod_id) && stderr.contains(staging_id), + "{stderr}" + ); + + let by_env = cli( + &origin, + &["assessment", review_id, "--environment", "staging"], + ) + .await; + assert_eq!(by_env.status.code(), Some(2)); + let staging_stdout = String::from_utf8(by_env.stdout).unwrap(); + assert!(staging_stdout.contains("Assessment incomplete: INCOMPLETE (WORLD_UNAVAILABLE, WORLD_UNAVAILABLE, CHECK_RECEIPT_ABSENT)"), "{staging_stdout}"); + assert!(!staging_stdout.contains("no findings")); + + // 6. Mismatched assessment ID from the server is refused. + let mismatched = cli(&origin, &["assessment", review_id, wrong_id]).await; + assert_eq!(mismatched.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&mismatched.stderr).contains("server returned assessment")); + + server.abort(); +}