Skip to content
Open
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
32 changes: 32 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,38 @@ pub async fn config(dir: &Path, key: &str) -> Result<Option<String>, GitError> {
}
}

/// Every value of a multi-valued `key`, in the order Git reads them, or
/// 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<Vec<Result<String, String>>, 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(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()),
_ => 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<PathBuf, GitError> {
Expand Down
45 changes: 39 additions & 6 deletions src/hooks.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<String>,
}

async fn settings(dir: &Path, hook: Hook) -> anyhow::Result<Settings> {
Expand Down Expand Up @@ -309,11 +312,32 @@ async fn settings(dir: &Path, hook: Hook) -> anyhow::Result<Settings> {
)
})?,
};
// 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());
// 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?)?,
fail_on,
on_incomplete: mode(value("onIncomplete").await?)?,
timeout: Duration::from_secs(seconds),
allow_paths,
})
}

Expand Down Expand Up @@ -452,7 +476,7 @@ pub(crate) async fn run(
let mut reports = Vec::new();
let mut api: Option<Result<Api, String>> = 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.
Expand Down Expand Up @@ -480,12 +504,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<LocalChanges, git::GitError>) -> Result<LocalChanges, Report> {
fn ready(
changes: Result<LocalChanges, git::GitError>,
hook: Hook,
allow_paths: &[String],
) -> Result<LocalChanges, Report> {
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)
}

Expand Down Expand Up @@ -748,6 +780,7 @@ mod tests {
fail_on,
on_incomplete,
timeout: Duration::from_secs(60),
allow_paths: Vec::new(),
}
}

Expand Down
8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1222,7 +1222,13 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result<Verdict> {
));
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,
Expand Down
66 changes: 52 additions & 14 deletions src/preflight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.<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;
Expand Down Expand Up @@ -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())
Expand All @@ -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(())
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand Down
108 changes: 108 additions & 0 deletions tests/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,114 @@ 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;
}

// 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(&not_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);
}

/// 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.
Expand Down