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    pub(crate) offline: bool,
216}
217
218/// Numbers temporary files. One per process, not per [`Cache`]: several clients
219/// in one process can share a directory, and a per-cache counter gave each of
220/// them the same names.
221static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
222
223impl Cache {
224    pub(crate) fn open(config: CacheConfig, offline: bool) -> Result<Self, ClientError> {
225        private_dir(&config.dir, true)?;
226        let entries = config.dir.join(ENTRY_DIR);
227        private_dir(&entries, true)?;
228        Ok(Self {
229            config,
230            entries,
231            offline,
232        })
233    }
234
235    fn entry_path(&self, key: &str) -> PathBuf {
236        debug_assert!(is_cache_key(key));
237        self.entries.join(format!("{key}.entry"))
238    }
239
240    fn temp_path(&self, key: &str) -> PathBuf {
241        self.entries.join(format!(
242            ".{key}.{}-{}.tmp",
243            std::process::id(),
244            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
245        ))
246    }
247
248    /// Read and check one entry; anything wrong removes it and returns `None`.
249    pub(crate) fn load_blocking(&self, key: &str) -> Option<(CacheEntryMeta, Vec<u8>)> {
250        if !is_cache_key(key) {
251            return None;
252        }
253        let path = self.entry_path(key);
254        let meta = std::fs::symlink_metadata(&path).ok()?;
255        let remove = |path: &Path| {
256            let _ = std::fs::remove_file(path);
257        };
258        if !meta.file_type().is_file() || meta.len() > self.config.max_entry_bytes + FRAMING_SLACK {
259            remove(&path);
260            return None;
261        }
262        let bytes = read_regular(&path, self.config.max_entry_bytes + FRAMING_SLACK).ok()?;
263        let max_body = usize::try_from(self.config.max_entry_bytes).unwrap_or(usize::MAX);
264        match decode_entry(&bytes, key, max_body) {
265            Ok((entry, body)) => {
266                let now = now_secs();
267                let age = now.saturating_sub(entry.validated_at);
268                if entry.validated_at > now.saturating_add(24 * 60 * 60)
269                    || age > self.config.max_age.as_secs()
270                {
271                    remove(&path);
272                    return None;
273                }
274                Some((entry, body))
275            }
276            Err(error) => {
277                tracing::debug!(%error, "cache entry refused and removed");
278                remove(&path);
279                None
280            }
281        }
282    }
283
284    pub(crate) async fn load(self: &Arc<Self>, key: &str) -> Option<(CacheEntryMeta, Vec<u8>)> {
285        let cache = Arc::clone(self);
286        let key = key.to_owned();
287        tokio::task::spawn_blocking(move || cache.load_blocking(&key))
288            .await
289            .ok()
290            .flatten()
291    }
292
293    /// Store one entry atomically. Never fails the caller: a problem is logged.
294    pub(crate) fn store_blocking(&self, key: &str, meta: CacheEntryMeta, body: &[u8]) {
295        if !is_cache_key(key) || body.len() as u64 > self.config.max_entry_bytes {
296            return;
297        }
298        let Ok(bytes) = encode_entry(meta, body) else {
299            return;
300        };
301        match write_entry_file(&self.temp_path(key), &bytes, &self.entry_path(key)) {
302            Ok(()) => self.prune_blocking(),
303            Err(error) => tracing::debug!(kind = ?error.kind(), "cache entry not written"),
304        }
305    }
306
307    pub(crate) async fn store(self: &Arc<Self>, key: &str, meta: CacheEntryMeta, body: Vec<u8>) {
308        let cache = Arc::clone(self);
309        let key = key.to_owned();
310        let _ = tokio::task::spawn_blocking(move || cache.store_blocking(&key, meta, &body)).await;
311    }
312
313    pub(crate) fn remove_blocking(&self, key: &str) {
314        if is_cache_key(key) {
315            let _ = std::fs::remove_file(self.entry_path(key));
316        }
317    }
318
319    pub(crate) async fn remove(self: &Arc<Self>, key: &str) {
320        let cache = Arc::clone(self);
321        let key = key.to_owned();
322        let _ = tokio::task::spawn_blocking(move || cache.remove_blocking(&key)).await;
323    }
324
325    /// Drop the oldest entries until the total is within the limit, and stale
326    /// temporary files left by a crash.
327    pub(crate) fn prune_blocking(&self) {
328        let Ok(dir) = std::fs::read_dir(&self.entries) else {
329            return;
330        };
331        let now = SystemTime::now();
332        let mut entries: Vec<(SystemTime, u64, PathBuf)> = Vec::new();
333        let mut total = 0u64;
334        for item in dir.flatten() {
335            let path = item.path();
336            let Ok(meta) = std::fs::symlink_metadata(&path) else {
337                continue;
338            };
339            let name = item.file_name();
340            let name = name.to_string_lossy();
341            if is_cache_temp(&name) {
342                let old = meta
343                    .modified()
344                    .ok()
345                    .and_then(|m| now.duration_since(m).ok())
346                    .is_some_and(|age| age > Duration::from_secs(3600));
347                if old {
348                    let _ = std::fs::remove_file(&path);
349                }
350                continue;
351            }
352            if !meta.file_type().is_file() || !name.ends_with(".entry") {
353                continue;
354            }
355            total = total.saturating_add(meta.len());
356            entries.push((meta.modified().unwrap_or(UNIX_EPOCH), meta.len(), path));
357        }
358        if total <= self.config.max_total_bytes {
359            return;
360        }
361        entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.cmp(&b.2)));
362        for (_, size, path) in entries {
363            if total <= self.config.max_total_bytes {
364                break;
365            }
366            if std::fs::remove_file(&path).is_ok() {
367                total = total.saturating_sub(size);
368            }
369        }
370    }
371
372    /// Begin writing an entry whose body is still arriving. `None` when the
373    /// temporary file cannot be created.
374    pub(crate) async fn start_tee(self: &Arc<Self>, key: &str) -> Option<CacheTee> {
375        if !is_cache_key(key) {
376            return None;
377        }
378        let tmp = self.temp_path(key);
379        let mut options = tokio::fs::OpenOptions::new();
380        options.write(true).create_new(true);
381        #[cfg(unix)]
382        options.mode(0o600);
383        let mut file = options.open(&tmp).await.ok()?;
384        if file.write_all(EntryBuilder::prefix()).await.is_err() {
385            let _ = std::fs::remove_file(&tmp);
386            return None;
387        }
388        Some(CacheTee {
389            cache: Arc::clone(self),
390            key: key.to_owned(),
391            file: Some(file),
392            tmp,
393            builder: EntryBuilder::new(),
394        })
395    }
396}
397
398/// Open `path` only if it is a regular file, and keep that true while opening.
399///
400/// The path is inspected with `lstat`, opened, and inspected again; the opened
401/// file must be the regular file the path names both times (same device and
402/// inode). A symbolic link swapped in between the checks is refused instead of
403/// followed, which `lstat`-then-read alone would not do. `between` runs after
404/// the first inspection and exists so a test can make that swap happen.
405#[cfg(unix)]
406fn open_regular_with(path: &Path, between: impl FnOnce()) -> std::io::Result<std::fs::File> {
407    use std::os::unix::fs::MetadataExt;
408    let invalid =
409        |what: &str| std::io::Error::new(std::io::ErrorKind::InvalidInput, what.to_owned());
410    let before = std::fs::symlink_metadata(path)?;
411    if !before.file_type().is_file() {
412        return Err(invalid("not a regular file"));
413    }
414    between();
415    let file = std::fs::File::open(path)?;
416    let opened = file.metadata()?;
417    let after = std::fs::symlink_metadata(path)?;
418    if !after.file_type().is_file()
419        || !opened.is_file()
420        || (opened.dev(), opened.ino()) != (after.dev(), after.ino())
421        || (opened.dev(), opened.ino()) != (before.dev(), before.ino())
422    {
423        return Err(invalid("the path changed while it was opened"));
424    }
425    Ok(file)
426}
427
428/// Read at most `limit` bytes of a regular file (see [`open_regular_with`]);
429/// a longer file is an error.
430fn read_regular(path: &Path, limit: u64) -> std::io::Result<Vec<u8>> {
431    use std::io::Read;
432    #[cfg(unix)]
433    let file = open_regular_with(path, || {})?;
434    #[cfg(not(unix))]
435    let file = {
436        if !std::fs::symlink_metadata(path)?.file_type().is_file() {
437            return Err(std::io::Error::new(
438                std::io::ErrorKind::InvalidInput,
439                "not a regular file",
440            ));
441        }
442        std::fs::File::open(path)?
443    };
444    let mut bytes = Vec::new();
445    file.take(limit + 1).read_to_end(&mut bytes)?;
446    if bytes.len() as u64 > limit {
447        return Err(std::io::Error::new(
448            std::io::ErrorKind::InvalidData,
449            "entry is larger than the limit",
450        ));
451    }
452    Ok(bytes)
453}
454
455/// Write `bytes` to the new file `tmp`, then rename it to `dest`. On failure
456/// `tmp` is removed only if this call created it: a file already at that path
457/// belongs to someone else.
458fn write_entry_file(tmp: &Path, bytes: &[u8], dest: &Path) -> std::io::Result<()> {
459    let mut file = open_private(tmp)?;
460    let result = file.write_all(bytes).and_then(|()| {
461        drop(file);
462        std::fs::rename(tmp, dest)
463    });
464    if result.is_err() {
465        let _ = std::fs::remove_file(tmp);
466    }
467    result
468}
469
470fn open_private(path: &Path) -> std::io::Result<std::fs::File> {
471    let mut options = std::fs::OpenOptions::new();
472    options.write(true).create_new(true);
473    #[cfg(unix)]
474    {
475        use std::os::unix::fs::OpenOptionsExt;
476        options.mode(0o600);
477    }
478    options.open(path)
479}
480
481/// An entry being written while the body streams past. The file is removed
482/// unless [`CacheTee::finish`] commits it, so a failed or cancelled download
483/// leaves nothing behind.
484pub(crate) struct CacheTee {
485    cache: Arc<Cache>,
486    key: String,
487    file: Option<tokio::fs::File>,
488    tmp: PathBuf,
489    builder: EntryBuilder,
490}
491
492impl CacheTee {
493    /// Add body bytes. Returns `false` once the entry is abandoned (too large
494    /// or a write failed); later calls are no-ops.
495    pub(crate) async fn write(&mut self, chunk: &[u8]) -> bool {
496        let Some(file) = self.file.as_mut() else {
497            return false;
498        };
499        if self.builder.len().saturating_add(chunk.len() as u64) > self.cache.config.max_entry_bytes
500            || file.write_all(chunk).await.is_err()
501        {
502            self.abandon();
503            return false;
504        }
505        self.builder.update(chunk);
506        true
507    }
508
509    fn abandon(&mut self) {
510        self.file = None;
511        let _ = std::fs::remove_file(&self.tmp);
512    }
513
514    /// Commit the entry. Call only after the body passed every check.
515    pub(crate) async fn finish(mut self, meta: CacheEntryMeta) {
516        let Some(mut file) = self.file.take() else {
517            return;
518        };
519        let builder = std::mem::take(&mut self.builder);
520        let Ok(trailer) = builder.trailer(meta) else {
521            self.abandon();
522            return;
523        };
524        if file.write_all(&trailer).await.is_err() || file.flush().await.is_err() {
525            drop(file);
526            let _ = std::fs::remove_file(&self.tmp);
527            return;
528        }
529        drop(file);
530        let cache = Arc::clone(&self.cache);
531        let tmp = self.tmp.clone();
532        let final_path = cache.entry_path(&self.key);
533        let committed = tokio::task::spawn_blocking(move || {
534            let ok = std::fs::rename(&tmp, final_path).is_ok();
535            if ok {
536                cache.prune_blocking();
537            } else {
538                let _ = std::fs::remove_file(&tmp);
539            }
540            ok
541        })
542        .await
543        .unwrap_or(false);
544        if committed {
545            // The temporary file no longer exists; nothing for Drop to remove.
546            self.tmp = PathBuf::new();
547        }
548    }
549}
550
551impl Drop for CacheTee {
552    fn drop(&mut self) {
553        if !self.tmp.as_os_str().is_empty() {
554            let _ = std::fs::remove_file(&self.tmp);
555        }
556    }
557}
558
559/// What `libtea cache stat` reports.
560///
561/// *Experimental.*
562#[derive(Debug, Clone, PartialEq, Eq)]
563#[non_exhaustive]
564pub struct CacheStats {
565    /// The directory inspected.
566    pub dir: PathBuf,
567    /// Whether it exists.
568    pub exists: bool,
569    /// Entry files.
570    pub entries: u64,
571    /// Bytes in entry files.
572    pub bytes: u64,
573    /// Files, directories and links that are not entries.
574    pub foreign: u64,
575    /// Seconds since the oldest entry file was written (by file time).
576    pub oldest_age_secs: Option<u64>,
577    /// Seconds since the newest entry file was written (by file time).
578    pub newest_age_secs: Option<u64>,
579}
580
581fn entry_files(dir: &Path) -> Result<Option<(PathBuf, std::fs::ReadDir)>, ClientError> {
582    if !private_dir(dir, false)? {
583        return Ok(None);
584    }
585    let entries = dir.join(ENTRY_DIR);
586    if !private_dir(&entries, false)? {
587        return Ok(None);
588    }
589    let read =
590        std::fs::read_dir(&entries).map_err(|e| io_error("reading the cache directory", &e))?;
591    Ok(Some((entries, read)))
592}
593
594/// Summarise a cache directory without changing it.
595///
596/// # Errors
597///
598/// Returns an error when the directory is a symbolic link, is open to other
599/// users, or cannot be read. A directory that does not exist is not an error.
600pub fn cache_stat(dir: &Path) -> Result<CacheStats, ClientError> {
601    let mut stats = CacheStats {
602        dir: dir.to_path_buf(),
603        exists: false,
604        entries: 0,
605        bytes: 0,
606        foreign: 0,
607        oldest_age_secs: None,
608        newest_age_secs: None,
609    };
610    let Some((_, read)) = entry_files(dir)? else {
611        return Ok(stats);
612    };
613    stats.exists = true;
614    let now = SystemTime::now();
615    for item in read.flatten() {
616        let name = item.file_name();
617        let name = name.to_string_lossy().into_owned();
618        let Ok(meta) = std::fs::symlink_metadata(item.path()) else {
619            continue;
620        };
621        let key = name.strip_suffix(".entry").unwrap_or("");
622        if meta.file_type().is_file() && is_cache_key(key) {
623            stats.entries += 1;
624            stats.bytes = stats.bytes.saturating_add(meta.len());
625            if let Some(age) = meta
626                .modified()
627                .ok()
628                .and_then(|m| now.duration_since(m).ok())
629            {
630                let age = age.as_secs();
631                stats.oldest_age_secs = Some(stats.oldest_age_secs.map_or(age, |o| o.max(age)));
632                stats.newest_age_secs = Some(stats.newest_age_secs.map_or(age, |n| n.min(age)));
633            }
634        } else if !name.ends_with(".tmp") {
635            stats.foreign += 1;
636        }
637    }
638    Ok(stats)
639}
640
641/// A temporary file the cache itself writes: `.<64 hex key>.<pid>-<n>.tmp`.
642/// Nothing else is a cache temporary file, whatever its name ends in.
643fn is_cache_temp(name: &str) -> bool {
644    let Some(rest) = name.strip_prefix('.') else {
645        return false;
646    };
647    let Some(rest) = rest.strip_suffix(".tmp") else {
648        return false;
649    };
650    let Some((key, tail)) = rest.split_once('.') else {
651        return false;
652    };
653    is_cache_key(key)
654        && tail.split_once('-').is_some_and(|(pid, n)| {
655            !pid.is_empty()
656                && !n.is_empty()
657                && pid.bytes().all(|b| b.is_ascii_digit())
658                && n.bytes().all(|b| b.is_ascii_digit())
659        })
660}
661
662/// Remove every cache entry (and stray temporary files) and return how many
663/// files were removed. Only files this cache writes are touched: names that are
664/// a cache key plus `.entry`, and `*.tmp`. Other files, and the directories
665/// themselves, are left alone. A symbolic link with an entry's name is removed
666/// as a link; its target is never followed.
667///
668/// # Errors
669///
670/// Returns an error when the directory is a symbolic link, is open to other
671/// users, or cannot be read.
672pub fn cache_clear(dir: &Path) -> Result<u64, ClientError> {
673    let Some((entries, read)) = entry_files(dir)? else {
674        return Ok(0);
675    };
676    let mut removed = 0;
677    for item in read.flatten() {
678        let name = item.file_name();
679        let name = name.to_string_lossy().into_owned();
680        let is_entry = name.strip_suffix(".entry").is_some_and(is_cache_key);
681        let is_temp = is_cache_temp(&name);
682        if !(is_entry || is_temp) {
683            continue;
684        }
685        let path = entries.join(&name);
686        let Ok(meta) = std::fs::symlink_metadata(&path) else {
687            continue;
688        };
689        if (meta.file_type().is_file() || meta.file_type().is_symlink())
690            && std::fs::remove_file(&path).is_ok()
691        {
692            removed += 1;
693        }
694    }
695    Ok(removed)
696}
697
698#[cfg(test)]
699mod temp_file_tests {
700    use super::*;
701
702    fn scratch(tag: &str) -> PathBuf {
703        let dir =
704            std::env::temp_dir().join(format!("libtea-cache-tmp-{tag}-{}", std::process::id()));
705        let _ = std::fs::remove_dir_all(&dir);
706        std::fs::create_dir_all(&dir).unwrap();
707        dir
708    }
709
710    #[test]
711    fn two_caches_on_one_directory_never_share_a_temporary_name() {
712        let dir = scratch("names");
713        // The cache creates its own directory, private; `scratch` is not.
714        let cache_dir = dir.join("cache");
715        let first = Cache::open(CacheConfig::new(&cache_dir), false).unwrap();
716        let second = Cache::open(CacheConfig::new(&cache_dir), false).unwrap();
717        let key = "0".repeat(64);
718        let names: std::collections::BTreeSet<PathBuf> = (0..4)
719            .flat_map(|_| [first.temp_path(&key), second.temp_path(&key)])
720            .collect();
721        assert_eq!(names.len(), 8);
722        let _ = std::fs::remove_dir_all(&dir);
723    }
724
725    #[test]
726    fn a_temporary_file_someone_else_created_is_left_alone() {
727        let dir = scratch("theirs");
728        let tmp = dir.join("theirs.tmp");
729        let dest = dir.join("entry");
730        std::fs::write(&tmp, b"theirs").unwrap();
731        let error = write_entry_file(&tmp, b"mine", &dest).unwrap_err();
732        assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
733        assert_eq!(std::fs::read(&tmp).unwrap(), b"theirs");
734        assert!(!dest.exists());
735        let _ = std::fs::remove_dir_all(&dir);
736    }
737
738    #[test]
739    fn a_failed_rename_removes_only_its_own_temporary_file() {
740        let dir = scratch("mine");
741        let tmp = dir.join("mine.tmp");
742        // A destination inside a missing directory: the rename fails.
743        let dest = dir.join("missing").join("entry");
744        assert!(write_entry_file(&tmp, b"mine", &dest).is_err());
745        assert!(!tmp.exists());
746        let _ = std::fs::remove_dir_all(&dir);
747    }
748}
749
750#[cfg(all(test, unix))]
751mod tests {
752    use super::*;
753
754    fn scratch(tag: &str) -> PathBuf {
755        let dir =
756            std::env::temp_dir().join(format!("libtea-cache-unit-{tag}-{}", std::process::id()));
757        let _ = std::fs::remove_dir_all(&dir);
758        std::fs::create_dir_all(&dir).unwrap();
759        dir
760    }
761
762    #[test]
763    fn ownership_is_compared_with_the_uid_of_a_file_just_created() {
764        let dir = scratch("uid");
765        let mine = current_uid(None).unwrap();
766        let probe = dir.join("probe");
767        std::fs::write(&probe, b"x").unwrap();
768        use std::os::unix::fs::MetadataExt;
769        assert_eq!(std::fs::metadata(&probe).unwrap().uid(), mine);
770        assert_eq!(std::fs::metadata(&dir).unwrap().uid(), mine);
771        assert!(owner_matches(mine, mine));
772        assert!(
773            !owner_matches(mine.wrapping_add(1), mine),
774            "another uid must not match"
775        );
776        assert!(!owner_matches(0, 501) && !owner_matches(501, 0));
777        let _ = std::fs::remove_dir_all(dir);
778    }
779
780    #[test]
781    fn a_regular_file_opens_and_a_symlink_never_does() {
782        let dir = scratch("nofollow");
783        let real = dir.join("real");
784        std::fs::write(&real, b"entry").unwrap();
785        assert_eq!(read_regular(&real, 100).unwrap(), b"entry");
786        let link = dir.join("link");
787        std::os::unix::fs::symlink(&real, &link).unwrap();
788        assert!(open_regular_with(&link, || {}).is_err());
789        assert!(read_regular(&link, 100).is_err());
790        assert!(
791            read_regular(&dir, 100).is_err(),
792            "a directory is not an entry"
793        );
794        assert!(read_regular(&real, 3).is_err(), "over the limit");
795        let _ = std::fs::remove_dir_all(dir);
796    }
797
798    #[test]
799    fn a_symlink_swapped_in_after_the_check_is_refused_not_followed() {
800        let dir = scratch("swap");
801        let entry = dir.join("entry");
802        let secret = dir.join("secret");
803        std::fs::write(&entry, b"genuine").unwrap();
804        std::fs::write(&secret, b"must not be read").unwrap();
805        // Between the first lstat and the open, replace the file by a link.
806        let swapped = open_regular_with(&entry, || {
807            std::fs::remove_file(&entry).unwrap();
808            std::os::unix::fs::symlink(&secret, &entry).unwrap();
809        });
810        assert!(swapped.is_err(), "the swapped-in link was followed");
811        // And a plain replacement by another regular file is noticed too.
812        // The original stays alive under a second name, so the replacement
813        // cannot be given the same inode number (a freed inode is reused at
814        // once on Linux, which would make the two indistinguishable).
815        let entry2 = dir.join("entry2");
816        let kept = dir.join("entry2-kept");
817        std::fs::write(&entry2, b"first").unwrap();
818        std::fs::hard_link(&entry2, &kept).unwrap();
819        let replaced = open_regular_with(&entry2, || {
820            std::fs::remove_file(&entry2).unwrap();
821            std::fs::write(&entry2, b"second").unwrap();
822        });
823        assert!(
824            replaced.is_err(),
825            "a different file than the one inspected was accepted"
826        );
827        let _ = std::fs::remove_dir_all(dir);
828    }
829
830    #[test]
831    fn only_the_caches_own_temporary_files_are_temporary_files() {
832        let key = "a".repeat(64);
833        assert!(is_cache_temp(&format!(".{key}.123-4.tmp")));
834        for other in [
835            ".mine.tmp",
836            ".notes.libtea.tmp",
837            "build.tmp",
838            &format!(".{key}.tmp"),
839            &format!(".{key}.x-4.tmp"),
840            &format!(".{key}.12-.tmp"),
841            &format!(".{key}.12-4.tmp.bak"),
842            &format!(".{}.1-2.tmp", "g".repeat(64)),
843            &format!(".{}.1-2.tmp", "a".repeat(63)),
844            &format!("{key}.1-2.tmp"),
845        ] {
846            assert!(!is_cache_temp(other), "{other}");
847        }
848    }
849}