Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,26 @@ pub struct Checks {
pub families: Vec<Check>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct UntrustedText {
pub untrusted_text: String,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct CheckFile {
pub path: UntrustedText,
pub revision: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Check {
pub name: String,
pub outcome: String,
pub lifecycle: String,
/// Empty when World cited no file, and on results recorded before World
/// cited files.
#[serde(default)]
pub files: Vec<CheckFile>,
pub detail: Option<String>,
pub unresolved_reason: Option<String>,
}
Expand Down
4 changes: 4 additions & 0 deletions src/outcome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ impl Outcome {
const COMPLETE_CHECKS: [&str; 3] = ["READY", "BLOCKED", "NOT_APPLICABLE"];
const COMPLETE_LIFECYCLES: [&str; 4] = ["GATING", "SHADOW", "QUARANTINED", "RETIRED"];
const KNOWN_ASSESSMENTS: [&str; 5] = ["PENDING", "RUNNING", "COMPLETED", "INCOMPLETE", "FAILED"];

pub(crate) fn known_check_lifecycle(lifecycle: &str) -> bool {
COMPLETE_LIFECYCLES.contains(&lifecycle)
}
// The server's classification policy owns this marker. The API publishes it in
// place of every CODE finding's risk domain, claim and impact once the review's
// protected evidence is missing or has expired.
Expand Down
151 changes: 149 additions & 2 deletions src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::cmp::Reverse;

use url::Url;

use crate::model::{Assessment, CodeAssessment, Finding, ReviewDetail};
use crate::model::{Assessment, Check, CodeAssessment, Finding, ReviewDetail};
use crate::outcome::{self, Outcome};
use crate::severity::Severity;
use crate::text::{one_line, terminal_safe};
Expand Down Expand Up @@ -41,8 +41,52 @@ fn finding(out: &mut Vec<String>, finding: &Finding) {
}
}

fn check_revision(revision: &str) -> String {
match revision {
"PROPOSED_CODE_REVISION" => "proposed".to_owned(),
"BASE_CODE_REVISION" => "base".to_owned(),
other => one_line(other),
}
}

fn check_noteworthy(check: &Check) -> bool {
!matches!(check.outcome.as_str(), "READY" | "NOT_APPLICABLE")
|| !outcome::known_check_lifecycle(&check.lifecycle)
}

/// Prints a check that blocked or left an evidence gap, along with the
/// repository files World cited. `check.detail` may carry environment values
/// and never appears in terminal summaries.
fn check_line(out: &mut Vec<String>, check: &Check) {
let reason = check
.unresolved_reason
.as_deref()
.map(|reason| format!(", {}", one_line(reason)))
.unwrap_or_default();
out.push(format!(
" check {:<10} {} ({}{})",
one_line(&check.outcome),
one_line(&check.name),
one_line(&check.lifecycle),
reason,
));
for file in &check.files {
out.push(format!(
" file ({}): {}",
check_revision(&file.revision),
one_line(&file.path.untrusted_text),
));
}
}

fn assessment(out: &mut Vec<String>, assessment: &Assessment) {
let name = one_line(&assessment.environment_display_name);
let checks: Vec<&Check> = assessment
.checks
.families
.iter()
.filter(|item| check_noteworthy(item))
.collect();
let mut findings: Vec<&Finding> = assessment.findings.iter().collect();
// Most severe first; a severity this CLI does not know prints last.
findings.sort_by_key(|item| Reverse(Severity::parse(&item.severity)));
Expand All @@ -53,15 +97,31 @@ fn assessment(out: &mut Vec<String>, assessment: &Assessment) {
one_line(&assessment.status),
one_line(&reasons.join(", "))
));
for item in &checks {
check_line(out, item);
}
if !findings.is_empty() {
out.push(" findings so far, not a complete result:".to_owned());
}
}
None if findings.is_empty() => {
None if findings.is_empty() && checks.is_empty() => {
out.push(format!("{name}: COMPLETED, no findings"));
}
None if findings.is_empty() => {
let noun = if checks.len() == 1 { "check" } else { "checks" };
out.push(format!(
"{name}: COMPLETED, no findings ({} blocked {noun})",
checks.len()
));
for item in &checks {
check_line(out, item);
}
}
None => {
out.push(format!("{name}: COMPLETED, {} findings", findings.len()));
for item in &checks {
check_line(out, item);
}
}
}
for item in findings {
Expand Down Expand Up @@ -276,4 +336,91 @@ mod tests {
assert!(!text.contains('\u{1b}'));
assert!(text.contains("x\u{FFFD}[2J y"));
}

#[test]
fn check_evidence_prints_cited_files_and_never_world_detail() {
use crate::model::{CheckFile, UntrustedText};

const PRIVATE: &str = "WORLD_SECRET_DETAIL_CANARY";

let mut blocked = sample("COMPLETED", Vec::new());
blocked.assessments[0].checks = Checks {
receipt_recorded: true,
status: "BLOCKED".to_owned(),
families: vec![
Check {
name: "Clean check".to_owned(),
outcome: "READY".to_owned(),
lifecycle: "GATING".to_owned(),
files: vec![CheckFile {
revision: "PROPOSED_CODE_REVISION".to_owned(),
path: UntrustedText {
untrusted_text: "quiet.tf".to_owned(),
},
}],
detail: Some(PRIVATE.to_owned()),
unresolved_reason: None,
},
Check {
name: "IAM boundary".to_owned(),
outcome: "BLOCKED".to_owned(),
lifecycle: "GATING".to_owned(),
files: vec![
CheckFile {
revision: "PROPOSED_CODE_REVISION".to_owned(),
path: UntrustedText {
untrusted_text: "infra/\u{1b}[2Jiam.tf\nnext".to_owned(),
},
},
CheckFile {
revision: "BASE_CODE_REVISION".to_owned(),
path: UntrustedText {
untrusted_text: "infra/roles.tf".to_owned(),
},
},
],
detail: Some(PRIVATE.to_owned()),
unresolved_reason: None,
},
],
};
let text = review(&blocked, outcome::terminal(&blocked), &url());
assert!(text.contains("production: COMPLETED, no findings (1 blocked check)"));
assert!(text.contains(" check BLOCKED IAM boundary (GATING)"));
assert!(text.contains(" file (proposed): infra/\u{FFFD}[2Jiam.tf next"));
assert!(text.contains(" file (base): infra/roles.tf"));
assert!(!text.contains("Clean check"));
assert!(!text.contains("quiet.tf"));
assert!(!text.contains('\u{1b}'));
assert!(!text.contains(PRIVATE));

let mut unresolved = sample("COMPLETED", Vec::new());
unresolved.assessments[0].incompleteness_kind = None;
unresolved.assessments[0].checks = Checks {
receipt_recorded: true,
status: "UNRESOLVED".to_owned(),
families: vec![Check {
name: "Environment reachability".to_owned(),
outcome: "UNRESOLVED".to_owned(),
lifecycle: "SHADOW".to_owned(),
files: vec![CheckFile {
revision: "PROPOSED_CODE_REVISION".to_owned(),
path: UntrustedText {
untrusted_text: "<b>deploy</b>.yml".to_owned(),
},
}],
detail: Some(PRIVATE.to_owned()),
unresolved_reason: Some("NEEDS_EVIDENCE".to_owned()),
}],
};
let gap_text = review(&unresolved, outcome::terminal(&unresolved), &url());
assert!(gap_text.contains("production: COMPLETED (incomplete: CHECKS_UNRESOLVED)"));
assert!(
gap_text
.contains(" check UNRESOLVED Environment reachability (SHADOW, NEEDS_EVIDENCE)")
);
assert!(gap_text.contains(" file (proposed): <b>deploy</b>.yml"));
assert!(!gap_text.contains("no findings"));
assert!(!gap_text.contains(PRIVATE));
}
}
14 changes: 8 additions & 6 deletions tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ use std::path::PathBuf;
use std::process::Command;

use proofline_cli::model::{
Assessment, Check, Checks, CodeAssessment, CommitReviewRequest, CommitReviewResponse,
CoverageUploadRequest, CoverageUploadResponse, EvidenceRef, FileReviewRequest,
FileReviewResponse, FileScope, FilterChoice, Finding, OpenItems, PatchReviewRequest,
PatchReviewResponse, RepositoryName, RepositoryNames, ReviewDetail, ReviewFilters, ReviewPage,
ReviewSubject, ReviewSummary, RunNowMode, RunNowRequest, RunNowResponse, StopResponse,
UploadedReport,
Assessment, Check, CheckFile, Checks, CodeAssessment, CommitReviewRequest,
CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, EvidenceRef,
FileReviewRequest, FileReviewResponse, FileScope, FilterChoice, Finding, OpenItems,
PatchReviewRequest, PatchReviewResponse, RepositoryName, RepositoryNames, ReviewDetail,
ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, RunNowRequest,
RunNowResponse, StopResponse, UntrustedText, UploadedReport,
};
use serde::Serialize;
use serde::de::DeserializeOwned;
Expand Down Expand Up @@ -162,6 +162,8 @@ fn types_match_the_public_contract() {
holds::<CodeAssessment>("CustomerCodeAssessment");
holds::<Checks>("CustomerChecks");
holds::<Check>("CustomerCheck");
holds::<CheckFile>("CheckFile");
holds::<UntrustedText>("UntrustedText");
holds::<Finding>("CustomerFinding");
holds::<EvidenceRef>("CustomerEvidenceRef");
holds::<RunNowRequest>("RunNowRequest");
Expand Down
77 changes: 77 additions & 0 deletions tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2188,3 +2188,80 @@ async fn fix_commands_preserve_context_and_never_retry_verification() {
assert_eq!(calls.lock().unwrap().len(), 4);
server.abort();
}

#[tokio::test]
async fn findings_print_cited_check_files_and_withhold_check_detail_from_text() {
const PRIVATE: &str = "WORLD_ENV_DETAIL_CANARY";
let body = json!({
"id": SELECTED_REVIEW,
"kind": "PULL_REQUEST",
"status": "COMPLETED",
"assessment_count": 1,
"head_commit_sha": "89abcdef0123456789abcdef0123456789abcdef",
"base_commit_sha": "0123456789abcdef0123456789abcdef01234567",
"pull_request_number": 42,
"repository_full_name": "acme/web",
"run_number": 1,
"subjects": [],
"assessments": [{
"id": "0190f3a0-0000-7000-8000-0000000000bb",
"environment_display_name": "production",
"status": "COMPLETED",
"findings": [],
"checks": {
"receipt_recorded": true,
"status": "UNRESOLVED",
"families": [{
"name": "Required configuration",
"outcome": "UNRESOLVED",
"lifecycle": "GATING",
"unresolved_reason": "UNSUPPORTED",
"detail": PRIVATE,
"files": [
{
"revision": "PROPOSED_CODE_REVISION",
"path": { "untrusted_text": "<b>deploy</b>\u{1b}[2J.yml" }
},
{
"revision": "BASE_CODE_REVISION",
"path": { "untrusted_text": "deploy.yml" }
}
]
}]
}
}]
});
let app = Router::new().route(
&format!("/api/v1/organizations/{ORG}/reviews/{SELECTED_REVIEW}"),
get(move || {
let body = body.clone();
async move { Json(body) }
}),
);
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() });

let text_out = cli(&origin, &["findings", "--review", SELECTED_REVIEW]).await;
assert_eq!(text_out.status.code(), Some(2), "{text_out:?}");
let stdout = String::from_utf8(text_out.stdout).unwrap();
assert!(stdout.contains("production: COMPLETED (incomplete: CHECKS_UNRESOLVED)"));
assert!(stdout.contains(" check UNRESOLVED Required configuration (GATING, UNSUPPORTED)"));
assert!(stdout.contains(" file (proposed): <b>deploy</b>\u{FFFD}[2J.yml"));
assert!(stdout.contains(" file (base): deploy.yml"));
assert!(!stdout.contains('\u{1b}'));
assert!(!stdout.contains(PRIVATE));

let json_out = cli(
&origin,
&["findings", "--review", SELECTED_REVIEW, "--json"],
)
.await;
assert_eq!(json_out.status.code(), Some(2), "{json_out:?}");
let result: Value = serde_json::from_slice(&json_out.stdout).unwrap();
assert_eq!(
result["review"]["assessments"][0]["checks"]["families"][0]["files"][1]["revision"],
"BASE_CODE_REVISION"
);
server.abort();
}