Skip to content
Closed
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
80 changes: 75 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -309,6 +321,8 @@ struct ReviewArgs {
pr: Option<u64>,
#[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.
Expand Down Expand Up @@ -438,6 +452,11 @@ pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdic
writeln!(stdout, "{}", serde_json::to_string_pretty(&document)?)?;
return Ok(Verdict::Done);
}
if let Command::Review(args) = &cli.command
&& args.local_preview.dry_run
{
return review_dry_run(args).await;
}
match &cli.command {
Command::Completions { shell } => {
completions(*shell, &mut std::io::stdout().lock())?;
Expand Down Expand Up @@ -1053,16 +1072,67 @@ async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result<Verdict> {
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<Verdict> {
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<Verdict> {
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<Verdict> {
let selection = local_selection(args);
let changes = git::local_changes(
std::path::Path::new("."),
&args.repository.remote,
Expand Down
180 changes: 144 additions & 36 deletions src/preflight.rs
Original file line number Diff line number Diff line change
@@ -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<Issue>);

#[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)]
Expand All @@ -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<Issue>) -> bool {
let mut refused = false;
for path in [&file.old, &file.new]
.iter()
.filter_map(|path| path.as_deref())
Expand All @@ -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<Lines, PreflightError> {
Expand Down Expand Up @@ -116,21 +177,44 @@ fn inspect_hunk(
lines: &mut Lines,
line: &str,
allowed: &[String],
refused: bool,
found: &mut Vec<Issue>,
) -> 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") {
Expand All @@ -149,12 +233,13 @@ fn inspect(
coordinate: &'static str,
text: &str,
allowed: &[String],
found: &mut Vec<Issue>,
) -> 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,
Expand Down Expand Up @@ -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() {
Expand Down
Loading