hazine 0.2.9

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
//! `hazine ui`: open a hazine server in the DuckDB UI on this machine.
//!
//! It opens an SSH tunnel to the server's Quack address, attaches the server
//! as a Quack database in a local DuckDB CLI, and starts the DuckDB UI. The
//! token comes from the server's env file (over SSH, with `sudo -n`) or from
//! `HAZINE_TOKEN`, and reaches DuckDB only through its environment.

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpListener};
use std::path::PathBuf;
use std::process::Stdio;
use std::time::Duration;

use tokio::net::TcpStream;
use tokio::process::{Child, Command};

use crate::Error;
use crate::setup::render;
use crate::supervisor::check_version;
use crate::tempdir::TempDir;

/// The environment variable that carries the token to the local DuckDB.
pub const TOKEN_ENV: &str = "HAZINE_TOKEN";

/// The server's env file, which `hazine setup` writes.
const REMOTE_ENV: &str = "/etc/hazine/hazine.env";

/// How long the tunnel may take to come up.
const TUNNEL_TIMEOUT: Duration = Duration::from_secs(20);

/// How `hazine ui` connects.
#[derive(Debug, Clone)]
pub struct Options {
    /// The server, as given to ssh: `host`, `user@host` or an ssh_config alias.
    pub host: String,
    /// The name the server gets in DuckDB.
    pub name: String,
    /// The local end of the tunnel.
    pub local_port: u16,
    /// Where the DuckDB UI listens.
    pub ui_port: u16,
    /// The token, if given; else read from the server.
    pub token: Option<String>,
    /// The local DuckDB CLI (2.0 or later).
    pub duckdb: PathBuf,
    /// A local database file to open; in memory without one.
    pub database: Option<PathBuf>,
    /// Open the UI in the browser (`duckdb -ui`); else only print its URL.
    pub open: bool,
    /// The ssh client.
    pub ssh: PathBuf,
}

/// The token and Quack address in the server's env file.
#[derive(Clone)]
struct Remote {
    token: String,
    quack_addr: SocketAddr,
}

/// Run the DuckDB UI attached to the server until the DuckDB CLI exits.
pub async fn run(options: Options) -> Result<(), Error> {
    check_name(&options.name)?;
    // Another DuckDB UI on the port would answer instead of this one.
    port_free(options.ui_port).map_err(|_| {
        Error::Tunnel(format!(
            "port {} is in use, perhaps by another DuckDB UI; pick another with --ui-port",
            options.ui_port
        ))
    })?;
    let version = check_version(&options.duckdb).await?;
    tracing::info!(%version, duckdb = %options.duckdb.display(), "found DuckDB");

    let remote = remote(&options).await?;
    let mut tunnel = open_tunnel(&options, remote.quack_addr).await?;
    tracing::info!(
        host = %options.host,
        local = %format!("127.0.0.1:{}", options.local_port),
        remote = %remote.quack_addr,
        "tunnel open"
    );

    let dir = TempDir::new()?;
    let init = dir.path().join("init.sql");
    std::fs::write(
        &init,
        init_sql(
            &options.name,
            options.local_port,
            options.ui_port,
            options.open,
        ),
    )?;

    let mut duckdb = Command::new(&options.duckdb);
    duckdb.args(["-no-agent", "-init"]).arg(&init);
    if options.open {
        duckdb.arg("-ui");
    }
    if let Some(database) = &options.database {
        duckdb.arg(database);
    }
    duckdb.env(TOKEN_ENV, &remote.token).kill_on_drop(true);
    let mut duckdb = duckdb.spawn().map_err(|source| Error::Spawn {
        program: options.duckdb.clone(),
        source,
    })?;

    // Ctrl-C is for DuckDB (it cancels the running query), not for hazine:
    // listening for it here keeps the default handler from ending hazine and
    // orphaning the tunnel.
    let ignore_ctrl_c = tokio::spawn(async { while tokio::signal::ctrl_c().await.is_ok() {} });
    let result = tokio::select! {
        status = duckdb.wait() => status.map_err(Error::from),
        status = tunnel.wait() => {
            let status = status?;
            Err(Error::Tunnel(format!("ssh exited ({status}); the connection to {} is gone", options.host)))
        }
    };
    ignore_ctrl_c.abort();
    // kill_on_drop does not wait; wait so the port is free when we return.
    let _ = tunnel.kill().await; // Already gone if it ended the select.
    let _ = duckdb.kill().await; // Already gone if it ended the select.
    let status = result?;
    tracing::info!(%status, "DuckDB exited; tunnel closed");
    Ok(())
}

