From e1f732b2979133c75ff79b302565ad3515ff0b05 Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Mon, 30 Nov 2026 20:44:20 +0200 Subject: [PATCH] Name a credential in a local patch before refusing it as a whole --- src/git.rs | 185 ++++++++++++++++++++++++++++++++++++++----- src/hooks.rs | 5 +- src/lib.rs | 8 +- src/preflight.rs | 10 ++- tests/hooks.rs | 68 ++++++++++++++++ tests/local_patch.rs | 36 +++++++++ 6 files changed, 287 insertions(+), 25 deletions(-) diff --git a/src/git.rs b/src/git.rs index c88f567..ee512b2 100644 --- a/src/git.rs +++ b/src/git.rs @@ -26,11 +26,11 @@ pub enum GitError { )] NoBase(String), #[error("the local changes include text that is not UTF-8, which Proofline cannot review")] - NotUtf8, + NotUtf8(Refused), #[error("the local changes make a {0} MiB patch; Proofline reviews patches up to 5 MiB")] - TooLarge(usize), + TooLarge(usize, Refused), #[error("the local changes include {0} files; Proofline reviews patches up to 3,000 files")] - TooManyFiles(usize), + TooManyFiles(usize, Refused), #[error("could not read the local patch's Git path metadata; no review was requested")] InvalidDiff, #[error("{0:?} names no commit in this checkout")] @@ -53,6 +53,29 @@ pub enum GitError { NotTrackedFile(String, String), } +impl GitError { + /// The patch a whole-patch refusal kept, so the secret preflight can still + /// read it. Nothing refused is ever uploaded. + pub(crate) fn refused(&self) -> Option<&LocalChanges> { + match self { + Self::NotUtf8(refused) + | Self::TooLarge(_, refused) + | Self::TooManyFiles(_, refused) => Some(&refused.0), + _ => None, + } + } +} + +/// A refused patch as text, with each byte that is not UTF-8 read as U+FFFD, +/// so its lines and paths keep their places. Its debug form omits the patch. +pub struct Refused(Box); + +impl std::fmt::Debug for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Refused(..)") + } +} + /// Two exact commits of a pushed change: the head, and the base it is /// compared with. Pinned from what the person named; the server /// verifies both on the connected source repository. @@ -433,27 +456,41 @@ async fn diff( args.push("--"); args.extend(path); let output = git_in(root, index, &args).await?; - let (paths, patch) = diff_paths(&output)?; - if patch.len() > MAX_PATCH_BYTES { - return Err(GitError::TooLarge(patch.len().div_ceil(1 << 20))); + read_diff(base_commit_sha, &output, (MAX_PATCH_BYTES, MAX_PATCH_FILES)) +} + +/// The changes in `--raw -z --patch` output, refused as a whole over +/// `max_bytes` or `max_files`, or when any of it is not UTF-8. +fn read_diff( + base_commit_sha: String, + output: &[u8], + (max_bytes, max_files): (usize, usize), +) -> Result { + let (paths, patch) = diff_paths(output)?; + // Paths are read lossily too, and the metadata holds nothing but them + // and ASCII, so one check covers both. + let utf8 = std::str::from_utf8(output).is_ok(); + let (bytes, files) = (patch.len(), paths.len()); + let changes = LocalChanges { + base_commit_sha, + patch: String::from_utf8_lossy(patch).into_owned(), + paths, + }; + if files != changes.files() { + return Err(GitError::InvalidDiff); } - if paths.len() > MAX_PATCH_FILES { - return Err(GitError::TooManyFiles(paths.len())); + // Each refusal keeps the patch, so a credential in it is still named. + if bytes > max_bytes { + let refused = Refused(Box::new(changes)); + return Err(GitError::TooLarge(bytes.div_ceil(1 << 20), refused)); } - let patch = String::from_utf8(patch.to_vec()).map_err(|_| GitError::NotUtf8)?; - if paths.len() - != patch - .lines() - .filter(|line| line.starts_with("diff --git ")) - .count() - { - return Err(GitError::InvalidDiff); + if files > max_files { + return Err(GitError::TooManyFiles(files, Refused(Box::new(changes)))); } - Ok(LocalChanges { - base_commit_sha, - patch, - paths, - }) + if !utf8 { + return Err(GitError::NotUtf8(Refused(Box::new(changes)))); + } + Ok(changes) } /// Separates `--raw -z --patch` metadata from the unchanged text patch. @@ -513,7 +550,7 @@ fn diff_path(output: &mut &[u8]) -> Result { if path.is_empty() { return Err(GitError::InvalidDiff); } - String::from_utf8(path.to_vec()).map_err(|_| GitError::NotUtf8) + Ok(String::from_utf8_lossy(path).into_owned()) } /// A Git configuration value as Git reads it in `dir`, or `None` when unset. @@ -739,6 +776,110 @@ mod tests { } } + /// Runs git with `input` on stdin and returns its trimmed stdout. + fn run_with(dir: &Path, args: &[&str], input: &[u8]) -> String { + use std::io::Write; + let mut child = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(input).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "git {args:?}: {output:?}"); + String::from_utf8(output.stdout).unwrap().trim().to_owned() + } + + /// A patch refused for text or a path that is not UTF-8 keeps both as + /// lossy text with the same lines, for the secret preflight, and never + /// prints them in its debug form. + #[tokio::test] + async fn a_refused_patch_keeps_lossy_text_and_paths_for_the_preflight() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + run(dir, &["init", "-q", "-b", "main"]); + run(dir, &["config", "user.email", "dev@example.com"]); + run(dir, &["config", "user.name", "dev"]); + run(dir, &["commit", "-q", "--allow-empty", "-m", "base"]); + let base = run(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + let token = format!("ghp_{}", "P".repeat(36)); + let blob = run_with( + dir, + &["hash-object", "-w", "--stdin"], + &[b"caf\xe9\n".as_slice(), token.as_bytes(), b"\n"].concat(), + ); + // The index takes the path's raw bytes, so no file system has to. + run_with( + dir, + &["update-index", "--index-info"], + &[ + format!("100644 blob {blob}\t").as_bytes(), + b"m\xe9nu.txt\n".as_slice(), + ] + .concat(), + ); + let tree = run(dir, &["write-tree"]).trim().to_owned(); + let head = run_with(dir, &["commit-tree", &tree, "-p", &base, "-m", "menu"], b""); + + let error = range_changes(dir, &base, &head).await.unwrap_err(); + assert!(matches!(error, GitError::NotUtf8(_)), "{error:?}"); + let changes = error.refused().unwrap(); + assert_eq!(changes.base_commit_sha, base); + assert_eq!(changes.paths.len(), 1); + assert_eq!(changes.paths[0].new.as_deref(), Some("m\u{FFFD}nu.txt")); + assert_eq!(changes.files(), 1); + assert!( + changes + .patch + .contains(&format!("@@ -0,0 +1,2 @@\n+caf\u{FFFD}\n+{token}\n")), + "{}", + changes.patch + ); + assert!(!format!("{error:?}").contains(&token)); + } + + /// The size and file-count refusals keep the patch too, so the preflight + /// still names its credential. Small limits stand in for 5 MiB and + /// 3,000 files. + #[test] + fn size_refusals_keep_the_credential_for_the_preflight() { + let token = format!("ghp_{}", "L".repeat(36)); + let section = |path: &str, line: &str| { + format!( + "diff --git a/{path} b/{path}\nnew file mode 100644\n\ + --- /dev/null\n+++ b/{path}\n@@ -0,0 +1,2 @@\n+public\n+{line}\n" + ) + }; + let output = [ + ":000000 100644 0000000 1111111 A\0first.txt\0", + ":000000 100644 0000000 2222222 A\0settings.py\0\0", + §ion("first.txt", "text"), + §ion("settings.py", &token), + ] + .concat(); + let base = "a".repeat(40); + let read = |limits| read_diff(base.clone(), output.as_bytes(), limits); + assert_eq!(read((usize::MAX, usize::MAX)).unwrap().files(), 2); + for (limits, refusal) in [ + ((64, usize::MAX), "1 MiB patch"), + ((usize::MAX, 1), "include 2 files"), + ] { + let error = read(limits).unwrap_err(); + assert!(error.to_string().contains(refusal), "{error}"); + let credential = crate::preflight::check_refused(&error, &[]) + .unwrap_err() + .to_string(); + assert!( + credential.contains("a GitHub token at \"settings.py\":2 (new line)"), + "{credential}" + ); + assert!(!format!("{error:?}").contains(&token)); + } + } + #[tokio::test] async fn local_changes_cover_the_work_tree_and_leave_the_index_alone() { let repo = tempfile::tempdir().unwrap(); diff --git a/src/hooks.rs b/src/hooks.rs index 9dc1807..2c62677 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -478,7 +478,10 @@ pub(crate) async fn run( /// The changes, once they are known to need a review and pass the local /// refusals that run before any upload. fn ready(changes: Result) -> Result { - let changes = changes.map_err(|error| Report::Unreviewed(error.to_string()))?; + let changes = changes.map_err(|error| match preflight::check_refused(&error, &[]) { + Err(credential) => Report::Unreviewed(credential.to_string()), + Ok(()) => Report::Unreviewed(error.to_string()), + })?; if changes.files() == 0 { return Err(Report::Nothing); } diff --git a/src/lib.rs b/src/lib.rs index 8bf7a9e..551cac6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1194,7 +1194,13 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { selection, args.path.as_deref(), ) - .await?; + .await + .map_err( + |error| match preflight::check_refused(&error, &args.allow_path) { + Err(credential) => anyhow::Error::from(credential), + Ok(()) => error.into(), + }, + )?; let files = changes.files(); if files == 0 && !args.verify.is_empty() { bail!( diff --git a/src/preflight.rs b/src/preflight.rs index 592ec54..c37b928 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -1,6 +1,6 @@ //! Local refusals before any patch bytes leave the checkout. -use crate::git::{LocalChanges, PatchPaths}; +use crate::git::{GitError, LocalChanges, PatchPaths}; #[derive(Debug, thiserror::Error)] pub(crate) enum PreflightError { @@ -31,6 +31,14 @@ struct Lines { new: usize, } +/// Checks the patch a whole-patch refusal kept, so a credential in it is named +/// before the refusal's own reason. `Ok` leaves that reason to report. +pub(crate) fn check_refused(error: &GitError, allowed: &[String]) -> Result<(), PreflightError> { + error + .refused() + .map_or(Ok(()), |changes| check(changes, allowed)) +} + pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), PreflightError> { for path in allowed { if path.starts_with('/') || path.split('/').any(|part| matches!(part, "" | "." | "..")) { diff --git a/tests/hooks.rs b/tests/hooks.rs index 66b492d..804b178 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -615,6 +615,74 @@ async fn each_pushed_branch_is_reviewed_against_the_commit_the_remote_has() { ); } +/// A pushed branch Proofline refuses as a whole, for text that is not UTF-8 +/// or for its size, still has its credentials named, with exact lines. +#[tokio::test] +async fn a_refused_push_still_names_the_credential_it_carries() { + let checkout = Checkout::new().await; + let uploads = Uploads::default(); + let origin = serve(uploads.clone(), "SERIOUS", false).await; + let github = format!("ghp_{}", "T".repeat(36)); + let latin1 = b"caf\xe9\n".to_vec(); + let large = "public text\n".repeat(600_000).into_bytes(); + for (branch, file, mut text, credential, refusal) in [ + ( + "latin1-token", + "settings.py", + latin1.clone(), + true, + "not UTF-8", + ), + ("latin1", "settings.py", latin1, false, "not UTF-8"), + ("large-token", "generated.txt", large, true, "MiB patch"), + ] { + if credential { + text.extend_from_slice(format!("TOKEN = \"{github}\"\n").as_bytes()); + } + checkout + .git(&["switch", "-q", "-c", branch, &checkout.base]) + .await; + tokio::fs::write(checkout.root().join(file), text) + .await + .unwrap(); + checkout.git(&["add", file]).await; + checkout.git(&["commit", "-qm", branch]).await; + let head = checkout.git(&["rev-parse", "HEAD"]).await; + let input = format!( + "refs/heads/{branch} {head} refs/heads/{branch} {}\n", + checkout.base + ); + let output = checkout + .proofline( + &origin, + &[ + "hook", + "run", + "pre-push", + "origin", + "https://github.com/acme/web.git", + ], + &input, + ) + .await; + let stderr = stderr(&output); + assert_eq!(output.status.code(), Some(0), "{branch}: {stderr}"); + assert!(stderr.contains("The push proceeds"), "{branch}: {stderr}"); + assert!(!stderr.contains(&github), "{branch}: {stderr}"); + if credential { + let line = if file == "settings.py" { 2 } else { 600_001 }; + assert!( + stderr.contains(&format!("a GitHub token at \"{file}\":{line} (new line)")), + "{branch}: {stderr}" + ); + assert!(!stderr.contains(refusal), "{branch}: {stderr}"); + } else { + assert!(stderr.contains(refusal), "{branch}: {stderr}"); + } + } + assert!(uploads.lock().unwrap().is_empty()); +} + /// Real pushes through the installed hook: the destination ref, not the /// source, says whether a line is a branch to review or a tag to skip. #[tokio::test] diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 670a586..9c57452 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -569,6 +569,42 @@ async fn local_selection_uploads_only_selected_bytes_and_refuses_before_http() { .await; assert_eq!(output.status.code(), Some(1)); assert!(String::from_utf8_lossy(&output.stderr).contains("3,000 files")); + // The file-count refusal doesn't hide a credential among the files. + checkout + .write("generated/7.txt", &format!("public text\n{github}\n")) + .await; + let output = checkout + .review(&server, &[], &["--include-untracked"]) + .await; + assert_refusal(&output, "\"generated/7.txt\":2 (new line)", &github); + assert!(!String::from_utf8_lossy(&output.stderr).contains("3,000 files")); + server.assert_no_requests(); + assert_eq!(checkout.index().await, index); + server.close().await; +} + +/// A patch refused for text that is not UTF-8 still has its credentials +/// named first, at exact lines; an exact override leaves only the refusal. +#[tokio::test] +async fn a_patch_that_is_not_utf8_names_its_credential_before_http() { + let github = format!("ghp_{}", "U".repeat(36)); + let checkout = Checkout::new(&[("settings.py", "base\n")]).await; + tokio::fs::write( + checkout.root().join("settings.py"), + [b"caf\xe9\n".as_slice(), format!("{github}\n").as_bytes()].concat(), + ) + .await + .unwrap(); + let index = checkout.index().await; + let server = Server::start(true).await; + let output = checkout.review(&server, &[], &[]).await; + assert_refusal(&output, "\"settings.py\":2 (new line)", &github); + assert!(!String::from_utf8_lossy(&output.stderr).contains("not UTF-8")); + let output = checkout.review(&server, &["settings.py"], &[]).await; + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("not UTF-8"), "{stderr}"); + assert!(!stderr.contains(&github), "{stderr}"); server.assert_no_requests(); assert_eq!(checkout.index().await, index); server.close().await;