Skip to main content

fluidattacks_core_git/clone/
https.rs

1use anyhow::{Context, Result};
2use base64::Engine;
3use std::path::Path;
4use tokio::process::Command;
5use url::Url;
6
7use super::{build_clone_args, reason, CloneOpts};
8use crate::types::CredentialKind;
9
10pub async fn clone_https(opts: &CloneOpts, dest: &Path) -> Result<()> {
11    let CredentialKind::Https { user, password } = &opts
12        .credentials
13        .as_ref()
14        .context("missing credentials")?
15        .kind
16    else {
17        anyhow::bail!("expected HTTPS credentials");
18    };
19    let repo_url = embed_credentials_in_url(&opts.repo_url, user, password)?;
20
21    let extra_config = vec!["-c".to_owned(), "http.sslVerify=false".to_owned()];
22    let args = build_clone_args(opts, &repo_url, dest, &extra_config);
23    run_git_clone(&args, &[password.as_str()]).await
24}
25
26pub async fn clone_https_token(opts: &CloneOpts, dest: &Path) -> Result<()> {
27    let CredentialKind::Token {
28        token,
29        is_pat,
30        oauth_type,
31    } = &opts
32        .credentials
33        .as_ref()
34        .context("missing credentials")?
35        .kind
36    else {
37        anyhow::bail!("expected Token credentials");
38    };
39
40    if *is_pat {
41        let encoded = base64::engine::general_purpose::STANDARD.encode(format!(":{token}"));
42        let extra_config = vec![
43            "-c".to_owned(),
44            "http.sslVerify=false".to_owned(),
45            "-c".to_owned(),
46            format!("http.extraHeader=Authorization: Basic {encoded}"),
47        ];
48        let args = build_clone_args(opts, &opts.repo_url, dest, &extra_config);
49        return run_git_clone(&args, &[token.as_str(), &encoded]).await;
50    }
51
52    let repo_url = embed_token_in_url(&opts.repo_url, token, oauth_type)?;
53    let extra_config = vec!["-c".to_owned(), "http.sslVerify=false".to_owned()];
54    let args = build_clone_args(opts, &repo_url, dest, &extra_config);
55    run_git_clone(&args, &[token.as_str()]).await
56}
57
58pub async fn clone_https_public(opts: &CloneOpts, dest: &Path) -> Result<()> {
59    let extra_config = vec!["-c".to_owned(), "http.sslVerify=false".to_owned()];
60    let args = build_clone_args(opts, &opts.repo_url, dest, &extra_config);
61    run_git_clone(&args, &[]).await
62}
63
64pub fn embed_token_in_url(url: &str, token: &str, provider: &str) -> Result<String> {
65    match provider {
66        "BITBUCKET" => embed_credentials_in_url(url, "x-token-auth", token),
67        "" => {
68            let mut parsed = Url::parse(url).context("parsing URL")?;
69            parsed
70                .set_username(token)
71                .map_err(|()| anyhow::anyhow!("failed to set the token as the user"))?;
72            Ok(parsed.to_string())
73        }
74        _ => embed_credentials_in_url(url, "oauth2", token),
75    }
76}
77
78pub fn embed_credentials_in_url(raw_url: &str, user: &str, password: &str) -> Result<String> {
79    let mut url = Url::parse(raw_url).context("parsing URL")?;
80    url.set_username(user)
81        .map_err(|()| anyhow::anyhow!("failed to set username"))?;
82    url.set_password(Some(password))
83        .map_err(|()| anyhow::anyhow!("failed to set password"))?;
84    Ok(url.to_string())
85}
86
87/// Build git config args for HTTPS operations (equivalent to Python's `get_https_git_config_args`).
88#[must_use]
89pub fn build_https_config_args(
90    follow_redirects: bool,
91    is_pat: bool,
92    token: Option<&str>,
93    disable_credential_prompt: bool,
94) -> Vec<String> {
95    let mut args = vec![
96        "-c".to_owned(),
97        "http.sslVerify=false".to_owned(),
98        "-c".to_owned(),
99        format!("http.followRedirects={follow_redirects}"),
100    ];
101    if is_pat {
102        if let Some(t) = token {
103            let encoded = base64::engine::general_purpose::STANDARD.encode(format!(":{t}"));
104            args.extend([
105                "-c".to_owned(),
106                format!("http.extraHeader=Authorization: Basic {encoded}"),
107            ]);
108        }
109    }
110    if disable_credential_prompt {
111        args.extend(["-c".to_owned(), "credential.helper=".to_owned()]);
112    }
113    args
114}
115
116/// Format URL with credentials embedded (equivalent to Python's `format_url`).
117#[allow(clippy::too_many_arguments)]
118pub fn format_https_url(
119    repo_url: &str,
120    user: Option<&str>,
121    password: Option<&str>,
122    token: Option<&str>,
123    provider: Option<&str>,
124    is_pat: bool,
125) -> Result<String> {
126    let mut parsed = Url::parse(repo_url).context("parsing URL")?;
127    // Re-quote the path
128    let path = parsed.path().to_owned();
129    parsed.set_path(&path);
130
131    if is_pat {
132        return Ok(parsed.to_string());
133    }
134
135    if let Some(t) = token {
136        let user_part = match provider {
137            Some(p) if p.eq_ignore_ascii_case("BITBUCKET") => "x-token-auth",
138            Some("") | None => "",
139            Some(_) => "oauth2",
140        };
141        if user_part.is_empty() {
142            // No provider: use token as username, no password
143            parsed
144                .set_username(t)
145                .map_err(|()| anyhow::anyhow!("set username"))?;
146            parsed
147                .set_password(None)
148                .map_err(|()| anyhow::anyhow!("set password"))?;
149        } else {
150            // Use username/password separately to avoid percent-encoding the colon
151            parsed
152                .set_username(user_part)
153                .map_err(|()| anyhow::anyhow!("set username"))?;
154            parsed
155                .set_password(Some(t))
156                .map_err(|()| anyhow::anyhow!("set password"))?;
157        }
158        return Ok(parsed.to_string());
159    }
160
161    if let (Some(u), Some(p)) = (user, password) {
162        parsed
163            .set_username(u)
164            .map_err(|()| anyhow::anyhow!("set username"))?;
165        parsed
166            .set_password(Some(p))
167            .map_err(|()| anyhow::anyhow!("set password"))?;
168        return Ok(parsed.to_string());
169    }
170
171    Ok(parsed.to_string())
172}
173
174async fn run_git_clone(args: &[String], secrets: &[&str]) -> Result<()> {
175    reason::run(Command::new("git").args(args), "HTTPS", secrets).await
176}
177
178#[cfg(test)]
179mod tests {
180    use super::{embed_token_in_url, format_https_url};
181
182    #[test]
183    fn a_credential_with_no_provider_carries_the_token_with_no_user() {
184        assert_eq!(
185            embed_token_in_url("https://gitlab.com/a/b.git", "tok", "").unwrap(),
186            "https://tok@gitlab.com/a/b.git"
187        );
188    }
189
190    #[test]
191    fn the_provider_names_the_user_even_off_its_own_domain() {
192        assert_eq!(
193            embed_token_in_url("https://git.acme.com/a/b.git", "tok", "BITBUCKET").unwrap(),
194            "https://x-token-auth:tok@git.acme.com/a/b.git"
195        );
196        assert_eq!(
197            embed_token_in_url("https://gitlab.com/a/b.git", "tok", "GITLAB").unwrap(),
198            "https://oauth2:tok@gitlab.com/a/b.git"
199        );
200    }
201
202    #[test]
203    fn an_empty_provider_formats_the_url_like_no_provider_at_all() {
204        let url = "https://gitlab.com/a/b.git";
205        let no_provider = format_https_url(url, None, None, Some("tok"), None, false).unwrap();
206        assert_eq!(no_provider, "https://tok@gitlab.com/a/b.git");
207        assert_eq!(
208            format_https_url(url, None, None, Some("tok"), Some(""), false).unwrap(),
209            no_provider
210        );
211    }
212}