Skip to main content

yaiko_core/
storage.rs

1//! Storage abstractions for local files and future object-storage adapters.
2
3use async_trait::async_trait;
4use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
5use hmac::{Hmac, Mac};
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8use std::path::{Component, Path, PathBuf};
9use std::time::{SystemTime, UNIX_EPOCH};
10use tokio::fs;
11use tokio::io::AsyncWriteExt;
12
13type HmacSha256 = Hmac<Sha256>;
14pub type StorageResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
15
16/// Backend-neutral byte storage contract.
17#[async_trait]
18pub trait Storage: Send + Sync {
19    async fn put(&self, key: &str, data: &[u8]) -> StorageResult<()>;
20    async fn get(&self, key: &str) -> StorageResult<Option<Vec<u8>>>;
21    async fn delete(&self, key: &str) -> StorageResult<()>;
22    async fn exists(&self, key: &str) -> StorageResult<bool>;
23}
24
25/// File metadata exposed by storage backends.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27pub struct StorageMetadata {
28    pub key: String,
29    pub size: u64,
30    pub checksum_sha256: String,
31    pub content_type: String,
32    pub modified_unix: Option<u64>,
33}
34
35/// HMAC-signed, expiring access token for a storage key.
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
37pub struct SignedAccess {
38    pub key: String,
39    pub expires_at: u64,
40    pub signature: String,
41}
42
43impl SignedAccess {
44    pub fn create(secret: &[u8], key: &str, expires_at: u64) -> StorageResult<Self> {
45        let signature = sign(secret, key, expires_at)?;
46        Ok(Self {
47            key: key.to_string(),
48            expires_at,
49            signature,
50        })
51    }
52
53    pub fn verify(&self, secret: &[u8], now_unix: u64) -> bool {
54        self.expires_at >= now_unix
55            && sign(secret, &self.key, self.expires_at)
56                .map(|expected| constant_time_eq(expected.as_bytes(), self.signature.as_bytes()))
57                .unwrap_or(false)
58    }
59}
60
61fn sign(secret: &[u8], key: &str, expires_at: u64) -> StorageResult<String> {
62    let mut mac = HmacSha256::new_from_slice(secret).map_err(|_| "invalid signing secret")?;
63    mac.update(format!("{}\n{}", key, expires_at).as_bytes());
64    Ok(URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()))
65}
66
67fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
68    left.len() == right.len()
69        && left
70            .iter()
71            .zip(right)
72            .fold(0u8, |acc, (a, b)| acc | (a ^ b))
73            == 0
74}
75
76/// Local filesystem storage with traversal-safe keys.
77#[derive(Debug, Clone)]
78pub struct LocalStorage {
79    root: PathBuf,
80}
81
82impl LocalStorage {
83    pub fn new(root: impl Into<PathBuf>) -> Self {
84        Self { root: root.into() }
85    }
86
87    pub fn root(&self) -> &Path {
88        &self.root
89    }
90
91    fn path_for(&self, key: &str) -> StorageResult<PathBuf> {
92        let path = Path::new(key);
93        if path.is_absolute()
94            || path
95                .components()
96                .any(|component| matches!(component, Component::ParentDir))
97        {
98            return Err("storage key must be a relative, traversal-safe path".into());
99        }
100        Ok(self.root.join(path))
101    }
102
103    pub async fn metadata(&self, key: &str) -> StorageResult<Option<StorageMetadata>> {
104        let path = self.path_for(key)?;
105        let metadata = match fs::metadata(&path).await {
106            Ok(metadata) => metadata,
107            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
108            Err(error) => return Err(error.into()),
109        };
110        let data = fs::read(&path).await?;
111        let checksum_sha256 = format!("sha256:{:x}", Sha256::digest(&data));
112        let modified_unix = metadata
113            .modified()
114            .ok()
115            .and_then(|value| value.duration_since(UNIX_EPOCH).ok())
116            .map(|value| value.as_secs());
117        Ok(Some(StorageMetadata {
118            key: key.to_string(),
119            size: metadata.len(),
120            checksum_sha256,
121            content_type: mime_guess::from_path(&path)
122                .first_or_octet_stream()
123                .essence_str()
124                .to_string(),
125            modified_unix,
126        }))
127    }
128
129    pub fn signed_access(
130        &self,
131        secret: &[u8],
132        key: &str,
133        expires_at: u64,
134    ) -> StorageResult<SignedAccess> {
135        let _ = self.path_for(key)?;
136        SignedAccess::create(secret, key, expires_at)
137    }
138
139    pub fn now_unix() -> u64 {
140        SystemTime::now()
141            .duration_since(UNIX_EPOCH)
142            .unwrap_or_default()
143            .as_secs()
144    }
145}
146
147#[async_trait]
148impl Storage for LocalStorage {
149    async fn put(&self, key: &str, data: &[u8]) -> StorageResult<()> {
150        let path = self.path_for(key)?;
151        if let Some(parent) = path.parent() {
152            fs::create_dir_all(parent).await?;
153        }
154        let mut file = fs::File::create(path).await?;
155        file.write_all(data).await?;
156        file.flush().await?;
157        Ok(())
158    }
159
160    async fn get(&self, key: &str) -> StorageResult<Option<Vec<u8>>> {
161        let path = self.path_for(key)?;
162        match fs::read(path).await {
163            Ok(data) => Ok(Some(data)),
164            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
165            Err(error) => Err(error.into()),
166        }
167    }
168
169    async fn delete(&self, key: &str) -> StorageResult<()> {
170        let path = self.path_for(key)?;
171        match fs::remove_file(path).await {
172            Ok(()) => Ok(()),
173            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
174            Err(error) => Err(error.into()),
175        }
176    }
177
178    async fn exists(&self, key: &str) -> StorageResult<bool> {
179        Ok(fs::metadata(self.path_for(key)?).await.is_ok())
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::Storage;
187
188    #[tokio::test]
189    async fn local_storage_round_trips_bytes_and_deletes() {
190        let directory = tempfile::tempdir().unwrap();
191        let storage = LocalStorage::new(directory.path());
192
193        storage.put("clips/sample.bin", b"hello").await.unwrap();
194        assert!(storage.exists("clips/sample.bin").await.unwrap());
195        assert_eq!(
196            storage.get("clips/sample.bin").await.unwrap(),
197            Some(b"hello".to_vec())
198        );
199
200        storage.delete("clips/sample.bin").await.unwrap();
201        assert!(!storage.exists("clips/sample.bin").await.unwrap());
202    }
203
204    #[tokio::test]
205    async fn metadata_and_signed_access_are_verifiable() {
206        let directory = tempfile::tempdir().unwrap();
207        let storage = LocalStorage::new(directory.path());
208        storage.put("clips/sample.txt", b"hello").await.unwrap();
209
210        let metadata = storage.metadata("clips/sample.txt").await.unwrap().unwrap();
211        assert_eq!(metadata.size, 5);
212        assert_eq!(metadata.content_type, "text/plain");
213        assert!(metadata.checksum_sha256.starts_with("sha256:"));
214
215        let access = storage
216            .signed_access(b"secret", "clips/sample.txt", LocalStorage::now_unix() + 60)
217            .unwrap();
218        assert!(access.verify(b"secret", LocalStorage::now_unix()));
219        assert!(!access.verify(b"wrong", LocalStorage::now_unix()));
220    }
221
222    #[tokio::test]
223    async fn local_storage_rejects_traversal_keys() {
224        let directory = tempfile::tempdir().unwrap();
225        let storage = LocalStorage::new(directory.path());
226        assert!(storage.put("../escape.txt", b"nope").await.is_err());
227    }
228}