diff --git a/README.md b/README.md index 614f5f4..40c2e74 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,14 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `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. +## Scans + +`proofline scan --ref main --budget 200` scans the whole repository at one commit, not a pull request's change. GitHub resolves the ref once, when the request arrives, and the scan records that commit; `--commit SHA` names an exact full SHA instead, and you give one of the two. The command waits for the scan review and prints it like `proofline review`, while `--no-wait` prints its link and `--json` prints JSON. + +`--budget` is required and has no default: it is the most credits the whole scan may spend, capped by the organization's on-demand scan limit, and a limit of 0 turns on-demand scans off. Results stay in Proofline and are never posted to GitHub. The token needs `scans:request` and live GitHub write access to the repository. The default sign-in omits that scope, so run `proofline login --scope reviews:read --scope findings:read --scope reviews:request --scope scans:request`; `--scope` replaces the defaults, so list every scope you want. + +The CLI prints the request ID before it sends anything and never repeats the request. When the outcome is unknown (the connection failed, the server failed, or its answer was unreadable) the command exits 4; repeat it with `--request-id ID` to read the first resolution instead of paying for a second scan. If GitHub cannot resolve the ref, nothing starts and nothing is spent, but repeating that ID returns the same answer, so omit `--request-id` to ask again; with `--json` the resolution is still printed. Other exit codes match `proofline review`: 0 for a complete result, 2 for an incomplete or unfinished one and 1 for a refusal or error. + ## Fix verification and agent sessions ```sh diff --git a/build.rs b/build.rs index 9241a96..b971479 100644 --- a/build.rs +++ b/build.rs @@ -32,6 +32,7 @@ const OPERATIONS: &[(&str, &str, &[&str])] = &[ ("post", "request_file_review", &["repo_id"]), ("post", "request_patch_review", &["repo_id"]), ("post", "request_review", &["repo_id", "number"]), + ("post", "request_scan", &["repo_id"]), ("post", "rerun_review", &["review_id"]), ("post", "start_agent_session", &["finding_id"]), ("post", "stop_review", &["review_id"]), diff --git a/src/api.rs b/src/api.rs index 80ba1d1..e28cad8 100644 --- a/src/api.rs +++ b/src/api.rs @@ -14,7 +14,7 @@ use crate::model::{ CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, FileReviewRequest, FileReviewResponse, PatchReviewRequest, PatchReviewResponse, RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, RunNowRequest, RunNowResponse, - StopResponse, + ScanRequest, ScanResponse, StopResponse, }; use crate::origin::Origin; use crate::text::terminal_safe; @@ -651,6 +651,26 @@ impl Api { Err(self.http.problem(&reply)) } + /// Requests a scan of one ref or commit. One attempt: the client never + /// repeats a POST, and the caller's `request_id` makes a deliberate retry + /// return the first resolution instead of scanning again. + pub async fn request_scan( + &self, + repository_id: Uuid, + request: &ScanRequest, + ) -> Result { + let repository = repository_id.to_string(); + let url = self.url_request_scan(&repository); + let (reply, _) = self + .http + .send(self.request(Method::POST, url).json(request)) + .await?; + if reply.status.is_success() { + return self.decode(&reply.body); + } + Err(self.http.problem(&reply)) + } + /// Stops the holder's own local review in one bounded attempt. A refusal /// starts no replacement review, and the client never repeats the POST. pub async fn stop_review( diff --git a/src/lib.rs b/src/lib.rs index 7e39553..9f5e6f0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ mod preflight; pub mod render; mod result; mod sarif; +mod scan; mod severity; pub mod text; pub mod update; @@ -112,6 +113,8 @@ enum Command { }, /// Rerun the original immutable review subject. Rerun(tools::RerunArgs), + /// Scan the whole repository at one ref or commit, within a credit budget. + Scan(scan::ScanArgs), /// List the recorded runs of a pull request. History(tools::HistoryArgs), /// Read the repository review guidance as JSON. @@ -483,6 +486,11 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let request = scan::request(&args)?; + let api = connect(Http::new(origin)?, token, cli.org).await?; + scan::run(&api, &args, &request).await + } Command::History(args) => { let api = connect(Http::new(origin)?, token, cli.org).await?; let (full_name, _) = reviewed_repository(&api, &args.repository).await?; diff --git a/src/model.rs b/src/model.rs index cb8e47f..08b476d 100644 --- a/src/model.rs +++ b/src/model.rs @@ -252,6 +252,29 @@ pub struct RunNowResponse { pub automatic_reviews_paused: bool, } +/// A whole-repository scan of one ref or exact commit. Sending the same +/// `request_id` again returns the first resolution instead of scanning again. +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ScanRequest { + pub request_id: Uuid, + pub budget_credits: i64, + #[serde(rename = "ref", skip_serializing_if = "Option::is_none")] + pub git_ref: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub commit_sha: Option, +} + +/// What a scan request resolved to. `outcome` is `CREATED`, `EXISTING` or +/// `REPOSITORY_UNAVAILABLE`; only the first two name a review. +#[derive(Debug, Deserialize, Serialize)] +pub struct ScanResponse { + pub resolution_id: Uuid, + pub outcome: String, + #[serde(default)] + pub review_id: Option, +} + #[derive(Debug, Deserialize, Serialize)] pub struct StopResponse { pub review_id: Uuid, diff --git a/src/scan.rs b/src/scan.rs new file mode 100644 index 0000000..667e9c3 --- /dev/null +++ b/src/scan.rs @@ -0,0 +1,169 @@ +//! Requests a whole-repository scan of one ref or commit. +//! +//! A scan spends credits, so the budget has no default, the request carries an +//! identity the caller can reuse, and the CLI never repeats the POST itself. + +use std::io::Write as _; + +use anyhow::bail; +use clap::Args; +use uuid::Uuid; + +use crate::api::{Api, ApiError}; +use crate::model::{ScanRequest, ScanResponse}; +use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, git, say, show, text, tools}; + +#[derive(Debug, Args)] +pub(crate) struct ScanArgs { + /// Branch, tag or other ref. GitHub resolves it once, when the request + /// arrives, and the scan records that commit. + #[arg( + long = "ref", + value_name = "REF", + conflicts_with = "commit", + required_unless_present = "commit" + )] + git_ref: Option, + /// Exact full SHA to scan; never a branch. + #[arg(long, value_name = "SHA")] + commit: Option, + /// Credits the whole scan may spend. Required, so a scan never spends + /// without a number you chose. The organization's on-demand limit caps it. + #[arg( + long, + value_name = "CREDITS", + value_parser = clap::value_parser!(i64).range(1..) + )] + budget: i64, + /// Identity of this request. Repeating it returns the first resolution + /// instead of scanning again. Omit it to get a fresh one, printed first. + #[arg(long, value_name = "UUID")] + request_id: Option, + /// Return the scan's link without waiting for its result. + #[arg(long)] + no_wait: bool, + #[command(flatten)] + repository: RepositoryArgs, + #[command(flatten)] + output: OutputArgs, +} + +/// The request body, checked before anything is sent. +pub(crate) fn request(args: &ScanArgs) -> anyhow::Result { + let commit_sha = args.commit.as_deref().map(git::commit_sha).transpose()?; + let git_ref = args.git_ref.as_deref().map(str::trim).map(str::to_owned); + if git_ref.as_deref() == Some("") { + bail!("--ref is empty; name a branch, a tag or another ref"); + } + Ok(ScanRequest { + request_id: args.request_id.unwrap_or_else(Uuid::now_v7), + budget_credits: args.budget, + git_ref, + commit_sha, + }) +} + +pub(crate) async fn run( + api: &Api, + args: &ScanArgs, + request: &ScanRequest, +) -> anyhow::Result { + let (name, repository_id) = crate::connected_repository(api, &args.repository).await?; + let name = text::terminal_safe(&name); + let target = request + .commit_sha + .as_deref() + .or(request.git_ref.as_deref()) + .map(text::terminal_safe) + .unwrap_or_default(); + // Said before the request, so a timeout still leaves the caller an + // identity that cannot start a second scan. + say(&format!( + "Requesting a scan of {name} at {target} with a budget of {} credits (request {}).", + request.budget_credits, request.request_id + )); + let response = match api.request_scan(repository_id, request).await { + Ok(response) => response, + Err(error) if error.status() == Some(403) => { + return Err(anyhow::Error::new(error).context( + "this sign-in cannot request scans; run `proofline login --scope reviews:read --scope findings:read --scope reviews:request --scope scans:request`, and have the token's repositories include this one", + )); + } + // The scan may have started, so the caller gets the one retry that + // cannot start a second one, and an exit code that says "unknown". + Err(error) if uncertain(&error) => { + say(&format!("proofline: {error}")); + say(&format!( + "The scan may have started. Repeat with --request-id {} to read its first resolution instead of starting a second scan.", + request.request_id + )); + return Ok(Verdict::Unavailable); + } + // A definite refusal created nothing; the server's reason is enough. + Err(error) => return Err(error.into()), + }; + if args.output.json && response.review_id.is_none() { + // Scripts read the resolution from stdout even when no scan started. + tools::json(&serde_json::to_value(&response)?)?; + } + let review_id = resolved(&response, request)?; + say(&format!( + "{} scan, resolution {}.", + if response.outcome == "EXISTING" { + "Found the existing" + } else { + "Started a" + }, + response.resolution_id + )); + if args.no_wait { + let url = api.review_url(review_id); + if args.output.json { + return tools::json(&serde_json::json!({ + "outcome": response.outcome, + "resolution_id": response.resolution_id, + "review_id": review_id, + "review_url": url.as_str(), + })); + } + writeln!(std::io::stdout().lock(), "{url}")?; + return Ok(Verdict::Done); + } + show( + api, + review_id, + true, + &args.output, + OutputFormat::from_json(args.output.json), + ) + .await +} + +/// Whether a failed request leaves its outcome unknown: the server may have +/// recorded it before the connection, its body or its answer failed. +const fn uncertain(error: &ApiError) -> bool { + match error { + ApiError::Transport { .. } | ApiError::Protocol { .. } => true, + ApiError::Problem { status, .. } => *status >= 500, + } +} + +/// The scan's review, or the reason there is none. +fn resolved(response: &ScanResponse, request: &ScanRequest) -> anyhow::Result { + match (response.outcome.as_str(), response.review_id) { + ("CREATED" | "EXISTING", Some(review_id)) => Ok(review_id), + ("CREATED" | "EXISTING", None) => bail!( + "the server reported a scan but named no review for resolution {}", + response.resolution_id + ), + ("REPOSITORY_UNAVAILABLE", _) => bail!( + "GitHub could not resolve the request, so no scan started and nothing was spent (resolution {}). Repeating request {} returns this same answer; omit --request-id to ask again", + response.resolution_id, + request.request_id + ), + (other, _) => bail!( + "the server answered with the unknown scan outcome {}; update this CLI with `proofline update`", + text::one_line(other) + ), + } +} diff --git a/tests/scan.rs b/tests/scan.rs new file mode 100644 index 0000000..435f496 --- /dev/null +++ b/tests/scan.rs @@ -0,0 +1,323 @@ +//! `proofline scan` against a loopback stand-in for the console: the wire +//! body, the one-attempt POST, and every way a scan request can resolve. + +use std::sync::{Arc, Mutex}; + +use axum::extract::{Path, State}; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use serde_json::{Value, json}; +use uuid::Uuid; + +const ORG: &str = "0190f3a0-0000-7000-8000-000000000001"; +const TOKEN: &str = "pld_secretsecretsecret"; +const REPOSITORY: &str = "0190f3a0-0000-7000-8000-000000000022"; +const REVIEW: &str = "0190f3a0-0000-7000-8000-000000000033"; +const RESOLUTION: &str = "0190f3a0-0000-7000-8000-000000000055"; +const REQUEST: &str = "0190f3a0-0000-7000-8000-000000000066"; + +#[derive(Clone)] +struct Fake { + bodies: Arc>>, + reply: Arc Response + Send + Sync>, +} + +async fn scan(State(fake): State, headers: HeaderMap, Json(body): Json) -> Response { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + fake.bodies.lock().unwrap().push(body); + (fake.reply)() +} + +async fn review(Path(id): Path) -> Json { + Json(json!({ + "id": id, + "kind": "REVISION_SCAN", + "status": "COMPLETED", + "publication": "PUBLISHED", + "assessment_count": 1, + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-000000000044", + "environment_display_name": "production", + "status": "COMPLETED", + "incompleteness_kind": null, + "findings": [], + "checks": {"receipt_recorded": true, "status": "READY", "families": []}, + }], + "head_commit_sha": "0123456789abcdef0123456789abcdef01234567", + "repository_full_name": "acme/web", + })) +} + +fn created(outcome: &'static str) -> Arc Response + Send + Sync> { + Arc::new(move || { + Json(json!({"resolution_id": RESOLUTION, "outcome": outcome, "review_id": REVIEW})) + .into_response() + }) +} + +fn refused(status: StatusCode, detail: &'static str) -> Arc Response + Send + Sync> { + Arc::new(move || { + ( + status, + Json(json!({"title": "invalid request", "status": status.as_u16(), "detail": detail})), + ) + .into_response() + }) +} + +async fn serve(reply: Arc Response + Send + Sync>) -> (String, Fake) { + let fake = Fake { + bodies: Arc::default(), + reply, + }; + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|| async { + Json(json!({ "repositories": [{ "id": REPOSITORY, "full_name": "acme/web" }] })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/scans"), + post(scan), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{{id}}"), + get(review), + ) + .with_state(fake.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (format!("http://{address}"), fake) +} + +async fn cli(origin: &str, args: &[&str]) -> std::process::Output { + let directory = tempfile::tempdir().unwrap(); + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .args([ + "--base-url", + origin, + "--org", + ORG, + "scan", + "--repo", + "acme/web", + ]) + .args(args) + .env("PROOFLINE_TOKEN", TOKEN) + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/proofline-test-unavailable-bus", + ) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PATH", "") + .current_dir(directory.path()); + tokio::time::timeout( + std::time::Duration::from_secs(15), + command.kill_on_drop(true).output(), + ) + .await + .unwrap() + .unwrap() +} + +fn stderr(output: &std::process::Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +#[tokio::test] +async fn a_ref_scan_sends_exactly_the_named_fields_and_prints_the_link() { + let (origin, fake) = serve(created("CREATED")).await; + let output = cli( + &origin, + &[ + "--ref", + "main", + "--budget", + "50", + "--request-id", + REQUEST, + "--no-wait", + "--json", + ], + ) + .await; + assert!(output.status.success(), "{}", stderr(&output)); + assert_eq!( + *fake.bodies.lock().unwrap(), + [json!({"request_id": REQUEST, "budget_credits": 50, "ref": "main"})] + ); + let printed: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(printed["outcome"], "CREATED"); + assert_eq!(printed["resolution_id"], RESOLUTION); + assert_eq!(printed["review_id"], REVIEW); + assert!( + printed["review_url"] + .as_str() + .unwrap() + .ends_with(&format!("/orgs/by-id/{ORG}/reviews/{REVIEW}")) + ); + assert!(stderr(&output).contains(REQUEST), "{}", stderr(&output)); +} + +#[tokio::test] +async fn a_commit_scan_waits_for_the_scan_review() { + let sha = "ABCDEF0123456789abcdef0123456789ABCDEF01"; + let (origin, fake) = serve(created("EXISTING")).await; + let output = cli( + &origin, + &["--commit", sha, "--budget", "5", "--request-id", REQUEST], + ) + .await; + assert!(output.status.success(), "{}", stderr(&output)); + let bodies = fake.bodies.lock().unwrap(); + assert_eq!( + *bodies, + [json!({ + "request_id": REQUEST, + "budget_credits": 5, + "commit_sha": sha.to_ascii_lowercase(), + })] + ); + assert!(stderr(&output).contains("Found the existing scan")); +} + +#[tokio::test] +async fn a_server_failure_exits_4_and_names_the_fresh_request_id_that_retries_safely() { + let (origin, fake) = serve(refused(StatusCode::INTERNAL_SERVER_ERROR, "boom")).await; + let output = cli(&origin, &["--ref", "main", "--budget", "5"]).await; + // Unknown outcome: exit 4, as `ci review` does when Proofline gives no answer. + assert_eq!(output.status.code(), Some(4)); + let bodies = fake.bodies.lock().unwrap(); + assert_eq!(bodies.len(), 1, "a failed POST must not be repeated"); + let id = bodies[0]["request_id"].as_str().unwrap(); + id.parse::().unwrap(); + let message = stderr(&output); + assert!(message.contains(&format!("--request-id {id}")), "{message}"); +} + +#[tokio::test] +async fn a_repository_github_cannot_resolve_starts_nothing_and_says_how_to_ask_again() { + let reply: Arc Response + Send + Sync> = Arc::new(|| { + Json(json!({"resolution_id": RESOLUTION, "outcome": "REPOSITORY_UNAVAILABLE"})) + .into_response() + }); + let (origin, fake) = serve(reply).await; + let output = cli( + &origin, + &[ + "--ref", + "main", + "--budget", + "5", + "--request-id", + REQUEST, + "--json", + ], + ) + .await; + assert_eq!(output.status.code(), Some(1)); + // Scripts still read the resolution from stdout. + let printed: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(printed["outcome"], "REPOSITORY_UNAVAILABLE"); + assert_eq!(printed["resolution_id"], RESOLUTION); + let message = stderr(&output); + assert!(message.contains("nothing was spent"), "{message}"); + assert!(message.contains("omit --request-id"), "{message}"); + assert_eq!(fake.bodies.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn a_disabled_scan_limit_shows_the_servers_reason() { + let (origin, _) = serve(refused( + StatusCode::BAD_REQUEST, + "On-demand scans are off; raise the limit in repository settings.", + )) + .await; + let output = cli(&origin, &["--ref", "main", "--budget", "5"]).await; + assert_eq!(output.status.code(), Some(1)); + let message = stderr(&output); + assert!(message.contains("On-demand scans are off"), "{message}"); + // A definite refusal created nothing, so no retry is suggested. + assert!(!message.contains("--request-id"), "{message}"); +} + +#[tokio::test] +async fn an_unreadable_answer_leaves_the_outcome_unknown() { + let reply: Arc Response + Send + Sync> = + Arc::new(|| (StatusCode::OK, "gateway").into_response()); + let (origin, fake) = serve(reply).await; + let output = cli( + &origin, + &["--ref", "main", "--budget", "5", "--request-id", REQUEST], + ) + .await; + assert_eq!(output.status.code(), Some(4), "{}", stderr(&output)); + assert!(stderr(&output).contains(&format!("--request-id {REQUEST}"))); + assert_eq!(fake.bodies.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn an_unknown_outcome_is_not_followed_and_cannot_drive_the_terminal() { + let reply: Arc Response + Send + Sync> = Arc::new(|| { + Json( + json!({"resolution_id": RESOLUTION, "outcome": "QUEUED\u{1b}[2J", "review_id": REVIEW}), + ) + .into_response() + }); + let (origin, _) = serve(reply).await; + let output = cli(&origin, &["--ref", "main", "--budget", "5"]).await; + assert_eq!(output.status.code(), Some(1)); + let message = stderr(&output); + assert!(message.contains("unknown scan outcome"), "{message}"); + assert!(!message.contains('\u{1b}'), "{message:?}"); +} + +#[tokio::test] +async fn a_token_without_the_scan_scope_is_told_which_login_to_run() { + let (origin, _) = serve(refused(StatusCode::FORBIDDEN, "missing scope")).await; + let output = cli(&origin, &["--ref", "main", "--budget", "5"]).await; + assert_eq!(output.status.code(), Some(1)); + assert!(stderr(&output).contains("--scope scans:request")); +} + +#[tokio::test] +async fn a_malformed_request_is_refused_before_any_http() { + for args in [ + &["--budget", "5"][..], + &["--ref", "main"][..], + &["--ref", "main", "--budget", "0"][..], + &["--ref", "main", "--budget", "-3"][..], + &[ + "--ref", + "main", + "--commit", + &"a".repeat(40), + "--budget", + "5", + ][..], + &["--commit", "main", "--budget", "5"][..], + &["--commit", &"a".repeat(39), "--budget", "5"][..], + &["--ref", " ", "--budget", "5"][..], + &[ + "--ref", + "main", + "--budget", + "5", + "--request-id", + "not-a-uuid", + ][..], + ] { + let output = cli("http://127.0.0.1:1", args).await; + assert!(!output.status.success(), "{args:?} should be refused"); + assert!( + !stderr(&output).contains("could not reach"), + "{args:?} reached the network: {}", + stderr(&output) + ); + } +}