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            .chain(
148                parsed
149                    .schema_documents()
150                    .iter()
151                    .map(|d| (d.path(), d.sha256())),
152            );
153        for (path, sha256) in files {
154            let mut file = dir.clone();
155            file.extend(path.split('/'));
156            match std::fs::read(&file) {
157                Ok(bytes) if crate::validator::sha256_hex(&bytes) == sha256 => {}
158                Ok(_) => return CacheStatus::Invalid(format!("{path}: not the pinned SHA-256")),
159                Err(e) => return CacheStatus::Invalid(format!("{path}: {e}")),
160            }
161        }
162        CacheStatus::Cached
163    }
164
165    /// Loads the fetched rule set `name` (or the alias `peppol`) from the cache.
166    ///
167    /// # Errors
168    ///
169    /// [`Error::Bundle`] for a name that is no fetched rule set; [`Error::NotCached`]
170    /// when it has not been fetched; [`Error::Bundle`] when the cache holds something
171    /// else in its place (a manifest that is not the catalogue's), and otherwise as
172    /// [`Validator::from_bundle_dir`], which checks the SHA-256 of every file.
173    pub fn load(&self, name: &str) -> Result<Validator, Error> {
174        let rule_set = catalogue::fetched_rule_set(name, None)?.ok_or_else(|| unknown(name))?;
175        self.load_rule_set(rule_set)
176    }
177
178    /// Loads `rule_set` from the cache, as [`RuleSetCache::load`].
179    ///
180    /// # Errors
181    ///
182    /// As [`RuleSetCache::load`].
183    pub fn load_rule_set(&self, rule_set: &FetchedRuleSet) -> Result<Validator, Error> {
184        let dir = self.bundle_dir(rule_set);
185        let manifest = match std::fs::read(dir.join(MANIFEST_FILE)) {
186            Ok(bytes) => bytes,
187            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
188                return Err(Error::NotCached {
189                    name: rule_set.name().to_owned(),
190                    dir: self.root.clone(),
191                });
192            }
193            Err(source) => {
194                return Err(Error::Io {
195                    path: dir.join(MANIFEST_FILE),
196                    source,
197                });
198            }
199        };
200        if manifest != rule_set.manifest().as_bytes() {
201            return Err(Error::bundle(format!(
202                "{}: not the manifest of {} {} that this version fetches; fetch it again",
203                dir.join(MANIFEST_FILE).display(),
204                rule_set.name(),
205                rule_set.version()
206            )));
207        }
208        Validator::from_bundle_dir(&dir)
209    }
210
211    /// Removes everything this crate put in the cache: the bundles, the downloads, the
212    /// tools and the temporary files (and the directory itself, when nothing else is in
213    /// it). Other files in the directory are left alone.
214    ///
215    /// # Errors
216    ///
217    /// [`Error::Io`] when something cannot be removed.
218    pub fn clear(&self) -> Result<(), Error> {
219        if !self.root.exists() {
220            return Ok(());
221        }
222        let lock = self.lock()?;
223        for dir in [RULES_DIR, DOWNLOADS_DIR, TOOLS_DIR, WORK_DIR] {
224            remove_dir(&self.root.join(dir))?;
225        }
226        remove_file(&self.root.join(TAG_FILE))?;
227        drop(lock);
228        remove_file(&self.root.join(LOCK_FILE))?;
229        // Only when empty: the directory may be one the user keeps other files in.
230        let _ = std::fs::remove_dir(&self.root);
231        Ok(())
232    }
233
234    /// Creates the cache directory, with its tag, and takes its lock: one fetch or
235    /// clear at a time (readers take no lock: what they read is checked, and a bundle
236    /// appears by a rename).
237    pub(crate) fn lock(&self) -> Result<File, Error> {
238        let io = |path: &Path| {
239            let path = path.to_path_buf();
240            move |source| Error::Io { path, source }
241        };
242        std::fs::create_dir_all(&self.root).map_err(io(&self.root))?;
243        let tag = self.root.join(TAG_FILE);
244        if !tag.exists() {
245            std::fs::write(&tag, TAG).map_err(io(&tag))?;
246        }
247        let path = self.root.join(LOCK_FILE);
248        let file = std::fs::OpenOptions::new()
249            .create(true)
250            .truncate(false)
251            .write(true)
252            .open(&path)
253            .map_err(io(&path))?;
254        file.lock().map_err(io(&path))?;
255        Ok(file)
256    }
257}
258
259fn remove_dir(dir: &Path) -> Result<(), Error> {
260    match std::fs::remove_dir_all(dir) {
261        Ok(()) => Ok(()),
262        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
263        Err(source) => Err(Error::Io {
264            path: dir.to_path_buf(),
265            source,
266        }),
267    }
268}
269
270fn remove_file(file: &Path) -> Result<(), Error> {
271    match std::fs::remove_file(file) {
272        Ok(()) => Ok(()),
273        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
274        Err(source) => Err(Error::Io {
275            path: file.to_path_buf(),
276            source,
277        }),
278    }
279}
280
281/// The error for a name that is no fetched rule set.
282pub(crate) fn unknown(name: &str) -> Error {
283    let names = catalogue::fetched_rule_sets()
284        .map(|all| {
285            all.iter()
286                .map(FetchedRuleSet::name)
287                .collect::<Vec<_>>()
288                .join(", ")
289        })
290        .unwrap_or_default();
291    Error::bundle(format!(
292        "no fetched rule set named {name:?} (fetched rule sets: {names}; aliases: {})",
293        catalogue::ALIASES
294            .iter()
295            .map(|(a, _)| *a)
296            .collect::<Vec<_>>()
297            .join(", ")
298    ))
299}
300
301/// The platform's cache directory for this crate.
302fn platform_dir() -> Option<PathBuf> {
303    let var = |name: &str| {
304        std::env::var_os(name)
305            .filter(|v| !v.is_empty())
306            .map(PathBuf::from)
307            .filter(|p| p.is_absolute())
308    };
309    if cfg!(windows) {
310        return var("LOCALAPPDATA").map(|d| d.join("einvoice-validator").join("cache"));
311    }
312    if cfg!(target_os = "macos") {
313        return var("HOME").map(|h| h.join("Library").join("Caches").join("einvoice-validator"));
314    }
315    var("XDG_CACHE_HOME")
316        .or_else(|| var("HOME").map(|h| h.join(".cache")))
317        .map(|d| d.join("einvoice-validator"))
318}
319
320impl Validator {
321    /// The fetched rule set `name` (see [`fetched_rule_sets`](crate::fetched_rule_sets)),
322    /// from the cache in its default directory ([`RuleSetCache::new`]), checked in full.
323    /// Never downloads anything: fetch it first with `RuleSetCache::fetch` (feature
324    /// `fetch`), or `einvoice-validate rules fetch NAME`.
325    ///
326    /// # Errors
327    ///
328    /// As [`RuleSetCache::new`] and [`RuleSetCache::load`]; [`Error::NotCached`] when
329    /// it has not been fetched.
330    pub fn from_cache(name: &str) -> Result<Self, Error> {
331        RuleSetCache::new()?.load(name)
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338
339    fn temp(name: &str) -> PathBuf {
340        let dir =
341            std::env::temp_dir().join(format!("einvoice-cache-test-{}-{name}", std::process::id()));
342        let _ = std::fs::remove_dir_all(&dir);
343        dir
344    }
345
346    #[test]
347    fn an_empty_cache_has_nothing() {
348        let cache = RuleSetCache::at(temp("empty"));
349        for r in catalogue::fetched_rule_sets().unwrap() {
350            assert_eq!(cache.status(r), CacheStatus::Missing, "{}", r.name());
351            match cache.load_rule_set(r) {
352                Err(Error::NotCached { name, dir }) => {
353                    assert_eq!(name, r.name());
354                    assert_eq!(dir, cache.root());
355                }
356                other => panic!("{}: {other:?}", r.name()),
357            }
358        }
359        assert!(matches!(cache.load("nope"), Err(Error::Bundle { .. })));
360        cache.clear().unwrap();
361        assert!(!cache.root().exists());
362    }
363
364    #[test]
365    fn bundle_dirs_follow_the_fetch_scripts() {
366        let cache = RuleSetCache::at("/c");
367        let dir = |n: &str| {
368            let r = catalogue::fetched_rule_set(n, None).unwrap().unwrap();
369            let release = r.release().to_owned();
370            (cache.bundle_dir(r), release)
371        };
372        // Made absolute: on Windows, with the current drive.
373        let rules = std::path::absolute("/c").unwrap().join("rules");
374        let (en16931, release) = dir("factur-x-en16931");
375        assert_eq!(en16931, rules.join(&release).join("en16931"));
376        let (peppol, release) = dir("peppol");
377        assert_eq!(peppol, rules.join(release));
378    }
379
380    #[test]
381    fn a_tampered_bundle_is_not_loaded() {
382        let cache = RuleSetCache::at(temp("tampered"));
383        let r = catalogue::fetched_rule_set("factur-x-minimum", None)
384            .unwrap()
385            .unwrap();
386        let dir = cache.bundle_dir(r);
387        std::fs::create_dir_all(&dir).unwrap();
388        // Another manifest.
389        std::fs::write(dir.join(MANIFEST_FILE), "format = 1\n").unwrap();
390        assert!(matches!(cache.status(r), CacheStatus::Invalid(_)));
391        let error = cache.load_rule_set(r).unwrap_err().to_string();
392        assert!(error.contains("fetch it again"), "{error}");
393        // The catalogue's manifest, but the files missing or altered.
394        std::fs::write(dir.join(MANIFEST_FILE), r.manifest()).unwrap();
395        let CacheStatus::Invalid(why) = cache.status(r) else {
396            panic!("{:?}", cache.status(r))
397        };
398        assert!(why.contains("FACTUR-X_MINIMUM.xslt"), "{why}");
399        std::fs::write(dir.join("FACTUR-X_MINIMUM.xslt"), "<x/>").unwrap();
400        let CacheStatus::Invalid(why) = cache.status(r) else {
401            panic!()
402        };
403        assert!(why.contains("SHA-256"), "{why}");
404        assert!(matches!(
405            cache.load_rule_set(r),
406            Err(Error::Checksum { .. })
407        ));
408        // clear removes it all, and leaves other files alone.
409        std::fs::write(cache.root().join("mine.txt"), "keep").unwrap();
410        cache.clear().unwrap();
411        assert!(!cache.root().join(RULES_DIR).exists());
412        assert!(cache.root().join("mine.txt").exists());
413        std::fs::remove_dir_all(cache.root()).unwrap();
414    }
415}