diff --git a/src/git.rs b/src/git.rs index 1c392b4..5eedf20 100644 --- a/src/git.rs +++ b/src/git.rs @@ -165,10 +165,36 @@ async fn git(args: &[&str]) -> Result { Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned()) } +/// Controls whether Git subprocesses may lazily fetch missing objects from a +/// promisor remote in a partial clone. +#[derive(Debug, Clone, Copy)] +enum FetchPolicy { + AllowLazy, + Offline, +} + /// Runs git in `dir` and returns its standard output untouched. async fn git_in(dir: &Path, index: Option<&Path>, args: &[&str]) -> Result, GitError> { + git_in_with_policy(dir, index, FetchPolicy::AllowLazy, args).await +} + +async fn git_in_with_policy( + dir: &Path, + index: Option<&Path>, + policy: FetchPolicy, + args: &[&str], +) -> Result, GitError> { let mut command = Command::new("git"); - command.arg("-C").arg(dir).args(args); + command.arg("-C").arg(dir); + if matches!(policy, FetchPolicy::Offline) { + // Empty `core.fsmonitor=` disables fsmonitor on both Git <= 2.35.1 + // (which treated `false` as a hook path) and newer releases. + command + .args(["-c", "core.fsmonitor="]) + .env("GIT_NO_LAZY_FETCH", "1") + .env("GIT_ALLOW_PROTOCOL", ""); + } + command.args(args); if let Some(index) = index { command.env("GIT_INDEX_FILE", index); } @@ -186,7 +212,15 @@ async fn git_in(dir: &Path, index: Option<&Path>, args: &[&str]) -> Result Result { - let output = git_in(dir, None, args).await?; + line_in_with_policy(dir, FetchPolicy::AllowLazy, args).await +} + +async fn line_in_with_policy( + dir: &Path, + policy: FetchPolicy, + args: &[&str], +) -> Result { + let output = git_in_with_policy(dir, None, policy, args).await?; Ok(String::from_utf8_lossy(&output).trim().to_owned()) } @@ -220,13 +254,16 @@ async fn merge_base( remote: &str, commit: &str, targets: &[&str], + policy: FetchPolicy, ) -> Result { for target in targets { - if line_in(dir, &["rev-parse", "--verify", "--quiet", target]) + if line_in_with_policy(dir, policy, &["rev-parse", "--verify", "--quiet", target]) .await .is_ok() { - return commit_sha(&line_in(dir, &["merge-base", commit, target]).await?); + return commit_sha( + &line_in_with_policy(dir, policy, &["merge-base", commit, target]).await?, + ); } } Err(GitError::NoBase(remote.to_owned())) @@ -234,9 +271,16 @@ async fn merge_base( /// The merge-base of `HEAD` with its upstream branch, or with `remote`'s /// default branch when there is no upstream. -async fn base(dir: &Path, remote: &str) -> Result { +async fn base(dir: &Path, remote: &str, policy: FetchPolicy) -> Result { let default = format!("refs/remotes/{remote}/HEAD"); - merge_base(dir, remote, "HEAD", &["@{upstream}", default.as_str()]).await + merge_base( + dir, + remote, + "HEAD", + &["@{upstream}", default.as_str()], + policy, + ) + .await } /// Which local bytes contribute to the patch against its pinned base. @@ -258,37 +302,67 @@ pub async fn local_changes( selection: LocalSelection, path: Option<&str>, ) -> Result { - let root = line_in(dir, &["rev-parse", "--show-toplevel"]).await?; + local_changes_with_policy(dir, remote, selection, path, FetchPolicy::AllowLazy).await +} + +/// Same as [`local_changes`], but forbids lazy promisor fetches in partial +/// clones so offline preflight never initiates Git network traffic. +pub async fn local_changes_offline( + dir: &Path, + remote: &str, + selection: LocalSelection, + path: Option<&str>, +) -> Result { + local_changes_with_policy(dir, remote, selection, path, FetchPolicy::Offline).await +} + +async fn local_changes_with_policy( + dir: &Path, + remote: &str, + selection: LocalSelection, + path: Option<&str>, + policy: FetchPolicy, +) -> Result { + let root = line_in_with_policy(dir, policy, &["rev-parse", "--show-toplevel"]).await?; let root = Path::new(&root); - let base_commit_sha = base(root, remote).await?; + let base_commit_sha = base(root, remote, policy).await?; let scratch = tempfile::tempdir() .map_err(|error| GitError::Unavailable(format!("no temporary directory: {error}")))?; let index = scratch.path().join("index"); - copy_index(root, &index).await?; + copy_index(root, &index, policy).await?; let add = match selection { LocalSelection::Tracked => Some("--update"), LocalSelection::Staged => None, LocalSelection::IncludeUntracked => Some("--all"), }; if let Some(add) = add { - git_in( - root, - Some(&index), - &["-c", "advice.addEmbeddedRepo=false", "add", add], - ) - .await?; + let mut add_args = vec!["-c", "advice.addEmbeddedRepo=false"]; + let hooks_config; + if matches!(policy, FetchPolicy::Offline) { + let empty_hooks = scratch.path().join("hooks"); + tokio::fs::create_dir_all(&empty_hooks) + .await + .map_err(|error| { + GitError::Unavailable(format!("could not isolate hooks: {error}")) + })?; + hooks_config = format!("core.hooksPath={}", empty_hooks.display()); + add_args.extend(["-c", hooks_config.as_str()]); + } + add_args.extend(["add", add]); + git_in_with_policy(root, Some(&index), policy, &add_args).await?; } if let Some(path) = path { - check_one_path(root, &index, &base_commit_sha, path).await?; + check_one_path(root, &index, &base_commit_sha, path, policy).await?; } - diff(root, Some(&index), base_commit_sha, None, path).await + diff(root, Some(&index), base_commit_sha, None, path, policy).await } /// Copies the repository's index to `index`. A repository with nothing /// staged yet has no index, which leaves `index` absent too. -async fn copy_index(root: &Path, index: &Path) -> Result<(), GitError> { - let current = line_in( +async fn copy_index(root: &Path, index: &Path, policy: FetchPolicy) -> Result<(), GitError> { + let current = line_in_with_policy( root, + policy, &["rev-parse", "--path-format=absolute", "--git-path", "index"], ) .await?; @@ -308,19 +382,22 @@ async fn check_one_path( index: &Path, base_commit_sha: &str, path: &str, + policy: FetchPolicy, ) -> Result<(), GitError> { if path.contains('\0') || path.split('/').any(|part| matches!(part, "" | "." | "..")) { return Err(GitError::InvalidLocalPath(path.to_owned())); } - let indexed = git_in( + let indexed = git_in_with_policy( root, Some(index), + policy, &["--literal-pathspecs", "ls-files", "-z", "--", path], ) .await?; - let base_paths = git_in( + let base_paths = git_in_with_policy( root, None, + policy, &[ "--literal-pathspecs", "ls-tree", @@ -355,14 +432,29 @@ async fn check_one_path( pub async fn range_changes(dir: &Path, base: &str, head: &str) -> Result { let root = line_in(dir, &["rev-parse", "--show-toplevel"]).await?; let head = commit_sha(head)?; - diff(Path::new(&root), None, commit_sha(base)?, Some(&head), None).await + diff( + Path::new(&root), + None, + commit_sha(base)?, + Some(&head), + None, + FetchPolicy::AllowLazy, + ) + .await } /// The base of a branch the remote does not have yet: its merge-base with /// `remote`'s default branch. pub async fn new_branch_base(dir: &Path, remote: &str, head: &str) -> Result { let default = format!("refs/remotes/{remote}/HEAD"); - merge_base(dir, remote, &commit_sha(head)?, &[default.as_str()]).await + merge_base( + dir, + remote, + &commit_sha(head)?, + &[default.as_str()], + FetchPolicy::AllowLazy, + ) + .await } /// The patch from `base_commit_sha` to `head`, or to `index` when `head` is @@ -373,6 +465,7 @@ async fn diff( base_commit_sha: String, head: Option<&str>, path: Option<&str>, + policy: FetchPolicy, ) -> Result { let mut args = vec![ "--literal-pathspecs", @@ -407,7 +500,7 @@ async fn diff( args.extend(head); args.push("--"); args.extend(path); - let output = git_in(root, index, &args).await?; + let output = git_in_with_policy(root, index, policy, &args).await?; let (paths, patch) = diff_paths(&output)?; if patch.len() > MAX_PATCH_BYTES { return Err(GitError::TooLarge(patch.len().div_ceil(1 << 20))); diff --git a/src/lib.rs b/src/lib.rs index bcffa71..4051b91 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -157,6 +157,14 @@ enum Command { /// Review the checkout's local changes, pushed commits, or an open pull /// request's current head. Review(ReviewArgs), + /// Inspect the checkout's local patch and check for sensitive files or + /// credentials without signing in or contacting Proofline. + /// + /// Working-tree mode stages changes into a scratch index, which may run + /// configured Git clean filters or user-configured Git hooks; pass + /// `--staged` to inspect the existing index without staging working-tree + /// files. + Preflight(PreflightArgs), /// Stop your own pending or running local patch, pushed-commit or named-file review. Stop(StopArgs), /// Show the findings of the latest review of a commit or pull request. @@ -290,6 +298,29 @@ struct LocalSelectionArgs { include_untracked: bool, } +#[derive(Debug, Args)] +struct PreflightArgs { + /// Inspect the original index against the base, excluding unstaged changes. + #[arg(long, conflicts_with = "include_untracked")] + staged: bool, + /// Include untracked files that Git does not ignore in the working-tree check. + #[arg(long, conflicts_with = "staged")] + include_untracked: bool, + /// Inspect only this literal repository-relative file in the local patch. + #[arg(long, value_name = "PATH")] + path: Option, + /// Allow secret-shaped patch content from this exact repository-relative + /// path. Repeat for more paths. + #[arg(long, value_name = "PATH")] + allow_path: Vec, + /// Git remote that names the base branch when there is no upstream. + #[arg(long, default_value = "origin")] + remote: String, + /// Print the preflight report as JSON. + #[arg(long)] + json: bool, +} + #[derive(Debug, Args)] struct ReviewArgs { /// Print the JSON result schema without requesting or reading a review. @@ -419,6 +450,9 @@ pub enum Verdict { /// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller. pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + if let Command::Preflight(args) = &cli.command { + return run_preflight(args).await; + } if let Some(path) = &cli.ca_cert { tls::trust(path)?; } @@ -448,6 +482,7 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result unreachable!("preflight returns before TLS setup"), Command::Update => update::install().await.map(|()| Verdict::Done), Command::UpdateCheck => { update::check().await; @@ -1033,6 +1068,130 @@ async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result { finish(api, requested.review_id, args).await } +#[derive(Debug, serde::Serialize)] +struct PreflightFindingOutput { + category: &'static str, + path: String, + #[serde(skip_serializing_if = "Option::is_none")] + line: Option, + #[serde(skip_serializing_if = "Option::is_none")] + coordinate: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + kind: Option<&'static str>, + message: String, +} + +#[derive(Debug, serde::Serialize)] +struct PreflightReport { + base_commit_sha: String, + files: usize, + paths: Vec, + patch_bytes: usize, + passed: bool, + findings: Vec, +} + +/// Inspects local changes and runs the full secret/sensitive-path preflight +/// locally without signing in or contacting Proofline. +async fn run_preflight(args: &PreflightArgs) -> anyhow::Result { + let selection = if args.staged { + git::LocalSelection::Staged + } else if args.include_untracked { + git::LocalSelection::IncludeUntracked + } else { + git::LocalSelection::Tracked + }; + let changes = git::local_changes_offline( + std::path::Path::new("."), + &args.remote, + selection, + args.path.as_deref(), + ) + .await?; + let findings = preflight::scan(&changes, &args.allow_path)?; + let files = changes.files(); + let paths = preflight::patch_paths(&changes); + let patch_bytes = changes.patch.len(); + let passed = findings.is_empty(); + let output_findings: Vec = findings + .iter() + .map(|finding| match finding { + preflight::Finding::EnvironmentPath { path } => PreflightFindingOutput { + category: "environment_path", + path: path.clone(), + line: None, + coordinate: None, + kind: None, + message: finding.message(), + }, + preflight::Finding::Secret { + path, + line, + coordinate, + kind, + } => PreflightFindingOutput { + category: "secret", + path: path.clone(), + line: Some(*line), + coordinate: Some(coordinate), + kind: Some(kind), + message: finding.message(), + }, + }) + .collect(); + + let mut stdout = std::io::stdout().lock(); + if args.json { + let report = PreflightReport { + base_commit_sha: changes.base_commit_sha, + files, + paths, + patch_bytes, + passed, + findings: output_findings, + }; + writeln!(stdout, "{}", serde_json::to_string_pretty(&report)?)?; + } else if files == 0 { + writeln!( + stdout, + "Nothing to review: the selected local changes match {}.", + changes.base_commit_sha + )?; + } else if passed { + writeln!( + stdout, + "Preflight passed: {files} changed {} ({patch_bytes} bytes) on {}.", + if files == 1 { "file" } else { "files" }, + changes.base_commit_sha + )?; + for path in &paths { + writeln!(stdout, " {path}")?; + } + } else { + writeln!( + stdout, + "Preflight blocked: {} {} across {files} changed {} ({patch_bytes} bytes) on {}:", + output_findings.len(), + if output_findings.len() == 1 { + "issue" + } else { + "issues" + }, + if files == 1 { "file" } else { "files" }, + changes.base_commit_sha + )?; + for finding in &output_findings { + writeln!(stdout, " - {}", finding.message)?; + } + } + + Ok(if passed { + Verdict::Done + } else { + Verdict::Blocked + }) +} + /// 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 { diff --git a/src/preflight.rs b/src/preflight.rs index 592ec54..595aa5e 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -25,25 +25,103 @@ pub(crate) enum PreflightError { InvalidPatch, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Finding { + EnvironmentPath { + path: String, + }, + Secret { + path: String, + line: usize, + coordinate: &'static str, + kind: &'static str, + }, +} + +impl Finding { + pub(crate) fn into_error(self) -> PreflightError { + match self { + Self::EnvironmentPath { path } => PreflightError::EnvironmentPath(path), + Self::Secret { + path, + line, + coordinate, + kind, + } => PreflightError::Secret { + path, + line, + coordinate, + kind, + }, + } + } + + pub(crate) fn message(&self) -> String { + self.clone().into_error().to_string() + } +} + #[derive(Debug)] struct Lines { old: usize, new: usize, } +pub(crate) fn patch_paths(changes: &LocalChanges) -> Vec { + changes + .paths + .iter() + .filter_map(|file| file.new.as_deref().or(file.old.as_deref())) + .map(str::to_owned) + .collect() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ScanMode { + First, + All, +} + pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), PreflightError> { + if let Some(first) = scan_with_mode(changes, allowed, ScanMode::First)? + .into_iter() + .next() + { + return Err(first.into_error()); + } + Ok(()) +} + +/// Inspects the entire local patch and returns every sensitive path or +/// credential-shaped finding without stopping at the first refusal. +pub(crate) fn scan( + changes: &LocalChanges, + allowed: &[String], +) -> Result, PreflightError> { + scan_with_mode(changes, allowed, ScanMode::All) +} + +fn scan_with_mode( + changes: &LocalChanges, + allowed: &[String], + mode: ScanMode, +) -> Result, PreflightError> { for path in allowed { if path.starts_with('/') || path.split('/').any(|part| matches!(part, "" | "." | "..")) { return Err(PreflightError::InvalidAllowPath(path.clone())); } } + let mut findings = Vec::new(); let mut paths = changes.paths.iter(); let mut current = None; let mut hunk = None; 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)?; + environment_paths(file, allowed, mode, &mut findings); + if mode == ScanMode::First && !findings.is_empty() { + return Ok(findings); + } current = Some(file); hunk = None; continue; @@ -58,32 +136,54 @@ pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), Pr "patch line", line, allowed, + mode, + &mut findings, )?; + if mode == ScanMode::First && !findings.is_empty() { + return Ok(findings); + } hunk = Some(hunk_lines(line)?); } else if let Some(lines) = &mut hunk { - inspect_hunk(file, lines, line, allowed)?; + inspect_hunk(file, lines, line, allowed, mode, &mut findings)?; + if mode == ScanMode::First && !findings.is_empty() { + return Ok(findings); + } } } if paths.next().is_some() { return Err(PreflightError::InvalidPatch); } - Ok(()) + Ok(findings) } -fn environment_paths(file: &PatchPaths, allowed: &[String]) -> Result<(), PreflightError> { +fn environment_paths( + file: &PatchPaths, + allowed: &[String], + mode: ScanMode, + findings: &mut Vec, +) { + let mut reported: Option<&str> = None; for path in [&file.old, &file.new] .iter() .filter_map(|path| path.as_deref()) { + if reported == Some(path) { + continue; + } if !is_allowed(path, allowed) && path .split('/') .any(|part| part == ".env" || part.starts_with(".env.")) { - return Err(PreflightError::EnvironmentPath(path.to_owned())); + reported = Some(path); + findings.push(Finding::EnvironmentPath { + path: path.to_owned(), + }); + if mode == ScanMode::First { + return; + } } } - Ok(()) } fn hunk_lines(line: &str) -> Result { @@ -116,12 +216,30 @@ fn inspect_hunk( lines: &mut Lines, line: &str, allowed: &[String], + mode: ScanMode, + findings: &mut Vec, ) -> Result<(), PreflightError> { if let Some(text) = line.strip_prefix('+') { - inspect(file.new.as_deref(), lines.new, "new line", text, allowed)?; + inspect( + file.new.as_deref(), + lines.new, + "new line", + text, + allowed, + mode, + findings, + )?; 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)?; + inspect( + file.old.as_deref(), + lines.old, + "base line", + text, + allowed, + mode, + findings, + )?; lines.old = next_line(lines.old)?; } else if let Some(text) = line.strip_prefix(' ') { inspect( @@ -130,6 +248,8 @@ fn inspect_hunk( "new line", text, allowed, + mode, + findings, )?; lines.old = next_line(lines.old)?; lines.new = next_line(lines.new)?; @@ -149,17 +269,22 @@ fn inspect( coordinate: &'static str, text: &str, allowed: &[String], + mode: ScanMode, + findings: &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 { - path: path.to_owned(), - line, - coordinate, - kind, - }); + if !is_allowed(path, allowed) { + for kind in secret_shapes(text) { + findings.push(Finding::Secret { + path: path.to_owned(), + line, + coordinate, + kind, + }); + if mode == ScanMode::First { + break; + } + } } Ok(()) } @@ -185,6 +310,41 @@ fn base32(byte: u8) -> bool { byte.is_ascii_uppercase() || matches!(byte, b'2'..=b'7') } +/// Standard RFC 4648 base64 data byte (without padding). +fn base64_data(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/') +} + +/// Azure Storage account keys are 64-byte secrets encoded as 88 base64 +/// characters (86 base64 data bytes followed by `==`) after a case-insensitive +/// `AccountKey=` connection-string field. +fn has_azure_storage_key(text: &str) -> bool { + const PREFIX: &[u8] = b"AccountKey="; + const DATA_LEN: usize = 86; + const KEY_LEN: usize = DATA_LEN + 2; + + let bytes = text.as_bytes(); + bytes + .windows(PREFIX.len()) + .enumerate() + .any(|(start, window)| { + if !window.eq_ignore_ascii_case(PREFIX) { + return false; + } + let Some(suffix) = bytes.get(start + PREFIX.len()..) else { + return false; + }; + if suffix.len() < KEY_LEN { + return false; + } + suffix[..DATA_LEN].iter().all(|byte| base64_data(*byte)) + && suffix[DATA_LEN..KEY_LEN] == *b"==" + && suffix + .get(KEY_LEN) + .is_none_or(|next| !base64_data(*next) && *next != b'=') + }) +} + fn has_token(text: &str, prefixes: &[&str], minimum: usize, body: fn(u8) -> bool) -> bool { prefixes.iter().any(|prefix| { text.match_indices(*prefix).any(|(start, prefix)| { @@ -273,20 +433,57 @@ const TOKEN_SHAPES: &[TokenShape] = &[ minimum: 52, body: base32, }, + TokenShape { + kind: "a GitLab personal access token", + prefixes: &["glpat-"], + minimum: 20, + body: token_byte, + }, + TokenShape { + kind: "an npm access token", + prefixes: &["npm_"], + minimum: 36, + body: alphanumeric, + }, + TokenShape { + kind: "a Hugging Face token", + prefixes: &["hf_"], + minimum: 34, + body: alphanumeric, + }, + TokenShape { + kind: "a PyPI API token", + prefixes: &["pypi-AgEIcHlwaS5vcmc"], + minimum: 50, + body: token_byte, + }, ]; /// Literal private-key markers and distinctive credential prefixes. This /// check refuses the original bytes; it never rewrites the reviewed patch. -fn secret_shape(text: &str) -> Option<&'static str> { +fn secret_shapes(text: &str) -> Vec<&'static str> { + let mut kinds = Vec::new(); if (text.contains("-----BEGIN ") || text.contains("-----END ")) && (text.contains("PRIVATE KEY-----") || text.contains("PRIVATE KEY BLOCK-----")) { - return Some("a private-key marker"); + kinds.push("a private-key marker"); } - TOKEN_SHAPES - .iter() - .find(|shape| has_token(text, shape.prefixes, shape.minimum, shape.body)) - .map(|shape| shape.kind) + if has_azure_storage_key(text) { + kinds.push("an Azure Storage account key"); + } + for shape in TOKEN_SHAPES { + if has_token(text, shape.prefixes, shape.minimum, shape.body) + && !kinds.contains(&shape.kind) + { + kinds.push(shape.kind); + } + } + kinds +} + +#[cfg(test)] +fn secret_shape(text: &str) -> Option<&'static str> { + secret_shapes(text).into_iter().next() } #[cfg(test)] @@ -344,6 +541,22 @@ mod tests { '8', "a Proofline token", ), + ( + &["glpat-"][..], + 20, + "Az09_.-", + '!', + "a GitLab personal access token", + ), + (&["npm_"][..], 36, "Az09", '_', "an npm access token"), + (&["hf_"][..], 34, "Az09", '_', "a Hugging Face token"), + ( + &["pypi-AgEIcHlwaS5vcmc"][..], + 50, + "Az09_.-", + '!', + "a PyPI API token", + ), ]; for (prefixes, minimum, alphabet, invalid, label) in cases { let body: String = alphabet.chars().cycle().take(minimum).collect(); @@ -388,4 +601,201 @@ mod tests { None ); } + + #[test] + fn azure_storage_account_keys_require_full_base64_key() { + let key: String = "AZaz09+/".chars().cycle().take(86).collect(); + let connection = format!( + "DefaultEndpointsProtocol=https;AccountName=demo;AccountKey={key}==;EndpointSuffix=core.windows.net" + ); + assert_eq!( + secret_shape(&connection), + Some("an Azure Storage account key") + ); + assert_eq!( + secret_shape(&format!("AccountKey={key}==")), + Some("an Azure Storage account key") + ); + assert_eq!( + secret_shape(&format!("accountkey={key}==;")), + Some("an Azure Storage account key") + ); + assert_eq!( + secret_shape(&format!("ACCOUNTKEY={key}==;")), + Some("an Azure Storage account key") + ); + // Short, missing padding, trailing extra base64 byte, or placeholder must pass. + let short_key: String = key.chars().take(85).collect(); + assert_eq!(secret_shape(&format!("AccountKey={short_key}==;")), None); + assert_eq!(secret_shape(&format!("AccountKey={key}=")), None); + assert_eq!(secret_shape(&format!("AccountKey={key}==A")), None); + assert_eq!(secret_shape("AccountKey=replace-me-in-env;"), None); + } + + #[test] + fn scan_collects_multiple_findings_across_files_and_respects_allow_path() { + use super::{Finding, scan}; + use crate::git::{LocalChanges, PatchPaths}; + + let azure_key = format!("{}==;", "A".repeat(86)); + let gitlab = format!("glpat-{}", "a".repeat(20)); + let patch = [ + "diff --git a/.env b/.env".to_owned(), + "--- /dev/null".to_owned(), + "+++ b/.env".to_owned(), + "@@ -0,0 +1 @@".to_owned(), + "+APP_ENV=local".to_owned(), + "diff --git a/infra/storage.tf b/infra/storage.tf".to_owned(), + "--- a/infra/storage.tf".to_owned(), + "+++ b/infra/storage.tf".to_owned(), + "@@ -1,1 +1,2 @@".to_owned(), + " resource \"azurerm_storage_account\" \"main\" {}".to_owned(), + format!("+AccountKey={azure_key}"), + "diff --git a/scripts/release.sh b/scripts/release.sh".to_owned(), + "--- a/scripts/release.sh".to_owned(), + "+++ b/scripts/release.sh".to_owned(), + "@@ -1,1 +1,2 @@".to_owned(), + " #!/bin/sh".to_owned(), + format!("+TOKEN={gitlab}"), + String::new(), + ] + .join("\n"); + let changes = LocalChanges { + base_commit_sha: "a".repeat(40), + patch, + paths: vec![ + PatchPaths { + old: None, + new: Some(".env".to_owned()), + }, + PatchPaths { + old: Some("infra/storage.tf".to_owned()), + new: Some("infra/storage.tf".to_owned()), + }, + PatchPaths { + old: Some("scripts/release.sh".to_owned()), + new: Some("scripts/release.sh".to_owned()), + }, + ], + }; + + let findings = scan(&changes, &[]).expect("patch parses cleanly"); + assert_eq!( + findings, + vec![ + Finding::EnvironmentPath { + path: ".env".to_owned(), + }, + Finding::Secret { + path: "infra/storage.tf".to_owned(), + line: 2, + coordinate: "new line", + kind: "an Azure Storage account key", + }, + Finding::Secret { + path: "scripts/release.sh".to_owned(), + line: 2, + coordinate: "new line", + kind: "a GitLab personal access token", + }, + ] + ); + + let allowed = vec!["infra/storage.tf".to_owned()]; + let filtered = scan(&changes, &allowed).expect("patch parses cleanly"); + assert_eq!(filtered.len(), 2); + assert!(filtered.iter().all(|f| match f { + Finding::EnvironmentPath { path } | Finding::Secret { path, .. } => { + path != "infra/storage.tf" + } + })); + } + + #[test] + fn scan_reports_every_credential_family_on_a_single_line() { + use super::{Finding, scan}; + use crate::git::{LocalChanges, PatchPaths}; + + let gitlab = format!("glpat-{}", "a".repeat(20)); + let npm = format!("npm_{}", "b".repeat(36)); + let patch = [ + "diff --git a/ci.env.sh b/ci.env.sh".to_owned(), + "--- /dev/null".to_owned(), + "+++ b/ci.env.sh".to_owned(), + "@@ -0,0 +1 @@".to_owned(), + format!("+GL={gitlab} NPM={npm}"), + String::new(), + ] + .join("\n"); + let changes = LocalChanges { + base_commit_sha: "a".repeat(40), + patch, + paths: vec![PatchPaths { + old: None, + new: Some("ci.env.sh".to_owned()), + }], + }; + + let findings = scan(&changes, &[]).expect("patch parses cleanly"); + assert_eq!( + findings, + vec![ + Finding::Secret { + path: "ci.env.sh".to_owned(), + line: 1, + coordinate: "new line", + kind: "a GitLab personal access token", + }, + Finding::Secret { + path: "ci.env.sh".to_owned(), + line: 1, + coordinate: "new line", + kind: "an npm access token", + }, + ] + ); + } + + #[test] + fn check_returns_earlier_refusal_before_later_patch_parse_error() { + use super::{PreflightError, check}; + use crate::git::{LocalChanges, PatchPaths}; + + let gitlab = format!("glpat-{}", "a".repeat(20)); + let patch = [ + "diff --git a/first.rs b/first.rs".to_owned(), + "--- /dev/null".to_owned(), + "+++ b/first.rs".to_owned(), + "@@ -0,0 +1 @@".to_owned(), + format!("+const TOKEN: &str = \"{gitlab}\";"), + "diff --git a/second.rs b/second.rs".to_owned(), + "@@ broken @@".to_owned(), + String::new(), + ] + .join("\n"); + let changes = LocalChanges { + base_commit_sha: "a".repeat(40), + patch, + paths: vec![ + PatchPaths { + old: None, + new: Some("first.rs".to_owned()), + }, + PatchPaths { + old: None, + new: Some("second.rs".to_owned()), + }, + ], + }; + + assert!(matches!( + check(&changes, &[]), + Err(PreflightError::Secret { + ref path, + line: 1, + kind: "a GitLab personal access token", + .. + }) if path == "first.rs" + )); + } } diff --git a/src/update.rs b/src/update.rs index d001d62..5e46c8c 100644 --- a/src/update.rs +++ b/src/update.rs @@ -81,6 +81,41 @@ fn write_cache(path: &Path, cache: &Cache) -> anyhow::Result<()> { Ok(()) } +fn subcommand(args: &[std::ffi::OsString]) -> Option<&std::ffi::OsStr> { + let mut index = 0; + while let Some(arg) = args.get(index) { + if arg == "--base-url" || arg == "--org" || arg == "--ca-cert" { + let value = args.get(index + 1)?; + if matches!(value.as_encoded_bytes(), [b'-', _, ..]) { + return None; + } + index += 2; + continue; + } + let bytes = arg.as_encoded_bytes(); + if bytes.starts_with(b"--base-url=") + || bytes.starts_with(b"--org=") + || bytes.starts_with(b"--ca-cert=") + { + index += 1; + continue; + } + if bytes.first().is_some_and(|byte| *byte == b'-') { + return None; + } + return Some(arg.as_os_str()); + } + None +} + +fn is_exempt(args: &[std::ffi::OsString]) -> bool { + args.iter() + // A shell evaluates `completions` at every start-up; keep it offline. + .any(|arg| arg == "update" || arg == "__update-check" || arg == "completions") + // `preflight` promises offline inspection only when invoked as the subcommand. + || subcommand(args).is_some_and(|cmd| cmd == "preflight") +} + /// Reads only local state; discovery continues in a child with closed streams. /// Call before starting the runtime, including for help and version invocations. pub fn on_invocation() { @@ -88,11 +123,7 @@ pub fn on_invocation() { return; } let args: Vec<_> = std::env::args_os().skip(1).collect(); - if args - .iter() - // A shell evaluates `completions` at every start-up; keep it offline. - .any(|arg| arg == "update" || arg == "__update-check" || arg == "completions") - { + if is_exempt(&args) { return; } let Some(path) = cache_path() else { diff --git a/src/update/tests.rs b/src/update/tests.rs index d7387c5..62148da 100644 --- a/src/update/tests.rs +++ b/src/update/tests.rs @@ -372,3 +372,44 @@ fn installed_symlink_is_reported_as_a_symlink() { assert!(error.contains("symbolic link"), "{executable:?}: {error}"); } } + +#[test] +fn preflight_exemption_matches_only_top_level_subcommand() { + let to_args = |items: &[&str]| -> Vec { + items.iter().map(std::ffi::OsString::from).collect() + }; + + assert!(is_exempt(&to_args(&["preflight"]))); + assert!(is_exempt(&to_args(&[ + "--base-url", + "http://127.0.0.1:1", + "--org", + "00000000-0000-0000-0000-000000000001", + "--ca-cert", + "/tmp/ca.pem", + "preflight", + "--json", + ]))); + assert!(is_exempt(&to_args(&[ + "--base-url=http://127.0.0.1:1", + "preflight", + ]))); + assert!(is_exempt(&to_args(&["--ca-cert", "-", "preflight"]))); + assert!(is_exempt(&to_args(&["--base-url", "-", "preflight"]))); + assert!(!is_exempt(&to_args(&[ + "review", + "--local", + "--path", + "preflight", + ]))); + assert!(!is_exempt(&to_args(&["--ca-cert", "preflight", "status"]))); + assert!(!is_exempt(&to_args(&["--help", "preflight"]))); + assert!(!is_exempt(&to_args(&["-h", "preflight"]))); + assert!(!is_exempt(&to_args(&["--version", "preflight"]))); + assert!(!is_exempt(&to_args(&["-V", "preflight"]))); + assert!(!is_exempt(&to_args(&["-hV", "preflight"]))); + assert!(!is_exempt(&to_args(&["-Vh", "preflight"]))); + assert!(!is_exempt(&to_args(&["--unknown", "preflight"]))); + assert!(!is_exempt(&to_args(&["--ca-cert", "--help", "preflight"]))); + assert!(!is_exempt(&to_args(&["--base-url", "-V", "preflight"]))); +} diff --git a/tests/preflight.rs b/tests/preflight.rs new file mode 100644 index 0000000..6dd947d --- /dev/null +++ b/tests/preflight.rs @@ -0,0 +1,363 @@ +//! Offline `proofline preflight` inspection and credential detection tests. + +use std::path::Path; +use std::process::Output; + +use serde_json::Value; +use tempfile::TempDir; +use tokio::process::Command; + +struct TempRepo { + dir: TempDir, + cache: TempDir, +} + +impl TempRepo { + async fn new(_label: &str) -> Self { + let dir = TempDir::new().expect("create temp dir"); + let cache = TempDir::new().expect("create cache dir"); + run_git(dir.path(), &["init", "-b", "main"]).await; + run_git(dir.path(), &["config", "user.email", "dev@example.com"]).await; + run_git(dir.path(), &["config", "user.name", "Dev"]).await; + std::fs::write(dir.path().join("app.rs"), "fn main() {}\n").expect("write app.rs"); + run_git(dir.path(), &["add", "app.rs"]).await; + run_git(dir.path(), &["commit", "-m", "initial"]).await; + let head = run_git(dir.path(), &["rev-parse", "HEAD"]).await; + run_git( + dir.path(), + &["update-ref", "refs/remotes/origin/main", head.trim()], + ) + .await; + run_git( + dir.path(), + &[ + "symbolic-ref", + "refs/remotes/origin/HEAD", + "refs/remotes/origin/main", + ], + ) + .await; + Self { dir, cache } + } + + fn path(&self) -> &Path { + self.dir.path() + } + + fn cache_path(&self) -> &Path { + self.cache.path() + } + + fn write(&self, rel: &str, content: &str) { + let full = self.dir.path().join(rel); + if let Some(parent) = full.parent() { + std::fs::create_dir_all(parent).expect("create parent dirs"); + } + std::fs::write(full, content).expect("write file"); + } + + async fn run_cli(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_proofline")) + .current_dir(self.dir.path()) + // Unreachable origin, empty token, and update checks left enabled prove + // preflight stays offline without opting out via PROOFLINE_NO_UPDATE_CHECK. + .env_remove("PROOFLINE_TOKEN") + .env_remove("PROOFLINE_NO_UPDATE_CHECK") + .env("HOME", self.cache.path()) + .env("XDG_CACHE_HOME", self.cache.path()) + .env("LOCALAPPDATA", self.cache.path()) + .env( + "PROOFLINE_CA_CERT", + self.cache.path().join("missing-ca.pem"), + ) + .env("PROOFLINE_BASE_URL", "http://127.0.0.1:1") + .args(args) + .output() + .await + .expect("run proofline binary") + } +} + +async fn run_git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(dir) + .args(args) + .output() + .await + .expect("run git"); + assert!( + out.status.success(), + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).into_owned() +} + +#[tokio::test] +async fn preflight_passes_offline_for_clean_changes_in_text_and_json() { + let repo = TempRepo::new("clean").await; + repo.write("app.rs", "fn main() { println!(\"hello\"); }\n"); + + let text_out = repo.run_cli(&["preflight"]).await; + assert!( + text_out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&text_out.stderr) + ); + let stdout = String::from_utf8_lossy(&text_out.stdout); + assert!( + stdout.contains("Preflight passed: 1 changed file"), + "{stdout}" + ); + assert!(stdout.contains("app.rs"), "{stdout}"); + + let json_out = repo.run_cli(&["preflight", "--json"]).await; + assert!(json_out.status.success()); + let report: Value = serde_json::from_slice(&json_out.stdout).expect("valid json"); + assert_eq!(report["passed"], true); + assert_eq!(report["files"], 1); + assert_eq!(report["paths"], serde_json::json!(["app.rs"])); + assert!(report["patch_bytes"].as_u64().unwrap_or(0) > 0); + assert_eq!(report["findings"].as_array().map(Vec::len), Some(0)); + assert!( + !repo.cache_path().join("proofline").exists(), + "preflight must not trigger startup update discovery or touch the update cache" + ); +} + +#[tokio::test] +async fn preflight_reports_all_findings_including_azure_and_registry_tokens_without_leaking_values() +{ + let repo = TempRepo::new("secrets").await; + let azure_key = format!("{}==;", "A".repeat(86)); + let gitlab_token = format!("glpat-{}", "b".repeat(20)); + let npm_token = format!("npm_{}", "c".repeat(36)); + let hf_token = format!("hf_{}", "d".repeat(34)); + let pypi_token = format!("pypi-AgEIcHlwaS5vcmc{}", "e".repeat(50)); + + repo.write(".env", "APP_ENV=local\n"); + repo.write( + "app.rs", + &format!( + "const AZ: &str = \"DefaultEndpointsProtocol=https;AccountName=demo;AccountKey={azure_key}EndpointSuffix=core.windows.net\";\n\ + const GL: &str = \"{gitlab_token}\";\n\ + const NPM: &str = \"{npm_token}\";\n\ + const HF: &str = \"{hf_token}\";\n\ + const PYPI: &str = \"{pypi_token}\";\n" + ), + ); + + let out = repo + .run_cli(&["preflight", "--include-untracked", "--json"]) + .await; + assert!( + !out.status.success(), + "preflight must fail when secrets exist" + ); + + let stdout_str = String::from_utf8_lossy(&out.stdout); + let stderr_str = String::from_utf8_lossy(&out.stderr); + for secret in [ + &azure_key, + &gitlab_token, + &npm_token, + &hf_token, + &pypi_token, + ] { + assert!(!stdout_str.contains(secret), "secret leaked to stdout"); + assert!(!stderr_str.contains(secret), "secret leaked to stderr"); + } + + let report: Value = serde_json::from_slice(&out.stdout).expect("valid json"); + assert_eq!(report["passed"], false); + let findings = report["findings"].as_array().expect("findings array"); + assert_eq!( + findings.len(), + 6, + "expected .env + 5 secret findings: {report}" + ); + let kinds: Vec<&str> = findings.iter().filter_map(|f| f["kind"].as_str()).collect(); + assert_eq!( + kinds, + vec![ + "an Azure Storage account key", + "a GitLab personal access token", + "an npm access token", + "a Hugging Face token", + "a PyPI API token", + ] + ); + assert_eq!(findings[0]["category"], "environment_path"); + assert_eq!(findings[0]["path"], ".env"); +} + +#[tokio::test] +async fn preflight_respects_allow_path_and_staged_selection() { + let repo = TempRepo::new("allow-staged").await; + let gitlab_token = format!("glpat-{}", "z".repeat(20)); + + // Stage a clean change to app.rs while leaving a secret unstaged in another tracked file. + repo.write("notes.txt", "safe\n"); + run_git(repo.path(), &["add", "notes.txt"]).await; + run_git(repo.path(), &["commit", "-m", "add notes"]).await; + let head = run_git(repo.path(), &["rev-parse", "HEAD"]).await; + run_git( + repo.path(), + &["update-ref", "refs/remotes/origin/main", head.trim()], + ) + .await; + + repo.write("app.rs", "fn main() { println!(\"staged\"); }\n"); + run_git(repo.path(), &["add", "app.rs"]).await; + repo.write("notes.txt", &format!("token={gitlab_token}\n")); + + let unstaged_fail = repo.run_cli(&["preflight", "--json"]).await; + assert!(!unstaged_fail.status.success()); + + let staged_out = repo.run_cli(&["preflight", "--staged", "--json"]).await; + assert!(staged_out.status.success()); + let staged_report: Value = serde_json::from_slice(&staged_out.stdout).expect("valid json"); + assert_eq!(staged_report["passed"], true); + assert_eq!(staged_report["paths"], serde_json::json!(["app.rs"])); + + let allowed_out = repo + .run_cli(&["preflight", "--allow-path", "notes.txt", "--json"]) + .await; + assert!(allowed_out.status.success()); + let allowed_report: Value = serde_json::from_slice(&allowed_out.stdout).expect("valid json"); + assert_eq!(allowed_report["passed"], true); +} + +#[tokio::test] +async fn preflight_does_not_lazy_fetch_missing_blobs_in_partial_clone() { + let root = TempDir::new().expect("create temp dir"); + let origin = root.path().join("origin.git"); + let seed = root.path().join("seed"); + let partial = root.path().join("partial"); + let cache = root.path().join("cache"); + std::fs::create_dir_all(&origin).expect("create origin dir"); + std::fs::create_dir_all(&seed).expect("create seed dir"); + std::fs::create_dir_all(&cache).expect("create cache dir"); + + run_git(&origin, &["init", "--bare", "-b", "main"]).await; + run_git(&origin, &["config", "uploadpack.allowFilter", "true"]).await; + + run_git(&seed, &["init", "-b", "main"]).await; + run_git(&seed, &["config", "user.email", "dev@example.com"]).await; + run_git(&seed, &["config", "user.name", "Dev"]).await; + std::fs::write(seed.join("app.rs"), "fn main() { /* v1 */ }\n").expect("write v1"); + run_git(&seed, &["add", "app.rs"]).await; + run_git(&seed, &["commit", "-m", "v1"]).await; + let base_sha = run_git(&seed, &["rev-parse", "HEAD"]).await; + std::fs::write(seed.join("app.rs"), "fn main() { /* v2 */ }\n").expect("write v2"); + run_git(&seed, &["add", "app.rs"]).await; + run_git(&seed, &["commit", "-m", "v2"]).await; + run_git( + &seed, + &["remote", "add", "origin", origin.to_str().expect("utf8")], + ) + .await; + run_git(&seed, &["push", "origin", "main"]).await; + + // Blobless clone has v2's blob in the working tree, but NOT v1's blob. + let origin_url = format!("file://{}", origin.display()); + run_git( + root.path(), + &[ + "clone", + "--filter=blob:none", + &origin_url, + partial.to_str().expect("utf8"), + ], + ) + .await; + // Point origin/main back at v1 so diffing against base requires v1's missing blob. + run_git( + &partial, + &["update-ref", "refs/remotes/origin/main", base_sha.trim()], + ) + .await; + std::fs::write(partial.join("app.rs"), "fn main() { /* v3 */ }\n").expect("write v3"); + run_git(&partial, &["add", "app.rs"]).await; + + let out = Command::new(env!("CARGO_BIN_EXE_proofline")) + .current_dir(&partial) + .env_remove("PROOFLINE_TOKEN") + .env_remove("PROOFLINE_NO_UPDATE_CHECK") + .env("HOME", &cache) + .env("XDG_CACHE_HOME", &cache) + .env("LOCALAPPDATA", &cache) + .env("PROOFLINE_BASE_URL", "http://127.0.0.1:1") + .args(["preflight", "--staged"]) + .output() + .await + .expect("run proofline binary"); + + assert!( + !out.status.success(), + "preflight must fail offline instead of lazily fetching the missing base blob; stdout: {}, stderr: {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("diff") && stderr.contains("failed"), + "expected propagated git missing-object error, got: {stderr}" + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn preflight_does_not_run_post_index_change_or_fsmonitor_hooks() { + use std::os::unix::fs::PermissionsExt as _; + + let repo = TempRepo::new("no-hooks").await; + let marker = repo.cache_path().join("hook-ran"); + let hook_path = repo.path().join(".git/hooks/post-index-change"); + std::fs::write( + &hook_path, + format!("#!/bin/sh\ntouch '{}'\n", marker.display()), + ) + .expect("write post-index-change hook"); + std::fs::set_permissions(&hook_path, std::fs::Permissions::from_mode(0o755)) + .expect("chmod hook"); + + let fsmonitor_marker = repo.cache_path().join("fsmonitor-ran"); + let fsmonitor_hook = repo.cache_path().join("fsmonitor.sh"); + std::fs::write( + &fsmonitor_hook, + format!( + "#!/bin/sh\ntouch '{}'\nprintf '\\0'\n", + fsmonitor_marker.display() + ), + ) + .expect("write fsmonitor hook"); + std::fs::set_permissions(&fsmonitor_hook, std::fs::Permissions::from_mode(0o755)) + .expect("chmod fsmonitor hook"); + run_git( + repo.path(), + &[ + "config", + "core.fsmonitor", + fsmonitor_hook.to_str().expect("utf8"), + ], + ) + .await; + + repo.write("app.rs", "fn main() { println!(\"changed\"); }\n"); + let out = repo.run_cli(&["preflight"]).await; + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert!( + !marker.exists(), + "preflight must not execute repository hooks when writing the scratch index" + ); + assert!( + !fsmonitor_marker.exists(), + "preflight must not execute core.fsmonitor hooks" + ); +}