fluidattacks-core-git 0.39.0

Fluid Attacks Core Git
Documentation
use anyhow::Context;
use base64::Engine;
use std::path::Path;
use tokio::process::Command;

use super::{build_clone_args, reason, CloneOpts};

pub async fn clone_ssh(opts: &CloneOpts, dest: &Path) -> anyhow::Result<()> {
    let crate::types::CredentialKind::Ssh { key } = &opts
        .credentials
        .as_ref()
        .context("missing credentials")?
        .kind
    else {
        anyhow::bail!("expected SSH credentials");
    };

    let key_data = base64::engine::general_purpose::STANDARD
        .decode(key)
        .context("decoding SSH key")?;

    let key_file = tempfile::Builder::new()
        .prefix("melts-ssh-key-")
        .tempfile()
        .context("creating SSH key file")?;

    std::fs::write(key_file.path(), &key_data).context("writing SSH key")?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(key_file.path(), std::fs::Permissions::from_mode(0o400))
            .context("setting SSH key permissions")?;
    }

    let repo_url = normalize_ssh_url(&opts.repo_url);
    let args = build_clone_args(opts, &repo_url, dest, &[]);

    let git_ssh_command = setup_ssh_env(key_file.path());

    reason::run(
        Command::new("git")
            .args(&args)
            .env("GIT_SSH_COMMAND", git_ssh_command),
        "SSH",
        &[],
    )
    .await
}

#[must_use]
pub fn setup_ssh_env(key_file_path: &Path) -> String {
    format!(
        "ssh -i {} -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa",
        key_file_path.display()
    )
}

#[must_use]
pub fn normalize_ssh_url(raw_url: &str) -> String {
    // Special cases that should not be transformed
    if raw_url.contains("source.developers.google") || raw_url.starts_with("ssh://FLUID") {
        return raw_url.to_owned();
    }

    // Add ssh:// scheme if missing
    let with_scheme = if raw_url.starts_with("ssh://") {
        raw_url.to_owned()
    } else {
        format!("ssh://{raw_url}")
    };

    // If URL has ssh:// scheme but no explicit port, ensure the path
    // starts with '/' so the part after the host isn't parsed as a port.
    // e.g. ssh://git@host:v3/org/repo → ssh://git@host:/v3/org/repo
    if with_scheme.starts_with("ssh://") && !url_has_port(&with_scheme) {
        if let [scheme, host, path] = with_scheme.splitn(3, ':').collect::<Vec<_>>().as_slice() {
            if !path.starts_with('/') {
                return format!("{scheme}:{host}:/{path}");
            }
        }
    }

    with_scheme
}

#[must_use]
pub fn url_has_port(url: &str) -> bool {
    // Parse as URL and check if port is a valid integer
    url::Url::parse(url).ok().and_then(|u| u.port()).is_some()
}

#[cfg(test)]
mod tests {
    use super::normalize_ssh_url;

    #[test]
    fn a_url_that_already_names_a_scheme_is_still_forced_through_ssh() {
        assert_eq!(
            normalize_ssh_url("https://gitlab.com/a/b.git"),
            "ssh://https://gitlab.com/a/b.git"
        );
    }

    #[test]
    fn the_scp_form_gets_the_default_port_placeholder() {
        assert_eq!(
            normalize_ssh_url("git@gitlab.com:a/b.git"),
            "ssh://git@gitlab.com:/a/b.git"
        );
    }

    #[test]
    fn an_explicit_port_and_the_two_exemptions_are_left_alone() {
        for url in [
            "ssh://git@gitlab.com:2222/a/b.git",
            "ssh://FLUID@example.com/a/b.git",
            "https://source.developers.google.com/a/b",
        ] {
            assert_eq!(normalize_ssh_url(url), url);
        }
    }
}