exedev 0.1.0

Official Rust SDK for exe.dev: create VMs, run commands on them, and run every exe.dev command
Documentation
// Code generated by "go run ./cmd/gensdkrs" in the exe.dev repository. DO NOT EDIT.

//! Local token signing: an exe0 token is its permissions, signed by an SSH
//! key on your account as `ssh-keygen -Y sign` signs them. See
//! <https://exe.dev/docs/https-api-local-key>.

use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use base64::Engine as _;
use serde_json::{Map, Value};

use crate::error::{Error, Result};
use crate::wire;

/// Makes an exe0 API token locally, without a request.
///
/// key is the path of an SSH private key on your exe.dev account (`ssh
/// exe.dev ssh-key add`), or of its public key when ssh-agent holds the
/// private key; a leading `~/` is your home directory. Removing the key from
/// your account revokes every token it signed. It is signed with `ssh-keygen
/// -Y sign`, which must be installed, and asks for the key's passphrase if it
/// has one.
///
/// The builder sets the token's claims; see
/// <https://exe.dev/docs/https-api#granular-permissions>. Without
/// [`cmds`](SignToken::cmds), a token may run a default set of commands that
/// includes new, ls, and whoami, but not ssh or rm.
///
/// ```no_run
/// # fn f() -> exedev::Result<()> {
/// use std::time::Duration;
/// let token = exedev::sign_token("~/.ssh/id_ed25519")
///     .cmds(["new", "ls", "ssh", "rm"])
///     .expires_in(Duration::from_secs(3600))
///     .sign()?;
/// let exe = exedev::Client::new(token)?;
/// # Ok(()) }
/// ```
pub fn sign_token(key: impl AsRef<Path>) -> SignToken {
    SignToken {
        key: key.as_ref().to_path_buf(),
        claims: Map::new(),
        payload: None,
        vm: None,
        namespace: None,
        ssh_keygen: "ssh-keygen".into(),
        err: None,
    }
}

/// [`sign_token`]: a token to sign.
#[derive(Debug, Clone)]
#[must_use = "call sign() to make the token"]
pub struct SignToken {
    key: PathBuf,
    claims: Map<String, Value>,
    payload: Option<String>,
    vm: Option<String>,
    namespace: Option<String>,
    ssh_keygen: PathBuf,
    err: Option<String>,
}

fn epoch(t: SystemTime) -> std::result::Result<u64, String> {
    t.duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .map_err(|_| "a time before 1970".to_string())
}

impl SignToken {
    /// The commands the token may run, such as `["new", "ls", "ssh", "rm"]`.
    pub fn cmds<I, S>(self, cmds: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let cmds: Vec<Value> = cmds.into_iter().map(|c| Value::String(c.into())).collect();
        self.claim("cmds", Value::Array(cmds))
    }

    /// When the token expires.
    pub fn expires_at(mut self, t: SystemTime) -> Self {
        match epoch(t) {
            Ok(s) => self.claim("exp", s.into()),
            Err(e) => {
                self.err.get_or_insert(e);
                self
            }
        }
    }

    /// Expires this long from now.
    pub fn expires_in(self, d: Duration) -> Self {
        self.expires_at(SystemTime::now() + d)
    }

    /// When the token becomes valid.
    pub fn not_before(mut self, t: SystemTime) -> Self {
        match epoch(t) {
            Ok(s) => self.claim("nbf", s.into()),
            Err(e) => {
                self.err.get_or_insert(e);
                self
            }
        }
    }

    /// Sets any claim, such as `"ctx"`.
    pub fn claim(mut self, name: impl Into<String>, value: Value) -> Self {
        self.claims.insert(name.into(), value);
        self
    }

    /// Signs this JSON as it is, in place of the claims.
    pub fn payload(mut self, json: impl Into<String>) -> Self {
        self.payload = Some(json.into());
        self
    }

    /// Makes a token for this VM's HTTPS endpoints instead of the API.
    pub fn vm(mut self, vm: impl Into<String>) -> Self {
        self.vm = Some(vm.into());
        self
    }

