@sigit / si Mirror · read-only
Fork 0

Mirror of github.com/getsigit/si.

Mirrored from https://github.com/getsigit/si.git

Synced Nov 24, 09:30 UTC

1 //! Git's credential helper protocol, and the `git` command lines built around
2 //! it.
3 //!
4 //! Git asks a helper for a password by writing `key=value` lines to its stdin,
5 //! ended by a blank line, and reads `key=value` lines back. `si` answers for
6 //! the sigit.si host only, with a short-lived token minted on demand, so no
7 //! credential is ever stored.
8
9 use {
10 crate::git::{hosts_match, RepoSlug},
11 anyhow::{anyhow, Context, Result},
12 std::{collections::HashMap, io::BufRead, path::Path, process::Command},
13 };
14
15 /// The attributes of one credential request, e.g. `protocol`, `host`, `path`.
16 pub type Request = HashMap<String, String>;
17
18 /// Read a request up to the first blank line, or the end of input.
19 pub fn parse_request(input: impl BufRead) -> Request {
20 let mut request = Request::new();
21 for line in input.lines().map_while(|line| line.ok()) {
22 let line = line.trim_end_matches('\r');
23 if line.is_empty() {
24 break;
25 }
26 if let Some((key, value)) = line.split_once('=') {
27 request.insert(key.to_string(), value.to_string());
28 }
29 }
30 request
31 }
32
33 /// Whether the request is for `base_url`, such as `https://sigit.si`. A
34 /// request for another host is none of our business, and a request over a
35 /// different scheme must not get a token that was meant for the secure one.
36 pub fn is_for_host(request: &Request, base_url: &str) -> bool {
37 let Some(host) = request.get("host") else {
38 return false;
39 };
40 if !hosts_match(host, base_url) {
41 return false;
42 }
43 match (request.get("protocol"), base_url.split_once("://")) {
44 (Some(protocol), Some((scheme, _))) => protocol.eq_ignore_ascii_case(scheme),
45 _ => true,
46 }
47 }
48
49 /// The reply git expects: two attributes and a blank line.
50 pub fn response(username: &str, password: &str) -> String {
51 format!("username={username}\npassword={password}\n\n")
52 }
53
54 /// `credential.<base>.helper`, the config key that scopes a helper to one
55 /// host.
56 pub fn helper_key(base_url: &str) -> String {
57 format!("credential.{base_url}.helper")
58 }
59
60 /// The helper command git runs, as a shell snippet: git appends the operation.
61 pub fn helper_command(exe: &Path) -> String {
62 let exe = exe.to_string_lossy().replace('\'', r"'\''");
63 format!("!'{exe}' auth git-credential")
64 }
65
66 /// The arguments for `git clone`. The leading empty `helper` entry clears any
67 /// helper inherited from the user's config, so the one that follows is the only
68 /// one asked.
69 pub fn clone_args(
70 base_url: &str,
71 exe: &Path,
72 slug: &RepoSlug,
73 dir: Option<&str>,
74 extra: &[String],
75 ) -> Vec<String> {
76 let key = helper_key(base_url);
77 let mut args = vec![
78 "-c".to_string(),
79 format!("{key}="),
80 "-c".to_string(),
81 format!("{key}={}", helper_command(exe)),
82 "clone".to_string(),
83 ];
84 args.extend(extra.iter().cloned());
85 args.push(format!("{base_url}/{}/{}.git", slug.owner, slug.name));
86 args.extend(dir.map(str::to_string));
87 args
88 }
89
90 fn git() -> Command {
91 Command::new("git")
92 }
93
94 fn not_found(error: std::io::Error) -> anyhow::Error {
95 if error.kind() == std::io::ErrorKind::NotFound {
96 anyhow!("`git` was not found on your PATH. Install git and try again.")
97 } else {
98 anyhow!("Could not run git: {error}")
99 }
100 }
101
102 /// Run `git clone` with the helper in place.
103 pub fn clone(args: &[String]) -> Result<()> {
104 let status = git().args(args).status().map_err(not_found)?;
105 if status.success() {
106 Ok(())
107 } else {
108 Err(anyhow!("git clone failed ({status})."))
109 }
110 }
111
112 /// Register the helper for `base_url` in the global git config, replacing any
113 /// earlier `si` entry. The empty entry first keeps a system-wide helper (such
114 /// as the macOS keychain) from answering for this host as well.
115 pub fn setup_global_helper(base_url: &str, exe: &Path) -> Result<()> {
116 let key = helper_key(base_url);
117
118 // Clear what we wrote before; exit code 5 only means there was none.
119 git()
120 .args(["config", "--global", "--unset-all", &key])
121 .status()
122 .map_err(not_found)?;
123
124 for value in [String::new(), helper_command(exe)] {
125 let status = git()
126 .args(["config", "--global", "--add", &key, &value])
127 .status()
128 .map_err(not_found)
129 .context("Could not write the global git config.")?;
130 if !status.success() {
131 return Err(anyhow!("`git config --global` failed ({status})."));
132 }
133 }
134 Ok(())
135 }
136
137 #[cfg(test)]
138 mod tests {
139 use super::*;
140
141 fn request(input: &str) -> Request {
142 parse_request(input.as_bytes())
143 }
144
145 #[test]
146 fn a_request_is_read_up_to_the_blank_line() {
147 let request = request("protocol=https\nhost=sigit.si\n\nignored=yes\n");
148 assert_eq!(request["host"], "sigit.si");
149 assert_eq!(request["protocol"], "https");
150 assert!(!request.contains_key("ignored"));
151 }
152
153 #[test]
154 fn a_request_may_end_without_a_blank_line() {
155 assert_eq!(request("host=sigit.si")["host"], "sigit.si");
156 }
157
158 #[test]
159 fn values_may_contain_equals_signs() {
160 assert_eq!(request("path=a=b\n")["path"], "a=b");
161 }
162
163 #[test]
164 fn the_configured_host_matches() {
165 let request = request("protocol=https\nhost=sigit.si\n\n");
166 assert!(is_for_host(&request, "https://sigit.si"));
167 }
168
169 #[test]
170 fn other_hosts_are_ignored() {
171 let request = request("protocol=https\nhost=github.com\n\n");
172 assert!(!is_for_host(&request, "https://sigit.si"));
173 }
174
175 #[test]
176 fn a_request_without_a_host_is_ignored() {
177 assert!(!is_for_host(
178 &request("protocol=https\n\n"),
179 "https://sigit.si"
180 ));
181 }
182
183 #[test]
184 fn a_plain_http_request_does_not_get_a_token_for_an_https_host() {
185 let request = request("protocol=http\nhost=sigit.si\n\n");
186 assert!(!is_for_host(&request, "https://sigit.si"));
187 }
188
189 #[test]
190 fn a_dev_host_matches_with_its_port() {
191 let request = request("protocol=http\nhost=localhost:3000\n\n");
192 assert!(is_for_host(&request, "http://localhost:3000"));
193 }
194
195 #[test]
196 fn the_response_ends_with_a_blank_line() {
197 assert_eq!(
198 response("x-access-token", "abc"),
199 "username=x-access-token\npassword=abc\n\n"
200 );
201 }
202
203 #[test]
204 fn the_helper_command_quotes_the_executable() {
205 let command = helper_command(Path::new("/opt/it's here/si"));
206 assert_eq!(command, r"!'/opt/it'\''s here/si' auth git-credential");
207 }
208
209 #[test]
210 fn clone_resets_the_helper_before_setting_ours() {
211 let slug = RepoSlug::parse("seto/demo").unwrap();
212 let args = clone_args(
213 "https://sigit.si",
214 Path::new("/bin/si"),
215 &slug,
216 Some("out"),
217 &["--depth".to_string(), "1".to_string()],
218 );
219 assert_eq!(
220 args,
221 [
222 "-c",
223 "credential.https://sigit.si.helper=",
224 "-c",
225 "credential.https://sigit.si.helper=!'/bin/si' auth git-credential",
226 "clone",
227 "--depth",
228 "1",
229 "https://sigit.si/seto/demo.git",
230 "out",
231 ]
232 );
233 }
234
235 #[test]
236 fn clone_without_a_directory_leaves_the_choice_to_git() {
237 let slug = RepoSlug::parse("seto/demo").unwrap();
238 let args = clone_args("https://sigit.si", Path::new("/bin/si"), &slug, None, &[]);
239 assert_eq!(args.last().unwrap(), "https://sigit.si/seto/demo.git");
240 }
241 }