Skip to main content

flexpool_files/
lib.rs

1//! flexpool's local files, read the one way both binaries read them.
2//!
3//! The domain crates are pure: they parse text and never open a file. This
4//! crate does the opening, for the daemon (`flexpoold`) and the command line (`flexpool`) alike,
5//! so neither binary depends on the other and the limits below exist once:
6//!
7//! - every read is bounded, even if the file grows after its size was checked;
8//! - a scenario's data file is a relative path inside the scenario's directory, symlinks
9//!   included (market-replay/SR-003).
10
11#![forbid(unsafe_code)]
12
13use std::io::Read as _;
14use std::path::{Component, Path, PathBuf};
15
16use flexpool_portfolio::edge::{EDGE_FILE, Edge, parse_edge};
17use flexpool_portfolio::{ASSETS_FILE, PORTFOLIO_FILE, Portfolio};
18use flexpool_rules::RuleBook;
19use flexpool_sim::{Replay, Scenario};
20
21/// Largest portfolio file read.
22pub const MAX_PORTFOLIO_BYTES: u64 = 64 * 1024 * 1024;
23/// Largest scenario or data file read.
24pub const MAX_SCENARIO_BYTES: u64 = 16 * 1024 * 1024;
25/// Largest alarm journal read.
26pub const MAX_JOURNAL_BYTES: u64 = 256 * 1024 * 1024;
27
28/// Reads at most `cap` bytes as UTF-8; a longer file is refused even if it grew after a size
29/// check (the read itself is bounded).
30///
31/// # Errors
32/// A sentence naming the file and the problem.
33pub fn read_capped_utf8(path: &Path, cap: u64) -> Result<String, String> {
34    let file =
35        std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
36    let mut bytes = Vec::new();
37    file.take(cap + 1)
38        .read_to_end(&mut bytes)
39        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
40    if bytes.len() as u64 > cap {
41        return Err(format!("{} is larger than {cap} bytes", path.display()));
42    }
43    String::from_utf8(bytes).map_err(|_| format!("{} is not UTF-8", path.display()))
44}
45
46fn read_portfolio_file(dir: &Path, name: &str, required: bool) -> Result<String, String> {
47    let path = dir.join(name);
48    match std::fs::metadata(&path) {
49        Err(_) if !required => Ok(String::new()),
50        Err(e) => Err(format!("{}: {e}", path.display())),
51        Ok(m) if m.len() > MAX_PORTFOLIO_BYTES => Err(format!(
52            "{} is larger than {MAX_PORTFOLIO_BYTES} bytes",
53            path.display()
54        )),
55        Ok(_) => read_capped_utf8(&path, MAX_PORTFOLIO_BYTES),
56    }
57}
58
59/// Reads and validates the portfolio in `dir` and its optional edge file, returning every problem.
60///
61/// # Errors
62/// Every problem as a sentence with file and line.
63pub fn load_portfolio(dir: &Path) -> Result<(Portfolio, Edge), Vec<String>> {
64    let toml = read_portfolio_file(dir, PORTFOLIO_FILE, true).map_err(|e| vec![e])?;
65    let csv = read_portfolio_file(dir, ASSETS_FILE, false).map_err(|e| vec![e])?;
66    let edge = read_portfolio_file(dir, EDGE_FILE, false).map_err(|e| vec![e])?;
67    let portfolio = flexpool_portfolio::parse(&toml, &csv)
68        .map_err(|ps| ps.iter().map(ToString::to_string).collect::<Vec<_>>())?;
69    let edge = parse_edge(&edge, &portfolio)
70        .map_err(|ps| ps.iter().map(ToString::to_string).collect::<Vec<_>>())?;
71    Ok((portfolio, edge))
72}
73
74fn read_scenario_file(path: &Path) -> Result<String, String> {
75    let meta =
76        std::fs::metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
77    if meta.len() > MAX_SCENARIO_BYTES {
78        return Err(format!(
79            "{} is {} bytes, more than the {MAX_SCENARIO_BYTES}-byte limit",
80            path.display(),
81            meta.len()
82        ));
83    }
84    // The size check gives the clear message; the bounded read holds even if the file grows.
85    read_capped_utf8(path, MAX_SCENARIO_BYTES)
86}
87
88/// Resolves a scenario's data file inside the scenario's directory (market-replay/SR-003).
89///
90/// # Errors
91/// A sentence naming the problem.
92pub fn contained(scenario_file: &Path, data: &Path) -> Result<PathBuf, String> {
93    if data.is_absolute()
94        || data
95            .components()
96            .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
97    {
98        return Err(format!(
99            "market.file {:?} must be a relative path inside the scenario's directory",
100            data.display().to_string()
101        ));
102    }
103    let base = scenario_file.parent().unwrap_or_else(|| Path::new("."));
104    let joined = base.join(data);
105    // Symlinks could still point outside: compare canonical paths when the file exists.
106    if let (Ok(base), Ok(target)) = (base.canonicalize(), joined.canonicalize())
107        && !target.starts_with(&base)
108    {
109        return Err(format!(
110            "market.file {:?} resolves outside the scenario's directory",
111            data.display().to_string()
112        ));
113    }
114    Ok(joined)
115}
116
117/// Loads and validates a scenario file, collecting every problem (parse, data file, data).
118///
119/// # Errors
120/// Every problem as a sentence.
121pub fn load_scenario(path: &Path) -> Result<Replay, Vec<String>> {
122    let text = read_scenario_file(path).map_err(|e| vec![e])?;
123    let parsed = Scenario::parse(&text);
124    let mut problems: Vec<String> = parsed
125        .as_ref()
126        .err()
127        .map_or_else(Vec::new, |ps| ps.iter().map(ToString::to_string).collect());
128    // The data file is checked even when other fields are invalid: every problem in one run.
129    let data = flexpool_sim::scenario::data_file(&text).and_then(|data| {
130        match contained(path, &data).and_then(|resolved| read_scenario_file(&resolved)) {
131            Ok(text) => Some(text),
132            Err(e) => {
133                problems.push(format!("market.file: {e}"));
134                None
135            }
136        }
137    });
138    let scenario = match parsed {
139        Ok(s) if problems.is_empty() => s,
140        _ => return Err(problems),
141    };
142    let rules =
143        RuleBook::bundled().map_err(|ps| ps.iter().map(ToString::to_string).collect::<Vec<_>>())?;
144    Replay::new(scenario, rules, data.as_deref()).map_err(|e| vec![e.to_string()])
145}
146
147/// A scenario's faults that name an asset the portfolio does not hold.
148#[must_use]
149pub fn fault_problems(scenario: &Scenario, portfolio: Option<&Portfolio>) -> Vec<String> {
150    let Some(portfolio) = portfolio else {
151        return Vec::new();
152    };
153    scenario
154        .faults
155        .iter()
156        .enumerate()
157        .filter(|(_, f)| portfolio.asset(&f.asset).is_none())
158        .map(|(i, f)| {
159            format!(
160                "fault[{}].asset: unknown asset {} (not in the portfolio)",
161                i + 1,
162                f.asset
163            )
164        })
165        .collect()
166}
167
168/// Checks an alarm journal's hash chain without starting anything; the number of records.
169///
170/// # Errors
171/// A sentence naming the file and the first broken line.
172pub fn verify_journal(path: &Path) -> Result<usize, String> {
173    let text = read_capped_utf8(path, MAX_JOURNAL_BYTES)?;
174    flexpool_alarms::verify(&text)
175        .map(|r| r.len())
176        .map_err(|e| format!("{} {e}", path.display()))
177}
178
179#[cfg(test)]
180mod tests {
181    #![allow(clippy::unwrap_used, reason = "tests fail loudly")]
182    use super::*;
183
184    #[test]
185    fn a_read_is_bounded_and_utf8() {
186        let dir = tempfile::tempdir().unwrap();
187        let path = dir.path().join("f.txt");
188        std::fs::write(&path, "12345").unwrap();
189        assert_eq!(read_capped_utf8(&path, 5).unwrap(), "12345");
190        assert!(
191            read_capped_utf8(&path, 4)
192                .unwrap_err()
193                .contains("larger than 4 bytes")
194        );
195        std::fs::write(&path, [0xff, 0xfe]).unwrap();
196        assert!(
197            read_capped_utf8(&path, 5)
198                .unwrap_err()
199                .contains("not UTF-8")
200        );
201    }
202
203    #[test]
204    fn a_data_file_stays_inside_the_scenario_directory() {
205        let dir = tempfile::tempdir().unwrap();
206        let scenario = dir.path().join("s.toml");
207        for bad in ["/etc/passwd", "../x.csv", "a/../../x.csv"] {
208            assert!(contained(&scenario, Path::new(bad)).is_err(), "{bad}");
209        }
210        assert!(contained(&scenario, Path::new("data/day.csv")).is_ok());
211    }
212}