/// The token and Quack address: the token from the options if given, the
/// rest from the server's env file over SSH.
async fn remote(options: &Options) -> Result<Remote, Error> {
    let default_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 1294));
    let output = Command::new(&options.ssh)
        .args(["-o", "BatchMode=yes", "--", &options.host])
        .arg(format!(
            "sudo -n grep -E '^(QUACK_TOKEN|HAZINE_QUACK_ADDR)=' {REMOTE_ENV}"
        ))
        .stdin(Stdio::null())
        .output()
        .await
        .map_err(|source| Error::Spawn {
            program: options.ssh.clone(),
            source,
        })?;
    let env = render::parse_env(&String::from_utf8_lossy(&output.stdout));
    let quack_addr = match env.get("HAZINE_QUACK_ADDR") {
        Some(addr) => addr.parse().map_err(|_| {
            Error::Tunnel(format!(
                "HAZINE_QUACK_ADDR on {} is not an address: {addr:?}",
                options.host
            ))
        })?,
        None => default_addr,
    };
    let token = match (&options.token, env.get("QUACK_TOKEN")) {
        (Some(token), _) if !token.is_empty() => token.clone(),
        (_, Some(token)) if !token.is_empty() => token.clone(),
        _ => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::Tunnel(format!(
                "cannot read the token from {REMOTE_ENV} on {} ({}); set {TOKEN_ENV}, \
                 or allow sudo without a password there",
                options.host,
                stderr.trim().lines().last().unwrap_or("no output"),
            )));
        }
    };
    Ok(Remote { token, quack_addr })
}

/// Start `ssh -N -L` and wait until the local end accepts connections.
async fn open_tunnel(options: &Options, remote: SocketAddr) -> Result<Child, Error> {
    let local = SocketAddr::from((Ipv4Addr::LOCALHOST, options.local_port));
    // A port in use would make ssh forward nothing, or connect us elsewhere.
    port_free(options.local_port).map_err(|_| {
        Error::Tunnel(format!(
            "local port {} is in use; pick another with --local-port",
            options.local_port
        ))
    })?;
    let mut ssh = Command::new(&options.ssh);
    ssh.args(tunnel_args(local, remote, &options.host))
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        // Its own process group: Ctrl-C in DuckDB must not end the tunnel.
        .process_group(0)
        .kill_on_drop(true);
    let mut child = ssh.spawn().map_err(|source| Error::Spawn {
        program: options.ssh.clone(),
        source,
    })?;
    let deadline = tokio::time::Instant::now() + TUNNEL_TIMEOUT;
    loop {
        if TcpStream::connect(local).await.is_ok() {
            return Ok(child);
        }
        if let Some(status) = child.try_wait()? {
            let mut stderr = String::new();
            if let Some(mut pipe) = child.stderr.take() {
                use tokio::io::AsyncReadExt;
                let _ = pipe.read_to_string(&mut stderr).await; // Best effort, for the message.
            }
            return Err(Error::Tunnel(format!(
                "ssh exited ({status}): {}",
                stderr.trim()
            )));
        }
        if tokio::time::Instant::now() > deadline {
            return Err(Error::Tunnel(format!(
                "the tunnel to {} did not open within {TUNNEL_TIMEOUT:?}",
                options.host
            )));
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

/// Fails if something listens on `port` on localhost, over IPv4 or IPv6: a
/// DuckDB UI, for one, listens on `[::1]` only, so binding 127.0.0.1 alone
/// would not notice it.
fn port_free(port: u16) -> std::io::Result<()> {
    for ip in [
        IpAddr::V4(Ipv4Addr::LOCALHOST),
        IpAddr::V6(Ipv6Addr::LOCALHOST),
    ] {
        let addr = SocketAddr::new(ip, port);
        if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(300)).is_ok() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::AddrInUse,
                format!("something listens on {addr}"),
            ));
        }
    }
    TcpListener::bind((Ipv4Addr::LOCALHOST, port)).map(drop)
}

/// `ssh` arguments for a tunnel from `local` to `remote` on `host`.
fn tunnel_args(local: SocketAddr, remote: SocketAddr, host: &str) -> Vec<String> {
    vec![
        "-N".into(),
        "-o".into(),
        "ExitOnForwardFailure=yes".into(),
        "-o".into(),
        "ServerAliveInterval=30".into(),
        "-L".into(),
        format!("{}:{}:{}", local.ip(), local.port(), forward_host(remote)),
        "--".into(),
        host.into(),
    ]
}