    /// The signing namespace, for an exe.dev that is not at exe.dev: by
    /// default `v0@exe.dev`, or `v0@VM.exe.xyz` with [`vm`](SignToken::vm).
    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }

    /// The ssh-keygen program to run; by default, `ssh-keygen` on PATH.
    pub fn ssh_keygen(mut self, program: impl AsRef<Path>) -> Self {
        self.ssh_keygen = program.as_ref().to_path_buf();
        self
    }

    /// Signs the token. This runs ssh-keygen, which may ask for a
    /// passphrase: in async code, call it from
    /// `tokio::task::spawn_blocking`.
    pub fn sign(self) -> Result<String> {
        if let Some(err) = self.err {
            return Err(Error::invalid(format!("sign_token: {err}")));
        }
        if let Some(vm) = &self.vm {
            wire::vm_name(vm)?;
        }
        let namespace = match (self.namespace, &self.vm) {
            (Some(ns), _) => ns,
            (None, Some(vm)) => format!("v0@{vm}.exe.xyz"),
            (None, None) => "v0@exe.dev".to_string(),
        };
        let payload = match self.payload {
            Some(p) => p,
            None => Value::Object(self.claims).to_string(),
        };
        let path = expand_home(&self.key);
        let program = self.ssh_keygen.display().to_string();
        let mut child = std::process::Command::new(&self.ssh_keygen)
            .args(["-Y", "sign", "-q", "-f"])
            .arg(&path)
            .args(["-n", &namespace])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| Error::io(format!("cannot run {program}"), e))?;
        let mut stdin = child.stdin.take().expect("stdin");
        let written = stdin.write_all(payload.as_bytes());
        drop(stdin);
        let out = child
            .wait_with_output()
            .map_err(|e| Error::io(format!("cannot run {program}"), e))?;
        written.map_err(|e| Error::io(format!("cannot run {program}"), e))?;
        let stdout = String::from_utf8_lossy(&out.stdout);
        let armor = stdout
            .split_once("-----BEGIN SSH SIGNATURE-----")
            .and_then(|(_, rest)| rest.split_once("-----END SSH SIGNATURE-----"))
            .map(|(body, _)| body);
        let Some(armor) = armor.filter(|_| out.status.success()) else {
            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
            let message = if stderr.is_empty() {
                format!("{}", out.status)
            } else {
                stderr
            };
            return Err(Error::Config(format!(
                "ssh-keygen -Y sign with {}: {message}",
                path.display()
            )));
        };
        let encoded: String = armor.split_whitespace().collect();
        let blob = base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .map_err(|_| Error::Config("ssh-keygen -Y sign printed a malformed signature".into()))?;
        let url = base64::engine::general_purpose::URL_SAFE_NO_PAD;
        Ok(format!("exe0.{}.{}", url.encode(payload.as_bytes()), url.encode(blob)))
    }
}

fn expand_home(path: &Path) -> PathBuf {
    if let Ok(rest) = path.strip_prefix("~")
        && let Some(home) = std::env::var_os("HOME")
    {
        return PathBuf::from(home).join(rest);
    }
    path.to_path_buf()
}

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

    #[test]
    fn signs_with_ssh_keygen() {
        let dir = std::env::temp_dir().join(format!("exedev-token-{}", wire::random_hex(4)));
        std::fs::create_dir_all(&dir).unwrap();
        let key = dir.join("id");
        let made = std::process::Command::new("ssh-keygen")
            .args(["-q", "-t", "ed25519", "-N", "", "-f"])
            .arg(&key)
            .status();
        if !made.is_ok_and(|s| s.success()) {
            eprintln!("skipping: no ssh-keygen");
            return;
        }
        let token = sign_token(&key)
            .cmds(["ls"])
            .claim("exp", 2000000000.into())
            .sign()
            .unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts[0], "exe0");
        let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(parts[1])
            .unwrap();
        assert_eq!(payload, br#"{"cmds":["ls"],"exp":2000000000}"#);
        let blob = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(parts[2])
            .unwrap();
        assert!(blob.starts_with(b"SSHSIG"));
        assert!(sign_token(&key).vm("-bad").sign().is_err());
        assert!(sign_token(dir.join("missing")).sign().is_err());
        std::fs::remove_dir_all(dir).unwrap();
    }
}