From e5d9e0499ea79e3e74b4911c41b08e2b58b68531 Mon Sep 17 00:00:00 2001 From: "MD. MOHIBUR RAHMAN" <35300157+mrpmohiburrahman@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:08:07 +0600 Subject: [PATCH] feat(review): add --dry-run and list every preflight refusal `proofline review --dry-run` builds the same local patch, prints the base commit, each changed file and the patch size, then runs the secret preflight. It reads no credential and sends no request. The preflight now collects every refusal instead of returning the first one. A patch with three secrets needs one run and one edit, not three. A refused `.env` path is listed once and its lines are not scanned again. `cargo test`, `cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` pass. --- README.md | 2 + src/lib.rs | 80 +++++++++++++++++-- src/preflight.rs | 180 ++++++++++++++++++++++++++++++++++--------- tests/local_patch.rs | 66 ++++++++++++++-- 4 files changed, 282 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 247d1f5..659b0c2 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ 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 review --dry-run` builds the same local patch, prints its base commit, each changed file and the patch size, then runs the secret preflight. It sends nothing and needs no sign-in. The preflight reports every refused path and line in one run, so you remove all of them in one edit; a refused `.env` path is listed once and its lines are not reported again. + `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 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/src/lib.rs b/src/lib.rs index 6196747..3f1f6da 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -298,6 +298,18 @@ struct LocalSelectionArgs { include_untracked: bool, } +/// What a local review shows without a server. +#[derive(Debug, Args)] +struct LocalPreviewArgs { + /// Print what this local review would send and every reason the secret + /// preflight refuses it, without signing in or sending anything. + #[arg( + long, + conflicts_with_all = ["schema", "pr", "commit", "range", "files", "verify", "no_wait", "fail_on", "json"] + )] + dry_run: bool, +} + #[derive(Debug, Args)] struct ReviewArgs { /// Print the JSON result schema without requesting or reading a review. @@ -309,6 +321,8 @@ struct ReviewArgs { pr: Option, #[command(flatten)] local_selection: LocalSelectionArgs, + #[command(flatten)] + local_preview: LocalPreviewArgs, /// Review the change this pushed commit makes against its first parent. /// The name is resolved once in the checkout; GitHub must have both commits. /// With --files, review complete selected files at that commit instead. @@ -438,6 +452,11 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { completions(*shell, &mut std::io::stdout().lock())?; @@ -1053,16 +1072,67 @@ async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result { finish(api, requested.review_id, args).await } -/// Reviews the checkout's local changes against the commit they build on. -/// Nothing is pushed: GitHub needs only the base commit. -async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { - let selection = if args.local_selection.staged { +/// The bytes a local review reads, from the selection flags. +fn local_selection(args: &ReviewArgs) -> git::LocalSelection { + if args.local_selection.staged { git::LocalSelection::Staged } else if args.local_selection.include_untracked { git::LocalSelection::IncludeUntracked } else { git::LocalSelection::Tracked - }; + } +} + +/// What one patch entry does, with Git's own path bytes quoted so a control +/// character in a name never reaches the terminal. +fn describe(path: &git::PatchPaths) -> String { + match (&path.old, &path.new) { + (None, Some(new)) => format!("added {new:?}"), + (Some(old), None) => format!("deleted {old:?}"), + (Some(old), Some(new)) if old != new => format!("renamed {old:?} -> {new:?}"), + (Some(path), Some(_)) => format!("modified {path:?}"), + // Git always names at least one endpoint of a patch entry. + (None, None) => "changed, with no path".to_owned(), + } +} + +/// Prints the patch a local review would send and every reason the preflight +/// refuses it. It reads no credential and makes no request, so a person can +/// check a checkout before signing in. +async fn review_dry_run(args: &ReviewArgs) -> anyhow::Result { + let changes = git::local_changes( + std::path::Path::new("."), + &args.repository.remote, + local_selection(args), + args.path.as_deref(), + ) + .await?; + let files = changes.files(); + if files == 0 { + say(&format!( + "Nothing to review: the selected local changes match {}.", + changes.base_commit_sha + )); + return Ok(Verdict::Done); + } + say(&format!( + "Local review would send {files} changed {} ({} bytes of patch) against {}.", + if files == 1 { "file" } else { "files" }, + changes.patch.len(), + changes.base_commit_sha + )); + for path in &changes.paths { + say(&format!(" {}", describe(path))); + } + preflight::check(&changes, &args.allow_path)?; + say("The secret preflight passed. Nothing was sent."); + Ok(Verdict::Done) +} + +/// Reviews the checkout's local changes against the commit they build on. +/// Nothing is pushed: GitHub needs only the base commit. +async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { + let selection = local_selection(args); let changes = git::local_changes( std::path::Path::new("."), &args.repository.remote, diff --git a/src/preflight.rs b/src/preflight.rs index 592ec54..e1d62e3 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -1,28 +1,75 @@ //! Local refusals before any patch bytes leave the checkout. +use std::fmt; + use crate::git::{LocalChanges, PatchPaths}; +/// How many refused lines the report prints before it counts the rest. A +/// patch may hold thousands of files, and a wall of lines hides the first +/// one the person must fix anyway. +const SHOWN: usize = 20; + #[derive(Debug, thiserror::Error)] pub(crate) enum PreflightError { #[error( "--allow-path {0:?} is not an exact repository-relative path; use the path from the local refusal" )] InvalidAllowPath(String), - #[error( - "local patch includes the sensitive .env path {0:?}; remove it before upload, or pass --allow-path for that exact path" - )] - EnvironmentPath(String), - #[error( - "local patch contains {kind} at {path:?}:{line} ({coordinate}); remove it before upload, or pass --allow-path for that exact path" - )] + #[error("{0}")] + Refused(Refusals), + #[error("could not map the local patch to file paths and lines; no review was requested")] + InvalidPatch, +} + +/// Every problem in the patch, in patch order. One run names them all, so the +/// person removes them in one edit instead of one run per secret. +#[derive(Debug)] +pub(crate) struct Refusals(Vec); + +#[derive(Debug)] +enum Issue { + /// A path Git tracks as an environment file, whatever its content. + SensitivePath(String), + /// A credential shape on one patch line. Secret { path: String, line: usize, coordinate: &'static str, kind: &'static str, }, - #[error("could not map the local patch to file paths and lines; no review was requested")] - InvalidPatch, +} + +impl fmt::Display for Refusals { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let count = self.0.len(); + write!( + formatter, + "local patch has {count} {}; remove {} before upload, or pass --allow-path for each exact path:", + if count == 1 { "problem" } else { "problems" }, + if count == 1 { "it" } else { "them" }, + )?; + for issue in self.0.iter().take(SHOWN) { + write!(formatter, "\n {issue}")?; + } + if count > SHOWN { + write!(formatter, "\n and {} more", count - SHOWN)?; + } + Ok(()) + } +} + +impl fmt::Display for Issue { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::SensitivePath(path) => write!(formatter, "{path:?}: a sensitive .env path"), + Self::Secret { + path, + line, + coordinate, + kind, + } => write!(formatter, "{path:?}:{line} ({coordinate}): {kind}"), + } + } } #[derive(Debug)] @@ -38,39 +85,52 @@ pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), Pr } } let mut paths = changes.paths.iter(); - let mut current = None; + let mut current: Option<(&PatchPaths, bool)> = None; let mut hunk = None; + let mut found = Vec::new(); for (patch_line, line) in changes.patch.lines().enumerate() { if line.starts_with("diff --git ") { let file = paths.next().ok_or(PreflightError::InvalidPatch)?; - environment_paths(file, allowed)?; - current = Some(file); + // A refused path is not scanned line by line: every one of its + // lines would repeat the same refusal. + let refused = environment_paths(file, allowed, &mut found); + current = Some((file, refused)); hunk = None; continue; } - let file = current.ok_or(PreflightError::InvalidPatch)?; + let (file, refused) = *current.as_ref().ok_or(PreflightError::InvalidPatch)?; if line.starts_with("@@ ") { // A section heading can quote a line outside the hunk. Its exact // coordinate is a patch line, not a guessed source-file line. - inspect( - file.new.as_deref().or(file.old.as_deref()), - patch_line + 1, - "patch line", - line, - allowed, - )?; + if !refused { + inspect( + file.new.as_deref().or(file.old.as_deref()), + patch_line + 1, + "patch line", + line, + allowed, + &mut found, + )?; + } hunk = Some(hunk_lines(line)?); } else if let Some(lines) = &mut hunk { - inspect_hunk(file, lines, line, allowed)?; + inspect_hunk(file, lines, line, allowed, refused, &mut found)?; } } if paths.next().is_some() { return Err(PreflightError::InvalidPatch); } - Ok(()) + if found.is_empty() { + Ok(()) + } else { + Err(PreflightError::Refused(Refusals(found))) + } } -fn environment_paths(file: &PatchPaths, allowed: &[String]) -> Result<(), PreflightError> { +/// Collects a refusal for each endpoint Git tracks as an environment file, +/// and reports whether the file's lines still need a scan. +fn environment_paths(file: &PatchPaths, allowed: &[String], found: &mut Vec) -> bool { + let mut refused = false; for path in [&file.old, &file.new] .iter() .filter_map(|path| path.as_deref()) @@ -80,10 +140,11 @@ fn environment_paths(file: &PatchPaths, allowed: &[String]) -> Result<(), Prefli .split('/') .any(|part| part == ".env" || part.starts_with(".env.")) { - return Err(PreflightError::EnvironmentPath(path.to_owned())); + found.push(Issue::SensitivePath(path.to_owned())); + refused = true; } } - Ok(()) + refused } fn hunk_lines(line: &str) -> Result { @@ -116,21 +177,44 @@ fn inspect_hunk( lines: &mut Lines, line: &str, allowed: &[String], + refused: bool, + found: &mut Vec, ) -> Result<(), PreflightError> { if let Some(text) = line.strip_prefix('+') { - inspect(file.new.as_deref(), lines.new, "new line", text, allowed)?; + if !refused { + inspect( + file.new.as_deref(), + lines.new, + "new line", + text, + allowed, + found, + )?; + } lines.new = next_line(lines.new)?; } else if let Some(text) = line.strip_prefix('-') { - inspect(file.old.as_deref(), lines.old, "base line", text, allowed)?; + if !refused { + inspect( + file.old.as_deref(), + lines.old, + "base line", + text, + allowed, + found, + )?; + } lines.old = next_line(lines.old)?; } else if let Some(text) = line.strip_prefix(' ') { - inspect( - file.new.as_deref().or(file.old.as_deref()), - lines.new, - "new line", - text, - allowed, - )?; + if !refused { + inspect( + file.new.as_deref().or(file.old.as_deref()), + lines.new, + "new line", + text, + allowed, + found, + )?; + } lines.old = next_line(lines.old)?; lines.new = next_line(lines.new)?; } else if !line.starts_with("\\ No newline at end of file") { @@ -149,12 +233,13 @@ fn inspect( coordinate: &'static str, text: &str, allowed: &[String], + found: &mut Vec, ) -> Result<(), PreflightError> { let path = path.ok_or(PreflightError::InvalidPatch)?; if !is_allowed(path, allowed) && let Some(kind) = secret_shape(text) { - return Err(PreflightError::Secret { + found.push(Issue::Secret { path: path.to_owned(), line, coordinate, @@ -291,7 +376,30 @@ fn secret_shape(text: &str) -> Option<&'static str> { #[cfg(test)] mod tests { - use super::secret_shape; + use super::{Issue, Refusals, SHOWN, secret_shape}; + + #[test] + fn every_refusal_is_listed_once_and_the_tail_is_counted() { + let one = Refusals(vec![Issue::SensitivePath(".env".to_owned())]); + assert_eq!( + one.to_string(), + "local patch has 1 problem; remove it before upload, or pass --allow-path for each exact path:\n \".env\": a sensitive .env path" + ); + let many = Refusals( + (1..=SHOWN + 2) + .map(|line| Issue::Secret { + path: "src/a.rs".to_owned(), + line, + coordinate: "new line", + kind: "a GitHub token", + }) + .collect(), + ); + let text = many.to_string(); + assert!(text.starts_with("local patch has 22 problems;"), "{text}"); + assert!(text.ends_with("\n and 2 more"), "{text}"); + assert_eq!(text.lines().count(), SHOWN + 2); + } #[test] fn credential_families_refuse_minimum_bodies_but_accept_short_or_invalid_ones() { diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 6da45f8..79970cf 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -514,7 +514,7 @@ async fn local_selection_uploads_only_selected_bytes_and_refuses_before_http() { let output = checkout .review(&server, &[], &["--include-untracked"]) .await; - assert_refusal(&output, "sensitive .env path \".env.local\"", &github); + assert_refusal(&output, "\".env.local\": a sensitive .env path", &github); assert_eq!(server.fixture.requests.load(Ordering::SeqCst), requests); assert_eq!(*server.fixture.uploads.lock().unwrap(), uploads); assert_eq!(checkout.index().await, index); @@ -554,6 +554,59 @@ async fn local_selection_uploads_only_selected_bytes_and_refuses_before_http() { server.close().await; } +#[tokio::test] +async fn a_dry_run_prints_the_patch_and_sends_nothing() { + let checkout = Checkout::new(&[("kept.txt", "one\n"), ("old.txt", "gone\n")]).await; + checkout.write("kept.txt", "one\ntwo\n").await; + checkout.write("added.txt", "new\n").await; + checkout.git(&["rm", "-q", "old.txt"]).await; + let server = Server::start(true).await; + let output = checkout + .review_and_wait(&server, &[], &["--dry-run", "--include-untracked"]) + .await; + let text = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "{text}"); + assert!(output.stdout.is_empty()); + assert!(text.contains("would send 3 changed files"), "{text}"); + for line in [ + "added \"added.txt\"", + "modified \"kept.txt\"", + "deleted \"old.txt\"", + "The secret preflight passed. Nothing was sent.", + ] { + assert!(text.contains(line), "{line}: {text}"); + } + server.assert_no_requests(); + server.close().await; +} + +#[tokio::test] +async fn a_dry_run_reports_every_refused_path_in_one_run() { + let github = format!("ghp_{}", "D".repeat(36)); + let checkout = Checkout::new(&[("kept.txt", "one\n")]).await; + checkout.write("kept.txt", "AKIAIOSFODNN7EXAMPLE\n").await; + checkout.write("added.txt", &format!("{github}\n")).await; + checkout.write(".env.local", "SETTING=local\n").await; + let server = Server::start(true).await; + let output = checkout + .review_and_wait(&server, &[], &["--dry-run", "--include-untracked"]) + .await; + let text = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{text}"); + assert!(output.stdout.is_empty()); + assert!(text.contains("local patch has 3 problems"), "{text}"); + for line in [ + "\".env.local\": a sensitive .env path", + "\"added.txt\":1 (new line): a GitHub token", + "\"kept.txt\":1 (new line): an AWS access-key ID", + ] { + assert!(text.contains(line), "{line}: {text}"); + } + assert!(!text.contains(&github), "{text}"); + server.assert_no_requests(); + server.close().await; +} + #[tokio::test] async fn added_context_deleted_and_quoted_content_refuses_before_http() { let github = format!("ghp_{}", "A".repeat(36)); @@ -623,9 +676,9 @@ async fn exact_overrides_keep_other_paths_blocked_and_upload_the_original_patch( let index = checkout.index().await; let server = Server::start(true).await; for (allowed, diagnostic) in [ - (vec![], "sensitive .env path \".env.local\""), + (vec![], "\".env.local\": a sensitive .env path"), (vec![".env.local"], "\"nested/token.txt\":2 (new line)"), - (vec!["*"], "sensitive .env path \".env.local\""), + (vec!["*"], "\".env.local\": a sensitive .env path"), ( vec![".env.local", "nested"], "\"nested/token.txt\":2 (new line)", @@ -674,8 +727,11 @@ async fn a_sensitive_rename_requires_both_exact_endpoints() { let index = checkout.index().await; let server = Server::start(true).await; for (allowed, diagnostic) in [ - (vec![], "sensitive .env path \".env.old\""), - (vec![".env.old"], "sensitive .env path \"config/.env.prod\""), + (vec![], "\".env.old\": a sensitive .env path"), + ( + vec![".env.old"], + "\"config/.env.prod\": a sensitive .env path", + ), ] { let output = checkout.review(&server, &allowed, &[]).await; assert_refusal(&output, diagnostic, private);