einvoice_validator/rulesets/
cache.rs1use std::fs::File;
5use std::path::{Path, PathBuf};
6
7use super::catalogue::{self, FetchedRuleSet};
8use crate::{Error, MANIFEST_FILE, RuleSet, Validator};
9
10pub const CACHE_ENV: &str = "EINVOICE_VALIDATOR_CACHE";
12
13pub(crate) const RULES_DIR: &str = "rules";
15pub(crate) const DOWNLOADS_DIR: &str = "downloads";
17pub(crate) const TOOLS_DIR: &str = "tools";
19pub(crate) const WORK_DIR: &str = "work";
21const LOCK_FILE: &str = ".lock";
23const 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#[derive(Debug, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum CacheStatus {
34 Cached,
37 Missing,
39 Invalid(String),
41}
42
43#[derive(Debug, Clone)]
61pub struct RuleSetCache {
62 root: PathBuf,
63}
64
65impl RuleSetCache {
66 pub fn new() -> Result<Self, Error> {
72 Ok(Self::at(Self::default_dir()?))
73 }
74
75 #[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 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 #[must_use]
102 pub fn root(&self) -> &Path {
103 &self.root
104 }
105
106 #[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 #[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 #[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 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 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 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 let _ = std::fs::remove_dir(&self.root);
225 Ok(())
226 }
227
228 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
275pub(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
295fn 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 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 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 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 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 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}