1use anyhow::{Context, Result};
2use base64::Engine;
3use http::uri::{PathAndQuery, Uri};
4use std::fmt;
5use std::path::Path;
6use tokio::process::Command;
7use url::Url;
8
9use super::{build_clone_args, reason, CloneOpts};
10use crate::errors::HttpsAccessError;
11use crate::types::CredentialKind;
12
13const USER_VAR: &str = "FLUIDATTACKS_GIT_USER";
14const PASSWORD_VAR: &str = "FLUIDATTACKS_GIT_PASSWORD";
15
16fn env_helper() -> String {
18 format!(
19 "!f() {{ if [ \"$1\" = get ]; then \
20 printf 'username=%s\\npassword=%s\\n' \"${USER_VAR}\" \"${PASSWORD_VAR}\"; fi; }}; f"
21 )
22}
23
24struct BareUrl {
27 url: String,
28 origin: String,
29}
30
31pub struct HttpsAccess {
38 url: String,
39 secret: Option<String>,
40 config: Vec<(String, String)>,
41 env: Vec<(String, String)>,
42}
43
44impl fmt::Debug for HttpsAccess {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.debug_struct("HttpsAccess")
48 .field("url", &self.url)
49 .finish_non_exhaustive()
50 }
51}
52
53impl HttpsAccess {
54 pub fn new(url: &str, credential: Option<&CredentialKind>) -> Result<Self, HttpsAccessError> {
55 match credential {
56 None => Ok(Self::public(url)),
57 Some(CredentialKind::Https { user, password }) => Self::basic(url, user, password),
58 Some(CredentialKind::Token {
59 token,
60 is_pat,
61 oauth_type,
62 }) => {
63 let (user, password) = token_login(token, oauth_type, *is_pat);
64 Ok(Self {
65 secret: Some(token.clone()),
66 ..Self::basic(url, user, password)?
67 })
68 }
69 Some(CredentialKind::Ssh { .. } | CredentialKind::AwsRole { .. }) => {
70 Err(HttpsAccessError::NotHttpsCredential)
71 }
72 }
73 }
74
75 fn public(url: &str) -> Self {
76 Self {
77 url: url.to_owned(),
78 secret: None,
79 config: Vec::new(),
80 env: Vec::new(),
81 }
82 }
83
84 fn basic(raw_url: &str, user: &str, password: &str) -> Result<Self, HttpsAccessError> {
85 if [user, password]
86 .iter()
87 .any(|value| value.contains(['\n', '\r', '\0']))
88 {
89 return Err(HttpsAccessError::CredentialLineBreak);
90 }
91 let url = bare_url(raw_url)?;
92 Ok(Self {
93 secret: Some(password.to_owned()),
94 config: vec![(format!("credential.{}.helper", url.origin), env_helper())],
95 env: vec![
96 (USER_VAR.to_owned(), user.to_owned()),
97 (PASSWORD_VAR.to_owned(), password.to_owned()),
98 ],
99 url: url.url,
100 })
101 }
102
103 #[must_use]
104 pub fn url(&self) -> &str {
105 &self.url
106 }
107
108 #[must_use]
110 pub fn git(&self) -> Command {
111 let mut command = Command::new("git");
112 command.args(["-c", "credential.helper="]);
116 for (key, value) in &self.config {
117 command.arg("-c").arg(format!("{key}={value}"));
118 }
119 command
120 .env("GIT_TERMINAL_PROMPT", "0")
121 .env_remove("GIT_TRACE_REDACT")
123 .env_remove("GIT_TRACE_CURL")
125 .envs(self.env.iter().cloned());
126 command
127 }
128
129 #[must_use]
130 pub fn secret(&self) -> Option<&str> {
131 self.secret.as_deref()
132 }
133}
134
135fn bare_url(raw_url: &str) -> Result<BareUrl, HttpsAccessError> {
136 let uri: Uri = raw_url.parse().map_err(|_| HttpsAccessError::Unparsable)?;
137 let scheme = uri
138 .scheme_str()
139 .filter(|scheme| matches!(*scheme, "http" | "https"))
140 .ok_or(HttpsAccessError::NotHttp)?;
141 let authority = uri.authority().ok_or(HttpsAccessError::Unparsable)?;
142 let port = authority
143 .port()
144 .map_or_else(String::new, |port| format!(":{port}"));
145 let host = format!("{}{port}", authority.host());
146 if authority.host().is_empty() || !authority.as_str().ends_with(&host) {
148 return Err(HttpsAccessError::Unparsable);
149 }
150 let origin = format!("{scheme}://{host}");
151 let path = uri.path_and_query().map_or("", PathAndQuery::as_str);
152 Ok(BareUrl {
153 url: format!("{origin}{path}"),
154 origin,
155 })
156}
157
158const fn token_login<'a>(token: &'a str, provider: &str, is_pat: bool) -> (&'a str, &'a str) {
161 if is_pat {
162 ("pat", token)
163 } else if provider.eq_ignore_ascii_case("BITBUCKET") {
164 ("x-token-auth", token)
165 } else if provider.is_empty() {
166 (token, "")
167 } else {
168 ("oauth2", token)
169 }
170}
171
172pub async fn clone_https(opts: &CloneOpts, dest: &Path) -> Result<()> {
173 let kind = &opts
174 .credentials
175 .as_ref()
176 .context("missing credentials")?
177 .kind;
178 if !matches!(kind, CredentialKind::Https { .. }) {
179 anyhow::bail!("expected HTTPS credentials");
180 }
181 run_git_clone(opts, dest, &HttpsAccess::new(&opts.repo_url, Some(kind))?).await
182}
183
184pub async fn clone_https_token(opts: &CloneOpts, dest: &Path) -> Result<()> {
185 let kind = &opts
186 .credentials
187 .as_ref()
188 .context("missing credentials")?
189 .kind;
190 if !matches!(kind, CredentialKind::Token { .. }) {
191 anyhow::bail!("expected Token credentials");
192 }
193 run_git_clone(opts, dest, &HttpsAccess::new(&opts.repo_url, Some(kind))?).await
194}
195
196pub async fn clone_https_public(opts: &CloneOpts, dest: &Path) -> Result<()> {
197 run_git_clone(opts, dest, &HttpsAccess::public(&opts.repo_url)).await
198}
199
200#[must_use]
202pub fn build_https_config_args(
203 follow_redirects: bool,
204 is_pat: bool,
205 token: Option<&str>,
206 disable_credential_prompt: bool,
207) -> Vec<String> {
208 let mut args = vec![
209 "-c".to_owned(),
210 "http.sslVerify=false".to_owned(),
211 "-c".to_owned(),
212 format!("http.followRedirects={follow_redirects}"),
213 ];
214 if is_pat {
215 if let Some(t) = token {
216 let encoded = base64::engine::general_purpose::STANDARD.encode(format!(":{t}"));
217 args.extend([
218 "-c".to_owned(),
219 format!("http.extraHeader=Authorization: Basic {encoded}"),
220 ]);
221 }
222 }
223 if disable_credential_prompt {
224 args.extend(["-c".to_owned(), "credential.helper=".to_owned()]);
225 }
226 args
227}
228
229#[allow(clippy::too_many_arguments)]
231pub fn format_https_url(
232 repo_url: &str,
233 user: Option<&str>,
234 password: Option<&str>,
235 token: Option<&str>,
236 provider: Option<&str>,
237 is_pat: bool,
238) -> Result<String> {
239 let mut parsed = Url::parse(repo_url).context("parsing URL")?;
240 let path = parsed.path().to_owned();
242 parsed.set_path(&path);
243
244 if is_pat {
245 return Ok(parsed.to_string());
246 }
247
248 if let Some(t) = token {
249 let user_part = match provider {
250 Some(p) if p.eq_ignore_ascii_case("BITBUCKET") => "x-token-auth",
251 Some("") | None => "",
252 Some(_) => "oauth2",
253 };
254 if user_part.is_empty() {
255 parsed
257 .set_username(t)
258 .map_err(|()| anyhow::anyhow!("set username"))?;
259 parsed
260 .set_password(None)
261 .map_err(|()| anyhow::anyhow!("set password"))?;
262 } else {
263 parsed
265 .set_username(user_part)
266 .map_err(|()| anyhow::anyhow!("set username"))?;
267 parsed
268 .set_password(Some(t))
269 .map_err(|()| anyhow::anyhow!("set password"))?;
270 }
271 return Ok(parsed.to_string());
272 }
273
274 if let (Some(u), Some(p)) = (user, password) {
275 parsed
276 .set_username(u)
277 .map_err(|()| anyhow::anyhow!("set username"))?;
278 parsed
279 .set_password(Some(p))
280 .map_err(|()| anyhow::anyhow!("set password"))?;
281 return Ok(parsed.to_string());
282 }
283
284 Ok(parsed.to_string())
285}
286
287async fn run_git_clone(opts: &CloneOpts, dest: &Path, access: &HttpsAccess) -> Result<()> {
288 let extra_config = vec!["-c".to_owned(), "http.sslVerify=false".to_owned()];
289 let args = build_clone_args(opts, access.url(), dest, &extra_config);
290 let mut command = access.git();
291 command.args(&args);
292 reason::run(&mut command, "HTTPS", access.secret().as_slice()).await
293}
294
295#[cfg(test)]
296mod tests {
297 use super::{format_https_url, token_login, HttpsAccess};
298 use crate::errors::HttpsAccessError;
299 use crate::types::CredentialKind;
300 use std::ffi::OsString;
301
302 fn args(access: &HttpsAccess) -> Vec<String> {
303 access
304 .git()
305 .as_std()
306 .get_args()
307 .map(|arg| arg.to_string_lossy().into_owned())
308 .collect()
309 }
310
311 fn token(token: &str, provider: &str) -> CredentialKind {
312 CredentialKind::Token {
313 token: token.to_owned(),
314 is_pat: false,
315 oauth_type: provider.to_owned(),
316 }
317 }
318
319 #[test]
320 fn a_token_with_no_provider_logs_in_as_the_user_with_no_password() {
321 assert_eq!(token_login("tok", "", false), ("tok", ""));
322 }
323
324 #[test]
325 fn the_provider_names_the_user_even_off_its_own_domain() {
326 assert_eq!(
327 token_login("tok", "BITBUCKET", false),
328 ("x-token-auth", "tok")
329 );
330 assert_eq!(token_login("tok", "GITLAB", false), ("oauth2", "tok"));
331 }
332
333 #[test]
334 fn the_provider_is_matched_ignoring_the_case() {
335 let url = "https://host/a/b.git";
336
337 assert_eq!(
338 format_https_url(url, None, None, Some("tok"), Some("Bitbucket"), false).unwrap(),
339 format_https_url(url, None, None, Some("tok"), Some("BITBUCKET"), false).unwrap()
340 );
341 assert_eq!(
342 token_login("tok", "Bitbucket", false),
343 token_login("tok", "BITBUCKET", false)
344 );
345 }
346
347 fn basic(user: &str, password: &str) -> CredentialKind {
348 CredentialKind::Https {
349 user: user.to_owned(),
350 password: password.to_owned(),
351 }
352 }
353
354 #[test]
355 fn the_url_drops_whatever_credential_it_carried() {
356 let access = HttpsAccess::new(
357 "https://olduser:oldpass@host/a/b.git",
358 Some(&token("tok", "")),
359 )
360 .unwrap();
361 assert_eq!(access.url(), "https://host/a/b.git");
362 }
363
364 #[test]
365 fn a_pat_logs_in_as_a_placeholder_user_whatever_the_provider() {
366 assert_eq!(token_login("tok", "", true), ("pat", "tok"));
367 assert_eq!(token_login("tok", "BITBUCKET", true), ("pat", "tok"));
368 }
369
370 #[test]
371 fn the_host_is_left_as_written_for_git_to_read() {
372 for (url, expected) in [
373 ("https://Host:443/a.git", "https://Host:443/a.git"),
374 ("https://[::1]:8443/a.git", "https://[::1]:8443/a.git"),
375 ("https://u:p@w@host/a.git", "https://host/a.git"),
376 ] {
377 let access = HttpsAccess::new(url, Some(&token("tok", ""))).unwrap();
378 let origin = expected.trim_end_matches("/a.git");
379 assert_eq!(access.url(), expected, "{url}");
380 let helper = format!("credential.{origin}.helper=");
381 let host = args(&access).get(3).cloned().unwrap_or_default();
382 assert!(host.starts_with(&helper), "{url}");
383 }
384 }
385
386 #[test]
387 fn each_failure_says_what_the_python_said_and_never_the_url() {
388 for (url, expected) in [
389 ("ftp://u:hunter2@host/a.git", HttpsAccessError::NotHttp),
390 ("host/a.git", HttpsAccessError::Unparsable),
391 ("https:u:hunter2@host/a.git", HttpsAccessError::Unparsable),
392 ("https:///host/a.git", HttpsAccessError::Unparsable),
393 ("https://u:hunter2@/a.git", HttpsAccessError::Unparsable),
394 ("https://u:hunter2@:443/a.git", HttpsAccessError::Unparsable),
395 (
396 "https://u:hunter2@host:99999/a.git",
397 HttpsAccessError::Unparsable,
398 ),
399 (
400 "https://u:hunter2@faß.de/a.git",
401 HttpsAccessError::Unparsable,
402 ),
403 (
404 "https://tok\\hunter2@host/a.git",
405 HttpsAccessError::Unparsable,
406 ),
407 ] {
408 let error = HttpsAccess::new(url, Some(&token("tok", ""))).unwrap_err();
409 assert_eq!(error, expected, "{url}");
410 assert!(!error.to_string().contains("hunter2"), "{url}");
411 }
412 assert_eq!(
413 HttpsAccessError::NotHttp.to_string(),
414 "expected an http or https url"
415 );
416 assert_eq!(
417 HttpsAccessError::Unparsable.to_string(),
418 "Invalid url: its host or port could not be parsed"
419 );
420 }
421
422 #[test]
423 fn no_credential_leaves_the_url_unchecked() {
424 let access = HttpsAccess::new("ftp://host:99999/a.git", None).unwrap();
425 assert_eq!(access.url(), "ftp://host:99999/a.git");
426 assert_eq!(args(&access), ["-c", "credential.helper="]);
427 }
428
429 #[test]
430 fn the_debug_shows_neither_the_login_nor_the_environment() {
431 let access =
432 HttpsAccess::new("https://host/a.git", Some(&basic("someone", "s3cr3t"))).unwrap();
433 let shown = format!("{access:?}");
434 assert!(shown.contains("https://host/a.git"), "{shown}");
435 assert!(!shown.contains("s3cr3t"), "{shown}");
436 assert!(!shown.contains("someone"), "{shown}");
437 }
438
439 #[test]
440 fn the_machine_helpers_are_dropped_before_the_host_helper() {
441 let access = HttpsAccess::new("https://host/a.git", Some(&token("tok", ""))).unwrap();
442 let args = args(&access);
443 let [flag, machine, host_flag, host] = args.as_slice() else {
444 panic!("{args:?}");
445 };
446 assert_eq!(
447 [flag, machine, host_flag],
448 ["-c", "credential.helper=", "-c"]
449 );
450 assert!(
451 host.starts_with("credential.https://host.helper=!f()"),
452 "{host}"
453 );
454 }
455
456 #[test]
457 fn the_login_goes_through_the_environment() {
458 let access = HttpsAccess::new("https://host/a.git", Some(&basic("u", "p"))).unwrap();
459 let envs: Vec<_> = access
460 .git()
461 .as_std()
462 .get_envs()
463 .map(|(name, value)| (name.to_owned(), value.map(ToOwned::to_owned)))
464 .collect();
465 let set = |value: &str| Some(OsString::from(value));
466 assert_eq!(
467 envs,
468 [
469 ("FLUIDATTACKS_GIT_PASSWORD".into(), set("p")),
470 ("FLUIDATTACKS_GIT_USER".into(), set("u")),
471 ("GIT_TERMINAL_PROMPT".into(), set("0")),
472 ("GIT_TRACE_CURL".into(), None),
473 ("GIT_TRACE_REDACT".into(), None),
474 ]
475 );
476 }
477
478 #[test]
479 fn a_credential_with_a_line_break_or_a_nul_is_refused() {
480 for credential in [
481 token("tok\nhost=x", ""),
482 token("tok\0x", "GITLAB"),
483 basic("u\rx", "p"),
484 basic("u", "p\nx"),
485 ] {
486 let error = HttpsAccess::new("https://host/a/b.git", Some(&credential)).unwrap_err();
487 assert_eq!(error, HttpsAccessError::CredentialLineBreak);
488 assert_eq!(
489 error.to_string(),
490 "Invalid credentials: a line break or a nul byte"
491 );
492 }
493 }
494
495 #[test]
496 fn an_empty_provider_formats_the_url_like_no_provider_at_all() {
497 let url = "https://gitlab.com/a/b.git";
498 let no_provider = format_https_url(url, None, None, Some("tok"), None, false).unwrap();
499 assert_eq!(no_provider, "https://tok@gitlab.com/a/b.git");
500 assert_eq!(
501 format_https_url(url, None, None, Some("tok"), Some(""), false).unwrap(),
502 no_provider
503 );
504 }
505}