flexpool-files 0.2.1

flexpool's local files, read bounded and contained: the portfolio directory, a scenario and its data file, an alarm journal.
Documentation
//! flexpool's local files, read the one way both binaries read them.
//!
//! The domain crates are pure: they parse text and never open a file. This
//! crate does the opening, for the daemon (`flexpoold`) and the command line (`flexpool`) alike,
//! so neither binary depends on the other and the limits below exist once:
//!
//! - every read is bounded, even if the file grows after its size was checked;
//! - a scenario's data file is a relative path inside the scenario's directory, symlinks
//!   included (market-replay/SR-003).

#![forbid(unsafe_code)]

use std::io::Read as _;
use std::path::{Component, Path, PathBuf};

use flexpool_portfolio::edge::{EDGE_FILE, Edge, parse_edge};
use flexpool_portfolio::{ASSETS_FILE, PORTFOLIO_FILE, Portfolio};
use flexpool_rules::RuleBook;
use flexpool_sim::{Replay, Scenario};

/// Largest portfolio file read.
pub const MAX_PORTFOLIO_BYTES: u64 = 64 * 1024 * 1024;
/// Largest scenario or data file read.
pub const MAX_SCENARIO_BYTES: u64 = 16 * 1024 * 1024;
/// Largest alarm journal read.
pub const MAX_JOURNAL_BYTES: u64 = 256 * 1024 * 1024;

