9.1 KiB · text History 2977adf
//! Where the server URL, API token and default organization and project
//! live between invocations.
//!
//! One file, `$XDG_CONFIG_HOME/vigil/config.toml`, written 0600: a token is
//! a bearer credential, so the file is treated like an SSH key rather than
//! a preference.
//!
//! Each setting resolves flag, then environment, then the file, so a CI
//! job or a one-off against a second server never has to touch it.

use anyhow::{Context, Result, anyhow};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

pub const ENV_URL: &str = "VIGIL_URL";
pub const ENV_TOKEN: &str = "VIGIL_TOKEN";
pub const ENV_ORG: &str = "VIGIL_ORG";
pub const ENV_PROJECT: &str = "VIGIL_PROJECT";
/// Overrides where the config file lives (tests, and anyone juggling
/// several servers).
pub const ENV_CONFIG: &str = "VIGIL_CONFIG";

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
    /// Base URL of the server, no trailing slash.
    pub url: Option<String>,
    pub token: Option<String>,
    /// Organization slug used when neither `--org` nor `VIGIL_ORG` names one.
    pub org: Option<String>,
    /// Project slug used when neither `--project` nor `VIGIL_PROJECT` names one.
    pub project: Option<String>,
}

impl Config {
    pub fn path() -> Result<PathBuf> {
        if let Some(path) = std::env::var_os(ENV_CONFIG) {
            return Ok(PathBuf::from(path));
        }
        let dir = dirs::config_dir().ok_or_else(|| {
            anyhow!("no config directory on this platform; set {ENV_URL} and {ENV_TOKEN} instead")
        })?;
        Ok(dir.join("vigil").join("config.toml"))
    }

    pub fn load() -> Result<Self> {
        Self::load_from(&Self::path()?)
    }

    pub fn load_from(path: &Path) -> Result<Self> {
        match std::fs::read_to_string(path) {
            Ok(raw) => toml::from_str(&raw)
                .with_context(|| format!("{} is not valid TOML", path.display())),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
        }
    }

    pub fn save(&self) -> Result<PathBuf> {
        let path = Self::path()?;
        self.save_to(&path)?;
        Ok(path)
    }

    pub fn save_to(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("creating {}", parent.display()))?;
        }
        let body = toml::to_string_pretty(self).context("serializing config")?;
        write_private(path, &body).with_context(|| format!("writing {}", path.display()))
    }

    /// Forget the credentials but keep the default organization and project.
    pub fn clear_credentials(&mut self) {
        self.url = None;
        self.token = None;
    }
}

/// Written with mode 0600 from the start, so the token is never readable by
/// others, not even between the write and a chmod.
#[cfg(unix)]
fn write_private(path: &Path, body: &str) -> std::io::Result<()> {
    use std::io::Write;
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};

    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(path)?;
    // An existing file keeps its old mode through `open`; tighten it.
    file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
    file.write_all(body.as_bytes())
}

#[cfg(not(unix))]
fn write_private(path: &Path, body: &str) -> std::io::Result<()> {
    std::fs::write(path, body)
}

/// Explicit values from the command line, before the environment and the
/// file are consulted.
#[derive(Debug, Default, Clone)]
pub struct Flags {
    pub url: Option<String>,
    pub token: Option<String>,
    pub org: Option<String>,
    pub project: Option<String>,
}

/// What a command runs with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settings {
    pub url: String,
    pub token: String,
    pub org: Option<String>,
    pub project: Option<String>,
}

/// Flag, then environment (via `env`, so tests needn't touch the process
/// environment), then the config file. An empty value counts as unset.
pub fn resolve(
    flags: &Flags,
    env: impl Fn(&str) -> Option<String>,
    cfg: &Config,
) -> Result<Settings> {
    let pick = |flag: &Option<String>, var: &str, file: &Option<String>| {
        flag.clone()
            .or_else(|| env(var))
            .or_else(|| file.clone())
            .filter(|v| !v.trim().is_empty())
    };

    let url = pick(&flags.url, ENV_URL, &cfg.url).ok_or_else(|| {
        anyhow!("not signed in: run `vgl login` (or set {ENV_URL} and {ENV_TOKEN})")
    })?;
    let token = pick(&flags.token, ENV_TOKEN, &cfg.token)
        .ok_or_else(|| anyhow!("no API token: run `vgl login` (or set {ENV_TOKEN})"))?;

    Ok(Settings {
        url: normalize_url(&url),
        token: token.trim().to_string(),
        org: pick(&flags.org, ENV_ORG, &cfg.org),
        project: pick(&flags.project, ENV_PROJECT, &cfg.project),
    })
}

