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 a repository-relative credential file is ignored and untracked.
39pub fn check_path_status(dir: &Path, path: &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", "--"])
60    .arg(path)
61    .stdout(Stdio::null())
62    .stderr(Stdio::null())
63    .status();
64  match tracked {
65    Ok(status) if status.success() => return GitStatus::GitRepoNotIgnored,
66    Ok(status) if status.code() == Some(1) => {}
67    _ => return GitStatus::Unavailable,
68  }
69
70  match Command::new("git")
71    .arg("-C")
72    .arg(dir)
73    .args(["check-ignore", "-q", "--"])
74    .arg(path)
75    .stdout(Stdio::null())
76    .stderr(Stdio::null())
77    .status()
78  {
79    Ok(status) if status.success() => GitStatus::GitRepoIgnored,
80    Ok(status) if status.code() == Some(1) => GitStatus::GitRepoNotIgnored,
81    _ => GitStatus::Unavailable,
82  }
83}
84
85/// Ask Git whether the local `.npmrc` is ignored and not tracked.
86pub fn check_git_status(dir: &Path) -> GitStatus {
87  check_path_status(dir, Path::new(".npmrc"))
88}
89
90/// Return the Git safety status without emitting terminal output.
91pub fn check_local_credential_safety(dir: &Path) -> GitStatus {
92  check_git_status(dir)
93}
94
95#[cfg(test)]
96mod tests {
97  use super::*;
98  use std::fs;
99  use tempfile::tempdir;
100
101  #[test]
102  fn git_determines_ignore_status() {
103    let dir = tempdir().unwrap();
104    assert_eq!(check_git_status(dir.path()), GitStatus::NotGitRepo);
105    let status = Command::new("git")
106      .arg("-C")
107      .arg(dir.path())
108      .args(["init", "-q"])
109      .status()
110      .unwrap();
111    assert!(status.success());
112    assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoNotIgnored);
113    fs::write(dir.path().join(".gitignore"), ".npmrc\n").unwrap();
114    assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoIgnored);
115    assert_eq!(
116      find_git_repo_root(dir.path()).unwrap(),
117      dir.path().canonicalize().unwrap()
118    );
119
120    assert_eq!(
121      check_path_status(dir.path(), Path::new(".env.local")),
122      GitStatus::GitRepoNotIgnored
123    );
124  }
125}