Skip to main content

gitpoulpi_cli_backend/
scoped_config.rs

1//! Reads of the config entries that decide how a repository authenticates,
2//! with the scope and file each one comes from (`git config --show-scope
3//! --show-origin`). The daemon builds a repository's [`NetworkAuth`] from
4//! them (ADR-0010): which credential helpers are the user's own (system and
5//! global scope) and which the repository brings (local, worktree, and
6//! anything an included file adds on their behalf, which git scopes as the
7//! including file), and which program the global `core.sshCommand` names.
8//!
9//! Read-only: `git config` runs nothing from the repository.
10//!
11//! [`NetworkAuth`]: gitpoulpi_core::domain::NetworkAuth
12
13use std::path::Path;
14
15use crate::process::git;
16
17/// One value of a multi-valued config key, in the order git read it.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ConfigEntry {
20    /// `system`, `global`, `local`, `worktree` or `command`.
21    pub scope: String,
22    /// `file:<path>` (or `command line:`), as git prints it.
23    pub origin: String,
24    /// The key as git prints it: section and variable lowercased, the
25    /// subsection (a URL) as written.
26    pub key: String,
27    pub value: String,
28}
29
30impl ConfigEntry {
31    /// Whether the user's own configuration (not the repository's) set it.
32    pub fn is_machine_wide(&self) -> bool {
33        matches!(self.scope.as_str(), "system" | "global")
34    }
35}
36
37/// Every entry whose key matches `pattern` (a regexp, as `--get-regexp`
38/// takes it), in config order. `Err` when git cannot be asked; no match is an
39/// empty list.
40pub fn config_entries(repo_root: &Path, pattern: &str) -> Result<Vec<ConfigEntry>, String> {
41    let out = git(
42        repo_root,
43        &[
44            "config",
45            "--show-scope",
46            "--show-origin",
47            "-z",
48            "--get-regexp",
49            pattern,
50        ],
51    )
52    .output()
53    .map_err(|e| format!("could not run git config: {e}"))?;
54    match out.status.code() {
55        Some(0) => {}
56        // 1: nothing matched.
57        Some(1) => return Ok(Vec::new()),
58        _ => {
59            return Err(format!(
60                "git config failed: {}",
61                String::from_utf8_lossy(&out.stderr).trim()
62            ))
63        }
64    }
65    Ok(parse_entries(&String::from_utf8_lossy(&out.stdout)))
66}
67
68/// `scope NUL origin NUL key NL value NUL`, repeated (`-z`).
69fn parse_entries(text: &str) -> Vec<ConfigEntry> {
70    let mut fields = text.split('\0');
71    let mut out = Vec::new();
72    while let (Some(scope), Some(origin), Some(rest)) =
73        (fields.next(), fields.next(), fields.next())
74    {
75        let (key, value) = rest.split_once('\n').unwrap_or((rest, ""));
76        out.push(ConfigEntry {
77            scope: scope.to_string(),
78            origin: origin.to_string(),
79            key: key.to_string(),
80            value: value.to_string(),
81        });
82    }
83    out
84}
85
86/// Every `credential.helper` and `credential.<url>.helper` entry.
87pub fn credential_helper_entries(repo_root: &Path) -> Result<Vec<ConfigEntry>, String> {
88    config_entries(repo_root, r"^credential\..*helper$")
89}
90
91/// Every `core.sshCommand` entry.
92pub fn ssh_command_entries(repo_root: &Path) -> Result<Vec<ConfigEntry>, String> {
93    config_entries(repo_root, r"^core\.sshcommand$")
94}
95
96/// The helpers that remain once the repository's own are dropped: the system
97/// and global entries, in order, as `(None, helper)` for `credential.helper`
98/// and `(Some(url), helper)` for `credential.<url>.helper`. An empty value
99/// is git's reset: it clears what was collected before it for the same
100/// scope of URLs, as git itself would.
101pub fn machine_wide_helpers(entries: &[ConfigEntry]) -> Vec<(Option<String>, String)> {
102    let mut kept: Vec<(Option<String>, String)> = Vec::new();
103    for e in entries.iter().filter(|e| e.is_machine_wide()) {
104        let Some(rest) = e.key.strip_prefix("credential.") else {
105            continue;
106        };
107        let url = match rest.strip_suffix(".helper") {
108            Some(url) if !url.is_empty() => Some(url.to_string()),
109            _ if rest == "helper" => None,
110            _ => continue,
111        };
112        if e.value.is_empty() {
113            kept.retain(|(u, _)| *u != url);
114        } else {
115            kept.push((url, e.value.clone()));
116        }
117    }
118    kept
119}
120
121/// The program word of the effective **global** `core.sshCommand` (system or
122/// global scope; the repository's own is what the profile overrides), or
123/// `ssh`. Users often point it at the Windows OpenSSH client to reach the
124/// Windows agent, so a key file must be offered through the same program.
125pub fn global_ssh_program(entries: &[ConfigEntry]) -> String {
126    entries
127        .iter()
128        .rfind(|e| e.is_machine_wide() && !e.value.trim().is_empty())
129        .and_then(|e| first_word(&e.value))
130        .unwrap_or_else(|| "ssh".to_string())
131}
132
133/// The first word of a shell command line, quotes removed. Backslashes are
134/// left alone so an unquoted Windows path stays whole.
135fn first_word(command: &str) -> Option<String> {
136    let s = command.trim_start();
137    let mut chars = s.chars();
138    match chars.next()? {
139        q @ ('"' | '\'') => {
140            let rest = &s[1..];
141            let end = rest.find(q)?;
142            Some(rest[..end].to_string()).filter(|w| !w.is_empty())
143        }
144        _ => s
145            .split(char::is_whitespace)
146            .next()
147            .map(str::to_string)
148            .filter(|w| !w.is_empty()),
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    fn entry(scope: &str, key: &str, value: &str) -> ConfigEntry {
157        ConfigEntry {
158            scope: scope.into(),
159            origin: "file:x".into(),
160            key: key.into(),
161            value: value.into(),
162        }
163    }
164
165    #[test]
166    fn the_null_separated_output_is_parsed() {
167        let text = "global\0file:/h/.gitconfig\0credential.helper\nstore\0\
168                    local\0file:.git/config\0credential.https://x.y.helper\n!f\0";
169        let entries = parse_entries(text);
170        assert_eq!(entries.len(), 2);
171        assert_eq!(entries[0].scope, "global");
172        assert_eq!(entries[0].value, "store");
173        assert_eq!(entries[1].key, "credential.https://x.y.helper");
174        assert_eq!(entries[1].origin, "file:.git/config");
175    }
176
177    #[test]
178    fn only_machine_wide_helpers_are_kept_and_a_reset_clears_its_own_scope() {
179        let entries = [
180            entry("system", "credential.helper", "manager"),
181            entry("global", "credential.helper", ""),
182            entry("global", "credential.helper", "store"),
183            entry("global", "credential.https://github.com.helper", "!gh"),
184            entry("local", "credential.helper", "!/missing/script"),
185            entry("local", "credential.https://github.com.helper", "!evil"),
186            entry("worktree", "credential.helper", "!worktree"),
187        ];
188        assert_eq!(
189            machine_wide_helpers(&entries),
190            vec![
191                (None, "store".to_string()),
192                (Some("https://github.com".to_string()), "!gh".to_string()),
193            ]
194        );
195    }
196
197    #[test]
198    fn the_ssh_program_is_the_first_word_of_the_global_command_only() {
199        assert_eq!(global_ssh_program(&[]), "ssh");
200        assert_eq!(
201            global_ssh_program(&[entry("local", "core.sshcommand", "evil -i x")]),
202            "ssh"
203        );
204        assert_eq!(
205            global_ssh_program(&[
206                entry("system", "core.sshcommand", "other"),
207                entry(
208                    "global",
209                    "core.sshcommand",
210                    "C:/Windows/System32/OpenSSH/ssh.exe -v"
211                ),
212                entry("local", "core.sshcommand", "evil"),
213            ]),
214            "C:/Windows/System32/OpenSSH/ssh.exe"
215        );
216        assert_eq!(
217            global_ssh_program(&[entry(
218                "global",
219                "core.sshcommand",
220                r#""C:\Program Files\OpenSSH\ssh.exe" -q"#
221            )]),
222            r"C:\Program Files\OpenSSH\ssh.exe"
223        );
224    }
225}