elsmith 0.1.0

An Emacs Lisp language server with Lean-verified protocol and editing rules
Documentation
use std::collections::BTreeSet;
use std::env;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

type Roots = BTreeSet<PathBuf>;

#[derive(Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Allowlist {
    #[serde(default)]
    roots: Roots,
}

pub fn config_dir() -> io::Result<PathBuf> {
    if let Some(path) = env::var_os("ELSMITH_CONFIG_DIR") {
        let path = PathBuf::from(path);
        return if path.is_absolute() {
            Ok(path)
        } else {
            Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "ELSMITH_CONFIG_DIR must be absolute",
            ))
        };
    }
    env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .or_else(|| {
            env::var_os("HOME")
                .map(PathBuf::from)
                .filter(|path| path.is_absolute())
                .map(|path| path.join(".config"))
        })
        .map(|path| path.join("elsmith"))
        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no user configuration directory"))
}

impl Allowlist {
    pub fn load(dir: &Path) -> io::Result<Self> {
        let source = match fs::read_to_string(dir.join("trusted-roots.toml")) {
            Ok(source) => source,
            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
            Err(err) => return Err(err),
        };
        let allowlist: Self = toml::from_str(&source).map_err(io::Error::other)?;
        if allowlist.roots.iter().any(|root| !root.is_absolute()) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "trusted roots must be absolute",
            ));
        }
        Ok(allowlist)
    }

    pub fn roots(&self) -> &BTreeSet<PathBuf> {
        &self.roots
    }

    pub fn add(dir: &Path, path: &Path) -> io::Result<Self> {
        let root = path.canonicalize()?;
        if !root.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "the trusted root must be a directory",
            ));
        }
        Self::edit(dir, |roots| roots.insert(root))
    }

    pub fn remove(dir: &Path, path: &Path) -> io::Result<Self> {
        let absolute = std::path::absolute(path)?;
        let canonical = path.canonicalize().ok();
        Self::edit(dir, |roots| {
            if roots.remove(&absolute) {
                return true;
            }
            canonical.is_some_and(|path| roots.remove(&path))
        })
    }

    fn edit(dir: &Path, edit: impl FnOnce(&mut Roots) -> bool) -> io::Result<Self> {
        fs::create_dir_all(dir)?;
        let lock = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .mode(0o600)
            .open(dir.join("trusted-roots.lock"))?;
        lock.lock()?;
        let mut allowlist = Self::load(dir)?;
        if edit(&mut allowlist.roots) {
            let mut file = tempfile::NamedTempFile::new_in(dir)?;
            let contents = toml::to_string(&allowlist).map_err(io::Error::other)?;
            file.write_all(contents.as_bytes())?;
            file.as_file().sync_all()?;
            file.persist(dir.join("trusted-roots.toml"))?;
        }
        Ok(allowlist)
    }
}

#[derive(Default)]
pub struct Trust {
    allowlist: Allowlist,
    trust_epoch: u64,
    active_roots: Roots,
}

impl Trust {
    pub fn refresh(&mut self, dir: Option<&Path>) -> io::Result<()> {
        let loaded = dir.map(Allowlist::load).transpose();
        let (allowlist, result) = match loaded {
            Ok(allowlist) => (allowlist.unwrap_or_default(), Ok(())),
            Err(err) => (Allowlist::default(), Err(err)),
        };
        let active_roots = allowlist
            .roots
            .iter()
            .filter(|path| path.is_dir() && path.canonicalize().as_ref().is_ok_and(|p| p == *path))
            .cloned()
            .collect::<Roots>();
        if !self.active_roots.is_subset(&active_roots)
            || !self.allowlist.roots.is_subset(&allowlist.roots)
        {
            self.trust_epoch = self.trust_epoch.saturating_add(1);
        }
        self.active_roots = active_roots;
        self.allowlist = allowlist;
        result
    }

    pub fn epoch(&self) -> u64 {
        self.trust_epoch
    }

    pub fn permits(&self, workspace: &Path, targets: &[&Path]) -> bool {
        let Ok(workspace) = workspace.canonicalize() else {
            return false;
        };
        workspace.is_dir()
            && self.active_roots.contains(&workspace)
            && targets.iter().all(|target| {
                workspace
                    .join(target)
                    .canonicalize()
                    .is_ok_and(|canonical| {
                        self.active_roots
                            .iter()
                            .any(|root| canonical.starts_with(root))
                    })
            })
    }
}

#[cfg(test)]
mod tests {
    use std::os::unix::fs::symlink;

    use super::*;

    #[test]
    fn canonical_roots_and_targets_are_required_and_revocation_advances_epoch() {
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path().join("workspace");
        let outside = temp.path().join("outside");
        let alias = temp.path().join("alias");
        let dependency = workspace.join("dependency");
        let dir = temp.path().join("config");
        fs::create_dir(&workspace).unwrap();
        fs::create_dir(&outside).unwrap();
        symlink(&workspace, &alias).unwrap();
        symlink(&outside, &dependency).unwrap();
        let mut trust = Trust::default();

        Allowlist::add(&dir, &alias).unwrap();
        trust.refresh(Some(&dir)).unwrap();
        assert_eq!(trust.epoch(), 0);
        assert!(trust.permits(&alias, &[]));
        assert!(!trust.permits(&outside, &[]));
        assert!(!trust.permits(&workspace, &[&dependency, Path::new("dependency")]));
        assert!(!trust.permits(&workspace, &[&outside]));

        Allowlist::add(&dir, &outside).unwrap();
        trust.refresh(Some(&dir)).unwrap();
        assert_eq!(trust.epoch(), 0);
        assert!(trust.permits(
            &workspace,
            &[&dependency, &outside, Path::new("dependency")]
        ));

        Allowlist::remove(&dir, &outside).unwrap();
        trust.refresh(Some(&dir)).unwrap();
        assert_eq!(trust.epoch(), 1);
        assert!(!trust.permits(&workspace, &[&dependency]));
        trust.refresh(Some(&dir)).unwrap();
        assert_eq!(trust.epoch(), 1);
    }

    #[test]
    fn malformed_allowlist_fails_closed() {
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path().join("workspace");
        fs::create_dir(&workspace).unwrap();
        Allowlist::add(temp.path(), &workspace).unwrap();
        let mut trust = Trust::default();
        trust.refresh(Some(temp.path())).unwrap();
        assert!(trust.permits(&workspace, &[]));
        fs::write(temp.path().join("trusted-roots.toml"), "roots = [").unwrap();
        assert!(trust.refresh(Some(temp.path())).is_err());
        assert!(!trust.permits(&workspace, &[]));
        assert_eq!(trust.epoch(), 1);
    }
}