From 486193932dcf1bc58eeba6d476a1ddc037d8bf58 Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Wed, 2 Dec 2026 12:24:23 +0200 Subject: [PATCH 1/2] Let Git hooks allow an exact path past the local preflight --- src/git.rs | 24 ++++++++++++++ src/hooks.rs | 35 ++++++++++++++++---- src/lib.rs | 8 ++++- src/preflight.rs | 66 +++++++++++++++++++++++++++++-------- tests/hooks.rs | 84 ++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 196 insertions(+), 21 deletions(-) diff --git a/src/git.rs b/src/git.rs index c88f567..4ec9137 100644 --- a/src/git.rs +++ b/src/git.rs @@ -538,6 +538,30 @@ pub async fn config(dir: &Path, key: &str) -> Result, GitError> { } } +/// Every value of a multi-valued `key`, in the order Git reads them, or +/// none when it is not set. Values are read whole, so one may hold any byte. +pub async fn config_all(dir: &Path, key: &str) -> Result, GitError> { + let output = Command::new("git") + .arg("-C") + .arg(dir) + .args(["config", "--get-all", "-z", key]) + .output() + .await + .map_err(|error| GitError::Unavailable(error.to_string()))?; + match output.status.code() { + Some(0) => Ok(String::from_utf8_lossy(&output.stdout) + .split_terminator('\0') + .map(str::to_owned) + .collect()), + // `git config --get-all` exits 1 for a key that is not set. + Some(1) => Ok(Vec::new()), + _ => Err(GitError::Failed { + command: format!("config --get-all {key}"), + stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(), + }), + } +} + /// The directory Git runs this repository's hooks from. Linked worktrees /// share it. pub async fn hooks_dir(dir: &Path) -> Result { diff --git a/src/hooks.rs b/src/hooks.rs index 7d5550a..fb12057 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -1,8 +1,9 @@ //! Git hooks that review a commit or a push as it leaves the checkout. //! `hooks install` writes one small script per hook. Git runs it, and it calls -//! `hook run`, which reviews exactly what the commit or push adds and applies -//! the developer's exit policy. A review that did not complete is printed as -//! not reviewed, never as clean. +//! `hook run`, which reviews what the push adds, or for a commit the staged +//! changes with every unpushed commit before them (a review starts at a commit +//! the server has), and applies the developer's exit policy. A review that did +//! not complete is printed as not reviewed, never as clean. use std::path::Path; use std::time::Duration; @@ -273,6 +274,8 @@ struct Settings { fail_on: Severity, on_incomplete: Mode, timeout: Duration, + /// Exact paths the local preflight lets through, like `--allow-path`. + allow_paths: Vec, } async fn settings(dir: &Path, hook: Hook) -> anyhow::Result { @@ -309,11 +312,22 @@ async fn settings(dir: &Path, hook: Hook) -> anyhow::Result { ) })?, }; + // A pre-commit patch holds every unpushed commit, so a file refused once + // is refused at each later commit until it is allowed here or pushed. + let key_allow = format!("proofline.hook.{}.allowPath", hook.name()); + let allow_paths = git::config_all(dir, &key_allow).await?; + if let Some(path) = allow_paths.iter().find(|path| !preflight::exact_path(path)) { + bail!( + "{key_allow} is {:?}; set it to an exact repository-relative path from the refusal", + one_line(path) + ); + } Ok(Settings { mode: mode(value("mode").await?)?, fail_on, on_incomplete: mode(value("onIncomplete").await?)?, timeout: Duration::from_secs(seconds), + allow_paths, }) } @@ -452,7 +466,7 @@ pub(crate) async fn run( let mut reports = Vec::new(); let mut api: Option> = None; for subject in subjects { - let report = match ready(subject.changes) { + let report = match ready(subject.changes, hook, &settings.allow_paths) { Err(report) => report, Ok(changes) => { // Connect once, and only when something needs a review. @@ -480,12 +494,20 @@ 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 { +fn ready( + changes: Result, + hook: Hook, + allow_paths: &[String], +) -> Result { let changes = changes.map_err(|error| Report::Unreviewed(error.to_string()))?; if changes.files() == 0 { return Err(Report::Nothing); } - preflight::check(&changes, &[]).map_err(|error| Report::Unreviewed(error.to_string()))?; + let allowed = preflight::Allowed { + paths: allow_paths, + by: preflight::Allowance::Hook(hook.name()), + }; + preflight::check(&changes, allowed).map_err(|error| Report::Unreviewed(error.to_string()))?; Ok(changes) } @@ -748,6 +770,7 @@ mod tests { fail_on, on_incomplete, timeout: Duration::from_secs(60), + allow_paths: Vec::new(), } } diff --git a/src/lib.rs b/src/lib.rs index 2ac4644..ced68b9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1222,7 +1222,13 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { )); return Ok(Verdict::Done); } - preflight::check(&changes, &args.allow_path)?; + preflight::check( + &changes, + preflight::Allowed { + paths: &args.allow_path, + by: preflight::Allowance::Flag, + }, + )?; let (name, repository_id) = connected_repository(api, &args.repository).await?; let request = PatchReviewRequest { base_commit_sha: changes.base_commit_sha, diff --git a/src/preflight.rs b/src/preflight.rs index 592ec54..9b9baa9 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -9,33 +9,67 @@ pub(crate) enum PreflightError { )] InvalidAllowPath(String), #[error( - "local patch includes the sensitive .env path {0:?}; remove it before upload, or pass --allow-path for that exact path" + "local patch includes the sensitive .env path {path:?}; remove it before upload, or {by}" )] - EnvironmentPath(String), + EnvironmentPath { path: String, by: Allowance }, #[error( - "local patch contains {kind} at {path:?}:{line} ({coordinate}); remove it before upload, or pass --allow-path for that exact path" + "local patch contains {kind} at {path:?}:{line} ({coordinate}); remove it before upload, or {by}" )] Secret { path: String, line: usize, coordinate: &'static str, kind: &'static str, + by: Allowance, }, #[error("could not map the local patch to file paths and lines; no review was requested")] InvalidPatch, } +/// Where a person lists the exact paths to upload despite a refusal, so the +/// refusal names the remedy that caller can take. +#[derive(Debug, Clone, Copy)] +pub(crate) enum Allowance { + /// `review --allow-path`. + Flag, + /// `proofline.hook..allowPath`, which a Git hook reads. + Hook(&'static str), +} + +impl std::fmt::Display for Allowance { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Flag => formatter.write_str("pass --allow-path for that exact path"), + Self::Hook(hook) => write!( + formatter, + "allow that exact path with git config --add proofline.hook.{hook}.allowPath" + ), + } + } +} + +/// The exact paths allowed past a refusal, and where they were listed. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Allowed<'a> { + pub(crate) paths: &'a [String], + pub(crate) by: Allowance, +} + +/// Whether `path` can name one patch path exactly: repository-relative, with +/// no empty, `.` or `..` segment. +pub(crate) fn exact_path(path: &str) -> bool { + !path.starts_with('/') && !path.split('/').any(|part| matches!(part, "" | "." | "..")) +} + #[derive(Debug)] struct Lines { old: usize, new: usize, } -pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), PreflightError> { - for path in allowed { - if path.starts_with('/') || path.split('/').any(|part| matches!(part, "" | "." | "..")) { - return Err(PreflightError::InvalidAllowPath(path.clone())); - } +pub(crate) fn check(changes: &LocalChanges, allowed: Allowed<'_>) -> Result<(), PreflightError> { + if let Some(path) = allowed.paths.iter().find(|path| !exact_path(path)) { + return Err(PreflightError::InvalidAllowPath(path.clone())); } let mut paths = changes.paths.iter(); let mut current = None; @@ -70,7 +104,7 @@ pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), Pr Ok(()) } -fn environment_paths(file: &PatchPaths, allowed: &[String]) -> Result<(), PreflightError> { +fn environment_paths(file: &PatchPaths, allowed: Allowed<'_>) -> Result<(), PreflightError> { for path in [&file.old, &file.new] .iter() .filter_map(|path| path.as_deref()) @@ -80,7 +114,10 @@ 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())); + return Err(PreflightError::EnvironmentPath { + path: path.to_owned(), + by: allowed.by, + }); } } Ok(()) @@ -115,7 +152,7 @@ fn inspect_hunk( file: &PatchPaths, lines: &mut Lines, line: &str, - allowed: &[String], + allowed: Allowed<'_>, ) -> Result<(), PreflightError> { if let Some(text) = line.strip_prefix('+') { inspect(file.new.as_deref(), lines.new, "new line", text, allowed)?; @@ -148,7 +185,7 @@ fn inspect( line: usize, coordinate: &'static str, text: &str, - allowed: &[String], + allowed: Allowed<'_>, ) -> Result<(), PreflightError> { let path = path.ok_or(PreflightError::InvalidPatch)?; if !is_allowed(path, allowed) @@ -159,13 +196,14 @@ fn inspect( line, coordinate, kind, + by: allowed.by, }); } Ok(()) } -fn is_allowed(path: &str, allowed: &[String]) -> bool { - allowed.iter().any(|candidate| candidate == path) +fn is_allowed(path: &str, allowed: Allowed<'_>) -> bool { + allowed.paths.iter().any(|candidate| candidate == path) } fn token_byte(byte: u8) -> bool { diff --git a/tests/hooks.rs b/tests/hooks.rs index bc910b0..bab4368 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -591,6 +591,90 @@ async fn the_exit_policy_blocks_only_on_request_and_never_reads_a_gap_as_clean() assert!(staged.contains("+fn main() { retry() }")); } +/// A pre-commit patch starts at the upstream merge-base, so a file the +/// preflight refuses in an unpushed commit is refused again at every later +/// commit. `allowPath` is the hook's `--allow-path`: each exact path it lists +/// is uploaded, and a refusal names it instead of the flag a hook cannot take. +#[tokio::test] +async fn allow_path_lets_later_commits_past_a_refusal_in_unpushed_history() { + let checkout = Checkout::new().await; + checkout + .commit(".env.example", "DATABASE_URL=postgres://localhost/dev\n") + .await; + let token = format!("ghp_{}", "A".repeat(36)); + checkout + .commit("config.rs", &format!("const TOKEN: &str = \"{token}\";\n")) + .await; + tokio::fs::write(checkout.root().join("orders.rs"), "fn main() { retry() }\n") + .await + .unwrap(); + checkout.git(&["add", "orders.rs"]).await; + let uploads = Uploads::default(); + let origin = serve(uploads.clone(), "WARNING", false).await; + let run = ["hook", "run", "pre-commit"]; + checkout + .git(&["config", "proofline.hook.pre-commit.onIncomplete", "block"]) + .await; + let key = "proofline.hook.pre-commit.allowPath"; + + let env_file = checkout.proofline(&origin, &run, "").await; + let text = stderr(&env_file); + assert_eq!(env_file.status.code(), Some(1), "{text}"); + assert!( + text.contains( + "sensitive .env path \".env.example\"; remove it before upload, or allow that exact path with git config --add proofline.hook.pre-commit.allowPath" + ), + "{text}" + ); + assert!(!text.contains("--allow-path"), "{text}"); + + checkout + .git(&["config", "--add", key, ".env.example"]) + .await; + let secret = checkout.proofline(&origin, &run, "").await; + let text = stderr(&secret); + assert_eq!(secret.status.code(), Some(1), "{text}"); + assert!( + text.contains( + "a GitHub token at \"config.rs\":1 (new line); remove it before upload, or allow that exact path with git config --add proofline.hook.pre-commit.allowPath" + ), + "{text}" + ); + assert!(!text.contains(&token), "{text}"); + assert!(uploads.lock().unwrap().is_empty()); + + checkout.git(&["config", "--add", key, "config.rs"]).await; + let reviewed = checkout.proofline(&origin, &run, "").await; + let text = stderr(&reviewed); + assert_eq!(reviewed.status.code(), Some(0), "{text}"); + assert!(text.contains("WARNING orders.rs:1"), "{text}"); + let patch = uploads.lock().unwrap()[0]["patch"] + .as_str() + .unwrap() + .to_owned(); + assert!(patch.contains("+DATABASE_URL=postgres://localhost/dev")); + assert!(patch.contains("+fn main() { retry() }")); + + // A value that is not an exact repository-relative path is refused by + // name before anything is read or sent, as the other settings are. + for invalid in ["/config.rs", "./config.rs", "src//config.rs", ""] { + checkout.git(&["config", "--add", key, invalid]).await; + let refused = checkout.proofline(&origin, &run, "").await; + let text = stderr(&refused); + assert_eq!(refused.status.code(), Some(1), "{invalid:?}: {text}"); + assert!( + text.contains(&format!( + "{key} is {invalid:?}; set it to an exact repository-relative path from the refusal" + )), + "{invalid:?}: {text}" + ); + checkout + .git(&["config", "--unset", "--fixed-value", key, invalid]) + .await; + } + assert_eq!(uploads.lock().unwrap().len(), 1); +} + /// Runs the pre-commit hook against a running review whose reads return /// `script` in turn, with `mode=block`, `onIncomplete=warn` and an /// eight-second timeout. Returns the reads that started and the output. From 88c929bfc1f86113a4bbedbb3092b6fa141c0ace Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Wed, 2 Dec 2026 12:45:34 +0200 Subject: [PATCH 2/2] Refuse a hook allowPath value that is not UTF-8 --- src/git.rs | 18 +++++++++++++----- src/hooks.rs | 22 ++++++++++++++++------ tests/hooks.rs | 24 ++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 11 deletions(-) diff --git a/src/git.rs b/src/git.rs index 4ec9137..a46eda9 100644 --- a/src/git.rs +++ b/src/git.rs @@ -539,8 +539,10 @@ pub async fn config(dir: &Path, key: &str) -> Result, GitError> { } /// Every value of a multi-valued `key`, in the order Git reads them, or -/// none when it is not set. Values are read whole, so one may hold any byte. -pub async fn config_all(dir: &Path, key: &str) -> Result, GitError> { +/// none when it is not set. Git ends each value with a NUL, so a value keeps +/// any whitespace or newline Git parsed into it. A value that is not UTF-8 is +/// an `Err` holding its lossy text, for naming it in a refusal only. +pub async fn config_all(dir: &Path, key: &str) -> Result>, GitError> { let output = Command::new("git") .arg("-C") .arg(dir) @@ -549,9 +551,15 @@ pub async fn config_all(dir: &Path, key: &str) -> Result, GitError> .await .map_err(|error| GitError::Unavailable(error.to_string()))?; match output.status.code() { - Some(0) => Ok(String::from_utf8_lossy(&output.stdout) - .split_terminator('\0') - .map(str::to_owned) + Some(0) => Ok(output + .stdout + .strip_suffix(&[0]) + .unwrap_or(&output.stdout) + .split(|byte| *byte == 0) + .map(|value| { + String::from_utf8(value.to_vec()) + .map_err(|_| String::from_utf8_lossy(value).into_owned()) + }) .collect()), // `git config --get-all` exits 1 for a key that is not set. Some(1) => Ok(Vec::new()), diff --git a/src/hooks.rs b/src/hooks.rs index fb12057..4f31360 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -315,12 +315,22 @@ async fn settings(dir: &Path, hook: Hook) -> anyhow::Result { // A pre-commit patch holds every unpushed commit, so a file refused once // is refused at each later commit until it is allowed here or pushed. let key_allow = format!("proofline.hook.{}.allowPath", hook.name()); - let allow_paths = git::config_all(dir, &key_allow).await?; - if let Some(path) = allow_paths.iter().find(|path| !preflight::exact_path(path)) { - bail!( - "{key_allow} is {:?}; set it to an exact repository-relative path from the refusal", - one_line(path) - ); + // A value that is not UTF-8 is refused rather than read lossily: a + // refused patch's paths may be read lossily too, and two different paths + // could then match one value. + let mut allow_paths = Vec::new(); + for value in git::config_all(dir, &key_allow).await? { + match value { + Ok(path) if preflight::exact_path(&path) => allow_paths.push(path), + Ok(path) => bail!( + "{key_allow} is {:?}; set it to an exact repository-relative path from the refusal", + one_line(&path) + ), + Err(lossy) => bail!( + "{key_allow} is {:?}, which is not UTF-8; set it to an exact repository-relative path from the refusal", + one_line(&lossy) + ), + } } Ok(Settings { mode: mode(value("mode").await?)?, diff --git a/tests/hooks.rs b/tests/hooks.rs index bab4368..0bdb2e3 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -672,6 +672,30 @@ async fn allow_path_lets_later_commits_past_a_refusal_in_unpushed_history() { .git(&["config", "--unset", "--fixed-value", key, invalid]) .await; } + + // A value that is not UTF-8 is refused by name too. Read lossily, it + // would match any path whose invalid bytes read the same way. + let mut config = tokio::fs::OpenOptions::new() + .append(true) + .open(checkout.root().join(".git/config")) + .await + .unwrap(); + tokio::io::AsyncWriteExt::write_all( + &mut config, + b"[proofline \"hook.pre-commit\"]\n\tallowPath = config\xff.rs\n", + ) + .await + .unwrap(); + drop(config); + let not_utf8 = checkout.proofline(&origin, &run, "").await; + let text = stderr(¬_utf8); + assert_eq!(not_utf8.status.code(), Some(1), "{text}"); + assert!( + text.contains(&format!( + "{key} is \"config\u{FFFD}.rs\", which is not UTF-8; set it to an exact repository-relative path from the refusal" + )), + "{text}" + ); assert_eq!(uploads.lock().unwrap().len(), 1); }