Skip to main content

node_auth/
vcs.rs

1//! Git-backed inspection of local credential file safety.
2
3use std::path::{Path, PathBuf};
4use std::process::{Command, Stdio};
5
6/// Whether Git reports the local `.npmrc` as safely ignored.
7#[derive(Debug, PartialEq, Eq, Clone, Copy)]
8pub enum GitStatus {
9    /// The directory does not belong to a Git repository.
10    NotGitRepo,
11    /// Git confirms `.npmrc` is ignored and untracked.
12    GitRepoIgnored,
13    /// Git reports `.npmrc` as tracked or not ignored.
14    GitRepoNotIgnored,
15    /// Git was unavailable or could not determine the answer.
16    Unavailable,
17}
18
19/// Ask Git for the repository root containing `start_dir`.
20pub fn find_git_repo_root(start_dir: &Path) -> Option<PathBuf> {
21    let output = Command::new("git")
22        .arg("-C")
23        .arg(start_dir)
24        .args(["rev-parse", "--show-toplevel"])
25        .stderr(Stdio::null())
26        .output()
27        .ok()?;
28    if !output.status.success() {
29        return None;
30    }
31    Some(
32        PathBuf::from(String::from_utf8(output.stdout).ok()?.trim())
33            .canonicalize()
34            .unwrap(),
35    )
36}
37
38/// Ask Git whether the local `.npmrc` is ignored and not tracked.
39pub fn check_git_status(dir: &Path) -> GitStatus {
40    let repo = match Command::new("git")
41        .arg("-C")
42        .arg(dir)
43        .args(["rev-parse", "--show-toplevel"])
44        .stdout(Stdio::null())
45        .stderr(Stdio::null())
46        .status()
47    {
48        Ok(status) if status.success() => true,
49        Ok(status) if status.code() == Some(128) => false,
50        _ => return GitStatus::Unavailable,
51    };
52    if !repo {
53        return GitStatus::NotGitRepo;
54    }
55
56    let tracked = Command::new("git")
57        .arg("-C")
58        .arg(dir)
59        .args(["ls-files", "--error-unmatch", "--", ".npmrc"])
60        .stdout(Stdio::null())
61        .stderr(Stdio::null())
62        .status();
63    match tracked {
64        Ok(status) if status.success() => return GitStatus::GitRepoNotIgnored,
65        Ok(status) if status.code() == Some(1) => {}
66        _ => return GitStatus::Unavailable,
67    }
68
69    match Command::new("git")
70        .arg("-C")
71        .arg(dir)
72        .args(["check-ignore", "-q", "--", ".npmrc"])
73        .stdout(Stdio::null())
74        .stderr(Stdio::null())
75        .status()
76    {
77        Ok(status) if status.success() => GitStatus::GitRepoIgnored,
78        Ok(status) if status.code() == Some(1) => GitStatus::GitRepoNotIgnored,
79        _ => GitStatus::Unavailable,
80    }
81}
82
83/// Return the Git safety status without emitting terminal output.
84pub fn check_local_credential_safety(dir: &Path) -> GitStatus {
85    check_git_status(dir)
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91    use std::fs;
92    use tempfile::tempdir;
93
94    #[test]
95    fn git_determines_ignore_status() {
96        let dir = tempdir().unwrap();
97        assert_eq!(check_git_status(dir.path()), GitStatus::NotGitRepo);
98        let status = Command::new("git")
99            .arg("-C")
100            .arg(dir.path())
101            .args(["init", "-q"])
102            .status()
103            .unwrap();
104        assert!(status.success());
105        assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoNotIgnored);
106        fs::write(dir.path().join(".gitignore"), ".npmrc\n").unwrap();
107        assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoIgnored);
108        assert_eq!(
109            find_git_repo_root(dir.path()).unwrap(),
110            dir.path().canonicalize().unwrap()
111        );
112    }
113}