Skip to main content

aft_base/
git_root_resolution.rs

1//! Resolve a path the user named (a tool's `path` argument, which may start
2//! with `~`) to the root a scan of it uses: the Git checkout containing it,
3//! or a narrow plain folder when it is in no checkout.
4
5use std::path::{Path, PathBuf};
6
7#[derive(Debug)]
8pub enum GitRootResolutionError {
9    PathNotFound(PathBuf),
10    NotAGitRoot,
11    ProtectedScanRoot,
12    Other(String),
13}
14
15pub fn resolve_git_root_from_user_path(
16    project_root: &Path,
17    raw_path: &str,
18    scan_root_is_protected: impl Fn(&Path) -> bool,
19) -> Result<PathBuf, GitRootResolutionError> {
20    let account_home = crate::production_storage::resolve_account_home_dir();
21    let environment_home = home_dir();
22    resolve_git_root_from_user_path_with_homes(
23        project_root,
24        raw_path,
25        account_home.as_deref(),
26        environment_home.as_deref(),
27        scan_root_is_protected,
28    )
29}
30
31fn resolve_git_root_from_user_path_with_homes(
32    project_root: &Path,
33    raw_path: &str,
34    account_home: Option<&Path>,
35    environment_home: Option<&Path>,
36    scan_root_is_protected: impl Fn(&Path) -> bool,
37) -> Result<PathBuf, GitRootResolutionError> {
38    let expanded = expand_tilde_with_home(raw_path, environment_home);
39    let requested = if expanded.is_absolute() {
40        expanded
41    } else {
42        project_root.join(expanded)
43    };
44    if !requested.exists() {
45        return Err(GitRootResolutionError::PathNotFound(requested));
46    }
47
48    let existing = nearest_existing_parent(&requested)
49        .ok_or_else(|| GitRootResolutionError::PathNotFound(requested.clone()))?;
50
51    // `nearest_existing_parent` returns an `fs::canonicalize` result, which on
52    // Windows is a verbatim (`\\?\C:\...`) path. Normalize before comparing the
53    // requested directory with the configured root so aliases such as `.` and
54    // symlinks remain local without requiring the workspace itself to be Git.
55    let existing = crate::path_identity::canonicalize_normalized(&existing);
56    if existing == crate::path_identity::canonicalize_normalized(project_root) {
57        return Ok(project_root.to_path_buf());
58    }
59
60    let git_base = if existing.is_file() {
61        existing.parent().unwrap_or(&existing).to_path_buf()
62    } else {
63        existing
64    };
65    match git_toplevel(&git_base) {
66        Ok(root) => Ok(root),
67        Err(error) if error == "not_a_git_root" => {
68            let account_home = account_home.or(environment_home);
69            // A scan must use the same narrow-root policy as a watcher, even
70            // though it never starts a watcher or builds an index. Exact-file
71            // authorization must not widen into a protected containing folder.
72            if scan_root_is_protected(&git_base) {
73                return Err(GitRootResolutionError::ProtectedScanRoot);
74            }
75            if (!crate::developer_tools::git_usable()
76                && crate::git_probe::repository_marker_or_uncertainty_in_directory(&git_base))
77                || plain_scan_root_is_too_broad(&git_base, account_home, environment_home)
78            {
79                return Err(GitRootResolutionError::NotAGitRoot);
80            }
81            Ok(git_base)
82        }
83        Err(error) => Err(GitRootResolutionError::Other(error)),
84    }
85}
86
87fn plain_scan_root_is_too_broad(
88    root: &Path,
89    account_home: Option<&Path>,
90    environment_home: Option<&Path>,
91) -> bool {
92    // HOME can differ from the OS account home, so a scan root must be narrow
93    // relative to both homes when both are available.
94    match (account_home, environment_home) {
95        (None, None) => project_root_is_too_broad(root, false, None),
96        (account_home, environment_home) => [account_home, environment_home]
97            .into_iter()
98            .flatten()
99            .any(|home| project_root_is_too_broad(root, false, Some(home))),
100    }
101}
102
103pub fn expand_tilde(raw: &str) -> PathBuf {
104    let home = home_dir();
105    expand_tilde_with_home(raw, home.as_deref())
106}
107
108fn expand_tilde_with_home(raw: &str, home: Option<&Path>) -> PathBuf {
109    if raw == "~" {
110        return home
111            .map(Path::to_path_buf)
112            .unwrap_or_else(|| PathBuf::from(raw));
113    }
114    if let Some(rest) = raw.strip_prefix("~/") {
115        if let Some(home) = home {
116            return home.join(rest);
117        }
118    }
119    PathBuf::from(raw)
120}
121
122fn home_dir() -> Option<PathBuf> {
123    crate::environment::non_empty_os_var("HOME")
124        .or_else(|| crate::environment::non_empty_os_var("USERPROFILE"))
125        .map(PathBuf::from)
126}
127
128fn nearest_existing_parent(path: &Path) -> Option<PathBuf> {
129    let mut current = path.to_path_buf();
130    loop {
131        if current.exists() {
132            return std::fs::canonicalize(&current).ok().or(Some(current));
133        }
134        if !current.pop() {
135            return None;
136        }
137    }
138}
139
140fn git_toplevel(base_dir: &Path) -> Result<PathBuf, String> {
141    let stdout = match crate::git_probe::toplevel_in_directory(base_dir) {
142        Ok(stdout) => stdout,
143        Err(crate::git_probe::ProbeError::Spawn(error))
144            if error.kind() == std::io::ErrorKind::NotFound
145                && !crate::git_probe::repository_marker_or_uncertainty_in_directory(base_dir) =>
146        {
147            return Err("not_a_git_root".to_string());
148        }
149        Err(crate::git_probe::ProbeError::Spawn(error)) => {
150            return Err(format!("failed to run git: {error}"));
151        }
152        Err(crate::git_probe::ProbeError::Failed { kind, output }) => {
153            if kind == crate::git_probe::FailureKind::NotRepository {
154                return Err("not_a_git_root".to_string());
155            }
156            let stderr = String::from_utf8_lossy(&output.stderr);
157            return Err(format!("git rev-parse failed: {}", stderr.trim()));
158        }
159    };
160
161    let toplevel = String::from_utf8_lossy(&stdout).trim().to_string();
162    if toplevel.is_empty() {
163        return Err("git rev-parse returned an empty toplevel".to_string());
164    }
165    let toplevel = PathBuf::from(toplevel);
166    Ok(std::fs::canonicalize(&toplevel).unwrap_or(toplevel))
167}
168
169pub fn project_root_is_too_broad(
170    canonical_root: &Path,
171    canonicalization_failed: bool,
172    account_home: Option<&Path>,
173) -> bool {
174    let root_identity = crate::policy_path::policy_path(canonical_root);
175    let account_home = account_home.filter(|home| home.is_dir());
176    canonicalization_failed
177        || crate::path_identity::project_root_volume(canonical_root, account_home)
178            .map(|volume| crate::policy_path::policy_path(&volume))
179            .is_none_or(|volume| {
180                let home_identity = account_home
181                    .map(crate::policy_path::policy_path)
182                    .unwrap_or_else(|| volume.clone());
183                crate::path_identity::project_root_is_narrow(
184                    &root_identity,
185                    &home_identity,
186                    &volume,
187                ) != Some(true)
188            })
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    #[cfg(unix)]
195    use std::process::Command;
196
197    /// With a relative PATH entry, `git` must still be found relative to the
198    /// project folder, where this probe has always started its child.
199    #[cfg(unix)]
200    #[test]
201    fn relative_path_entry_finds_git_from_the_project_folder() {
202        let dir = tempfile::tempdir().unwrap();
203        crate::git_probe::write_stub_git_for_test(&dir.path().join("bin"), "/stub-toplevel");
204        let path = crate::git_probe::relative_bin_path_for_test();
205        let toplevel = crate::git_probe::with_child_env_for_test(&[("PATH", &path)], || {
206            git_toplevel(dir.path())
207        })
208        .unwrap();
209        assert_eq!(toplevel, PathBuf::from("/stub-toplevel"));
210    }
211
212    /// A repository with a corrupt HEAD makes Git print its ordinary "not a git
213    /// repository" message. That is damaged metadata, not proof of absence.
214    #[test]
215    fn corrupt_repository_metadata_is_a_git_failure_not_absence() {
216        assert!(crate::developer_tools::git_usable());
217        let dir = tempfile::tempdir().unwrap();
218        crate::git_probe::init_repository_with_corrupt_head_for_test(dir.path());
219        let error = git_toplevel(dir.path()).unwrap_err();
220        assert!(error.starts_with("git rev-parse failed:"), "{error}");
221    }
222
223    #[test]
224    fn plain_folder_resolves_to_its_own_scan_root() {
225        let project = tempfile::tempdir().unwrap();
226        let folder = tempfile::tempdir().unwrap();
227        let root = resolve_git_root_from_user_path(
228            project.path(),
229            folder.path().to_str().unwrap(),
230            |_| false,
231        )
232        .unwrap();
233        assert_eq!(
234            root,
235            crate::path_identity::canonicalize_normalized(folder.path())
236        );
237    }
238
239    #[cfg(unix)]
240    #[test]
241    fn plain_folder_resolves_without_a_git_executable() {
242        let project = tempfile::tempdir().unwrap();
243        let folder = tempfile::tempdir().unwrap();
244        let bin = tempfile::tempdir().unwrap();
245        let root =
246            crate::git_probe::with_child_env_for_test(&[("PATH", bin.path().as_os_str())], || {
247                resolve_git_root_from_user_path(
248                    project.path(),
249                    folder.path().to_str().unwrap(),
250                    |_| false,
251                )
252            })
253            .unwrap();
254        assert_eq!(
255            root,
256            crate::path_identity::canonicalize_normalized(folder.path())
257        );
258    }
259
260    #[cfg(unix)]
261    #[test]
262    fn repository_without_a_git_executable_keeps_resolution_failure() {
263        let _git_env = crate::test_env::hermetic_git_env_guard();
264        let project = tempfile::tempdir().unwrap();
265        let folder = tempfile::tempdir().unwrap();
266        init_git(folder.path());
267        let bin = tempfile::tempdir().unwrap();
268        let error =
269            crate::git_probe::with_child_env_for_test(&[("PATH", bin.path().as_os_str())], || {
270                resolve_git_root_from_user_path(
271                    project.path(),
272                    folder.path().to_str().unwrap(),
273                    |_| false,
274                )
275            })
276            .unwrap_err();
277        assert!(
278            matches!(error, GitRootResolutionError::Other(ref message) if message.starts_with("failed to run git:")),
279            "{error:?}"
280        );
281    }
282
283    #[test]
284    fn plain_folder_scan_roots_refuse_environment_and_account_homes() {
285        let project = tempfile::tempdir().unwrap();
286        let environment_home = tempfile::tempdir().unwrap();
287        let account_home = tempfile::tempdir().unwrap();
288
289        for (label, home) in [
290            ("environment home", environment_home.path()),
291            ("account home", account_home.path()),
292        ] {
293            for root in home.ancestors() {
294                assert!(
295                    matches!(
296                        resolve_git_root_from_user_path_with_homes(
297                            project.path(),
298                            &root.to_string_lossy(),
299                            Some(account_home.path()),
300                            Some(environment_home.path()),
301                            |_| false,
302                        ),
303                        Err(GitRootResolutionError::NotAGitRoot)
304                    ),
305                    "unsafe {label} scan root: {}",
306                    root.display()
307                );
308            }
309        }
310    }
311
312    #[test]
313    fn real_account_home_is_refused_when_available() {
314        // A host's account home may also be a Git checkout. Check the broad-root
315        // policy directly so Git-root resolution cannot bypass this assertion.
316        match crate::production_storage::resolve_account_home_dir() {
317            Some(home) => assert!(
318                project_root_is_too_broad(&home, false, Some(&home),),
319                "account home must be treated as too broad: {}",
320                home.display()
321            ),
322            None => eprintln!(
323                "skipping real account-home assertion: the host could not provide an account home"
324            ),
325        }
326    }
327
328    #[cfg(unix)]
329    fn git_command(root: &Path) -> Command {
330        let mut command = Command::new("git");
331        crate::test_env::apply_hermetic_git_env(command.current_dir(root));
332        command
333    }
334
335    #[cfg(unix)]
336    fn init_git(root: &Path) {
337        let status = git_command(root)
338            .args(["init"])
339            .status()
340            .expect("run git init");
341        assert!(status.success(), "git init failed");
342        let status = git_command(root)
343            .args(["config", "user.email", "test@example.com"])
344            .status()
345            .expect("configure git email");
346        assert!(status.success(), "git config email failed");
347        let status = git_command(root)
348            .args(["config", "user.name", "AFT Test"])
349            .status()
350            .expect("configure git name");
351        assert!(status.success(), "git config name failed");
352    }
353}