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, SshKey};
104    use crate::clone::tests::{opts, source};
105    use crate::clone::{clone_to_temp, CloneShape};
106    use crate::errors::SshKeyError;
107    use crate::types::CredentialKind;
108
109    #[test]
110    fn a_key_that_is_not_base64_is_refused() {
111        let written = SshKey::write("a");
112
113        assert!(matches!(written, Err(SshKeyError::Decode(_))));
114    }
115
116    #[test]
117    fn a_server_that_never_connects_or_stops_answering_is_given_up_on() {
118        let command = setup_ssh_env(Path::new("/tmp/a_key")).unwrap();
119        let command = command.to_string_lossy();
120
121        assert!(command.contains("-o ConnectTimeout=30"));
122        assert!(command.contains("-o ServerAliveInterval=60"));
123        assert!(command.contains("-o ServerAliveCountMax=10"));
124    }
125
126    #[test]
127    fn no_http_config_goes_to_git() {
128        let args = clone_args(&opts(CloneShape::SingleBranch), Path::new("/tmp/a_root"));
129
130        assert!(!args
131            .iter()
132            .any(|arg| arg.to_string_lossy().starts_with("http.")));
133    }
134
135    #[test]
136    fn the_scp_form_with_a_scheme_in_front_loses_the_scheme() {
137        for (stored, read) in [
138            (
139                "ssh://git@gitlab.com:org/repo.git",
140                "git@gitlab.com:org/repo.git",
141            ),
142            (
143                "ssh://git@ssh.dev.azure.com:v3/O/P/R",
144                "git@ssh.dev.azure.com:v3/O/P/R",
145            ),
146            (
147                "ssh://site@git.wpengine.com:site.git",
148                "site@git.wpengine.com:site.git",
149            ),
150        ] {
151            assert_eq!(drop_scp_scheme(stored), read);
152        }
153    }
154
155    #[test]
156    fn a_url_git_reads_as_meant_is_left_alone() {
157        for url in [
158            "ssh://git@gitlab.com:2222/org/repo.git",
159            "ssh://git@gitlab.com/org/repo.git",
160            "git@gitlab.com:org/repo.git",
161            "git@gitlab.com:2222/org/repo.git",
162        ] {
163            assert_eq!(drop_scp_scheme(url), url);
164        }
165    }
166
167    #[tokio::test]
168    async fn a_url_that_is_not_ssh_clones_nothing() {
169        let tmp = tempfile::tempdir().unwrap();
170        let url = source(tmp.path());
171        let key = CredentialKind::Ssh {
172            key: base64::engine::general_purpose::STANDARD.encode("not a real key"),
173        };
174
175        let outcome = clone_to_temp(tmp.path(), &url, "main", Some(&key), false, false).await;
176
177        assert!(outcome.is_err(), "{outcome:?}");
178    }
179}