Skip to main content

fallow_engine/
base_worktree_registration.rs

1//! Git registration of detached base snapshots.
2//!
3//! A base snapshot is a linked worktree only while it is created. Fallow then
4//! removes its Git admin entry and keeps the directory, so Git-aware tools do
5//! not see the snapshot while the base analysis reads it, and a process that
6//! dies before cleanup leaves no registered worktree behind (issues #1815 and
7//! #3885). The CLI audit cache and the programmatic base snapshot share this
8//! lifecycle.
9
10use std::fs;
11use std::io::Write as _;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15/// Last segment of the gitdir that the stub of a deregistered snapshot names.
16const UNREGISTERED_GITDIR_NAME: &str = "fallow-audit-unregistered";
17
18/// Stub of older versions. Its gitdir is relative, so Git resolves it inside
19/// the snapshot, where the untrusted base commit can supply a directory of
20/// that name with its own config. It is recognized only to replace it.
21const LEGACY_UNREGISTERED_GITDIR_STUB: &str = "gitdir: fallow-audit-unregistered\n";
22
23/// Prefix of every admin entry and snapshot directory that Fallow creates.
24const FALLOW_BASE_WORKTREE_PREFIX: &str = "fallow-audit-base-";
25
26/// Gitfile contents written into `<snapshot>/.git` after Fallow deregisters
27/// a base snapshot.
28///
29/// The `.git` file is REPLACED, never deleted: both discovery walkers use the
30/// `ignore` crate with `require_git` on, whose gitignore handling is gated on
31/// `<root>/.git` existing. Deleting the gitfile would silently stop the base
32/// pass from honoring `.gitignore`, inflating base findings and skewing
33/// audit's introduced-vs-inherited split.
34///
35/// The stub names the absolute path `<snapshot>/.git/fallow-audit-unregistered`.
36/// That path can never exist, because `<snapshot>/.git` is this regular file,
37/// and the committed tree cannot supply a `.git` entry. So a `git` command in
38/// the snapshot fails and never reads a config from the untrusted base commit.
39#[must_use]
40pub fn unregistered_gitdir_stub(snapshot: &Path) -> String {
41    let gitdir = snapshot.join(".git").join(UNREGISTERED_GITDIR_NAME);
42    format!("gitdir: {}\n", gitdir.display())
43}
44
45/// Return whether `contents` is the stub of a deregistered snapshot at
46/// `snapshot`, in the current or the legacy form.
47#[must_use]
48pub fn is_unregistered_gitdir_stub(snapshot: &Path, contents: &str) -> bool {
49    if contents == LEGACY_UNREGISTERED_GITDIR_STUB {
50        return true;
51    }
52    let Some(gitdir) = parse_worktree_gitdir(contents) else {
53        return false;
54    };
55    let Some(gitfile) = gitdir
56        .file_name()
57        .is_some_and(|name| name == UNREGISTERED_GITDIR_NAME)
58        .then(|| gitdir.parent())
59        .flatten()
60    else {
61        return false;
62    };
63    if gitfile.file_name().is_none_or(|name| name != ".git") {
64        return false;
65    }
66    gitfile
67        .parent()
68        .is_some_and(|owner| owner == snapshot || same_existing_path(owner, snapshot))
69}
70
71fn same_existing_path(left: &Path, right: &Path) -> bool {
72    match (dunce::canonicalize(left), dunce::canonicalize(right)) {
73        (Ok(left), Ok(right)) => left == right,
74        _ => false,
75    }
76}
77
78/// Return the deregistered snapshot that contains `dir`, if any.
79///
80/// The walk stops at the first `.git` entry. A Fallow stub marks a snapshot.
81/// Any other `.git` entry is an ordinary repository boundary.
82#[must_use]
83pub fn enclosing_unregistered_snapshot(dir: &Path) -> Option<PathBuf> {
84    let dir = std::path::absolute(dir).ok()?;
85    for candidate in dir.ancestors() {
86        let gitfile = candidate.join(".git");
87        let Ok(metadata) = fs::symlink_metadata(&gitfile) else {
88            continue;
89        };
90        if !is_regular_file(&metadata) {
91            return None;
92        }
93        let contents = fs::read_to_string(&gitfile).ok()?;
94        return is_unregistered_gitdir_stub(candidate, &contents).then(|| candidate.to_path_buf());
95    }
96    None
97}
98
99/// Keep a `git` command that runs in `cwd` from discovering a repository
100/// inside a deregistered base snapshot.
101///
102/// The snapshot holds the untrusted base commit. It can contain a directory
103/// that looks like a bare repository, and Git would read its config. When
104/// `cwd` is inside a snapshot, the command gets a `GIT_DIR` that does not
105/// exist and a `GIT_CEILING_DIRECTORIES` at the snapshot parent, so Git stops
106/// with "not a git repository". Outside a snapshot, the command is unchanged.
107pub fn confine_git_to_host(command: &mut Command, cwd: &Path) {
108    let Some(snapshot) = enclosing_unregistered_snapshot(cwd) else {
109        return;
110    };
111    command.env(
112        "GIT_DIR",
113        snapshot.join(".git").join(UNREGISTERED_GITDIR_NAME),
114    );
115    if let Some(parent) = snapshot.parent() {
116        command.env("GIT_CEILING_DIRECTORIES", parent);
117    }
118}
119
120/// Deregister a Fallow base snapshot from Git while KEEPING its directory.
121///
122/// Targets the single admin dir this worktree owns via its `.git` gitfile
123/// pointer, rather than a global `git worktree prune`, so a user's unrelated
124/// prunable worktrees are never collaterally deregistered and Git's
125/// name-collision admin suffixing (`<name>1`) is handled for free. The `.git`
126/// gitfile is REPLACED with [`unregistered_gitdir_stub`], never deleted.
127/// A missing directory and an already deregistered snapshot are success. A
128/// legacy stub is replaced with the current one.
129///
130/// # Errors
131///
132/// Returns an error when the gitfile is not a regular file, when its admin
133/// entry is not a Fallow entry of `repo_root` that links back to `path`, or
134/// when the admin entry or the gitfile cannot be changed.
135pub fn deregister_base_worktree(repo_root: &Path, path: &Path) -> std::io::Result<()> {
136    if !path.exists() {
137        return Ok(());
138    }
139    let gitfile = path.join(".git");
140    let metadata = fs::symlink_metadata(&gitfile)?;
141    if !is_regular_file(&metadata) {
142        return Err(std::io::Error::new(
143            std::io::ErrorKind::InvalidData,
144            "refusing to deregister through a non-file audit worktree .git entry",
145        ));
146    }
147    let contents = fs::read_to_string(&gitfile)?;
148    if is_unregistered_gitdir_stub(path, &contents) {
149        if contents == unregistered_gitdir_stub(path) {
150            return Ok(());
151        }
152        return write_unregistered_gitdir_stub(&gitfile);
153    }
154    let Some(admin_dir) = trusted_base_worktree_admin_dir(repo_root, path) else {
155        return Err(std::io::Error::new(
156            std::io::ErrorKind::InvalidData,
157            "refusing to deregister an unverified audit worktree admin entry",
158        ));
159    };
160    match fs::remove_dir_all(&admin_dir) {
161        Ok(()) => {}
162        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
163        Err(err) => return Err(err),
164    }
165    write_unregistered_gitdir_stub(&gitfile)
166}
167
168/// Write the [`unregistered_gitdir_stub`] of the snapshot that owns `gitfile`
169/// into `gitfile`, creating it when it is missing.
170///
171/// # Errors
172///
173/// Returns an error when `gitfile` exists but is not a regular file, or when
174/// the write fails.
175pub fn write_unregistered_gitdir_stub(gitfile: &Path) -> std::io::Result<()> {
176    let mut options = fs::OpenOptions::new();
177    options.write(true).truncate(true);
178    match fs::symlink_metadata(gitfile) {
179        Ok(metadata) if is_regular_file(&metadata) => {}
180        Ok(_) => {
181            return Err(std::io::Error::new(
182                std::io::ErrorKind::InvalidData,
183                "refusing to replace non-file audit worktree .git entry",
184            ));
185        }
186        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
187            options.create_new(true);
188        }
189        Err(error) => return Err(error),
190    }
191    let snapshot = gitfile.parent().ok_or_else(|| {
192        std::io::Error::new(
193            std::io::ErrorKind::InvalidInput,
194            "audit worktree .git entry has no parent directory",
195        )
196    })?;
197    let stub = unregistered_gitdir_stub(snapshot);
198    let mut file = options.open(gitfile)?;
199    file.write_all(stub.as_bytes())?;
200    file.sync_all()
201}
202
203/// Return the Git admin entry of the snapshot at `path` when it is a Fallow
204/// entry of `repo_root` whose backlink points at `path`.
205#[must_use]
206pub fn trusted_base_worktree_admin_dir(repo_root: &Path, path: &Path) -> Option<PathBuf> {
207    let gitfile = path.join(".git");
208    let metadata = fs::symlink_metadata(&gitfile).ok()?;
209    if !is_regular_file(&metadata) {
210        return None;
211    }
212    let contents = fs::read_to_string(&gitfile).ok()?;
213    let admin_dir = parse_worktree_gitdir(&contents)?;
214    if !is_fallow_admin_dir(&admin_dir) {
215        return None;
216    }
217    let common_dir = crate::changed_files::resolve_git_common_dir(repo_root).ok()?;
218    let worktrees_dir = dunce::canonicalize(common_dir.join("worktrees")).ok()?;
219    let admin_parent = dunce::canonicalize(admin_dir.parent()?).ok()?;
220    if admin_parent != worktrees_dir {
221        return None;
222    }
223    let backlink = fs::read_to_string(admin_dir.join("gitdir")).ok()?;
224    let expected_gitfile = dunce::canonicalize(&gitfile).ok()?;
225    let actual_gitfile = dunce::canonicalize(Path::new(backlink.trim())).ok()?;
226    (actual_gitfile == expected_gitfile).then_some(admin_dir)
227}
228
229/// Parse the `gitdir: <path>` pointer from a linked-worktree `.git` gitfile.
230#[must_use]
231pub fn parse_worktree_gitdir(contents: &str) -> Option<PathBuf> {
232    contents
233        .lines()
234        .find_map(|line| line.trim().strip_prefix("gitdir:"))
235        .map(|rest| PathBuf::from(rest.trim()))
236}
237
238#[expect(
239    clippy::filetype_is_file,
240    reason = "a gitfile must be a regular file, not an arbitrary non-directory"
241)]
242fn is_regular_file(metadata: &fs::Metadata) -> bool {
243    metadata.file_type().is_file()
244}
245
246/// True when an admin dir basename is one Fallow itself created, used as a
247/// safety belt before removing it.
248fn is_fallow_admin_dir(admin_dir: &Path) -> bool {
249    admin_dir
250        .file_name()
251        .and_then(|name| name.to_str())
252        .is_some_and(|name| name.starts_with(FALLOW_BASE_WORKTREE_PREFIX))
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::repo_refs::{TemporaryBaseWorktree, create_detached_base_worktree};
259
260    fn git(root: &Path, args: &[&str]) -> String {
261        let output = crate::git_fixture::fixture_git_command_with_identity(
262            root,
263            crate::git_fixture::FixtureIdentity::RepositoryConfig,
264        )
265        .args(args)
266        .output()
267        .expect("git command starts");
268        assert!(
269            output.status.success(),
270            "git {args:?} failed: {}",
271            String::from_utf8_lossy(&output.stderr)
272        );
273        String::from_utf8_lossy(&output.stdout).trim().to_owned()
274    }
275
276    fn committed_repo(parent: &Path) -> PathBuf {
277        let repo = parent.join("repo");
278        fs::create_dir_all(&repo).expect("create repo");
279        git(&repo, &["init", "-b", "main"]);
280        git(&repo, &["config", "user.name", "Test User"]);
281        git(&repo, &["config", "user.email", "test@example.com"]);
282        git(&repo, &["config", "commit.gpgsign", "false"]);
283        fs::write(repo.join(".gitignore"), "ignored/\n").expect("write gitignore");
284        fs::write(repo.join("tracked.txt"), "committed\n").expect("write tracked file");
285        git(&repo, &["add", "."]);
286        git(&repo, &["commit", "-m", "initial"]);
287        repo
288    }
289
290    fn registered_worktrees(repo: &Path) -> Vec<String> {
291        git(repo, &["worktree", "list", "--porcelain"])
292            .lines()
293            .filter_map(|line| line.strip_prefix("worktree "))
294            .map(str::to_owned)
295            .collect()
296    }
297
298    /// Issue #3885: the programmatic base snapshot must not stay registered
299    /// while the base analysis reads it, so a host process that stops before
300    /// `Drop` leaves no Git worktree entry behind.
301    #[test]
302    fn temporary_base_worktree_is_unregistered_while_it_is_in_use() {
303        let temp = tempfile::tempdir().expect("temp dir");
304        let repo = committed_repo(temp.path());
305        let before = registered_worktrees(&repo);
306
307        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
308            .expect("temporary worktree should be created");
309
310        assert_eq!(
311            registered_worktrees(&repo),
312            before,
313            "the base snapshot must be deregistered before analysis reads it"
314        );
315        assert_eq!(
316            fs::read_to_string(worktree.path().join("tracked.txt")).expect("read tracked file"),
317            "committed\n"
318        );
319        assert_eq!(
320            fs::read_to_string(worktree.path().join(".git")).expect("read gitfile"),
321            unregistered_gitdir_stub(worktree.path()),
322            "the gitfile stays as a stub so gitignore handling still applies"
323        );
324
325        let path = worktree.path().to_path_buf();
326        drop(worktree);
327        assert!(!path.exists(), "temporary worktree must clean up on drop");
328        assert_eq!(registered_worktrees(&repo), before);
329    }
330
331    #[test]
332    fn registered_snapshot_index_keeps_gitlinks_until_deregistration() {
333        let temp = tempfile::tempdir().expect("temp dir");
334        let repo = committed_repo(temp.path());
335        let gitlink_commit = git(&repo, &["rev-parse", "HEAD"]);
336        let cacheinfo = format!("160000,{gitlink_commit},vendor/submodule");
337        git(&repo, &["update-index", "--add", "--cacheinfo", &cacheinfo]);
338        git(&repo, &["commit", "-m", "gitlink"]);
339        let destination = temp.path().join("fallow-audit-base-index-probe");
340
341        create_detached_base_worktree(&repo, &destination, "HEAD")
342            .expect("registered worktree should be created");
343        assert!(
344            git(&destination, &["ls-files", "--stage", "vendor/submodule"])
345                .starts_with(&format!("160000 {gitlink_commit} 0\t")),
346            "the linked worktree index must retain the gitlink object id"
347        );
348
349        deregister_base_worktree(&repo, &destination).expect("snapshot deregisters");
350        assert_eq!(registered_worktrees(&repo).len(), 1);
351        assert!(destination.join("tracked.txt").is_file());
352    }
353
354    /// Write a directory that Git accepts as a repository, whose config runs
355    /// `marker` as the fsmonitor hook.
356    #[cfg(unix)]
357    fn write_crafted_gitdir(dir: &Path, marker: &Path) {
358        fs::create_dir_all(dir.join("objects")).expect("create objects");
359        fs::create_dir_all(dir.join("refs")).expect("create refs");
360        fs::write(dir.join("objects/.keep"), "").expect("write objects keep");
361        fs::write(dir.join("refs/.keep"), "").expect("write refs keep");
362        fs::write(dir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
363        fs::write(
364            dir.join("config"),
365            format!(
366                "[core]\n\trepositoryformatversion = 0\n\tfsmonitor = \"touch '{}'; false\"\n",
367                marker.display()
368            ),
369        )
370        .expect("write config");
371    }
372
373    #[cfg(unix)]
374    fn raw_git_status(cwd: &Path, confine: bool) -> bool {
375        let mut command = std::process::Command::new("git");
376        crate::changed_files::clear_ambient_git_env(&mut command);
377        if confine {
378            confine_git_to_host(&mut command, cwd);
379        }
380        command
381            .args(["status", "--porcelain"])
382            .current_dir(cwd)
383            .output()
384            .expect("git command starts")
385            .status
386            .success()
387    }
388
389    /// The base commit is untrusted. A top-level `fallow-audit-unregistered/`
390    /// or a nested directory shaped as a bare repository must never become
391    /// the repository of a `git` command inside the snapshot.
392    #[cfg(unix)]
393    #[test]
394    fn crafted_gitdirs_in_the_base_commit_are_never_read() {
395        let temp = tempfile::tempdir().expect("temp dir");
396        let repo = committed_repo(temp.path());
397        let marker = temp.path().join("fsmonitor-ran");
398        write_crafted_gitdir(&repo.join(UNREGISTERED_GITDIR_NAME), &marker);
399        write_crafted_gitdir(&repo.join("pkg"), &marker);
400        git(&repo, &["add", "-f", "."]);
401        git(&repo, &["commit", "-m", "crafted"]);
402
403        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
404            .expect("temporary worktree should be created");
405        let snapshot = worktree.path();
406        assert!(
407            snapshot
408                .join(UNREGISTERED_GITDIR_NAME)
409                .join("config")
410                .is_file()
411        );
412
413        assert!(
414            !raw_git_status(snapshot, false),
415            "Git at the snapshot root must not find a repository"
416        );
417        assert!(!raw_git_status(&snapshot.join("pkg"), true));
418        assert!(!crate::churn::is_git_repo(snapshot));
419        assert!(!crate::churn::is_git_repo(&snapshot.join("pkg")));
420        assert!(
421            crate::changed_files::resolve_git_toplevel(&snapshot.join("pkg")).is_err(),
422            "changed-file probes must not find the nested bare repository"
423        );
424        for dir in [snapshot.to_path_buf(), snapshot.join("pkg")] {
425            let status = crate::git_env::git_command(&dir)
426                .args(["status", "--porcelain"])
427                .output()
428                .expect("git command starts")
429                .status;
430            assert!(
431                !status.success(),
432                "the shared Git wrapper found a repository"
433            );
434        }
435        assert!(
436            !marker.exists(),
437            "a config from the base commit ran a command"
438        );
439    }
440
441    /// The shared Git wrapper also refuses a bare repository that Git would
442    /// find on its own outside a snapshot, and keeps ordinary checkouts.
443    #[cfg(unix)]
444    #[test]
445    fn shared_git_wrapper_refuses_implicit_bare_repositories() {
446        let temp = tempfile::tempdir().expect("temp dir");
447        let repo = committed_repo(temp.path());
448        let marker = temp.path().join("fsmonitor-ran");
449        let bare = temp.path().join("bare");
450        write_crafted_gitdir(&bare, &marker);
451        fs::create_dir_all(repo.join("sub")).expect("create subdirectory");
452
453        let run = |dir: &Path| {
454            crate::git_env::git_command(dir)
455                .args(["status", "--porcelain"])
456                .output()
457                .expect("git command starts")
458                .status
459                .success()
460        };
461
462        assert!(!run(&bare), "an implicit bare repository must be refused");
463        assert!(!marker.exists());
464        assert!(run(&repo), "an ordinary checkout must keep working");
465        assert!(
466            run(&repo.join("sub")),
467            "a checkout subdirectory must keep working"
468        );
469    }
470
471    /// A project whose `.git` is a gitfile into a bare clone (the bare-clone
472    /// worktree layout) keeps working with `safe.bareRepository=explicit`,
473    /// for repository probes and for a base snapshot.
474    #[test]
475    fn bare_clone_worktree_layout_keeps_working() {
476        let temp = tempfile::tempdir().expect("temp dir");
477        let source = committed_repo(temp.path());
478        let bare = temp.path().join("bare.git");
479        let linked = temp.path().join("linked");
480        let parent = temp.path();
481        git(
482            parent,
483            &[
484                "clone",
485                "--quiet",
486                "--bare",
487                source.to_str().expect("UTF-8"),
488                "bare.git",
489            ],
490        );
491        git(
492            &bare,
493            &[
494                "worktree",
495                "add",
496                "--quiet",
497                linked.to_str().expect("UTF-8"),
498                "main",
499            ],
500        );
501        assert!(
502            fs::symlink_metadata(linked.join(".git"))
503                .expect("gitfile")
504                .is_file()
505        );
506
507        let toplevel = crate::git_env::git_command(&linked)
508            .args(["rev-parse", "--show-toplevel"])
509            .output()
510            .expect("git command starts");
511        assert!(toplevel.status.success(), "{toplevel:?}");
512        assert!(crate::churn::is_git_repo(&linked));
513        assert!(crate::changed_files::resolve_git_toplevel(&linked).is_ok());
514
515        let worktree = TemporaryBaseWorktree::create(&linked, "HEAD", &[])
516            .expect("base snapshot from a bare-clone worktree");
517        assert!(worktree.path().join("tracked.txt").is_file());
518        assert_eq!(
519            registered_worktrees(&bare).len(),
520            2,
521            "only the bare clone and its linked worktree stay registered"
522        );
523    }
524
525    /// The stub keeps `.gitignore` handling of the base pass, which needs a
526    /// `.git` entry at the walk root.
527    #[test]
528    fn unregistered_snapshot_keeps_gitignore_handling() {
529        let temp = tempfile::tempdir().expect("temp dir");
530        let repo = committed_repo(temp.path());
531        let worktree = TemporaryBaseWorktree::create(&repo, "HEAD", &[])
532            .expect("temporary worktree should be created");
533        fs::create_dir_all(worktree.path().join("ignored")).expect("create ignored dir");
534        fs::write(worktree.path().join("ignored/skip.ts"), "").expect("write ignored file");
535
536        let walked: Vec<PathBuf> = ignore::WalkBuilder::new(worktree.path())
537            .build()
538            .filter_map(Result::ok)
539            .map(|entry| entry.into_path())
540            .collect();
541
542        assert!(walked.iter().any(|path| path.ends_with("tracked.txt")));
543        assert!(
544            !walked.iter().any(|path| path.ends_with("ignored/skip.ts")),
545            "the base walk must honor .gitignore: {walked:?}"
546        );
547        assert_eq!(
548            enclosing_unregistered_snapshot(&worktree.path().join("ignored")).as_deref(),
549            Some(worktree.path())
550        );
551    }
552}