guth-sync 0.1.0

Private-by-default rsync plugin for Guth and guth-cli.
Documentation
use guth_cli::install_manifest;
use guth_sync::plugin_manifest;
use guth_sync::profile::{parse_profile_id, Profile};
use guth_sync::transfer::{host, transfer, Direction, TransferOptions};
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use zeroize::Zeroizing;

fn main() -> ExitCode {
    match run(std::env::args_os().skip(1).collect()) {
        Ok(code) => ExitCode::from(code),
        Err(error) => {
            eprintln!("guth-sync: {error}");
            ExitCode::FAILURE
        }
    }
}

fn run(arguments: Vec<OsString>) -> io::Result<u8> {
    let command = arguments.first().and_then(|value| value.to_str());
    match command {
        Some("init") => {
            let root = required_path(&arguments, 1, "usage: guth-sync init <folder>")?;
            let profile = Profile::create(root)?;
            println!(
                "Created profile {} for {}",
                profile.id(),
                profile.root().display()
            );
            println!(
                "Run `guth-sync pairing-code {}` to pair another machine.",
                profile.id()
            );
            Ok(0)
        }
        Some("join") => {
            let root = required_path(&arguments, 1, "usage: guth-sync join <folder>")?;
            let pairing_code = Zeroizing::new(
                if arguments
                    .get(2)
                    .is_some_and(|value| value == "--code-stdin")
                {
                    let mut pairing_code = String::new();
                    io::stdin().take(256).read_to_string(&mut pairing_code)?;
                    pairing_code
                } else {
                    rpassword::prompt_password("Pairing code: ")?
                },
            );
            let profile = Profile::join(root, &pairing_code)?;
            println!(
                "Joined profile {} for {}",
                profile.id(),
                profile.root().display()
            );
            Ok(0)
        }
        Some("pairing-code") => {
            let profile = load_argument_profile(&arguments, 1)?;
            let pairing_code = profile.pairing_code();
            println!("{}", pairing_code.as_str());
            eprintln!("Keep this code private. It grants access to this sync profile.");
            Ok(0)
        }
        Some("profiles") => {
            let profiles = Profile::list()?;
            if profiles.is_empty() {
                println!("No Guth Sync profiles configured.");
            } else {
                for (id, root) in profiles {
                    println!("{id}  {}", root.display());
                }
            }
            Ok(0)
        }
        Some("install-plugin") => {
            let executable = std::env::current_exe()?;
            let path = install_manifest(&plugin_manifest(executable)?)?;
            println!("Installed Guth Sync plugin manifest at {}", path.display());
            Ok(0)
        }
        Some("authorized-key") => {
            let public_key = required_path(
                &arguments,
                1,
                "usage: guth-sync authorized-key <ssh-public-key>",
            )?;
            println!("{}", restricted_authorized_key(public_key)?);
            Ok(0)
        }
        Some("push") | Some("pull") => run_transfer(&arguments),
        Some("host") => Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "host mode requires a restricted SSH key generated by `guth-sync authorized-key`",
        )),
        Some("forced-host") => {
            let (profile, access) = forced_host_request()?;
            let status = host(&profile, &access)?;
            Ok(exit_code(status.code()))
        }
        Some("help") | Some("--help") | Some("-h") | None => {
            print_help();
            Ok(0)
        }
        Some("version") | Some("--version") | Some("-V") => {
            println!("guth-sync {}", env!("CARGO_PKG_VERSION"));
            Ok(0)
        }
        Some(other) => Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("unknown command: {other}"),
        )),
    }
}

fn run_transfer(arguments: &[OsString]) -> io::Result<u8> {
    let direction = if arguments[0] == "push" {
        Direction::Push
    } else {
        Direction::Pull
    };
    let profile = load_argument_profile(arguments, 1)?;
    let endpoint = required_text(
        arguments,
        2,
        "usage: guth-sync <push|pull> <profile-uuid> <user@host> <--all|paths...>",
    )?;
    let mut all = false;
    let mut options = TransferOptions::default();
    let mut paths = Vec::new();
    let mut remaining = arguments[3..].iter();
    while let Some(argument) = remaining.next() {
        match argument.to_str() {
            Some("--all") => all = true,
            Some("--dry-run") => options.dry_run = true,
            Some("--port") => {
                options.port = remaining
                    .next()
                    .and_then(|value| value.to_str())
                    .and_then(|value| value.parse::<u16>().ok())
                    .filter(|port| *port > 0)
                    .ok_or_else(|| {
                        io::Error::new(io::ErrorKind::InvalidInput, "--port requires a valid port")
                    })?;
            }
            Some("--identity") => {
                options.identity = Some(PathBuf::from(remaining.next().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidInput, "--identity requires a path")
                })?));
            }
            Some("--known-hosts") => {
                options.known_hosts = Some(PathBuf::from(remaining.next().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidInput, "--known-hosts requires a path")
                })?));
            }
            Some("--remote-program") => {
                options.remote_program =
                    required_iterator_text(remaining.next(), "--remote-program requires a path")?
                        .to_string();
            }
            Some(value) if value.starts_with('-') => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("unsupported transfer option: {value}"),
                ));
            }
            _ => paths.push(PathBuf::from(argument)),
        }
    }
    let status = transfer(&profile, direction, endpoint, &paths, all, &options)?;
    Ok(exit_code(status.code()))
}

