Skip to main content

vector_core/
vcache.rs

1//! Vector Cache: the pictures and media Vector keeps for itself (avatars, banners, emoji,
2//! icons, previews), sealed on disk under a per-install key so nothing in the app's folders is
3//! a plain image to a gallery, an indexer or another app.
4//!
5//! A file is `VCC1` ‖ key id (4) ‖ nonce (12) ‖ ChaCha20 ciphertext. The stream seeks, so a
6//! video plays by range. A file written before sealing has no header and reads as it is.
7
8use std::io::{Read, Write};
9use std::path::{Path, PathBuf};
10use std::sync::{Arc, OnceLock};
11
12use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
13use zeroize::Zeroizing;
14
15/// Vector's caches under `<app_data>/cache/`. Nothing else there is Vector Cache: on Android the
16/// folder is the system's own cache directory, which also holds the webview's files.
17pub const KINDS: [&str; 12] = [
18    "avatars", "banners", "emojis", "emoji_pack_icons", "emoji_spritesheets", "miniapp_icons",
19    "inline_images", "embed_videos", "gif_previews", "svg_renders", "previews", "stills",
20];
21
22const MAGIC: &[u8; 4] = b"VCC1";
23const HEADER: usize = 4 + 4 + 12;
24const CHUNK: usize = 256 * 1024;
25
26struct Key {
27    bytes: Zeroizing<[u8; 32]>,
28    id: [u8; 4],
29}
30
31/// The install's key, read or made once. None until the app's folder is known.
32fn key() -> Option<&'static Key> {
33    static KEY: OnceLock<Key> = OnceLock::new();
34    static MAKING: std::sync::Mutex<()> = std::sync::Mutex::new(());
35    if let Some(key) = KEY.get() {
36        return Some(key);
37    }
38    // One maker at a time: a second reader must never find the file half written.
39    let _making = MAKING.lock().unwrap_or_else(|e| e.into_inner());
40    if let Some(key) = KEY.get() {
41        return Some(key);
42    }
43    let path = key_path().ok()?;
44    let bytes = load_or_create(&path).map_err(|e| crate::log_warn!("[VCache] no cache key: {}", e)).ok()?;
45    Some(KEY.get_or_init(|| Key { id: key_id(&bytes), bytes }))
46}
47
48fn key_path() -> Result<PathBuf, String> {
49    Ok(crate::db::get_app_data_dir()?.join("vcache.key"))
50}
51
52fn key_id(key: &[u8; 32]) -> [u8; 4] {
53    use sha2::Digest;
54    let digest = sha2::Sha256::digest([b"vcache key id".as_slice(), key].concat());
55    [digest[0], digest[1], digest[2], digest[3]]
56}
57
58const WRONG_LENGTH: &str = "cache key has the wrong length";
59
60fn load_or_create(path: &Path) -> Result<Zeroizing<[u8; 32]>, String> {
61    let read = |path: &Path| -> Result<Zeroizing<[u8; 32]>, String> {
62        let raw = Zeroizing::new(std::fs::read(path).map_err(|e| e.to_string())?);
63        let mut key = Zeroizing::new([0u8; 32]);
64        if raw.len() != 32 {
65            return Err(WRONG_LENGTH.into());
66        }
67        key.copy_from_slice(&raw);
68        Ok(key)
69    };
70    if path.exists() {
71        match read(path) {
72            Ok(key) => return Ok(key),
73            // A key file that isn't a key is set aside, never left to block every write: what
74            // it sealed reads as missing and is fetched again. A read that merely failed is
75            // tried again later.
76            Err(e) if e == WRONG_LENGTH => {
77                crate::log_warn!("[VCache] cache key unusable, starting a new one");
78                let stamp = crate::clock::now_secs();
79                std::fs::rename(path, path.with_extension(format!("key.unusable-{stamp}"))).map_err(|e| e.to_string())?;
80            }
81            Err(e) => return Err(e),
82        }
83    }
84    if let Some(dir) = path.parent() {
85        std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
86    }
87    let mut key = Zeroizing::new([0u8; 32]);
88    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut *key);
89    // Written whole beside it, then linked into place: a key file is complete or absent, and
90    // another process that made one first keeps it.
91    let tmp = temp_beside(path);
92    create_private(&tmp)
93        .and_then(|mut f| f.write_all(&*key).and_then(|_| f.sync_all()).map_err(|e| e.to_string()))
94        .inspect_err(|_| {
95            let _ = std::fs::remove_file(&tmp);
96        })?;
97    let linked = std::fs::hard_link(&tmp, path);
98    let result = match linked {
99        Ok(()) => Ok(key),
100        Err(_) if path.exists() => read(path),
101        // A filesystem without links: the rename still never shows a partial key.
102        Err(_) => std::fs::rename(&tmp, path).map(|_| key).map_err(|e| e.to_string()),
103    };
104    let _ = std::fs::remove_file(&tmp);
105    result
106}
107
108fn cipher(key: &Key, nonce: &[u8; 12]) -> chacha20::ChaCha20 {
109    chacha20::ChaCha20::new((&*key.bytes).into(), nonce.into())
110}
111
112fn fresh_header(key: &Key) -> ([u8; HEADER], [u8; 12]) {
113    let mut nonce = [0u8; 12];
114    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce);
115    let mut header = [0u8; HEADER];
116    header[..4].copy_from_slice(MAGIC);
117    header[4..8].copy_from_slice(&key.id);
118    header[8..].copy_from_slice(&nonce);
119    (header, nonce)
120}
121
122/// What a file's first bytes say about it.
123enum Kind {
124    /// Ours, under this nonce.
125    Sealed([u8; 12]),
126    /// Ours, under a key this install no longer has: unreadable, so absent.
127    Foreign,
128    /// Written before sealing.
129    Plain,
130}
131
132fn kind(head: &[u8], key: &Key) -> Kind {
133    if head.len() < HEADER || &head[..4] != MAGIC {
134        return Kind::Plain;
135    }
136    if head[4..8] != key.id {
137        return Kind::Foreign;
138    }
139    let mut nonce = [0u8; 12];
140    nonce.copy_from_slice(&head[8..HEADER]);
141    Kind::Sealed(nonce)
142}
143
144/// Sealed `plain`, ready to write.
145pub fn seal(plain: &[u8]) -> Result<Vec<u8>, String> {
146    let key = key().ok_or("Vector's cache key isn't available")?;
147    let (header, nonce) = fresh_header(key);
148    let mut out = Vec::with_capacity(HEADER + plain.len());
149    out.extend_from_slice(&header);
150    out.extend_from_slice(plain);
151    cipher(key, &nonce).apply_keystream(&mut out[HEADER..]);
152    Ok(out)
153}
154
155/// Write `plain` to `path` sealed: beside it first, then into place.
156pub fn write(path: &Path, plain: &[u8]) -> Result<(), String> {
157    let sealed = seal(plain)?;
158    let tmp = temp_beside(path);
159    write_private(&tmp, &sealed).and_then(|_| std::fs::rename(&tmp, path).map_err(|e| e.to_string())).inspect_err(|_| {
160        let _ = std::fs::remove_file(&tmp);
161    })
162}
163
164/// Write what `src` holds to `path` sealed, a chunk at a time: a large file never sits whole in
165/// memory, or plain on disk.
166pub fn write_source(src: &dyn crate::media::MediaSource, path: &Path) -> Result<(), String> {
167    let key = key().ok_or("Vector's cache key isn't available")?;
168    let (header, nonce) = fresh_header(key);
169    let mut cipher = cipher(key, &nonce);
170    let tmp = temp_beside(path);
171    let result = (|| -> Result<(), String> {
172        let mut output = std::io::BufWriter::with_capacity(CHUNK, create_private(&tmp)?);
173        output.write_all(&header).map_err(|e| e.to_string())?;
174        let mut buf = Zeroizing::new(vec![0u8; CHUNK]);
175        let mut at = 0u64;
176        while at < src.len() {
177            let n = src.read_at(at, &mut buf).map_err(|e| e.to_string())?;
178            if n == 0 {
179                return Err("the source ended early".into());
180            }
181            cipher.apply_keystream(&mut buf[..n]);
182            output.write_all(&buf[..n]).map_err(|e| e.to_string())?;
183            at += n as u64;
184        }
185        output.flush().map_err(|e| e.to_string())?;
186        output.get_ref().sync_data().map_err(|e| e.to_string())?;
187        std::fs::rename(&tmp, path).map_err(|e| e.to_string())
188    })();
189    if result.is_err() {
190        let _ = std::fs::remove_file(&tmp);
191    }
192    result
193}
194
195/// `src` sealed into a temp beside `path`, synced, then renamed over it: `path` is never partial,
196/// and `src` may be `path` itself, in which case a write that replaced it meanwhile wins.
197fn seal_stream(src: &Path, path: &Path) -> Result<(), String> {
198    let key = key().ok_or("Vector's cache key isn't available")?;
199    let (header, nonce) = fresh_header(key);
200    let mut cipher = cipher(key, &nonce);
201    let tmp = temp_beside(path);
202    let result = (|| -> Result<(), String> {
203        let mut input = std::fs::File::open(src).map_err(|e| e.to_string())?;
204        let mut output = std::io::BufWriter::with_capacity(CHUNK, create_private(&tmp)?);
205        output.write_all(&header).map_err(|e| e.to_string())?;
206        let mut buf = Zeroizing::new(vec![0u8; CHUNK]);
207        loop {
208            let n = input.read(&mut buf).map_err(|e| e.to_string())?;
209            if n == 0 {
210                break;
211            }
212            cipher.apply_keystream(&mut buf[..n]);
213            output.write_all(&buf[..n]).map_err(|e| e.to_string())?;
214        }
215        output.flush().map_err(|e| e.to_string())?;
216        output.get_ref().sync_data().map_err(|e| e.to_string())?;
217        if src == path && is_sealed(path) {
218            return Err("sealed meanwhile".into());
219        }
220        std::fs::rename(&tmp, path).map_err(|e| e.to_string())
221    })();
222    if result.is_err() {
223        let _ = std::fs::remove_file(&tmp);
224    }
225    result
226}
227
228/// Where a sealed file's ciphertext starts.
229pub const HEADER_LEN: u64 = HEADER as u64;
230
231/// A sealed file written a piece at a time, at any offset: a download's part file, which a
232/// resume continues. Once whole it is a cache file as it stands.
233pub struct Sealer {
234    key: Zeroizing<[u8; 32]>,
235    nonce: [u8; 12],
236}
237
238impl Sealer {
239    /// The part file at `path`, continued under its own header, or begun afresh (emptied, with a
240    /// new header) when it has none this install can continue.
241    pub fn for_part(path: &Path) -> Result<Sealer, String> {
242        let key = key().ok_or("Vector's cache key isn't available")?;
243        if let Ok(mut file) = std::fs::File::open(path) {
244            let mut head = [0u8; HEADER];
245            if read_up_to(&mut file, &mut head) == HEADER {
246                if let Kind::Sealed(nonce) = kind(&head, key) {
247                    return Ok(Sealer { key: Zeroizing::new(*key.bytes), nonce });
248                }
249            }
250        }
251        let (header, nonce) = fresh_header(key);
252        let mut file = create_private(path)?;
253        file.write_all(&header).map_err(|e| e.to_string())?;
254        Ok(Sealer { key: Zeroizing::new(*key.bytes), nonce })
255    }
256
257    /// Seal `buf`, the plaintext that sits `offset` bytes into the file's content.
258    pub fn seal_at(&self, offset: u64, buf: &mut [u8]) -> Result<(), String> {
259        let mut cipher = chacha20::ChaCha20::new((&*self.key).into(), (&self.nonce).into());
260        cipher.try_seek(offset).map_err(|_| "past the end of the cipher".to_string())?;
261        cipher.apply_keystream(buf);
262        Ok(())
263    }
264}
265
266/// The plaintext of a file Vector may have sealed: a cache file, sealed or from before sealing,
267/// and any other file as it is. A file under a lost key reads as missing, so its caller fetches
268/// it again and the write replaces it.
269pub fn read(path: &Path) -> Result<Zeroizing<Vec<u8>>, String> {
270    let mut bytes = Zeroizing::new(std::fs::read(path).map_err(|e| e.to_string())?);
271    let Some(key) = key() else {
272        return if bytes.starts_with(MAGIC) { Err("Vector's cache key isn't available".into()) } else { Ok(bytes) };
273    };
274    match kind(&bytes, key) {
275        Kind::Plain => Ok(bytes),
276        Kind::Foreign => Err("not found".into()),
277        Kind::Sealed(nonce) => {
278            cipher(key, &nonce).apply_keystream(&mut bytes[HEADER..]);
279            bytes.drain(..HEADER);
280            Ok(bytes)
281        }
282    }
283}
284
285/// Whether `path` is a sealed cache file: another app reading it would see only ciphertext.
286pub fn is_sealed(path: &Path) -> bool {
287    let Ok(mut file) = std::fs::File::open(path) else { return false };
288    let mut head = [0u8; 4];
289    read_up_to(&mut file, &mut head) == 4 && &head == MAGIC
290}
291
292/// Whether `path` holds a cache file this install can read, without reading it.
293pub fn readable(path: &Path) -> bool {
294    let Ok(mut file) = std::fs::File::open(path) else { return false };
295    let mut head = [0u8; HEADER];
296    let n = read_up_to(&mut file, &mut head);
297    // An empty file is a write a crash cut short.
298    if n == 0 {
299        return false;
300    }
301    match key() {
302        Some(key) => !matches!(kind(&head[..n], key), Kind::Foreign),
303        None => !head[..n].starts_with(MAGIC),
304    }
305}
306
307/// Seal a file written before sealing, in place. False when it was sealed already.
308pub fn seal_in_place(path: &Path) -> Result<bool, String> {
309    let mut head = [0u8; HEADER];
310    let n = read_up_to(&mut std::fs::File::open(path).map_err(|e| e.to_string())?, &mut head);
311    if head[..n].starts_with(MAGIC) {
312        return Ok(false);
313    }
314    let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
315    seal_stream(path, path)?;
316    // Age-based sweeps read the mtime: sealing isn't a use.
317    if let (Some(t), Ok(f)) = (modified, std::fs::OpenOptions::new().write(true).open(path)) {
318        let _ = f.set_modified(t);
319    }
320    Ok(true)
321}
322
323/// Seal every legacy picture and video under `dir`, recursively; sidecars and markers stay as
324/// they are. Returns how many were sealed.
325pub fn seal_dir(dir: &Path) -> usize {
326    const MEDIA: [&str; 13] = ["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "svg", "tif", "tiff", "mp4", "webm", "mov"];
327    let Ok(entries) = std::fs::read_dir(dir) else { return 0 };
328    let mut sealed = 0;
329    for entry in entries.flatten() {
330        let path = entry.path();
331        let Ok(kind) = entry.file_type() else { continue };
332        let media = path.extension().and_then(|e| e.to_str()).is_some_and(|e| MEDIA.contains(&e.to_ascii_lowercase().as_str()));
333        if kind.is_dir() {
334            sealed += seal_dir(&path);
335        } else if path.extension().is_some_and(|e| e == "vtmp") {
336            // A write cut short: ciphertext with no file to become. A fresh one may be in flight.
337            let age = entry.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok());
338            if age.is_some_and(|age| age > std::time::Duration::from_secs(600)) {
339                let _ = std::fs::remove_file(&path);
340            }
341        } else if kind.is_file() && media && seal_in_place(&path).unwrap_or(false) {
342            sealed += 1;
343        }
344    }
345    sealed
346}
347
348/// Seal everything Vector cached before sealing: the shared cache and every account's
349/// wallpapers. Idempotent; a sealed file costs one header read.
350pub fn seal_legacy() -> usize {
351    static DONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
352    let Ok(root) = crate::db::get_app_data_dir() else { return 0 };
353    // Files from before sealing don't reappear: once a launch is enough.
354    if DONE.swap(true, std::sync::atomic::Ordering::AcqRel) {
355        return 0;
356    }
357    let mut sealed: usize = KINDS.iter().map(|kind| seal_dir(&root.join("cache").join(kind))).sum();
358    if let Ok(entries) = std::fs::read_dir(root) {
359        for account in entries.flatten() {
360            let real_dir = account.file_type().is_ok_and(|t| t.is_dir());
361            if real_dir && account.file_name().to_string_lossy().starts_with("npub1") {
362                sealed += seal_dir(&account.path().join("wallpapers"));
363            }
364        }
365    }
366    sealed
367}
368
369/// The cache file a page asks for by its path under the app's folder: `cache/…` or an
370/// account's `wallpapers/…`. Anything else, or any path that climbs out, is refused.
371pub fn resolve(rel: &str) -> Option<PathBuf> {
372    let parts: Vec<&str> = rel.split('/').collect();
373    let clean = parts.iter().all(|p| !p.is_empty() && *p != "." && *p != ".." && !p.contains(['\\', ':', '\0']));
374    let allowed = match parts.as_slice() {
375        ["cache", kind, _, ..] => KINDS.contains(kind),
376        [account, "wallpapers", _, ..] => account.starts_with("npub1"),
377        _ => false,
378    };
379    if !clean || !allowed {
380        return None;
381    }
382    let root = crate::db::get_app_data_dir().ok()?;
383    let path = parts.iter().fold(root.clone(), |p, part| p.join(part));
384    // A link inside the folder could still point out of it.
385    let (real, real_root) = (std::fs::canonicalize(&path).ok()?, std::fs::canonicalize(root).ok()?);
386    real.starts_with(&real_root).then_some(real)
387}
388
389/// A request path's segment text, percent-decoded.
390pub fn decode_rel(encoded: &str) -> Option<String> {
391    let bytes = encoded.as_bytes();
392    let mut out = Vec::with_capacity(bytes.len());
393    let mut i = 0;
394    while i < bytes.len() {
395        if bytes[i] == b'%' {
396            let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?;
397            out.push(u8::from_str_radix(hex, 16).ok()?);
398            i += 3;
399        } else {
400            out.push(bytes[i]);
401            i += 1;
402        }
403    }
404    String::from_utf8(out).ok()
405}
406
407/// A cache file as a page may show it. A cached SVG is a render Vector drew and wrapped, so the
408/// page gets the picture inside, never SVG markup; anything else opens as it is.
409pub fn open_for_page(path: &Path) -> Option<Arc<dyn crate::media::MediaSource>> {
410    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase();
411    if ext == "svg" {
412        let png = crate::svg::unwrap_raster(&read(path).ok()?)?;
413        return Some(Arc::new(InMemory { bytes: png, mime: "image/png" }));
414    }
415    open(path, crate::crypto::mime_from_extension(&ext))
416}
417
418struct InMemory {
419    bytes: Vec<u8>,
420    mime: &'static str,
421}
422
423impl crate::media::MediaSource for InMemory {
424    fn len(&self) -> u64 {
425        self.bytes.len() as u64
426    }
427
428    fn mime(&self) -> &str {
429        self.mime
430    }
431
432    fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize> {
433        let start = usize::try_from(offset).unwrap_or(usize::MAX).min(self.bytes.len());
434        let n = buf.len().min(self.bytes.len() - start);
435        buf[..n].copy_from_slice(&self.bytes[start..start + n]);
436        Ok(n)
437    }
438}
439
440/// A cache file read by range: what a player or a large picture asks for.
441pub fn open(path: &Path, mime: &str) -> Option<Arc<dyn crate::media::MediaSource>> {
442    let mut file = std::fs::File::open(path).ok()?;
443    let total = file.metadata().ok()?.len();
444    let mut head = [0u8; HEADER];
445    let n = read_up_to(&mut file, &mut head);
446    let sealed = match key() {
447        Some(key) => match kind(&head[..n], key) {
448            Kind::Sealed(nonce) => Some((key, nonce)),
449            Kind::Foreign => return None,
450            Kind::Plain => None,
451        },
452        None if head[..n].starts_with(MAGIC) => return None,
453        None => None,
454    };
455    Some(Arc::new(match sealed {
456        Some((key, nonce)) => CacheFile {
457            file,
458            offset: HEADER as u64,
459            len: total.saturating_sub(HEADER as u64),
460            key: Some((Zeroizing::new(*key.bytes), nonce)),
461            mime: mime.to_string(),
462        },
463        None => CacheFile { file, offset: 0, len: total, key: None, mime: mime.to_string() },
464    }))
465}
466
467struct CacheFile {
468    file: std::fs::File,
469    offset: u64,
470    len: u64,
471    key: Option<(Zeroizing<[u8; 32]>, [u8; 12])>,
472    mime: String,
473}
474
475impl crate::media::MediaSource for CacheFile {
476    fn len(&self) -> u64 {
477        self.len
478    }
479
480    fn mime(&self) -> &str {
481        &self.mime
482    }
483
484    fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize> {
485        if offset >= self.len {
486            return Ok(0);
487        }
488        let n = buf.len().min(usize::try_from(self.len - offset).unwrap_or(usize::MAX));
489        let part = &mut buf[..n];
490        crate::media::store::read_exact_at(&self.file, part, self.offset + offset)?;
491        if let Some((key, nonce)) = &self.key {
492            let mut cipher = chacha20::ChaCha20::new((&**key).into(), nonce.into());
493            cipher.try_seek(offset).map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "past the end of the cipher"))?;
494            cipher.apply_keystream(part);
495        }
496        Ok(n)
497    }
498}
499
500fn read_up_to(file: &mut std::fs::File, buf: &mut [u8]) -> usize {
501    let mut filled = 0;
502    while filled < buf.len() {
503        match file.read(&mut buf[filled..]) {
504            Ok(0) | Err(_) => break,
505            Ok(n) => filled += n,
506        }
507    }
508    filled
509}
510
511fn temp_beside(path: &Path) -> PathBuf {
512    let mut id = [0u8; 6];
513    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut id);
514    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
515    path.with_file_name(format!(".{name}.{}.vtmp", crate::simd::hex::bytes_to_hex_string(&id)))
516}
517
518fn create_private(path: &Path) -> Result<std::fs::File, String> {
519    let mut options = std::fs::OpenOptions::new();
520    options.write(true).create(true).truncate(true);
521    #[cfg(unix)]
522    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
523    options.open(path).map_err(|e| e.to_string())
524}
525
526fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
527    create_private(path)?.write_all(bytes).map_err(|e| e.to_string())
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533
534    fn ready() -> std::sync::MutexGuard<'static, ()> {
535        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
536        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
537        guard
538    }
539
540    #[test]
541    fn a_sealed_file_reads_back_and_holds_no_plaintext() {
542        let _g = ready();
543        let dir = tempfile::tempdir().unwrap();
544        let path = dir.path().join("face.png");
545        let plain: Vec<u8> = (0..100_000u32).map(|i| (i * 7 % 251) as u8).collect();
546        write(&path, &plain).unwrap();
547        let raw = std::fs::read(&path).unwrap();
548        assert!(raw.starts_with(MAGIC) && raw.len() == plain.len() + HEADER);
549        assert!(!raw.windows(64).any(|w| w == &plain[1000..1064]));
550        assert_eq!(&*read(&path).unwrap(), &plain);
551        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
552    }
553
554    #[test]
555    fn a_range_reads_any_window() {
556        let _g = ready();
557        let dir = tempfile::tempdir().unwrap();
558        let path = dir.path().join("clip.mp4");
559        let plain: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect();
560        write(&path, &plain).unwrap();
561        let src = open(&path, "video/mp4").unwrap();
562        assert_eq!(src.len(), plain.len() as u64);
563        for (start, len) in [(0usize, 10usize), (63, 130), (131_071, 5000), (299_990, 50)] {
564            let mut buf = vec![0u8; len];
565            let n = src.read_at(start as u64, &mut buf).unwrap();
566            assert_eq!(&buf[..n], &plain[start..(start + len).min(plain.len())]);
567        }
568    }
569
570    #[test]
571    fn a_legacy_file_reads_as_it_is_until_sealed_in_place() {
572        let _g = ready();
573        let dir = tempfile::tempdir().unwrap();
574        let path = dir.path().join("old.jpg");
575        std::fs::write(&path, b"\xFF\xD8\xFF legacy jpeg").unwrap();
576        assert_eq!(&*read(&path).unwrap(), b"\xFF\xD8\xFF legacy jpeg");
577        assert_eq!(crate::media::read_all(&*open(&path, "image/jpeg").unwrap()).unwrap(), b"\xFF\xD8\xFF legacy jpeg");
578        assert!(seal_in_place(&path).unwrap());
579        assert!(!seal_in_place(&path).unwrap());
580        assert!(std::fs::read(&path).unwrap().starts_with(MAGIC));
581        assert_eq!(&*read(&path).unwrap(), b"\xFF\xD8\xFF legacy jpeg");
582    }
583
584    #[test]
585    fn a_file_under_another_key_is_treated_as_missing() {
586        let _g = ready();
587        let dir = tempfile::tempdir().unwrap();
588        let path = dir.path().join("stranger.png");
589        let mut raw = seal(b"under this key").unwrap();
590        raw[4] ^= 0xff;
591        std::fs::write(&path, &raw).unwrap();
592        assert!(!readable(&path));
593        assert!(open(&path, "image/png").is_none());
594        assert!(read(&path).is_err());
595        assert!(path.exists(), "a read never deletes");
596    }
597
598    #[test]
599    fn a_cached_svg_reaches_a_page_as_the_picture_inside() {
600        let _g = ready();
601        let dir = tempfile::tempdir().unwrap();
602        let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="2"><rect width="4" height="2" fill="red"/></svg>"#;
603        let wrapped = crate::svg::rasterize_wrapped(svg, 64).unwrap();
604        let path = dir.path().join("face.svg");
605        write(&path, &wrapped).unwrap();
606        let src = open_for_page(&path).unwrap();
607        assert_eq!(src.mime(), "image/png");
608        assert!(crate::media::read_all(&*src).unwrap().starts_with(b"\x89PNG"));
609        // Markup Vector didn't draw never reaches a page.
610        let raw = dir.path().join("raw.svg");
611        write(&raw, svg).unwrap();
612        assert!(open_for_page(&raw).is_none());
613        let empty = dir.path().join("empty.svg");
614        write(&empty, &crate::svg::empty_wrapped()).unwrap();
615        assert!(open_for_page(&empty).is_none());
616    }
617
618    #[test]
619    fn a_part_written_in_pieces_and_resumed_reads_whole() {
620        let _g = ready();
621        let dir = tempfile::tempdir().unwrap();
622        let part = dir.path().join("v.part");
623        let plain: Vec<u8> = (0..200_000u32).map(|i| (i % 239) as u8).collect();
624        let first = Sealer::for_part(&part).unwrap();
625        let mut a = plain[..70_001].to_vec();
626        first.seal_at(0, &mut a).unwrap();
627        std::fs::OpenOptions::new().append(true).open(&part).unwrap().write_all(&a).unwrap();
628        // A resume reads the header back and continues under it.
629        let again = Sealer::for_part(&part).unwrap();
630        let mut b = plain[70_001..].to_vec();
631        again.seal_at(70_001, &mut b).unwrap();
632        std::fs::OpenOptions::new().append(true).open(&part).unwrap().write_all(&b).unwrap();
633        assert_eq!(&*read(&part).unwrap(), &plain);
634        assert!(!std::fs::read(&part).unwrap().windows(32).any(|w| w == &plain[100..132]));
635
636        // A part from before sealing starts over.
637        let old = dir.path().join("old.part");
638        std::fs::write(&old, b"plaintext from an older download").unwrap();
639        Sealer::for_part(&old).unwrap();
640        assert_eq!(std::fs::metadata(&old).unwrap().len(), HEADER_LEN);
641    }
642
643    #[test]
644    fn a_streamed_seal_matches_and_a_directory_seals_once() {
645        let _g = ready();
646        let dir = tempfile::tempdir().unwrap();
647        let part = dir.path().join("v.part");
648        let plain: Vec<u8> = (0..(CHUNK * 2 + 77) as u32).map(|i| (i % 241) as u8).collect();
649        std::fs::write(&part, &plain).unwrap();
650        let dest = dir.path().join("v.mp4");
651        seal_stream(&part, &dest).unwrap();
652        assert_eq!(&*read(&dest).unwrap(), &plain);
653
654        let nested = dir.path().join("thumbs");
655        std::fs::create_dir_all(&nested).unwrap();
656        std::fs::write(nested.join("a.png"), b"\x89PNG plain").unwrap();
657        std::fs::write(dir.path().join("b.gif"), b"GIF89a plain").unwrap();
658        std::fs::write(dir.path().join("sheet.json"), b"{}").unwrap();
659        assert_eq!(seal_dir(dir.path()), 2);
660        assert_eq!(std::fs::read(dir.path().join("sheet.json")).unwrap(), b"{}", "sidecars stay readable");
661        assert_eq!(seal_dir(dir.path()), 0);
662        assert_eq!(&*read(&nested.join("a.png")).unwrap(), b"\x89PNG plain");
663    }
664}