Skip to content
Merged
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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"]),
Expand Down
22 changes: 21 additions & 1 deletion src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<ScanResponse, ApiError> {
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(
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ mod preflight;
pub mod render;
mod result;
mod sarif;
mod scan;
mod severity;
pub mod text;
pub mod update;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -483,6 +486,11 @@ pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdic
let api = connect(Http::new(origin)?, token, cli.org).await?;
tools::rerun(&api, &args).await
}
Command::Scan(args) => {
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?;
Expand Down
23 changes: 23 additions & 0 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commit_sha: Option<String>,
}

/// 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<Uuid>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct StopResponse {
pub review_id: Uuid,
Expand Down
169 changes: 169 additions & 0 deletions src/scan.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
/// Exact full SHA to scan; never a branch.
#[arg(long, value_name = "SHA")]
commit: Option<String>,
/// 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<Uuid>,
/// 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<ScanRequest> {
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<Verdict> {
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<Uuid> {
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)
),
}
}
Loading