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
29  if !output.status.success() {
30    return None;
31  }
32
33  Some(
34    PathBuf::from(String::from_utf8(output.stdout).ok()?.trim())
35      .canonicalize()
36      .unwrap(),
37  )
38}
39
40/// Ask Git whether a repository-relative credential file is ignored and untracked.
41pub fn check_path_status(dir: &Path, path: &Path) -> GitStatus {
42  let repo = match Command::new("git")
43    .arg("-C")
44    .arg(dir)
45    .args(["rev-parse", "--show-toplevel"])
46    .stdout(Stdio::null())
47    .stderr(Stdio::null())
48    .status()
49  {
50    Ok(status) if status.success() => true,
51    Ok(status) if status.code() == Some(128) => false,
52    _ => return GitStatus::Unavailable,
53  };
54
55  if !repo {
56    return GitStatus::NotGitRepo;
57  }
58
59  let tracked = Command::new("git")
60    .arg("-C")
61    .arg(dir)
62    .args(["ls-files", "--error-unmatch", "--"])
63    .arg(path)
64    .stdout(Stdio::null())
65    .stderr(Stdio::null())
66    .status();
67
68  match tracked {
69    Ok(status) if status.success() => return GitStatus::GitRepoNotIgnored,
70    Ok(status) if status.code() == Some(1) => {}
71    _ => return GitStatus::Unavailable,
72  }
73
74  match Command::new("git")
75    .arg("-C")
76    .arg(dir)
77    .args(["check-ignore", "-q", "--"])
78    .arg(path)
79    .stdout(Stdio::null())
80    .stderr(Stdio::null())
81    .status()
82  {
83    Ok(status) if status.success() => GitStatus::GitRepoIgnored,
84    Ok(status) if status.code() == Some(1) => GitStatus::GitRepoNotIgnored,
85    _ => GitStatus::Unavailable,
86  }
87}
88
89/// Ask Git whether the local `.npmrc` is ignored and not tracked.
90pub fn check_git_status(dir: &Path) -> GitStatus {
91  check_path_status(dir, Path::new(".npmrc"))
92}
93
94/// Return the Git safety status without emitting terminal output.
95pub fn check_local_credential_safety(dir: &Path) -> GitStatus {
96  check_git_status(dir)
97}
98
99#[cfg(test)]
100mod tests {
101  use super::*;
102  use std::fs;
103  use tempfile::tempdir;
104
105  #[test]
106  fn git_determines_ignore_status() {
107    let dir = tempdir().unwrap();
108    assert_eq!(check_git_status(dir.path()), GitStatus::NotGitRepo);
109
110    let status = Command::new("git")
111      .arg("-C")
112      .arg(dir.path())
113      .args(["init", "-q"])
114      .status()
115      .unwrap();
116    assert!(status.success());
117    assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoNotIgnored);
118
119    fs::write(dir.path().join(".gitignore"), ".npmrc\n").unwrap();
120
121    assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoIgnored);
122    assert_eq!(
123      find_git_repo_root(dir.path()).unwrap(),
124      dir.path().canonicalize().unwrap()
125    );
126
127    assert_eq!(
128      check_path_status(dir.path(), Path::new(".env.local")),
129      GitStatus::GitRepoNotIgnored
130    );
131  }
132}