guth-sync 0.1.1

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

const PROFILE_REPORT_BYTES_LIMIT: usize = 60 * 1024;

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 json = match arguments.as_slice() {
                [_] => false,
                [_, value] if value == "--json" => true,
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "usage: guth-sync profiles [--json]",
                    ))
                }
            };
            let profiles = Profile::list()?;
            let policy = AccessPolicy::load()?;
            if json {
                let mut entries = Vec::with_capacity(profiles.len());
                for (id, root, policy_required) in profiles {
                    entries.push(ProfileReportEntry {
                        id,
                        root,
                        read_only: policy.read_only_checked(id, policy_required)?,
                    });
                }
                let report = ProfileReport {
                    schema: 1,
                    all_read_only: policy.all_read_only(),
                    profiles: entries,
                };
                let output = serde_json::to_vec(&report).map_err(|error| {
                    io::Error::other(format!("could not encode profile report: {error}"))
                })?;
                if output.len() > PROFILE_REPORT_BYTES_LIMIT {
                    return Err(io::Error::other(
                        "profile report exceeds the Guth plugin output limit",
                    ));
                }
                println!("{}", String::from_utf8_lossy(&output));
            } else if profiles.is_empty() {
                println!("No Guth Sync profiles configured.");
            } else {
                for (id, root, policy_required) in profiles {
                    let _ = policy.read_only_checked(id, policy_required)?;
                    println!("{id}  {}", root.display());
                }
            }
            Ok(0)
        }
        Some("read-only") => {
            if arguments.len() != 3 {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "usage: guth-sync read-only <profile-uuid|--all> <on|off>",
                ));
            }
            let read_only =
                match required_text(&arguments, 2, "read-only setting must be on or off")? {
                    "on" => true,
                    "off" => false,
                    _ => {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "read-only setting must be on or off",
                        ))
                    }
                };
            let target = required_text(&arguments, 1, "profile UUID or --all is required")?;
            if target == "--all" {
                AccessPolicy::set_all(read_only)?;
                println!(
                    "All local Guth Sync profiles are now {}.",
                    if read_only { "read-only" } else { "read-write" }
                );
            } else {
                let profile_id = parse_profile_id(target)?;
                AccessPolicy::set_profile(profile_id, read_only)?;
                println!(
                    "Profile {profile_id} is now {} on this instance.",
                    if read_only { "read-only" } else { "read-write" }
                );
            }
            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
}

#[derive(Serialize)]
struct ProfileReport {
    schema: u32,
    all_read_only: bool,
    profiles: Vec<ProfileReportEntry>,
}

#[derive(Serialize)]
struct ProfileReportEntry {
    id: uuid::Uuid,
    root: PathBuf,
    read_only: bool,
}

fn print_help() {
    println!(
        "Guth Sync {}\n\nUSAGE:\n    guth-sync init <folder>\n    guth-sync join <folder> [--code-stdin]\n    guth-sync profiles [--json]\n    guth-sync read-only <profile-uuid|--all> <on|off>\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\nRead-only is local to this Guth instance: peers may pull from it, but peers cannot push to it and it cannot pull. Transfers use SSH and rsync, never delete destination-only files, and do not persist endpoints or sessions.",
        env!("CARGO_PKG_VERSION")
    );
}