hayson-engine 0.26.0

Storage engine for hayson document databases — the embeddable core behind hayson-server, hayson-cli and hayson-browser
Documentation
use std::path::Path;

use crate::atomic::write_atomic;
use crate::crypto::Sealer;
use crate::errors::{HaysonCipherError, HaysonSchemaError};

use super::parse::parse_catalog;
use super::serialize::{catalog_document, serialize_catalog};
use super::types::Catalog;

#[cfg(unix)]
const PERMISSION_BITS: u32 = 0o777;

/// Parses the catalog's own serialized form back before it is allowed near the disk — a catalog
/// this build could write but not read back would leave the next open() unable to see its tables.
pub fn assert_catalog_readable(path: &Path, catalog: &Catalog) -> Result<(), HaysonSchemaError> {
    parse_catalog(&catalog_document(catalog)).map(|_| ()).map_err(|error| {
        HaysonSchemaError(format!(
            "refusing to write \"{}\": the catalog it would hold is one this build of hayson cannot read back — {}; nothing on disk was changed, and the declaration in the way has to go before the change can",
            path.display(),
            error.0,
        ))
    })
}

#[cfg(unix)]
fn permissions_of(path: &Path) -> std::io::Result<Option<u32>> {
    use std::os::unix::fs::PermissionsExt;
    match std::fs::metadata(path) {
        Ok(metadata) => Ok(Some(metadata.permissions().mode() & PERMISSION_BITS)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

// NOTE: wasi has no permission bits at all; the host sandbox bounds fs access instead.
#[cfg(not(unix))]
fn permissions_of(_path: &Path) -> std::io::Result<Option<u32>> {
    Ok(None)
}

/// Writes the catalog atomically (`.tmp` → `fsync` → `rename`, via [`write_atomic`]), inheriting
/// the permissions of the file it replaces so `.tmp` is never briefly world-readable
/// (see `docs/format.md`, "Zapis, kolejność kluczy, uprawnienia"). Refuses first, via
/// [`assert_catalog_readable`], leaving the file on disk untouched.
pub fn write_catalog(path: &Path, catalog: &Catalog) -> Result<(), Box<dyn std::error::Error>> {
    write_catalog_sealed(path, catalog, None)
}

/// [`write_catalog`] whose file is sealed with `sealer` when one is given — the catalog is the first
/// thing an open reads, so it is also what tells a wrong key from a right one.
pub fn write_catalog_sealed(
    path: &Path,
    catalog: &Catalog,
    sealer: Option<&Sealer>,
) -> Result<(), Box<dyn std::error::Error>> {
    assert_catalog_readable(path, catalog)?;
    let mode = permissions_of(path)?;
    let contents = serialize_catalog(catalog);
    match sealer {
        Some(sealer) => write_atomic(path, &sealer.seal_blob(CATALOG_SCOPE, contents.as_bytes()), mode)?,
        None => write_atomic(path, contents.as_bytes(), mode)?,
    }
    Ok(())
}

/// The scope the catalog is sealed under.
pub const CATALOG_SCOPE: &str = "catalog";

/// The text of the catalog file at `path`. A sealed one is opened with `sealer`: an encrypted file
/// read without keys, a plain one read with keys, and a wrong key are each refused with a message of
/// their own, so a caller can tell them apart. `None` when there is no file.
pub fn read_catalog_text(path: &Path, sealer: Option<&Sealer>) -> Result<Option<String>, ReadCatalogError> {
    let bytes = match std::fs::read(path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(ReadCatalogError::Io(error)),
    };
    let sealed = crate::crypto::is_sealed_blob(&bytes);
    let plain = match (sealed, sealer) {
        (true, Some(sealer)) => sealer
            .open_blob(CATALOG_SCOPE, &bytes)
            .map_err(ReadCatalogError::Cipher)?,
        (true, None) => {
            return Err(ReadCatalogError::Encrypted(
                HaysonCipherError::new("", crate::crypto::STORAGE_FIELD, format!(
                    "\"{}\" is encrypted — open the database with its encryption key", path.display()
                )),
            ))
        }
        (false, Some(_)) => {
            return Err(ReadCatalogError::NotEncrypted(
                HaysonCipherError::new("", crate::crypto::STORAGE_FIELD, format!(
                    "\"{}\" is not encrypted, but an encryption key was given — convert the database first, or open it without the key", path.display()
                )),
            ))
        }
        (false, None) => bytes,
    };
    String::from_utf8(plain)
        .map(Some)
        .map_err(|error| ReadCatalogError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, error)))
}

#[derive(Debug)]
pub enum ReadCatalogError {
    Io(std::io::Error),
    /// The key does not open the catalog (wrong key, or a damaged file).
    Cipher(HaysonCipherError),
    /// The catalog is sealed and no key was given.
    Encrypted(HaysonCipherError),
    /// A key was given for a catalog that is not sealed.
    NotEncrypted(HaysonCipherError),
}

impl ReadCatalogError {
    /// The code a [`crate::database::Problem`] about this refusal carries.
    pub fn problem_code(&self) -> &'static str {
        match self {
            ReadCatalogError::Io(_) => "catalog-unreadable",
            ReadCatalogError::Cipher(_) => "catalog-key-rejected",
            ReadCatalogError::Encrypted(_) => "catalog-encrypted",
            ReadCatalogError::NotEncrypted(_) => "catalog-not-encrypted",
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::fs;

    use super::*;
    use crate::catalog::build::empty_catalog;
    use crate::catalog::types::CatalogLayout;

    #[test]
    fn writes_the_catalog_atomically() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hayson.json");
        let catalog = empty_catalog(CatalogLayout::Flat, 1_000);

        write_catalog(&path, &catalog).unwrap();

        let on_disk = fs::read_to_string(&path).unwrap();
        assert!(on_disk.contains("\"catalogVersion\": 2"));
        assert!(!path.with_extension("json.tmp").exists());

        let reparsed = parse_catalog(&serde_json::from_str(&on_disk).unwrap()).unwrap();
        assert_eq!(reparsed.tables, BTreeMap::new());
    }

    #[test]
    fn refuses_before_touching_disk_when_the_catalog_cannot_be_read_back() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hayson.json");
        fs::write(&path, "original").unwrap();

        let mut catalog = empty_catalog(CatalogLayout::Flat, 1_000);
        catalog.catalog_version = 3;

        assert!(write_catalog(&path, &catalog).is_err());
        assert_eq!(fs::read_to_string(&path).unwrap(), "original");
    }
}