Skip to main content

yaiko_core/
media_cache_key.rs

1//! Deterministic cache keys for media preview artifacts.
2
3use sha2::{Digest, Sha256};
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub enum CacheKeyError {
7    InvalidPath,
8    InvalidProfile,
9    TooLong,
10}
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct ThumbnailCacheKey {
14    pub key: String,
15    pub source: String,
16    pub profile: String,
17    pub version: u32,
18}
19
20impl ThumbnailCacheKey {
21    pub fn new(
22        source: impl Into<String>,
23        profile: impl Into<String>,
24        version: u32,
25    ) -> Result<Self, CacheKeyError> {
26        let source = normalize_source(source.into())?;
27        let profile = normalize_profile(profile.into())?;
28        if version == 0 {
29            return Err(CacheKeyError::InvalidProfile);
30        }
31        let digest = Sha256::digest(format!("v{}\0{}\0{}", version, source, profile).as_bytes());
32        let key = format!("media:thumb:v{}:{}", version, hex(&digest));
33        if key.len() > 128 {
34            return Err(CacheKeyError::TooLong);
35        }
36        Ok(Self {
37            key,
38            source,
39            profile,
40            version,
41        })
42    }
43    pub fn matches_source(&self, source: &str) -> bool {
44        normalize_source(source.to_string())
45            .map(|value| value == self.source)
46            .unwrap_or(false)
47    }
48    pub fn matches_profile(&self, profile: &str) -> bool {
49        normalize_profile(profile.to_string())
50            .map(|value| value == self.profile)
51            .unwrap_or(false)
52    }
53}
54
55fn normalize_source(source: String) -> Result<String, CacheKeyError> {
56    let source = source.trim().replace('\\', "/");
57    if source.is_empty()
58        || source.len() > 512
59        || source.starts_with('/')
60        || source
61            .split('/')
62            .any(|part| part == ".." || part.is_empty() && !source.is_empty())
63    {
64        return Err(CacheKeyError::InvalidPath);
65    }
66    Ok(source)
67}
68fn normalize_profile(profile: String) -> Result<String, CacheKeyError> {
69    let profile = profile.trim().to_ascii_lowercase();
70    if profile.is_empty()
71        || profile.len() > 256
72        || profile.chars().any(|c| c.is_control() || c.is_whitespace())
73    {
74        return Err(CacheKeyError::InvalidProfile);
75    }
76    Ok(profile)
77}
78fn hex(bytes: &[u8]) -> String {
79    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    #[test]
86    fn canonicalizes_sources_and_profiles_deterministically() {
87        let a = ThumbnailCacheKey::new("renders\\video.mp4", " JPEG_1280 ", 1).unwrap();
88        let b = ThumbnailCacheKey::new("renders/video.mp4", "jpeg_1280", 1).unwrap();
89        assert_eq!(a, b);
90        assert!(a.key.starts_with("media:thumb:v1:"));
91        assert!(a.key.len() <= 128);
92    }
93    #[test]
94    fn differentiates_profiles_versions_and_sources() {
95        let base = ThumbnailCacheKey::new("video.mp4", "jpeg_640", 1).unwrap();
96        assert_ne!(
97            base,
98            ThumbnailCacheKey::new("video.mp4", "jpeg_1280", 1).unwrap()
99        );
100        assert_ne!(
101            base,
102            ThumbnailCacheKey::new("video.mp4", "jpeg_640", 2).unwrap()
103        );
104        assert_ne!(
105            base,
106            ThumbnailCacheKey::new("other.mp4", "jpeg_640", 1).unwrap()
107        );
108        assert!(base.matches_source("video.mp4"));
109        assert!(base.matches_profile(" JPEG_640 "));
110    }
111    #[test]
112    fn rejects_unsafe_sources_profiles_and_versions() {
113        assert_eq!(
114            ThumbnailCacheKey::new("../video.mp4", "jpeg", 1),
115            Err(CacheKeyError::InvalidPath)
116        );
117        assert_eq!(
118            ThumbnailCacheKey::new("/video.mp4", "jpeg", 1),
119            Err(CacheKeyError::InvalidPath)
120        );
121        assert_eq!(
122            ThumbnailCacheKey::new("video.mp4", "", 1),
123            Err(CacheKeyError::InvalidProfile)
124        );
125        assert_eq!(
126            ThumbnailCacheKey::new("video.mp4", "jpeg profile", 1),
127            Err(CacheKeyError::InvalidProfile)
128        );
129        assert_eq!(
130            ThumbnailCacheKey::new("video.mp4", "jpeg", 0),
131            Err(CacheKeyError::InvalidProfile)
132        );
133    }
134}