Skip to main content

fluidattacks_core_git/clone/
ssh.rs

1use anyhow::Context;
2use base64::Engine;
3use std::ffi::OsString;
4use std::io::Write;
5use std::os::unix::ffi::{OsStrExt, OsStringExt};
6use std::path::Path;
7use tempfile::NamedTempFile;
8use tokio::process::Command;
9
10use super::{build_clone_args, reason, CloneOpts};
11use crate::errors::{CloneError, SshKeyError};
12
13// As GIT_ALLOW_PROTOCOL, keeps a `file://` or local path url from reaching a repository on this machine.
14pub(crate) const ONLY_SSH: &str = "ssh";
15
16pub(crate) struct SshKey {
17    // Never read, but kept so the key file lives until git ends; dropping it deletes the file.
18    _file: NamedTempFile,
19    pub(crate) command: OsString,
20}
21
22impl SshKey {
23    pub(crate) fn write(key: &str) -> Result<Self, SshKeyError> {
24        let file = key_file(key)?;
25        let command = setup_ssh_env(file.path())?;
26        Ok(Self {
27            _file: file,
28            command,
29        })
30    }
31}
32
33pub async fn clone_ssh(opts: &CloneOpts, dest: &Path) -> anyhow::Result<()> {
34    let crate::types::CredentialKind::Ssh { key } = &opts
35        .credentials
36        .as_ref()
37        .context("missing credentials")?
38        .kind
39    else {
40        anyhow::bail!("expected SSH credentials");
41    };
42    Ok(run_git_clone(opts, dest, key).await?)
43}
44
45pub(super) async fn run_git_clone(
46    opts: &CloneOpts,
47    dest: &Path,
48    key: &str,
49) -> Result<(), CloneError> {
50    let key = SshKey::write(key)?;
51    let mut command = Command::new("git");
52    command
53        .args(clone_args(opts, dest))
54        .env("GIT_SSH_COMMAND", &key.command)
55        .env("GIT_ALLOW_PROTOCOL", ONLY_SSH);
56    Ok(reason::run(&mut command, &[]).await?)
57}
58
59// git reads no http config over ssh.
60fn clone_args(opts: &CloneOpts, dest: &Path) -> Vec<OsString> {
61    build_clone_args(opts, drop_scp_scheme(&opts.repo_url), dest, &[])
62}
63
64/// tempfile creates it as 0600, which is what ssh demands of a private key.
65fn key_file(key: &str) -> Result<NamedTempFile, SshKeyError> {
66    let key = base64::engine::general_purpose::STANDARD.decode(key)?;
67    let mut file = tempfile::Builder::new()
68        .prefix("melts-ssh-key-")
69        .tempfile()
70        .map_err(SshKeyError::File)?;
71    file.write_all(&key).map_err(SshKeyError::File)?;
72    Ok(file)
73}
74
75/// Fails only for a path with a nul byte, which no shell can quote.
76pub fn setup_ssh_env(key_file_path: &Path) -> Result<OsString, shlex::QuoteError> {
77    // git hands the command to a shell, so a path with a space would split in two.
78    let key = shlex::bytes::try_quote(key_file_path.as_os_str().as_bytes())?;
79    let mut command = b"ssh -i ".to_vec();
80    command.extend_from_slice(&key);
81    command.extend_from_slice(
82        b" -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa -o ConnectTimeout=30 -o ServerAliveInterval=60 -o ServerAliveCountMax=10",
83    );
84    Ok(OsString::from_vec(command))
85}
86
87/// integrates stores scp urls as `ssh://git@host:org/repo`, which git cannot read, so the `ssh://`
88/// is dropped.
89#[must_use]
90pub(crate) fn drop_scp_scheme(url: &str) -> &str {
91    match url.strip_prefix("ssh://") {
92        Some(scp) if url::Url::parse(url).is_err() => scp,
93        _ => url,
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use std::path::Path;
100
101    use base64::Engine;
102
103    use super::{clone_args, drop_scp_scheme, setup_ssh_env};
104    use crate::clone::tests::{opts, source};
105    use crate::clone::{clone_to_temp, CloneShape};
106    use crate::types::CredentialKind;
107
108    #[test]
109    fn a_server_that_never_connects_or_stops_answering_is_given_up_on() {
110        let command = setup_ssh_env(Path::new("/tmp/a_key")).unwrap();
111        let command = command.to_string_lossy();
112
113        assert!(command.contains("-o ConnectTimeout=30"));
114        assert!(command.contains("-o ServerAliveInterval=60"));
115        assert!(command.contains("-o ServerAliveCountMax=10"));
116    }
117
118    #[test]
119    fn no_http_config_goes_to_git() {
120        let args = clone_args(&opts(CloneShape::SingleBranch), Path::new("/tmp/a_root"));
121
122        assert!(!args
123            .iter()
124            .any(|arg| arg.to_string_lossy().starts_with("http.")));
125    }
126
127    #[test]
128    fn the_scp_form_with_a_scheme_in_front_loses_the_scheme() {
129        for (stored, read) in [
130            (
131                "ssh://git@gitlab.com:org/repo.git",
132                "git@gitlab.com:org/repo.git",
133            ),
134            (
135                "ssh://git@ssh.dev.azure.com:v3/O/P/R",
136                "git@ssh.dev.azure.com:v3/O/P/R",
137            ),
138            (
139                "ssh://site@git.wpengine.com:site.git",
140                "site@git.wpengine.com:site.git",
141            ),
142        ] {
143            assert_eq!(drop_scp_scheme(stored), read);
144        }
145    }
146
147    #[test]
148    fn a_url_git_reads_as_meant_is_left_alone() {
149        for url in [
150            "ssh://git@gitlab.com:2222/org/repo.git",
151            "ssh://git@gitlab.com/org/repo.git",
152            "git@gitlab.com:org/repo.git",
153            "git@gitlab.com:2222/org/repo.git",
154        ] {
155            assert_eq!(drop_scp_scheme(url), url);
156        }
157    }
158
159    #[tokio::test]
160    async fn a_url_that_is_not_ssh_clones_nothing() {
161        let tmp = tempfile::tempdir().unwrap();
162        let url = source(tmp.path());
163        let key = CredentialKind::Ssh {
164            key: base64::engine::general_purpose::STANDARD.encode("not a real key"),
165        };
166
167        let outcome = clone_to_temp(tmp.path(), &url, "main", Some(&key), false, false).await;
168
169        assert!(outcome.is_err(), "{outcome:?}");
170    }
171}