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 .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 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 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 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 let _ = std::fs::remove_dir(&self.root);
231 Ok(())
232 }
233
234 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
281pub(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
301fn 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 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 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 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 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 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}