second-brain-api 0.11.0

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
use std::io::ErrorKind;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

pub fn make_private(
    data_dir: &Path,
    db_path: &Path,
    index_dir: &Path,
) -> Vec<(PathBuf, std::io::Error)> {
    let mut failures = Vec::new();
    set_mode(data_dir, 0o700, &mut failures);
    for name in ["api.token", "sync.key"] {
        set_mode(&data_dir.join(name), 0o600, &mut failures);
    }
    for suffix in ["", "-wal", "-shm"] {
        let mut path = db_path.as_os_str().to_owned();
        path.push(suffix);
        set_mode(Path::new(&path), 0o600, &mut failures);
    }
    restrict_tree(index_dir, &mut failures);
    failures
}

fn restrict_tree(dir: &Path, failures: &mut Vec<(PathBuf, std::io::Error)>) {
    match std::fs::metadata(dir) {
        Ok(meta) if meta.is_dir() => {}
        Ok(_) => return,
        Err(e) if e.kind() == ErrorKind::NotFound => return,
        Err(e) => return failures.push((dir.to_path_buf(), e)),
    }
    set_mode(dir, 0o700, failures);
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) => return failures.push((dir.to_path_buf(), e)),
    };
    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                failures.push((dir.to_path_buf(), e));
                continue;
            }
        };
        let path = entry.path();
        match entry.file_type() {
            Ok(t) if t.is_dir() => restrict_tree(&path, failures),
            Ok(t) if t.is_file() => set_mode(&path, 0o600, failures),
            Ok(_) => {}
            Err(e) => failures.push((path, e)),
        }
    }
}

fn set_mode(path: &Path, mode: u32, failures: &mut Vec<(PathBuf, std::io::Error)>) {
    match std::fs::metadata(path) {
        Ok(meta) if meta.permissions().mode() & 0o777 == mode => return,
        Ok(_) => {}
        Err(e) if e.kind() == ErrorKind::NotFound => return,
        Err(e) => return failures.push((path.to_path_buf(), e)),
    }
    if let Err(e) = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)) {
        failures.push((path.to_path_buf(), e));
    }
}

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

    fn set(p: &Path, mode: u32) {
        std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap();
    }

    fn mode(p: &Path) -> u32 {
        std::fs::symlink_metadata(p).unwrap().permissions().mode() & 0o777
    }

    fn touch(p: &Path, m: u32) {
        std::fs::write(p, "x").unwrap();
        set(p, m);
    }

    #[test]
    fn tightens_an_existing_install() {
        let root = tempfile::tempdir().unwrap();
        let data = root.path().join(".second-brain");
        let index = data.join("brain.indexes");
        let nested = index.join("tantivy");
        std::fs::create_dir_all(&nested).unwrap();
        set(&data, 0o775);
        set(&index, 0o775);
        set(&nested, 0o775);
        let files = [
            data.join("brain.db"),
            data.join("brain.db-wal"),
            data.join("brain.db-shm"),
            data.join("sync.key"),
            data.join("api.token"),
            index.join("vectors.usearch"),
            nested.join("meta.json"),
        ];
        for f in &files {
            touch(f, 0o664);
        }

        let failures = make_private(&data, &data.join("brain.db"), &index);

        assert!(failures.is_empty(), "{failures:?}");
        for dir in [&data, &index, &nested] {
            assert_eq!(mode(dir), 0o700, "{}", dir.display());
        }
        for f in &files {
            assert_eq!(mode(f), 0o600, "{}", f.display());
        }
    }

    #[test]
    fn a_db_outside_the_data_dir_is_tightened_too() {
        let root = tempfile::tempdir().unwrap();
        let data = root.path().join("data");
        let elsewhere = root.path().join("elsewhere");
        std::fs::create_dir_all(&data).unwrap();
        std::fs::create_dir_all(&elsewhere).unwrap();
        let db = elsewhere.join("custom.db");
        touch(&db, 0o644);
        touch(&elsewhere.join("custom.db-wal"), 0o644);
        let index = elsewhere.join("custom.indexes");
        std::fs::create_dir(&index).unwrap();
        touch(&index.join("f"), 0o644);

        assert!(make_private(&data, &db, &index).is_empty());
        assert_eq!(mode(&db), 0o600);
        assert_eq!(mode(&elsewhere.join("custom.db-wal")), 0o600);
        assert_eq!(mode(&index), 0o700);
        assert_eq!(mode(&index.join("f")), 0o600);
    }

    #[test]
    fn missing_paths_are_skipped_without_failures() {
        let root = tempfile::tempdir().unwrap();
        let data = root.path().join("absent");
        assert!(
            make_private(&data, &data.join("brain.db"), &data.join("brain.indexes")).is_empty()
        );
    }

    #[test]
    fn symlinks_in_the_index_are_not_followed() {
        let root = tempfile::tempdir().unwrap();
        let outside = root.path().join("outside.txt");
        touch(&outside, 0o644);
        let index = root.path().join("brain.indexes");
        std::fs::create_dir(&index).unwrap();
        std::os::unix::fs::symlink(&outside, index.join("link")).unwrap();

        make_private(root.path(), &root.path().join("brain.db"), &index);

        assert_eq!(mode(&outside), 0o644);
    }
}