/// The process environment, for [`resolve`].
pub fn process_env(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

/// Trim the trailing slash (and a pasted `/api/0`), and add a scheme if
/// the user typed a bare host.
pub fn normalize_url(raw: &str) -> String {
    let trimmed = raw.trim().trim_end_matches('/');
    let trimmed = trimmed.strip_suffix("/api/0").unwrap_or(trimmed);
    if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
        trimmed.to_string()
    } else {
        format!("https://{trimmed}")
    }
}

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

    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |k| map.get(k).cloned()
    }

    fn file() -> Config {
        Config {
            url: Some("https://file.example.com".into()),
            token: Some("file-token".into()),
            org: Some("file-org".into()),
            project: Some("file-project".into()),
        }
    }

    #[test]
    fn the_file_is_the_fallback() {
        let s = resolve(&Flags::default(), env_of(&[]), &file()).unwrap();
        assert_eq!(s.url, "https://file.example.com");
        assert_eq!(s.token, "file-token");
        assert_eq!(s.org.as_deref(), Some("file-org"));
        assert_eq!(s.project.as_deref(), Some("file-project"));
    }

    #[test]
    fn the_environment_beats_the_file() {
        let env = env_of(&[
            (ENV_URL, "http://localhost:4000/"),
            (ENV_TOKEN, "env-token"),
            (ENV_ORG, "env-org"),
            (ENV_PROJECT, "env-project"),
        ]);
        let s = resolve(&Flags::default(), env, &file()).unwrap();
        assert_eq!(s.url, "http://localhost:4000");
        assert_eq!(s.token, "env-token");
        assert_eq!(s.org.as_deref(), Some("env-org"));
        assert_eq!(s.project.as_deref(), Some("env-project"));
    }

    #[test]
    fn flags_beat_the_environment() {
        let env = env_of(&[(ENV_TOKEN, "env-token"), (ENV_ORG, "env-org")]);
        let flags = Flags {
            url: Some("vigil.example.com".into()),
            token: Some("flag-token".into()),
            org: Some("flag-org".into()),
            project: None,
        };
        let s = resolve(&flags, env, &file()).unwrap();
        assert_eq!(s.url, "https://vigil.example.com");
        assert_eq!(s.token, "flag-token");
        assert_eq!(s.org.as_deref(), Some("flag-org"));
        assert_eq!(s.project.as_deref(), Some("file-project"));
    }

    #[test]
    fn nothing_anywhere_is_an_error_naming_login() {
        let err = resolve(&Flags::default(), env_of(&[]), &Config::default()).unwrap_err();
        assert!(err.to_string().contains("vgl login"));
        let s = resolve(
            &Flags::default(),
            env_of(&[(ENV_URL, "http://x"), (ENV_TOKEN, "t"), (ENV_ORG, "")]),
            &Config::default(),
        )
        .unwrap();
        assert_eq!(s.org, None);
    }

    #[test]
    fn normalizes_urls() {
        assert_eq!(
            normalize_url("vigil.example.com/"),
            "https://vigil.example.com"
        );
        assert_eq!(
            normalize_url("http://localhost:4000/api/0/"),
            "http://localhost:4000"
        );
        assert_eq!(
            normalize_url("https://example.com/vigil"),
            "https://example.com/vigil"
        );
    }

    #[test]
    fn saves_privately_and_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nested").join("config.toml");
        file().save_to(&path).unwrap();
        assert_eq!(Config::load_from(&path).unwrap(), file());

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }

        let missing = dir.path().join("none.toml");
        assert_eq!(Config::load_from(&missing).unwrap(), Config::default());
    }
}