fn load_argument_profile(arguments: &[OsString], index: usize) -> io::Result<Profile> {
    let id = required_text(arguments, index, "profile UUID is required")?;
    Profile::load(parse_profile_id(id)?)
}

fn forced_host_request() -> io::Result<(Profile, String)> {
    if std::env::var_os("SSH_CONNECTION").is_none() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "forced host mode is available only through SSH",
        ));
    }
    let command = std::env::var("SSH_ORIGINAL_COMMAND")
        .map_err(|_| io::Error::new(io::ErrorKind::PermissionDenied, "missing SSH command"))?;
    if command.len() > 512 || command.chars().any(char::is_control) {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "invalid SSH command",
        ));
    }
    let parts = command.split_ascii_whitespace().collect::<Vec<_>>();
    if parts.len() != 7
        || parts[1] != "host"
        || Path::new(parts[0])
            .file_name()
            .and_then(|name| name.to_str())
            != Some("guth-sync")
        || parts[4..] != ["--server", "--daemon", "."]
    {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "SSH key is restricted to Guth Sync transfers",
        ));
    }
    let access = match parts[3] {
        "read" | "write" => parts[3].to_string(),
        _ => {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "invalid Guth Sync access mode",
            ))
        }
    };
    let profile = Profile::load(parse_profile_id(parts[2])?)?;
    Ok((profile, access))
}

fn restricted_authorized_key(path: &Path) -> io::Result<String> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || !metadata.is_file() || metadata.len() > 16 * 1024 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "SSH public key must be a small regular file",
        ));
    }
    let content = fs::read_to_string(path)?;
    let mut parts = content.split_ascii_whitespace();
    let kind = parts.next().unwrap_or_default();
    let key = parts.next().unwrap_or_default();
    if !matches!(
        kind,
        "ssh-ed25519"
            | "sk-ssh-ed25519@openssh.com"
            | "ecdsa-sha2-nistp256"
            | "sk-ecdsa-sha2-nistp256@openssh.com"
    ) || key.is_empty()
        || key.len() > 12 * 1024
        || !key
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'='))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "unsupported or malformed SSH public key",
        ));
    }
    let executable = std::env::current_exe()?;
    let executable = executable
        .to_str()
        .filter(|value| {
            value.starts_with('/')
                && value.bytes().all(|byte| {
                    byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'-' | b'_')
                })
        })
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "guth-sync executable path is not safe for a forced command",
            )
        })?;
    Ok(format!(
        "restrict,command=\"{executable} forced-host\" {kind} {key}"
    ))
}

fn required_path<'a>(arguments: &'a [OsString], index: usize, usage: &str) -> io::Result<&'a Path> {
    arguments
        .get(index)
        .map(Path::new)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, usage))
}

fn required_text<'a>(arguments: &'a [OsString], index: usize, usage: &str) -> io::Result<&'a str> {
    arguments
        .get(index)
        .and_then(|value| value.to_str())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, usage))
}

fn required_iterator_text<'a>(value: Option<&'a OsString>, usage: &str) -> io::Result<&'a str> {
    value
        .and_then(|value| value.to_str())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, usage))
}

fn exit_code(code: Option<i32>) -> u8 {
    code.unwrap_or(1).clamp(0, u8::MAX as i32) as u8
}

fn print_help() {
    println!(
        "Guth Sync {}\n\nUSAGE:\n    guth-sync init <folder>\n    guth-sync join <folder> [--code-stdin]\n    guth-sync profiles\n    guth-sync pairing-code <profile-uuid>\n    guth-sync authorized-key <ssh-public-key>\n    guth-sync push <profile-uuid> <user@host> <--all|paths...> [OPTIONS]\n    guth-sync pull <profile-uuid> <user@host> <--all|paths...> [OPTIONS]\n    guth-sync install-plugin\n\nOPTIONS:\n    --dry-run\n    --port N\n    --identity /absolute/private/key\n    --known-hosts /absolute/known_hosts\n    --remote-program /absolute/guth-sync\n\nTransfers use SSH and rsync, never delete destination-only files, and do not persist endpoints or sessions.",
        env!("CARGO_PKG_VERSION")
    );
}