/// Reads at most `cap` bytes as UTF-8; a longer file is refused even if it grew after a size
/// check (the read itself is bounded).
///
/// # Errors
/// A sentence naming the file and the problem.
pub fn read_capped_utf8(path: &Path, cap: u64) -> Result<String, String> {
    let file =
        std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    let mut bytes = Vec::new();
    file.take(cap + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    if bytes.len() as u64 > cap {
        return Err(format!("{} is larger than {cap} bytes", path.display()));
    }
    String::from_utf8(bytes).map_err(|_| format!("{} is not UTF-8", path.display()))
}

fn read_portfolio_file(dir: &Path, name: &str, required: bool) -> Result<String, String> {
    let path = dir.join(name);
    match std::fs::metadata(&path) {
        Err(_) if !required => Ok(String::new()),
        Err(e) => Err(format!("{}: {e}", path.display())),
        Ok(m) if m.len() > MAX_PORTFOLIO_BYTES => Err(format!(
            "{} is larger than {MAX_PORTFOLIO_BYTES} bytes",
            path.display()
        )),
        Ok(_) => read_capped_utf8(&path, MAX_PORTFOLIO_BYTES),
    }
}

/// Reads and validates the portfolio in `dir` and its optional edge file, returning every problem.
///
/// # Errors
/// Every problem as a sentence with file and line.
pub fn load_portfolio(dir: &Path) -> Result<(Portfolio, Edge), Vec<String>> {
    let toml = read_portfolio_file(dir, PORTFOLIO_FILE, true).map_err(|e| vec![e])?;
    let csv = read_portfolio_file(dir, ASSETS_FILE, false).map_err(|e| vec![e])?;
    let edge = read_portfolio_file(dir, EDGE_FILE, false).map_err(|e| vec![e])?;
    let portfolio = flexpool_portfolio::parse(&toml, &csv)
        .map_err(|ps| ps.iter().map(ToString::to_string).collect::<Vec<_>>())?;
    let edge = parse_edge(&edge, &portfolio)
        .map_err(|ps| ps.iter().map(ToString::to_string).collect::<Vec<_>>())?;
    Ok((portfolio, edge))
}

fn read_scenario_file(path: &Path) -> Result<String, String> {
    let meta =
        std::fs::metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    if meta.len() > MAX_SCENARIO_BYTES {
        return Err(format!(
            "{} is {} bytes, more than the {MAX_SCENARIO_BYTES}-byte limit",
            path.display(),
            meta.len()
        ));
    }
    // The size check gives the clear message; the bounded read holds even if the file grows.
    read_capped_utf8(path, MAX_SCENARIO_BYTES)
}

/// Resolves a scenario's data file inside the scenario's directory (market-replay/SR-003).
///
/// # Errors
/// A sentence naming the problem.
pub fn contained(scenario_file: &Path, data: &Path) -> Result<PathBuf, String> {
    if data.is_absolute()
        || data
            .components()
            .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
    {
        return Err(format!(
            "market.file {:?} must be a relative path inside the scenario's directory",
            data.display().to_string()
        ));
    }
    let base = scenario_file.parent().unwrap_or_else(|| Path::new("."));
    let joined = base.join(data);
    // Symlinks could still point outside: compare canonical paths when the file exists.
    if let (Ok(base), Ok(target)) = (base.canonicalize(), joined.canonicalize())
        && !target.starts_with(&base)
    {
        return Err(format!(
            "market.file {:?} resolves outside the scenario's directory",
            data.display().to_string()
        ));
    }
    Ok(joined)
}

/// Loads and validates a scenario file, collecting every problem (parse, data file, data).
///
/// # Errors
/// Every problem as a sentence.
pub fn load_scenario(path: &Path) -> Result<Replay, Vec<String>> {
    let text = read_scenario_file(path).map_err(|e| vec![e])?;
    let parsed = Scenario::parse(&text);
    let mut problems: Vec<String> = parsed
        .as_ref()
        .err()
        .map_or_else(Vec::new, |ps| ps.iter().map(ToString::to_string).collect());
    // The data file is checked even when other fields are invalid: every problem in one run.
    let data = flexpool_sim::scenario::data_file(&text).and_then(|data| {
        match contained(path, &data).and_then(|resolved| read_scenario_file(&resolved)) {
            Ok(text) => Some(text),
            Err(e) => {
                problems.push(format!("market.file: {e}"));
                None
            }
        }
    });
    let scenario = match parsed {
        Ok(s) if problems.is_empty() => s,
        _ => return Err(problems),
    };
    let rules =
        RuleBook::bundled().map_err(|ps| ps.iter().map(ToString::to_string).collect::<Vec<_>>())?;
    Replay::new(scenario, rules, data.as_deref()).map_err(|e| vec![e.to_string()])
}

/// A scenario's faults that name an asset the portfolio does not hold.
#[must_use]
pub fn fault_problems(scenario: &Scenario, portfolio: Option<&Portfolio>) -> Vec<String> {
    let Some(portfolio) = portfolio else {
        return Vec::new();
    };
    scenario
        .faults
        .iter()
        .enumerate()
        .filter(|(_, f)| portfolio.asset(&f.asset).is_none())
        .map(|(i, f)| {
            format!(
                "fault[{}].asset: unknown asset {} (not in the portfolio)",
                i + 1,
                f.asset
            )
        })
        .collect()
}

/// Checks an alarm journal's hash chain without starting anything; the number of records.
///
/// # Errors
/// A sentence naming the file and the first broken line.
pub fn verify_journal(path: &Path) -> Result<usize, String> {
    let text = read_capped_utf8(path, MAX_JOURNAL_BYTES)?;
    flexpool_alarms::verify(&text)
        .map(|r| r.len())
        .map_err(|e| format!("{} {e}", path.display()))
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, reason = "tests fail loudly")]
    use super::*;

    #[test]
    fn a_read_is_bounded_and_utf8() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("f.txt");
        std::fs::write(&path, "12345").unwrap();
        assert_eq!(read_capped_utf8(&path, 5).unwrap(), "12345");
        assert!(
            read_capped_utf8(&path, 4)
                .unwrap_err()
                .contains("larger than 4 bytes")
        );
        std::fs::write(&path, [0xff, 0xfe]).unwrap();
        assert!(
            read_capped_utf8(&path, 5)
                .unwrap_err()
                .contains("not UTF-8")
        );
    }

    #[test]
    fn a_data_file_stays_inside_the_scenario_directory() {
        let dir = tempfile::tempdir().unwrap();
        let scenario = dir.path().join("s.toml");
        for bad in ["/etc/passwd", "../x.csv", "a/../../x.csv"] {
            assert!(contained(&scenario, Path::new(bad)).is_err(), "{bad}");
        }
        assert!(contained(&scenario, Path::new("data/day.csv")).is_ok());
    }
}