Skip to main content

libtea_client/
cache.rs

1//! Opt-in persistent HTTP cache (`docs/cache.md`).
2//!
3//! *Experimental until 0.9.* Enabled with [`crate::ClientBuilder::cache_dir`] or
4//! [`crate::ClientBuilder::cache`]. Off by default.
5//!
6//! What it is: a per-user directory of response bodies, used to send
7//! conditional `GET`s (`ETag` / `Last-Modified`) and, with
8//! [`crate::ClientBuilder::offline`], to answer without the network.
9//!
10//! What it is not: a trust boundary. An entry is checked for truncation and
11//! corruption (length and SHA-256), but anyone who can write the directory can
12//! write a consistent entry. So the directory is created private (mode 0700,
13//! files 0600 on Unix), a symbolic link or a directory open to other users is
14//! refused, artifact bytes are checked against their declared checksums every
15//! time they are used, and an entry that fails any check is treated as absent
16//! and removed. Writes are atomic (temporary file, then rename) but are not
17//! `fsync`ed; a crash can lose an entry, never leave a half-written one in use.
18
19use std::io::Write;
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::Arc;
23use std::time::{Duration, SystemTime, UNIX_EPOCH};
24
25use libtea_core::escape_control_chars;
26use libtea_core::http_cache::{
27    decode_entry, encode_entry, is_cache_key, CacheEntryMeta, EntryBuilder,
28};
29use tokio::io::AsyncWriteExt;
30
31use crate::error::ClientError;
32
33/// Largest metadata block plus framing an entry file adds to its body.
34const FRAMING_SLACK: u64 = 80 * 1024;
35const ENTRY_DIR: &str = "v1";
36
37/// Cache settings. Defaults are conservative; every limit is a ceiling.
38///
39/// *Experimental.*
40#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub struct CacheConfig {
43    /// The cache directory. Created private if missing.
44    pub dir: PathBuf,
45    /// Total bytes of entries kept; the oldest are removed past this.
46    pub max_total_bytes: u64,
47    /// Largest body stored. A larger response is simply not cached.
48    pub max_entry_bytes: u64,
49    /// Oldest an entry may be, counted from its last successful revalidation.
50    /// An older entry is treated as absent, offline mode included.
51    pub max_age: Duration,
52    /// Also store responses to requests that carried credentials, and
53    /// `Cache-Control: private` responses. Off by default.
54    pub authenticated: bool,
55}
56
57impl CacheConfig {
58    /// Defaults: 512 MiB total, 64 MiB per entry, 7 days, no authenticated
59    /// responses.
60    #[must_use]
61    pub fn new(dir: impl Into<PathBuf>) -> Self {
62        Self {
63            dir: dir.into(),
64            max_total_bytes: 512 * 1024 * 1024,
65            max_entry_bytes: 64 * 1024 * 1024,
66            max_age: Duration::from_secs(7 * 24 * 60 * 60),
67            authenticated: false,
68        }
69    }
70
71    /// Set [`Self::max_total_bytes`].
72    #[must_use]
73    pub fn with_max_total_bytes(mut self, value: u64) -> Self {
74        self.max_total_bytes = value;
75        self
76    }
77
78    /// Set [`Self::max_entry_bytes`].
79    #[must_use]
80    pub fn with_max_entry_bytes(mut self, value: u64) -> Self {
81        self.max_entry_bytes = value;
82        self
83    }
84
85    /// Set [`Self::max_age`].
86    #[must_use]
87    pub fn with_max_age(mut self, value: Duration) -> Self {
88        self.max_age = value;
89        self
90    }
91
92    /// Set [`Self::authenticated`].
93    #[must_use]
94    pub fn with_authenticated(mut self, value: bool) -> Self {
95        self.authenticated = value;
96        self
97    }
98}
99
100pub(crate) fn now_secs() -> u64 {
101    SystemTime::now()
102        .duration_since(UNIX_EPOCH)
103        .map_or(0, |elapsed| elapsed.as_secs())
104}
105
106fn io_error(what: &str, err: &std::io::Error) -> ClientError {
107    ClientError::Io(escape_control_chars(&format!("{what}: {}", err.kind())))
108}
109
110fn refuse(path: &Path, why: &str) -> ClientError {
111    ClientError::Io(escape_control_chars(&format!(
112        "cache directory {}: {why}",
113        path.display()
114    )))
115}
116
117/// Check (and optionally create) a directory the cache will use. Returns
118/// whether it exists. Refuses a symbolic link, a non-directory, and on Unix a
119/// directory that group or others can access.
120fn private_dir(path: &Path, create: bool) -> Result<bool, ClientError> {
121    match std::fs::symlink_metadata(path) {
122        Ok(meta) if meta.file_type().is_symlink() => {
123            Err(refuse(path, "is a symbolic link; refusing to use it"))
124        }
125        Ok(meta) if !meta.is_dir() => Err(refuse(path, "is not a directory")),
126        Ok(meta) => {
127            #[cfg(unix)]
128            {
129                use std::os::unix::fs::{MetadataExt, PermissionsExt};
130                // A private directory that someone else owns is theirs to
131                // change; refuse it. The reference uid is that of a file this
132                // process has just created, so no uid lookup is needed.
133                if !owner_matches(meta.uid(), current_uid(Some(path))?) {
134                    return Err(refuse(
135                        path,
136                        "is owned by another user; use a directory you own",
137                    ));
138                }
139                let mode = meta.permissions().mode() & 0o777;
140                if mode & 0o077 != 0 {
141                    return Err(refuse(
142                        path,
143                        &format!(
144                            "is accessible by other users (mode {mode:o}); run chmod 700 on it"
145                        ),
146                    ));
147                }
148            }
149            #[cfg(not(unix))]
150            let _ = meta;
151            Ok(true)
152        }
153        Err(err) if err.kind() == std::io::ErrorKind::NotFound && create => {
154            let mut builder = std::fs::DirBuilder::new();
155            builder.recursive(true);
156            #[cfg(unix)]
157            {
158                use std::os::unix::fs::DirBuilderExt;
159                builder.mode(0o700);
160            }
161            builder
162                .create(path)
163                .map_err(|e| io_error("creating the cache directory", &e))?;
164            // Look again: what we created must be what we meant to create.
165            private_dir(path, false)
166        }
167        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
168        Err(err) => Err(io_error("inspecting the cache directory", &err)),
169    }
170}
171
172/// Whether a directory owned by `dir_uid` belongs to the user running the
173/// process, whose files get `own_uid`.
174#[cfg(unix)]
175pub(crate) fn owner_matches(dir_uid: u32, own_uid: u32) -> bool {
176    dir_uid == own_uid
177}
178
179/// The uid this process creates files as: the owner of a file created now,
180/// in the temporary directory or, if that is not writable, in `fallback`.
181#[cfg(unix)]
182pub(crate) fn current_uid(fallback: Option<&Path>) -> Result<u32, ClientError> {
183    use std::os::unix::fs::MetadataExt;
184    static COUNTER: AtomicU64 = AtomicU64::new(0);
185    let name = format!(
186        ".libtea-uid-{}-{}",
187        std::process::id(),
188        COUNTER.fetch_add(1, Ordering::Relaxed)
189    );
190    let mut last = None;
191    for dir in std::iter::once(std::env::temp_dir()).chain(fallback.map(Path::to_path_buf)) {
192        let probe = dir.join(&name);
193        match open_private(&probe) {
194            Ok(file) => {
195                let uid = file
196                    .metadata()
197                    .map_err(|e| io_error("checking directory ownership", &e))?
198                    .uid();
199                drop(file);
200                let _ = std::fs::remove_file(&probe);
201                return Ok(uid);
202            }
203            Err(err) => last = Some(err),
204        }
205    }
206    Err(match last {
207        Some(err) => io_error("checking directory ownership", &err),
208        None => ClientError::Io("checking directory ownership".into()),
209    })
210}
211
212pub(crate) struct Cache {
213    pub(crate) config: CacheConfig,
214    entries: PathBuf,
215    counter: AtomicU64,
216    pub(crate) offline: bool,
217}
218
219impl Cache {
220    pub(crate) fn open(config: CacheConfig, offline: bool) -> Result<Self, ClientError> {
221        private_dir(&config.dir, true)?;
222        let entries = config.dir.join(ENTRY_DIR);
223        private_dir(&entries, true)?;
224        Ok(Self {
225            config,
226            entries,
227            counter: AtomicU64::new(0),
228            offline,
229        })
230    }
231
232    fn entry_path(&self, key: &str) -> PathBuf {
233        debug_assert!(is_cache_key(key));
234        self.entries.join(format!("{key}.entry"))
235    }
236
237    fn temp_path(&self, key: &str) -> PathBuf {
238        self.entries.join(format!(
239            ".{key}.{}-{}.tmp",
240            std::process::id(),
241            self.counter.fetch_add(1, Ordering::Relaxed)
242        ))
243    }
244
245    /// Read and check one entry; anything wrong removes it and returns `None`.
246    pub(crate) fn load_blocking(&self, key: &str) -> Option<(CacheEntryMeta, Vec<u8>)> {
247        if !is_cache_key(key) {
248            return None;
249        }
250        let path = self.entry_path(key);
251        let meta = std::fs::symlink_metadata(&path).ok()?;
252        let remove = |path: &Path| {
253            let _ = std::fs::remove_file(path);
254        };
255        if !meta.file_type().is_file() || meta.len() > self.config.max_entry_bytes + FRAMING_SLACK {
256            remove(&path);
257            return None;
258        }
259        let bytes = read_regular(&path, self.config.max_entry_bytes + FRAMING_SLACK).ok()?;
260        let max_body = usize::try_from(self.config.max_entry_bytes).unwrap_or(usize::MAX);
261        match decode_entry(&bytes, key, max_body) {
262            Ok((entry, body)) => {
263                let now = now_secs();
264                let age = now.saturating_sub(entry.validated_at);
265                if entry.validated_at > now.saturating_add(24 * 60 * 60)
266                    || age > self.config.max_age.as_secs()
267                {
268                    remove(&path);
269                    return None;
270                }
271                Some((entry, body))
272            }
273            Err(error) => {
274                tracing::debug!(%error, "cache entry refused and removed");
275                remove(&path);
276                None
277            }
278        }
279    }
280
281    pub(crate) async fn load(self: &Arc<Self>, key: &str) -> Option<(CacheEntryMeta, Vec<u8>)> {
282        let cache = Arc::clone(self);
283        let key = key.to_owned();
284        tokio::task::spawn_blocking(move || cache.load_blocking(&key))
285            .await
286            .ok()
287            .flatten()
288    }
289
290    /// Store one entry atomically. Never fails the caller: a problem is logged.
291    pub(crate) fn store_blocking(&self, key: &str, meta: CacheEntryMeta, body: &[u8]) {
292        if !is_cache_key(key) || body.len() as u64 > self.config.max_entry_bytes {
293            return;
294        }
295        let Ok(bytes) = encode_entry(meta, body) else {
296            return;
297        };
298        let tmp = self.temp_path(key);
299        let result = open_private(&tmp)
300            .and_then(|mut file| file.write_all(&bytes))
301            .and_then(|()| std::fs::rename(&tmp, self.entry_path(key)));
302        match result {
303            Ok(()) => self.prune_blocking(),
304            Err(error) => {
305                tracing::debug!(kind = ?error.kind(), "cache entry not written");
306                let _ = std::fs::remove_file(&tmp);
307            }
308        }
309    }
310
311    pub(crate) async fn store(self: &Arc<Self>, key: &str, meta: CacheEntryMeta, body: Vec<u8>) {
312        let cache = Arc::clone(self);
313        let key = key.to_owned();
314        let _ = tokio::task::spawn_blocking(move || cache.store_blocking(&key, meta, &body)).await;
315    }
316
317    pub(crate) fn remove_blocking(&self, key: &str) {
318        if is_cache_key(key) {
319            let _ = std::fs::remove_file(self.entry_path(key));
320        }
321    }
322
323    pub(crate) async fn remove(self: &Arc<Self>, key: &str) {
324        let cache = Arc::clone(self);
325        let key = key.to_owned();
326        let _ = tokio::task::spawn_blocking(move || cache.remove_blocking(&key)).await;
327    }
328
329    /// Drop the oldest entries until the total is within the limit, and stale
330    /// temporary files left by a crash.
331    pub(crate) fn prune_blocking(&self) {
332        let Ok(dir) = std::fs::read_dir(&self.entries) else {
333            return;
334        };
335        let now = SystemTime::now();
336        let mut entries: Vec<(SystemTime, u64, PathBuf)> = Vec::new();
337        let mut total = 0u64;
338        for item in dir.flatten() {
339            let path = item.path();
340            let Ok(meta) = std::fs::symlink_metadata(&path) else {
341                continue;
342            };
343            let name = item.file_name();
344            let name = name.to_string_lossy();
345            if is_cache_temp(&name) {
346                let old = meta
347                    .modified()
348                    .ok()
349                    .and_then(|m| now.duration_since(m).ok())
350                    .is_some_and(|age| age > Duration::from_secs(3600));
351                if old {
352                    let _ = std::fs::remove_file(&path);
353                }
354                continue;
355            }
356            if !meta.file_type().is_file() || !name.ends_with(".entry") {
357                continue;
358            }
359            total = total.saturating_add(meta.len());
360            entries.push((meta.modified().unwrap_or(UNIX_EPOCH), meta.len(), path));
361        }
362        if total <= self.config.max_total_bytes {
363            return;
364        }
365        entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.cmp(&b.2)));
366        for (_, size, path) in entries {
367            if total <= self.config.max_total_bytes {
368                break;
369            }
370            if std::fs::remove_file(&path).is_ok() {
371                total = total.saturating_sub(size);
372            }
373        }
374    }
375
376    /// Begin writing an entry whose body is still arriving. `None` when the
377    /// temporary file cannot be created.
378    pub(crate) async fn start_tee(self: &Arc<Self>, key: &str) -> Option<CacheTee> {
379        if !is_cache_key(key) {
380            return None;
381        }
382        let tmp = self.temp_path(key);
383        let mut options = tokio::fs::OpenOptions::new();
384        options.write(true).create_new(true);
385        #[cfg(unix)]
386        options.mode(0o600);
387        let mut file = options.open(&tmp).await.ok()?;
388        if file.write_all(EntryBuilder::prefix()).await.is_err() {
389            let _ = std::fs::remove_file(&tmp);
390            return None;
391        }
392        Some(CacheTee {
393            cache: Arc::clone(self),
394            key: key.to_owned(),
395            file: Some(file),
396            tmp,
397            builder: EntryBuilder::new(),
398        })
399    }
400}
401
402/// Open `path` only if it is a regular file, and keep that true while opening.
403///
404/// The path is inspected with `lstat`, opened, and inspected again; the opened
405/// file must be the regular file the path names both times (same device and
406/// inode). A symbolic link swapped in between the checks is refused instead of
407/// followed, which `lstat`-then-read alone would not do. `between` runs after
408/// the first inspection and exists so a test can make that swap happen.
409#[cfg(unix)]
410fn open_regular_with(path: &Path, between: impl FnOnce()) -> std::io::Result<std::fs::File> {
411    use std::os::unix::fs::MetadataExt;
412    let invalid =
413        |what: &str| std::io::Error::new(std::io::ErrorKind::InvalidInput, what.to_owned());
414    let before = std::fs::symlink_metadata(path)?;
415    if !before.file_type().is_file() {
416        return Err(invalid("not a regular file"));
417    }
418    between();
419    let file = std::fs::File::open(path)?;
420    let opened = file.metadata()?;
421    let after = std::fs::symlink_metadata(path)?;
422    if !after.file_type().is_file()
423        || !opened.is_file()
424        || (opened.dev(), opened.ino()) != (after.dev(), after.ino())
425        || (opened.dev(), opened.ino()) != (before.dev(), before.ino())
426    {
427        return Err(invalid("the path changed while it was opened"));
428    }
429    Ok(file)
430}
431
432/// Read at most `limit` bytes of a regular file (see [`open_regular_with`]);
433/// a longer file is an error.
434fn read_regular(path: &Path, limit: u64) -> std::io::Result<Vec<u8>> {
435    use std::io::Read;
436    #[cfg(unix)]
437    let file = open_regular_with(path, || {})?;
438    #[cfg(not(unix))]
439    let file = {
440        if !std::fs::symlink_metadata(path)?.file_type().is_file() {
441            return Err(std::io::Error::new(
442                std::io::ErrorKind::InvalidInput,
443                "not a regular file",
444            ));
445        }
446        std::fs::File::open(path)?
447    };
448    let mut bytes = Vec::new();
449    file.take(limit + 1).read_to_end(&mut bytes)?;
450    if bytes.len() as u64 > limit {
451        return Err(std::io::Error::new(
452            std::io::ErrorKind::InvalidData,
453            "entry is larger than the limit",
454        ));
455    }
456    Ok(bytes)
457}
458
459fn open_private(path: &Path) -> std::io::Result<std::fs::File> {
460    let mut options = std::fs::OpenOptions::new();
461    options.write(true).create_new(true);
462    #[cfg(unix)]
463    {
464        use std::os::unix::fs::OpenOptionsExt;
465        options.mode(0o600);
466    }
467    options.open(path)
468}
469
470/// An entry being written while the body streams past. The file is removed
471/// unless [`CacheTee::finish`] commits it, so a failed or cancelled download
472/// leaves nothing behind.
473pub(crate) struct CacheTee {
474    cache: Arc<Cache>,
475    key: String,
476    file: Option<tokio::fs::File>,
477    tmp: PathBuf,
478    builder: EntryBuilder,
479}
480
481impl CacheTee {
482    /// Add body bytes. Returns `false` once the entry is abandoned (too large
483    /// or a write failed); later calls are no-ops.
484    pub(crate) async fn write(&mut self, chunk: &[u8]) -> bool {
485        let Some(file) = self.file.as_mut() else {
486            return false;
487        };
488        if self.builder.len().saturating_add(chunk.len() as u64) > self.cache.config.max_entry_bytes
489            || file.write_all(chunk).await.is_err()
490        {
491            self.abandon();
492            return false;
493        }
494        self.builder.update(chunk);
495        true
496    }
497
498    fn abandon(&mut self) {
499        self.file = None;
500        let _ = std::fs::remove_file(&self.tmp);
501    }
502
503    /// Commit the entry. Call only after the body passed every check.
504    pub(crate) async fn finish(mut self, meta: CacheEntryMeta) {
505        let Some(mut file) = self.file.take() else {
506            return;
507        };
508        let builder = std::mem::take(&mut self.builder);
509        let Ok(trailer) = builder.trailer(meta) else {
510            self.abandon();
511            return;
512        };
513        if file.write_all(&trailer).await.is_err() || file.flush().await.is_err() {
514            drop(file);
515            let _ = std::fs::remove_file(&self.tmp);
516            return;
517        }
518        drop(file);
519        let cache = Arc::clone(&self.cache);
520        let tmp = self.tmp.clone();
521        let final_path = cache.entry_path(&self.key);
522        let committed = tokio::task::spawn_blocking(move || {
523            let ok = std::fs::rename(&tmp, final_path).is_ok();
524            if ok {
525                cache.prune_blocking();
526            } else {
527                let _ = std::fs::remove_file(&tmp);
528            }
529            ok
530        })
531        .await
532        .unwrap_or(false);
533        if committed {
534            // The temporary file no longer exists; nothing for Drop to remove.
535            self.tmp = PathBuf::new();
536        }
537    }
538}
539
540impl Drop for CacheTee {
541    fn drop(&mut self) {
542        if !self.tmp.as_os_str().is_empty() {
543            let _ = std::fs::remove_file(&self.tmp);
544        }
545    }
546}
547
548/// What `libtea cache stat` reports.
549///
550/// *Experimental.*
551#[derive(Debug, Clone, PartialEq, Eq)]
552#[non_exhaustive]
553pub struct CacheStats {
554    /// The directory inspected.
555    pub dir: PathBuf,
556    /// Whether it exists.
557    pub exists: bool,
558    /// Entry files.
559    pub entries: u64,
560    /// Bytes in entry files.
561    pub bytes: u64,
562    /// Files, directories and links that are not entries.
563    pub foreign: u64,
564    /// Seconds since the oldest entry file was written (by file time).
565    pub oldest_age_secs: Option<u64>,
566    /// Seconds since the newest entry file was written (by file time).
567    pub newest_age_secs: Option<u64>,
568}
569
570fn entry_files(dir: &Path) -> Result<Option<(PathBuf, std::fs::ReadDir)>, ClientError> {
571    if !private_dir(dir, false)? {
572        return Ok(None);
573    }
574    let entries = dir.join(ENTRY_DIR);
575    if !private_dir(&entries, false)? {
576        return Ok(None);
577    }
578    let read =
579        std::fs::read_dir(&entries).map_err(|e| io_error("reading the cache directory", &e))?;
580    Ok(Some((entries, read)))
581}
582
583/// Summarise a cache directory without changing it.
584///
585/// # Errors
586///
587/// Returns an error when the directory is a symbolic link, is open to other
588/// users, or cannot be read. A directory that does not exist is not an error.
589pub fn cache_stat(dir: &Path) -> Result<CacheStats, ClientError> {
590    let mut stats = CacheStats {
591        dir: dir.to_path_buf(),
592        exists: false,
593        entries: 0,
594        bytes: 0,
595        foreign: 0,
596        oldest_age_secs: None,
597        newest_age_secs: None,
598    };
599    let Some((_, read)) = entry_files(dir)? else {
600        return Ok(stats);
601    };
602    stats.exists = true;
603    let now = SystemTime::now();
604    for item in read.flatten() {
605        let name = item.file_name();
606        let name = name.to_string_lossy().into_owned();
607        let Ok(meta) = std::fs::symlink_metadata(item.path()) else {
608            continue;
609        };
610        let key = name.strip_suffix(".entry").unwrap_or("");
611        if meta.file_type().is_file() && is_cache_key(key) {
612            stats.entries += 1;
613            stats.bytes = stats.bytes.saturating_add(meta.len());
614            if let Some(age) = meta
615                .modified()
616                .ok()
617                .and_then(|m| now.duration_since(m).ok())
618            {
619                let age = age.as_secs();
620                stats.oldest_age_secs = Some(stats.oldest_age_secs.map_or(age, |o| o.max(age)));
621                stats.newest_age_secs = Some(stats.newest_age_secs.map_or(age, |n| n.min(age)));
622            }
623        } else if !name.ends_with(".tmp") {
624            stats.foreign += 1;
625        }
626    }
627    Ok(stats)
628}
629
630/// A temporary file the cache itself writes: `.<64 hex key>.<pid>-<n>.tmp`.
631/// Nothing else is a cache temporary file, whatever its name ends in.
632fn is_cache_temp(name: &str) -> bool {
633    let Some(rest) = name.strip_prefix('.') else {
634        return false;
635    };
636    let Some(rest) = rest.strip_suffix(".tmp") else {
637        return false;
638    };
639    let Some((key, tail)) = rest.split_once('.') else {
640        return false;
641    };
642    is_cache_key(key)
643        && tail.split_once('-').is_some_and(|(pid, n)| {
644            !pid.is_empty()
645                && !n.is_empty()
646                && pid.bytes().all(|b| b.is_ascii_digit())
647                && n.bytes().all(|b| b.is_ascii_digit())
648        })
649}
650
651/// Remove every cache entry (and stray temporary files) and return how many
652/// files were removed. Only files this cache writes are touched: names that are
653/// a cache key plus `.entry`, and `*.tmp`. Other files, and the directories
654/// themselves, are left alone. A symbolic link with an entry's name is removed
655/// as a link; its target is never followed.
656///
657/// # Errors
658///
659/// Returns an error when the directory is a symbolic link, is open to other
660/// users, or cannot be read.
661pub fn cache_clear(dir: &Path) -> Result<u64, ClientError> {
662    let Some((entries, read)) = entry_files(dir)? else {
663        return Ok(0);
664    };
665    let mut removed = 0;
666    for item in read.flatten() {
667        let name = item.file_name();
668        let name = name.to_string_lossy().into_owned();
669        let is_entry = name.strip_suffix(".entry").is_some_and(is_cache_key);
670        let is_temp = is_cache_temp(&name);
671        if !(is_entry || is_temp) {
672            continue;
673        }
674        let path = entries.join(&name);
675        let Ok(meta) = std::fs::symlink_metadata(&path) else {
676            continue;
677        };
678        if (meta.file_type().is_file() || meta.file_type().is_symlink())
679            && std::fs::remove_file(&path).is_ok()
680        {
681            removed += 1;
682        }
683    }
684    Ok(removed)
685}
686
687#[cfg(all(test, unix))]
688mod tests {
689    use super::*;
690
691    fn scratch(tag: &str) -> PathBuf {
692        let dir =
693            std::env::temp_dir().join(format!("libtea-cache-unit-{tag}-{}", std::process::id()));
694        let _ = std::fs::remove_dir_all(&dir);
695        std::fs::create_dir_all(&dir).unwrap();
696        dir
697    }
698
699    #[test]
700    fn ownership_is_compared_with_the_uid_of_a_file_just_created() {
701        let dir = scratch("uid");
702        let mine = current_uid(None).unwrap();
703        let probe = dir.join("probe");
704        std::fs::write(&probe, b"x").unwrap();
705        use std::os::unix::fs::MetadataExt;
706        assert_eq!(std::fs::metadata(&probe).unwrap().uid(), mine);
707        assert_eq!(std::fs::metadata(&dir).unwrap().uid(), mine);
708        assert!(owner_matches(mine, mine));
709        assert!(
710            !owner_matches(mine.wrapping_add(1), mine),
711            "another uid must not match"
712        );
713        assert!(!owner_matches(0, 501) && !owner_matches(501, 0));
714        let _ = std::fs::remove_dir_all(dir);
715    }
716
717    #[test]
718    fn a_regular_file_opens_and_a_symlink_never_does() {
719        let dir = scratch("nofollow");
720        let real = dir.join("real");
721        std::fs::write(&real, b"entry").unwrap();
722        assert_eq!(read_regular(&real, 100).unwrap(), b"entry");
723        let link = dir.join("link");
724        std::os::unix::fs::symlink(&real, &link).unwrap();
725        assert!(open_regular_with(&link, || {}).is_err());
726        assert!(read_regular(&link, 100).is_err());
727        assert!(
728            read_regular(&dir, 100).is_err(),
729            "a directory is not an entry"
730        );
731        assert!(read_regular(&real, 3).is_err(), "over the limit");
732        let _ = std::fs::remove_dir_all(dir);
733    }
734
735    #[test]
736    fn a_symlink_swapped_in_after_the_check_is_refused_not_followed() {
737        let dir = scratch("swap");
738        let entry = dir.join("entry");
739        let secret = dir.join("secret");
740        std::fs::write(&entry, b"genuine").unwrap();
741        std::fs::write(&secret, b"must not be read").unwrap();
742        // Between the first lstat and the open, replace the file by a link.
743        let swapped = open_regular_with(&entry, || {
744            std::fs::remove_file(&entry).unwrap();
745            std::os::unix::fs::symlink(&secret, &entry).unwrap();
746        });
747        assert!(swapped.is_err(), "the swapped-in link was followed");
748        // And a plain replacement by another regular file is noticed too.
749        // The original stays alive under a second name, so the replacement
750        // cannot be given the same inode number (a freed inode is reused at
751        // once on Linux, which would make the two indistinguishable).
752        let entry2 = dir.join("entry2");
753        let kept = dir.join("entry2-kept");
754        std::fs::write(&entry2, b"first").unwrap();
755        std::fs::hard_link(&entry2, &kept).unwrap();
756        let replaced = open_regular_with(&entry2, || {
757            std::fs::remove_file(&entry2).unwrap();
758            std::fs::write(&entry2, b"second").unwrap();
759        });
760        assert!(
761            replaced.is_err(),
762            "a different file than the one inspected was accepted"
763        );
764        let _ = std::fs::remove_dir_all(dir);
765    }
766
767    #[test]
768    fn only_the_caches_own_temporary_files_are_temporary_files() {
769        let key = "a".repeat(64);
770        assert!(is_cache_temp(&format!(".{key}.123-4.tmp")));
771        for other in [
772            ".mine.tmp",
773            ".notes.libtea.tmp",
774            "build.tmp",
775            &format!(".{key}.tmp"),
776            &format!(".{key}.x-4.tmp"),
777            &format!(".{key}.12-.tmp"),
778            &format!(".{key}.12-4.tmp.bak"),
779            &format!(".{}.1-2.tmp", "g".repeat(64)),
780            &format!(".{}.1-2.tmp", "a".repeat(63)),
781            &format!("{key}.1-2.tmp"),
782        ] {
783            assert!(!is_cache_temp(other), "{other}");
784        }
785    }
786}