/// `remote` as the `host:port` part of `-L`; IPv6 in brackets.
fn forward_host(remote: SocketAddr) -> String {
    match remote {
        SocketAddr::V4(addr) => addr.to_string(),
        SocketAddr::V6(addr) => format!("[{}]:{}", addr.ip(), addr.port()),
    }
}

/// The local DuckDB's init file: attach the server through the tunnel, and
/// put the UI on `ui_port`. With `open` false, start the UI server without
/// opening a browser.
fn init_sql(name: &str, local_port: u16, ui_port: u16, open: bool) -> String {
    let uri = format!("quack:127.0.0.1:{local_port}");
    let start = if open {
        ""
    } else {
        "CALL start_ui_server();\n"
    };
    format!(
        "-- Written by hazine ui. The token comes from ${TOKEN_ENV}.\n\
         LOAD quack;\n\
         CREATE SECRET hazine_{name} (TYPE quack, SCOPE '{uri}', TOKEN getenv('{TOKEN_ENV}'));\n\
         ATTACH '{uri}' AS \"{name}\" (TYPE quack, DISABLE_SSL true);\n\
         SET ui_local_port = {ui_port};\n\
         {start}"
    )
}

/// The name for a server: the first label of its host name, e.g. `hermione`
/// for `user@hermione.front-matter.de`.
pub fn default_name(host: &str) -> String {
    let host = host.rsplit('@').next().unwrap_or(host);
    let label = host.split('.').next().unwrap_or(host);
    let name: String = label
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();
    if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
        format!("hazine_{name}")
    } else {
        name
    }
}

/// A database name: letters, digits and `_`, not starting with a digit.
fn check_name(name: &str) -> Result<(), Error> {
    let valid = !name.is_empty()
        && !name.starts_with(|c: char| c.is_ascii_digit())
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
    if valid {
        Ok(())
    } else {
        Err(Error::InvalidSetting {
            name: "name",
            reason: format!("{name:?}: use letters, digits and _"),
        })
    }
}

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

    #[test]
    fn names_come_from_the_host() {
        for (host, name) in [
            ("hermione.front-matter.de", "hermione"),
            ("martin@hermione.front-matter.de", "hermione"),
            ("my-server", "my_server"),
            ("10.0.0.5", "hazine_10"),
        ] {
            assert_eq!(default_name(host), name, "{host}");
            assert!(check_name(&default_name(host)).is_ok(), "{host}");
        }
        for bad in ["", "1abc", "a-b", "a\"b"] {
            assert!(check_name(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn the_init_file_attaches_without_the_token() {
        let sql = init_sql("hermione", 1294, 4213, true);
        assert!(sql.contains("TOKEN getenv('HAZINE_TOKEN')"));
        assert!(sql.contains(
            "ATTACH 'quack:127.0.0.1:1294' AS \"hermione\" (TYPE quack, DISABLE_SSL true);"
        ));
        assert!(sql.contains("SET ui_local_port = 4213;"));
        assert!(!sql.contains("start_ui_server"));
        assert!(init_sql("hermione", 1294, 4299, false).contains("CALL start_ui_server();"));
    }

    #[test]
    fn ports_in_use_on_ipv4_or_ipv6_are_noticed() {
        for ip in ["127.0.0.1", "[::1]"] {
            let listener = TcpListener::bind(format!("{ip}:0")).unwrap();
            let port = listener.local_addr().unwrap().port();
            assert!(port_free(port).is_err(), "{ip}:{port}");
        }
        let free = TcpListener::bind("127.0.0.1:0")
            .unwrap()
            .local_addr()
            .unwrap()
            .port();
        assert!(port_free(free).is_ok());
    }

    #[test]
    fn the_tunnel_forwards_to_the_quack_address() {
        let local = "127.0.0.1:1300".parse().unwrap();
        let args = tunnel_args(local, "127.0.0.1:1294".parse().unwrap(), "hermione");
        assert_eq!(args[6], "127.0.0.1:1300:127.0.0.1:1294");
        assert_eq!(args.last().map(String::as_str), Some("hermione"));
        let args = tunnel_args(local, "[::1]:1294".parse().unwrap(), "h");
        assert_eq!(args[6], "127.0.0.1:1300:[::1]:1294");
    }
}