Skip to main content

einvoice_validator/rulesets/
cache.rs

1//! The cache of fetched rule sets: where it is, what it holds, and loading a rule set
2//! from it, every file checked.
3
4use std::fs::File;
5use std::path::{Path, PathBuf};
6
7use super::catalogue::{self, FetchedRuleSet};
8use crate::{Error, MANIFEST_FILE, RuleSet, Validator};
9
10/// The environment variable that sets the cache directory, overriding the platform's.
11pub const CACHE_ENV: &str = "EINVOICE_VALIDATOR_CACHE";
12
13/// The directory of the assembled bundles, under the cache root.
14pub(crate) const RULES_DIR: &str = "rules";
15/// The directory of the downloads in progress or not yet assembled.
16pub(crate) const DOWNLOADS_DIR: &str = "downloads";
17/// The directory of the tools a fetch runs (Apache Maven and its local repository).
18pub(crate) const TOOLS_DIR: &str = "tools";
19/// The directory of temporary work.
20pub(crate) const WORK_DIR: &str = "work";
21/// The lock file of the cache.
22const LOCK_FILE: &str = ".lock";
23/// The cache directory tag (<https://bford.info/cachedir/>).
24const TAG_FILE: &str = "CACHEDIR.TAG";
25const TAG: &str = "Signature: 8a477f597d28d172789f06886806bc55
26# This file is a cache directory tag created by einvoice-validator.
27# For information about cache directory tags, see https://bford.info/cachedir/
28";
29
30/// What the cache holds of a fetched rule set.
31#[derive(Debug, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum CacheStatus {
34    /// Its bundle is in the cache, its manifest the catalogue's and every file with the
35    /// SHA-256 the manifest records.
36    Cached,
37    /// It has not been fetched.
38    Missing,
39    /// Something is in its place, but not its bundle as fetched: why.
40    Invalid(String),
41}
42
43/// The cache of the rule sets fetched from their publishers ([`fetched_rule_sets`]):
44/// a directory holding, under `rules/`, the bundle of each fetched rule set, laid out
45/// as the fetch scripts of the repository lay them out
46/// ([`FetchedRuleSet::bundle_path`]).
47///
48/// The default directory is the platform's cache directory: `$XDG_CACHE_HOME`, else
49/// `~/.cache`, on Linux and the BSDs; `~/Library/Caches` on macOS; `%LOCALAPPDATA%` on
50/// Windows (with `einvoice-validator/` under it, and `cache/` under that on Windows);
51/// the environment variable [`CACHE_ENV`] (`EINVOICE_VALIDATOR_CACHE`) overrides it.
52///
53/// Nothing is ever downloaded except by `RuleSetCache::fetch` (feature `fetch`):
54/// loading a rule set that is not in the cache is [`Error::NotCached`]. A loaded rule
55/// set is checked in full on every load: its manifest must be, byte for byte, the one
56/// the catalogue of this version gives, and every file must have the SHA-256 that
57/// manifest records, so a cache can be used offline and is never trusted.
58///
59/// [`fetched_rule_sets`]: crate::fetched_rule_sets
60#[derive(Debug, Clone)]
61pub struct RuleSetCache {
62    root: PathBuf,
63}
64
65impl RuleSetCache {
66    /// The cache in the default directory ([`RuleSetCache::default_dir`]).
67    ///
68    /// # Errors
69    ///
70    /// As [`RuleSetCache::default_dir`].
71    pub fn new() -> Result<Self, Error> {
72        Ok(Self::at(Self::default_dir()?))
73    }
74
75    /// The cache in the directory `root` (created when something is fetched).
76    #[must_use]
77    pub fn at(root: impl Into<PathBuf>) -> Self {
78        let root = root.into();
79        let root = std::path::absolute(&root).unwrap_or(root);
80        Self { root }
81    }
82
83    /// The default cache directory: [`CACHE_ENV`] when it is set and not empty, else
84    /// the platform's cache directory (see [`RuleSetCache`]).
85    ///
86    /// # Errors
87    ///
88    /// [`Error::Fetch`] when there is no home or cache directory to put it in.
89    pub fn default_dir() -> Result<PathBuf, Error> {
90        if let Some(dir) = std::env::var_os(CACHE_ENV).filter(|v| !v.is_empty()) {
91            return Ok(PathBuf::from(dir));
92        }
93        platform_dir().ok_or_else(|| Error::Fetch {
94            message: format!(
95                "no cache directory: neither the platform's cache directory nor {CACHE_ENV} is set"
96            ),
97        })
98    }
99
100    /// The cache directory.
101    #[must_use]
102    pub fn root(&self) -> &Path {
103        &self.root
104    }
105
106    /// The directory of the bundle of `rule_set` in the cache, whether it is there or
107    /// not: what `einvoice-validate --bundle` takes.
108    #[must_use]
109    pub fn bundle_dir(&self, rule_set: &FetchedRuleSet) -> PathBuf {
110        let mut dir = self.root.join(RULES_DIR);
111        dir.extend(rule_set.bundle_path().split('/'));
112        dir
113    }
114
115    /// The release directory of the family of `rule_set` in the cache.
116    #[cfg(feature = "fetch")]
117    pub(crate) fn release_dir(&self, rule_set: &FetchedRuleSet) -> PathBuf {
118        self.root.join(RULES_DIR).join(rule_set.release())
119    }
120
121    /// What the cache holds of `rule_set`: its manifest and every file it names are
122    /// checked (read and hashed), the stylesheets are not prepared.
123    #[must_use]
124    pub fn status(&self, rule_set: &FetchedRuleSet) -> CacheStatus {
125        let dir = self.bundle_dir(rule_set);
126        let manifest = match std::fs::read(dir.join(MANIFEST_FILE)) {
127            Ok(bytes) => bytes,
128            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return CacheStatus::Missing,
129            Err(e) => return CacheStatus::Invalid(format!("{MANIFEST_FILE}: {e}")),
130        };
131        if manifest != rule_set.manifest().as_bytes() {
132            return CacheStatus::Invalid(format!(
133                "{MANIFEST_FILE} is not the manifest of {} {}",
134                rule_set.name(),
135                rule_set.version()
136            ));
137        }
138        let parsed = match RuleSet::parse(rule_set.manifest()) {
139            Ok(parsed) => parsed,
140            Err(e) => return CacheStatus::Invalid(e.to_string()),
141        };
142        let files = parsed
143            .stylesheets()
144            .iter()
145            .map(|s| (s.path(), s.sha256()))
146            .chain(parsed.resources().iter().map(|r| (r.path(), r.sha256())));
147        for (path, sha256) in files {
148            let mut file = dir.clone();
149            file.extend(path.split('/'));
150            match std::fs::read(&file) {
151                Ok(bytes) if crate::validator::sha256_hex(&bytes) == sha256 => {}
152                Ok(_) => return CacheStatus::Invalid(format!("{path}: not the pinned SHA-256")),
153                Err(e) => return CacheStatus::Invalid(format!("{path}: {e}")),
154            }
155        }
156        CacheStatus::Cached
157    }
158
159    /// Loads the fetched rule set `name` (or the alias `peppol`) from the cache.
160    ///
161    /// # Errors
162    ///
163    /// [`Error::Bundle`] for a name that is no fetched rule set; [`Error::NotCached`]
164    /// when it has not been fetched; [`Error::Bundle`] when the cache holds something
165    /// else in its place (a manifest that is not the catalogue's), and otherwise as
166    /// [`Validator::from_bundle_dir`], which checks the SHA-256 of every file.
167    pub fn load(&self, name: &str) -> Result<Validator, Error> {
168        let rule_set = catalogue::fetched_rule_set(name, None)?.ok_or_else(|| unknown(name))?;
169        self.load_rule_set(rule_set)
170    }
171
172    /// Loads `rule_set` from the cache, as [`RuleSetCache::load`].
173    ///
174    /// # Errors
175    ///
176    /// As [`RuleSetCache::load`].
177    pub fn load_rule_set(&self, rule_set: &FetchedRuleSet) -> Result<Validator, Error> {
178        let dir = self.bundle_dir(rule_set);
179        let manifest = match std::fs::read(dir.join(MANIFEST_FILE)) {
180            Ok(bytes) => bytes,
181            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
182                return Err(Error::NotCached {
183                    name: rule_set.name().to_owned(),
184                    dir: self.root.clone(),
185                });
186            }
187            Err(source) => {
188                return Err(Error::Io {
189                    path: dir.join(MANIFEST_FILE),
190                    source,
191                });
192            }
193        };
194        if manifest != rule_set.manifest().as_bytes() {
195            return Err(Error::bundle(format!(
196                "{}: not the manifest of {} {} that this version fetches; fetch it again",
197                dir.join(MANIFEST_FILE).display(),
198                rule_set.name(),
199                rule_set.version()
200            )));
201        }
202        Validator::from_bundle_dir(&dir)
203    }
204
205    /// Removes everything this crate put in the cache: the bundles, the downloads, the
206    /// tools and the temporary files (and the directory itself, when nothing else is in
207    /// it). Other files in the directory are left alone.
208    ///
209    /// # Errors
210    ///
211    /// [`Error::Io`] when something cannot be removed.
212    pub fn clear(&self) -> Result<(), Error> {
213        if !self.root.exists() {
214            return Ok(());
215        }
216        let lock = self.lock()?;
217        for dir in [RULES_DIR, DOWNLOADS_DIR, TOOLS_DIR, WORK_DIR] {
218            remove_dir(&self.root.join(dir))?;
219        }
220        remove_file(&self.root.join(TAG_FILE))?;
221        drop(lock);
222        remove_file(&self.root.join(LOCK_FILE))?;
223        // Only when empty: the directory may be one the user keeps other files in.
224        let _ = std::fs::remove_dir(&self.root);
225        Ok(())
226    }
227
228    /// Creates the cache directory, with its tag, and takes its lock: one fetch or
229    /// clear at a time (readers take no lock: what they read is checked, and a bundle
230    /// appears by a rename).
231    pub(crate) fn lock(&self) -> Result<File, Error> {
232        let io = |path: &Path| {
233            let path = path.to_path_buf();
234            move |source| Error::Io { path, source }
235        };
236        std::fs::create_dir_all(&self.root).map_err(io(&self.root))?;
237        let tag = self.root.join(TAG_FILE);
238        if !tag.exists() {
239            std::fs::write(&tag, TAG).map_err(io(&tag))?;
240        }
241        let path = self.root.join(LOCK_FILE);
242        let file = std::fs::OpenOptions::new()
243            .create(true)
244            .truncate(false)
245            .write(true)
246            .open(&path)
247            .map_err(io(&path))?;
248        file.lock().map_err(io(&path))?;
249        Ok(file)
250    }
251}
252
253fn remove_dir(dir: &Path) -> Result<(), Error> {
254    match std::fs::remove_dir_all(dir) {
255        Ok(()) => Ok(()),
256        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
257        Err(source) => Err(Error::Io {
258            path: dir.to_path_buf(),
259            source,
260        }),
261    }
262}
263
264fn remove_file(file: &Path) -> Result<(), Error> {
265    match std::fs::remove_file(file) {
266        Ok(()) => Ok(()),
267        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
268        Err(source) => Err(Error::Io {
269            path: file.to_path_buf(),
270            source,
271        }),
272    }
273}
274
275/// The error for a name that is no fetched rule set.
276pub(crate) fn unknown(name: &str) -> Error {
277    let names = catalogue::fetched_rule_sets()
278        .map(|all| {
279            all.iter()
280                .map(FetchedRuleSet::name)
281                .collect::<Vec<_>>()
282                .join(", ")
283        })
284        .unwrap_or_default();
285    Error::bundle(format!(
286        "no fetched rule set named {name:?} (fetched rule sets: {names}; aliases: {})",
287        catalogue::ALIASES
288            .iter()
289            .map(|(a, _)| *a)
290            .collect::<Vec<_>>()
291            .join(", ")
292    ))
293}
294
295/// The platform's cache directory for this crate.
296fn platform_dir() -> Option<PathBuf> {
297    let var = |name: &str| {
298        std::env::var_os(name)
299            .filter(|v| !v.is_empty())
300            .map(PathBuf::from)
301            .filter(|p| p.is_absolute())
302    };
303    if cfg!(windows) {
304        return var("LOCALAPPDATA").map(|d| d.join("einvoice-validator").join("cache"));
305    }
306    if cfg!(target_os = "macos") {
307        return var("HOME").map(|h| h.join("Library").join("Caches").join("einvoice-validator"));
308    }
309    var("XDG_CACHE_HOME")
310        .or_else(|| var("HOME").map(|h| h.join(".cache")))
311        .map(|d| d.join("einvoice-validator"))
312}
313
314impl Validator {
315    /// The fetched rule set `name` (see [`fetched_rule_sets`](crate::fetched_rule_sets)),
316    /// from the cache in its default directory ([`RuleSetCache::new`]), checked in full.
317    /// Never downloads anything: fetch it first with `RuleSetCache::fetch` (feature
318    /// `fetch`), or `einvoice-validate rules fetch NAME`.
319    ///
320    /// # Errors
321    ///
322    /// As [`RuleSetCache::new`] and [`RuleSetCache::load`]; [`Error::NotCached`] when
323    /// it has not been fetched.
324    pub fn from_cache(name: &str) -> Result<Self, Error> {
325        RuleSetCache::new()?.load(name)
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    fn temp(name: &str) -> PathBuf {
334        let dir =
335            std::env::temp_dir().join(format!("einvoice-cache-test-{}-{name}", std::process::id()));
336        let _ = std::fs::remove_dir_all(&dir);
337        dir
338    }
339
340    #[test]
341    fn an_empty_cache_has_nothing() {
342        let cache = RuleSetCache::at(temp("empty"));
343        for r in catalogue::fetched_rule_sets().unwrap() {
344            assert_eq!(cache.status(r), CacheStatus::Missing, "{}", r.name());
345            match cache.load_rule_set(r) {
346                Err(Error::NotCached { name, dir }) => {
347                    assert_eq!(name, r.name());
348                    assert_eq!(dir, cache.root());
349                }
350                other => panic!("{}: {other:?}", r.name()),
351            }
352        }
353        assert!(matches!(cache.load("nope"), Err(Error::Bundle { .. })));
354        cache.clear().unwrap();
355        assert!(!cache.root().exists());
356    }
357
358    #[test]
359    fn bundle_dirs_follow_the_fetch_scripts() {
360        let cache = RuleSetCache::at("/c");
361        let dir = |n: &str| {
362            let r = catalogue::fetched_rule_set(n, None).unwrap().unwrap();
363            let release = r.release().to_owned();
364            (cache.bundle_dir(r), release)
365        };
366        // Made absolute: on Windows, with the current drive.
367        let rules = std::path::absolute("/c").unwrap().join("rules");
368        let (en16931, release) = dir("factur-x-en16931");
369        assert_eq!(en16931, rules.join(&release).join("en16931"));
370        let (peppol, release) = dir("peppol");
371        assert_eq!(peppol, rules.join(release));
372    }
373
374    #[test]
375    fn a_tampered_bundle_is_not_loaded() {
376        let cache = RuleSetCache::at(temp("tampered"));
377        let r = catalogue::fetched_rule_set("factur-x-minimum", None)
378            .unwrap()
379            .unwrap();
380        let dir = cache.bundle_dir(r);
381        std::fs::create_dir_all(&dir).unwrap();
382        // Another manifest.
383        std::fs::write(dir.join(MANIFEST_FILE), "format = 1\n").unwrap();
384        assert!(matches!(cache.status(r), CacheStatus::Invalid(_)));
385        let error = cache.load_rule_set(r).unwrap_err().to_string();
386        assert!(error.contains("fetch it again"), "{error}");
387        // The catalogue's manifest, but the files missing or altered.
388        std::fs::write(dir.join(MANIFEST_FILE), r.manifest()).unwrap();
389        let CacheStatus::Invalid(why) = cache.status(r) else {
390            panic!("{:?}", cache.status(r))
391        };
392        assert!(why.contains("FACTUR-X_MINIMUM.xslt"), "{why}");
393        std::fs::write(dir.join("FACTUR-X_MINIMUM.xslt"), "<x/>").unwrap();
394        let CacheStatus::Invalid(why) = cache.status(r) else {
395            panic!()
396        };
397        assert!(why.contains("SHA-256"), "{why}");
398        assert!(matches!(
399            cache.load_rule_set(r),
400            Err(Error::Checksum { .. })
401        ));
402        // clear removes it all, and leaves other files alone.
403        std::fs::write(cache.root().join("mine.txt"), "keep").unwrap();
404        cache.clear().unwrap();
405        assert!(!cache.root().join(RULES_DIR).exists());
406        assert!(cache.root().join("mine.txt").exists());
407        std::fs::remove_dir_all(cache.root()).unwrap();
408    }
409}