Skip to main content

vector_core/media/
store.rs

1//! Files this account keeps, as the ciphertext they arrived as, under `<account>/media/`. The
2//! ledger (`db::media_store`) holds each file's key; nothing here is ever plaintext.
3
4use std::collections::HashSet;
5#[cfg(not(target_arch = "wasm32"))]
6use std::path::Path;
7use std::path::PathBuf;
8use std::sync::{Arc, RwLock};
9
10#[cfg(not(target_arch = "wasm32"))]
11use zeroize::Zeroizing;
12
13use crate::db::media_store::{self, Origin, StoredMedia};
14
15/// The hashes this account keeps, read once its database opens: residency is asked under the
16/// STATE lock, where a query has no business.
17#[derive(Default)]
18struct Index(RwLock<Option<HashSet<[u8; 32]>>>);
19
20struct IndexKey;
21
22fn index() -> Arc<Index> {
23    crate::db::current_session().scoped::<IndexKey, Index>()
24}
25
26/// Built with the session, so a rebind's copy of the session map shares it.
27pub(crate) fn attach(session: &Arc<crate::db::Session>) {
28    let _ = session.scoped::<IndexKey, Index>();
29}
30
31/// Read the kept hashes into `session` once its database opens, straight from `conn`: the
32/// task opening it may still be bound to the account before.
33pub(crate) fn load_index(session: &Arc<crate::db::Session>, conn: &rusqlite::Connection) {
34    let hashes = conn.prepare("SELECT hash FROM media_store").ok().map(|mut stmt| {
35        stmt.query_map([], |r| r.get::<_, String>(0))
36            .map(|rows| rows.flatten().filter_map(|h| crate::simd::hex::hex_to_bytes_32_checked(&h)).collect::<HashSet<_>>())
37            .unwrap_or_default()
38    });
39    *session.scoped::<IndexKey, Index>().0.write().unwrap_or_else(|e| e.into_inner()) = hashes;
40}
41
42pub fn holds(hash: &[u8; 32]) -> bool {
43    index().0.read().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|set| set.contains(hash))
44}
45
46/// Stop answering for `hash` at once, before its row and file go: a read already under way then
47/// finds it gone instead of putting it back in memory.
48#[cfg(target_arch = "wasm32")]
49pub(crate) fn stop_holding(hash: &[u8; 32]) {
50    indexed(*hash, false);
51}
52
53fn indexed(hash: [u8; 32], present: bool) {
54    if let Some(set) = index().0.write().unwrap_or_else(|e| e.into_inner()).as_mut() {
55        if present {
56            set.insert(hash);
57        } else {
58            set.remove(&hash);
59        }
60    }
61}
62
63pub fn dir() -> Result<PathBuf, String> {
64    Ok(crate::db::current_account_dir()?.join("media"))
65}
66
67pub(crate) fn fresh_name() -> String {
68    let mut bytes = [0u8; 16];
69    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);
70    crate::simd::hex::bytes_to_hex_string(&bytes)
71}
72
73/// What a kept file is, besides its bytes.
74#[derive(Debug, Clone)]
75pub struct Keep {
76    pub hash: [u8; 32],
77    pub key: String,
78    pub nonce: String,
79    pub blob_sha256: String,
80    pub pt_len: u64,
81    pub mime: String,
82    pub origin: Origin,
83}
84
85/// Keep a verified blob: `src` moves into the store, then a row records how to open it.
86#[cfg(not(target_arch = "wasm32"))]
87pub fn keep_file(src: &Path, keep: Keep) -> Result<(), String> {
88    let (dir, name) = place(src)?;
89    record(&dir.join(&name), name, keep)
90}
91
92/// Move `src` into the store under a fresh name, durable. Returns the store and the name.
93#[cfg(not(target_arch = "wasm32"))]
94fn place(src: &Path) -> Result<(PathBuf, String), String> {
95    let dir = dir()?;
96    std::fs::create_dir_all(&dir).map_err(|e| format!("Couldn't keep the file: {e}"))?;
97    let name = fresh_name();
98    let dest = dir.join(&name);
99    // A rename can't cross filesystems: copy beside the destination, then rename that.
100    if std::fs::rename(src, &dest).is_err() {
101        let tmp = dir.join(format!(".{name}.tmp"));
102        std::fs::copy(src, &tmp)
103            .and_then(|_| std::fs::rename(&tmp, &dest))
104            .map_err(|e| {
105                let _ = std::fs::remove_file(&tmp);
106                format!("Couldn't keep the file: {e}")
107            })?;
108        let _ = std::fs::remove_file(src);
109    }
110    settle(&dir, &dest).inspect_err(|_| {
111        let _ = std::fs::remove_file(&dest);
112    })?;
113    Ok((dir, name))
114}
115
116/// Keep a sealed file in place of anything kept for its hash, once it has read back whole as
117/// those bytes. An old copy goes only after the new one is recorded.
118#[cfg(not(target_arch = "wasm32"))]
119pub fn keep_verified(src: &Path, keep: Keep) -> Result<(), String> {
120    let (dir, name) = place(src)?;
121    let dest = dir.join(&name);
122    let hex = crate::simd::hex::bytes_to_hex_32(&keep.hash);
123    let good = crate::crypto::stream::verify_file(&dest, &keep.key, &keep.nonce).is_ok_and(|seen| seen.output_sha256 == hex);
124    if !good {
125        let _ = std::fs::remove_file(&dest);
126        return Err("the kept copy didn't read back as the file".into());
127    }
128    let hash = keep.hash;
129    let entry = StoredMedia {
130        hash, file: name, key: keep.key, nonce: keep.nonce, blob_sha256: keep.blob_sha256,
131        pt_len: keep.pt_len, mime: keep.mime, origin: keep.origin,
132    };
133    match media_store::replace(&entry) {
134        Ok(old) => {
135            indexed(hash, true);
136            if let Some(old) = old {
137                let _ = std::fs::remove_file(dir.join(old));
138            }
139            Ok(())
140        }
141        Err(e) => {
142            let _ = std::fs::remove_file(&dest);
143            Err(e)
144        }
145    }
146}
147
148/// Keep a verified blob held in memory.
149#[cfg(not(target_arch = "wasm32"))]
150pub fn keep_bytes(blob: &[u8], keep: Keep) -> Result<(), String> {
151    let dir = dir()?;
152    std::fs::create_dir_all(&dir).map_err(|e| format!("Couldn't keep the file: {e}"))?;
153    let name = fresh_name();
154    let (tmp, dest) = (dir.join(format!(".{name}.tmp")), dir.join(&name));
155    std::fs::write(&tmp, blob).and_then(|_| std::fs::rename(&tmp, &dest)).map_err(|e| {
156        let _ = std::fs::remove_file(&tmp);
157        format!("Couldn't keep the file: {e}")
158    })?;
159    settle(&dir, &dest).inspect_err(|_| {
160        let _ = std::fs::remove_file(&dest);
161    })?;
162    record(&dest, name, keep)
163}
164
165/// Seal plaintext under fresh parameters and keep it: for bytes that came without a blob of
166/// their own to keep (an unencrypted source, a file being imported).
167#[cfg(not(target_arch = "wasm32"))]
168pub fn keep_sealed(plain: &[u8], hash: [u8; 32], mime: &str, origin: Origin) -> Result<(), String> {
169    let params = crate::crypto::generate_encryption_params();
170    let blob = crate::crypto::encrypt_data(plain, &params)?;
171    keep_bytes(&blob, Keep {
172        hash, key: params.key.clone(), nonce: params.nonce.clone(), blob_sha256: crate::crypto::sha256_hex(&blob),
173        pt_len: plain.len() as u64, mime: mime.to_string(), origin,
174    })
175}
176
177/// Durable before its row exists, and dated now: a rename keeps an old download's mtime, which
178/// the orphan sweep would read as abandoned.
179#[cfg(not(target_arch = "wasm32"))]
180fn settle(dir: &Path, file: &Path) -> Result<(), String> {
181    let f = std::fs::OpenOptions::new().write(true).open(file).map_err(|e| format!("Couldn't keep the file: {e}"))?;
182    let _ = f.set_modified(web_time::SystemTime::now());
183    f.sync_all().map_err(|e| format!("Couldn't keep the file: {e}"))?;
184    // Windows can't open a directory to sync it; there the rename is already durable.
185    if let Ok(d) = std::fs::File::open(dir) {
186        let _ = d.sync_all();
187    }
188    Ok(())
189}
190
191#[cfg(not(target_arch = "wasm32"))]
192fn record(dest: &Path, file: String, keep: Keep) -> Result<(), String> {
193    match record_row(file, keep) {
194        Ok(true) => Ok(()),
195        // Kept already: this copy is spare.
196        Ok(false) => {
197            let _ = std::fs::remove_file(dest);
198            Ok(())
199        }
200        Err(e) => {
201            let _ = std::fs::remove_file(dest);
202            Err(e)
203        }
204    }
205}
206
207/// The row for a file just written; false when the hash was kept already.
208fn record_row(file: String, keep: Keep) -> Result<bool, String> {
209    let hash = keep.hash;
210    let entry = StoredMedia {
211        hash, file, key: keep.key, nonce: keep.nonce, blob_sha256: keep.blob_sha256,
212        pt_len: keep.pt_len, mime: keep.mime, origin: keep.origin,
213    };
214    let fresh = media_store::insert(&entry)?;
215    indexed(hash, true);
216    Ok(fresh)
217}
218
219/// Keep plaintext on the web, sealed under fresh parameters into the origin's private files.
220#[cfg(target_arch = "wasm32")]
221pub async fn keep_sealed(plain: &[u8], hash: [u8; 32], mime: &str, origin: Origin) -> Result<(), String> {
222    let params = crate::crypto::generate_encryption_params();
223    let blob = crate::crypto::encrypt_data(plain, &params)?;
224    let name = fresh_name();
225    let path = dir()?.join(&name);
226    crate::webfiles::write(&path, &blob).await?;
227    let keep = Keep {
228        hash, key: params.key.clone(), nonce: params.nonce.clone(), blob_sha256: crate::crypto::sha256_hex(&blob),
229        pt_len: plain.len() as u64, mime: mime.to_string(), origin,
230    };
231    match record_row(name, keep) {
232        Ok(true) => Ok(()),
233        other => {
234            crate::webfiles::remove(&path).await;
235            other.map(|_| ())
236        }
237    }
238}
239
240/// A kept file's plaintext and type on the web, read whole: the origin's files are async.
241#[cfg(target_arch = "wasm32")]
242pub async fn read_plain(hash: &[u8; 32]) -> Option<(Vec<u8>, String)> {
243    if !holds(hash) {
244        return None;
245    }
246    let entry = media_store::get(hash).ok().flatten()?;
247    let blob = crate::webfiles::read(&dir().ok()?.join(&entry.file)).await.ok()?;
248    let plain = crate::crypto::decrypt_data_owned(blob, &entry.key, &entry.nonce).ok()?;
249    Some((plain, entry.mime))
250}
251
252/// Stop keeping `hash` on the web: the row first, then its file.
253#[cfg(target_arch = "wasm32")]
254pub async fn forget(hash: &[u8; 32]) {
255    if let Ok(Some(file)) = media_store::remove(hash) {
256        if let Ok(dir) = dir() {
257            crate::webfiles::remove(&dir.join(file)).await;
258        }
259        let _ = crate::db::attachments::clear_kept(&crate::simd::hex::bytes_to_hex_32(hash));
260    }
261    indexed(*hash, false);
262}
263
264/// Stop keeping `hash`: the row goes first, then its file, and the attachments that had no
265/// other copy are no longer downloaded.
266#[cfg(not(target_arch = "wasm32"))]
267pub fn forget(hash: &[u8; 32]) {
268    if let Ok(Some(file)) = media_store::remove(hash) {
269        if let Ok(dir) = dir() {
270            let _ = std::fs::remove_file(dir.join(file));
271        }
272        let _ = crate::db::attachments::clear_kept(&crate::simd::hex::bytes_to_hex_32(hash));
273    }
274    indexed(*hash, false);
275}
276
277/// The files kept here, and their size in bytes.
278pub fn kept_files() -> (u64, u64) {
279    media_store::totals()
280        .unwrap_or_default()
281        .into_iter()
282        .fold((0, 0), |(files, bytes), (_, n, size)| (files + n, bytes + size))
283}
284
285/// Forget every kept file whose type `matches`; returns the hashes forgotten.
286#[cfg(not(target_arch = "wasm32"))]
287pub fn forget_where(matches: impl Fn(&str) -> bool) -> Vec<[u8; 32]> {
288    let rows = media_store::totals_by_hash().unwrap_or_default();
289    let gone: Vec<[u8; 32]> = rows.into_iter().filter(|(_, mime)| matches(mime)).map(|(h, _)| h).collect();
290    for hash in &gone {
291        forget(hash);
292    }
293    gone
294}
295
296/// A kept file, read through its own keystream.
297#[cfg(not(target_arch = "wasm32"))]
298pub fn open(hash: &[u8; 32]) -> Option<Arc<dyn super::MediaSource>> {
299    if !holds(hash) {
300        return None;
301    }
302    let entry = media_store::get(hash).ok().flatten()?;
303    let (key, nonce) = crate::crypto::attachment_params(&entry.key, &entry.nonce, "Invalid key").ok()?;
304    let file = std::fs::File::open(dir().ok()?.join(&entry.file)).ok()?;
305    // The blob is the plaintext and its 16-byte tag.
306    if file.metadata().ok()?.len() != entry.pt_len + 16 {
307        return None;
308    }
309    Some(Arc::new(StoredGcm { file, key: Zeroizing::new(key), nonce, len: entry.pt_len, mime: entry.mime }))
310}
311
312/// What reading a kept copy back whole found.
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub enum Check {
315    /// It opens under its key, tag and all, and is those bytes.
316    Good,
317    /// Provably not those bytes: gone, the wrong size, or other bytes under a key that opened.
318    Bad,
319    /// It couldn't be checked: a key that won't open yet, or a read that failed.
320    Unknown,
321}
322
323/// Read the kept copy of `hash` back whole: for when it is about to become the only one.
324#[cfg(not(target_arch = "wasm32"))]
325pub fn read_back(hash: &[u8; 32]) -> Check {
326    let Ok(dir) = dir() else { return Check::Unknown };
327    let entry = match media_store::get(hash) {
328        Ok(Some(entry)) => entry,
329        // No row is no copy; a row whose key won't open can't be judged.
330        Ok(None) if media_store::has_row(hash) == Ok(false) => return Check::Bad,
331        _ => return Check::Unknown,
332    };
333    let path = dir.join(&entry.file);
334    match std::fs::metadata(&path) {
335        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Check::Bad,
336        Err(_) => return Check::Unknown,
337        Ok(meta) if meta.len() != entry.pt_len + 16 => return Check::Bad,
338        Ok(_) => {}
339    }
340    match crate::crypto::stream::verify_file(&path, &entry.key, &entry.nonce) {
341        Ok(seen) if seen.output_sha256 == crate::simd::hex::bytes_to_hex_32(hash) => Check::Good,
342        Ok(_) => Check::Bad,
343        Err(e) if e == crate::crypto::stream::TAG_MISMATCH => Check::Bad,
344        Err(_) => Check::Unknown,
345    }
346}
347
348
349#[cfg(not(target_arch = "wasm32"))]
350impl StoredGcm {
351    /// A blob of our own sealing, read the same way: `path` holds ciphertext and tag.
352    pub(super) fn sealed(path: &Path, key_hex: &str, nonce_hex: &str, mime: &str) -> Option<Self> {
353        let (key, nonce) = crate::crypto::attachment_params(key_hex, nonce_hex, "Invalid key").ok()?;
354        let file = std::fs::File::open(path).ok()?;
355        let len = file.metadata().ok()?.len().checked_sub(16)?;
356        Some(StoredGcm { file, key: Zeroizing::new(key), nonce, len, mime: mime.to_string() })
357    }
358}
359
360#[cfg(target_arch = "wasm32")]
361pub fn open(_hash: &[u8; 32]) -> Option<Arc<dyn super::MediaSource>> {
362    None
363}
364
365/// A kept blob, decrypted a range at a time. Its tag was checked when it was kept; anyone who
366/// could change the file since could change the database too.
367#[cfg(not(target_arch = "wasm32"))]
368pub(super) struct StoredGcm {
369    file: std::fs::File,
370    key: Zeroizing<[u8; 32]>,
371    nonce: [u8; 16],
372    len: u64,
373    mime: String,
374}
375
376#[cfg(not(target_arch = "wasm32"))]
377impl super::MediaSource for StoredGcm {
378    fn len(&self) -> u64 {
379        self.len
380    }
381
382    fn mime(&self) -> &str {
383        &self.mime
384    }
385
386    fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize> {
387        if offset >= self.len {
388            return Ok(0);
389        }
390        let n = buf.len().min(usize::try_from(self.len - offset).unwrap_or(usize::MAX));
391        let part = &mut buf[..n];
392        read_exact_at(&self.file, part, offset)?;
393        crate::crypto::gcm::Keystream::new(&self.key, &self.nonce)
394            .apply_at(offset, part)
395            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "past the end of the cipher"))?;
396        Ok(n)
397    }
398}
399
400#[cfg(unix)]
401pub(crate) fn read_exact_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
402    std::os::unix::fs::FileExt::read_exact_at(file, buf, offset)
403}
404
405#[cfg(windows)]
406pub(crate) fn read_exact_at(file: &std::fs::File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> {
407    while !buf.is_empty() {
408        match std::os::windows::fs::FileExt::seek_read(file, buf, offset)? {
409            0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
410            n => {
411                buf = &mut buf[n..];
412                offset += n as u64;
413            }
414        }
415    }
416    Ok(())
417}
418
419/// Check every row against its file. A file missing once is marked; missing twice, its row
420/// goes, since some rows hold the only key there is. Returns the hashes no longer kept.
421#[cfg(not(target_arch = "wasm32"))]
422pub fn check() -> Vec<[u8; 32]> {
423    let (Ok(dir), Ok(rows), Ok(named)) = (dir(), media_store::all(), media_store::files()) else {
424        crate::log_warn!("[Media] the kept files couldn't be listed; the launch check is skipped");
425        return Vec::new();
426    };
427    if rows.len() < named.len() {
428        crate::log_warn!("[Media] {} kept rows don't read; their files are left alone", named.len() - rows.len());
429    }
430    let (mut lost, mut found, mut gone) = (Vec::new(), Vec::new(), Vec::new());
431    for (hash, file, missing) in rows {
432        if dir.join(&file).is_file() {
433            if missing {
434                found.push(hash);
435            }
436        } else if missing {
437            forget(&hash);
438            gone.push(hash);
439        } else {
440            lost.push(hash);
441        }
442    }
443    let _ = media_store::set_missing(&lost, &found);
444    // Files no row names, from a crash between a file and its row, once they're an hour old.
445    if let Ok(entries) = std::fs::read_dir(&dir) {
446        let hour = std::time::Duration::from_secs(3600);
447        for entry in entries.flatten() {
448            let name = entry.file_name().to_string_lossy().into_owned();
449            let old = entry.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > hour);
450            if old && !named.contains(&name) {
451                let _ = std::fs::remove_file(entry.path());
452            }
453        }
454    }
455    gone
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(95000);
463
464    fn make_test_npub(n: u32) -> String {
465        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
466        let mut payload = vec![b'q'; 58];
467        let mut x = n as u64;
468        let mut i = 58;
469        while x > 0 && i > 0 {
470            i -= 1;
471            payload[i] = BECH32[(x as usize) % 32];
472            x /= 32;
473        }
474        format!("npub1{}", String::from_utf8(payload).unwrap())
475    }
476
477    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
478        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
479        crate::db::close_database();
480        let tmp = tempfile::tempdir().unwrap();
481        let account = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
482        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
483        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
484        crate::db::set_current_account(account.clone()).unwrap();
485        crate::db::init_database(&account).unwrap();
486        (tmp, guard)
487    }
488
489    fn sealed(len: usize) -> (Vec<u8>, Vec<u8>, crate::crypto::EncryptionParams) {
490        let plain: Vec<u8> = (0..len).map(|i| (i * 17 % 251) as u8).collect();
491        let params = crate::crypto::generate_encryption_params();
492        let blob = crate::crypto::encrypt_data(&plain, &params).unwrap();
493        (plain, blob, params)
494    }
495
496    fn keep_of(plain: &[u8], blob: &[u8], params: &crate::crypto::EncryptionParams) -> Keep {
497        Keep {
498            hash: crate::simd::hex::hex_to_bytes_32(&crate::crypto::sha256_hex(plain)),
499            key: params.key.clone(), nonce: params.nonce.clone(), blob_sha256: crate::crypto::sha256_hex(blob),
500            pt_len: plain.len() as u64, mime: "video/mp4".into(), origin: Origin::Received,
501        }
502    }
503
504    #[test]
505    fn a_kept_blob_reads_back_any_range_and_never_as_plaintext_on_disk() {
506        let (_tmp, _guard) = init_test_db();
507        let (plain, blob, params) = sealed(300_001);
508        let keep = keep_of(&plain, &blob, &params);
509        keep_bytes(&blob, keep.clone()).unwrap();
510        assert!(holds(&keep.hash) && crate::media::resident(&keep.hash));
511
512        let src = crate::media::open(&keep.hash).expect("kept");
513        assert_eq!((src.len(), src.mime()), (plain.len() as u64, "video/mp4"));
514        for (at, n) in [(0usize, 16usize), (15, 2), (4095, 70_000), (300_000, 1), (299_990, 50)] {
515            let mut buf = vec![0u8; n];
516            let got = src.read_at(at as u64, &mut buf).unwrap();
517            assert_eq!(&buf[..got], &plain[at..(at + n).min(plain.len())], "at {at}");
518        }
519        assert_eq!(crate::media::read_all(&*src).unwrap(), plain);
520
521        let on_disk: Vec<Vec<u8>> = std::fs::read_dir(dir().unwrap()).unwrap().flatten().map(|e| std::fs::read(e.path()).unwrap()).collect();
522        assert_eq!(on_disk, vec![blob], "the store holds the blob, nothing else");
523    }
524
525    #[test]
526    fn a_file_is_kept_once_and_forgotten_row_first() {
527        let (_tmp, _guard) = init_test_db();
528        let (plain, blob, params) = sealed(64);
529        let keep = keep_of(&plain, &blob, &params);
530        let part = dir().unwrap().with_file_name("x.part");
531        std::fs::write(&part, &blob).unwrap();
532        keep_file(&part, keep.clone()).unwrap();
533        assert!(!part.exists(), "the download moved in");
534        keep_bytes(&blob, keep.clone()).unwrap();
535        assert_eq!(std::fs::read_dir(dir().unwrap()).unwrap().count(), 1, "a second copy of the same hash isn't kept");
536
537        forget(&keep.hash);
538        assert!(!holds(&keep.hash) && crate::media::open(&keep.hash).is_none());
539        assert_eq!(std::fs::read_dir(dir().unwrap()).unwrap().count(), 0);
540        assert_eq!(media_store::get(&keep.hash).unwrap(), None);
541    }
542
543    #[test]
544    fn a_missing_file_goes_on_its_second_miss_and_an_orphan_once_it_is_old() {
545        let (_tmp, _guard) = init_test_db();
546        let (plain, blob, params) = sealed(32);
547        let keep = keep_of(&plain, &blob, &params);
548        keep_bytes(&blob, keep.clone()).unwrap();
549        let file = media_store::get(&keep.hash).unwrap().unwrap().file;
550        std::fs::remove_file(dir().unwrap().join(&file)).unwrap();
551        assert!(check().is_empty(), "one miss only marks it");
552        assert!(holds(&keep.hash));
553        assert_eq!(check(), vec![keep.hash]);
554        assert!(!holds(&keep.hash));
555
556        let orphan = dir().unwrap().join("feedface");
557        std::fs::write(&orphan, b"x").unwrap();
558        check();
559        assert!(orphan.exists(), "a new file may be a keep in flight");
560        let f = std::fs::OpenOptions::new().write(true).open(&orphan).unwrap();
561        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(7200)).unwrap();
562        check();
563        assert!(!orphan.exists());
564    }
565
566    #[test]
567    fn a_kept_file_hours_old_is_never_taken_for_an_orphan() {
568        let (_tmp, _guard) = init_test_db();
569        let (plain, blob, params) = sealed(48);
570        let keep = keep_of(&plain, &blob, &params);
571        keep_bytes(&blob, keep.clone()).unwrap();
572        let path = dir().unwrap().join(media_store::get(&keep.hash).unwrap().unwrap().file);
573        let f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
574        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(7200)).unwrap();
575        assert!(check().is_empty());
576        assert!(path.exists() && holds(&keep.hash), "a row names it, however old");
577    }
578
579    #[test]
580    fn a_file_found_again_starts_its_misses_over() {
581        let (_tmp, _guard) = init_test_db();
582        let (plain, blob, params) = sealed(56);
583        let keep = keep_of(&plain, &blob, &params);
584        keep_bytes(&blob, keep.clone()).unwrap();
585        let path = dir().unwrap().join(media_store::get(&keep.hash).unwrap().unwrap().file);
586        let bytes = std::fs::read(&path).unwrap();
587        std::fs::remove_file(&path).unwrap();
588        assert!(check().is_empty(), "one miss only marks it");
589        std::fs::write(&path, &bytes).unwrap();
590        assert!(check().is_empty(), "found again");
591        std::fs::remove_file(&path).unwrap();
592        assert!(check().is_empty(), "a miss after it was found is a first miss");
593        assert!(holds(&keep.hash));
594    }
595
596    #[test]
597    fn a_file_only_an_unreadable_row_names_is_never_swept() {
598        let (_tmp, _guard) = init_test_db();
599        let (plain, blob, params) = sealed(64);
600        keep_bytes(&blob, keep_of(&plain, &blob, &params)).unwrap();
601        crate::db::get_write_connection_guard_static()
602            .unwrap()
603            .execute(
604                "INSERT INTO media_store (hash, file, format, key, nonce, blob_sha256, pt_len, mime, origin, created_at, used_at)
605                 SELECT 'nothex', 'unnamed', format, key, nonce, blob_sha256, pt_len, mime, origin, created_at, used_at FROM media_store LIMIT 1",
606                [],
607            )
608            .unwrap();
609        let file = dir().unwrap().join("unnamed");
610        std::fs::write(&file, b"x").unwrap();
611        let f = std::fs::OpenOptions::new().write(true).open(&file).unwrap();
612        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(7200)).unwrap();
613        let stray = dir().unwrap().join("stray");
614        std::fs::write(&stray, b"x").unwrap();
615        let f = std::fs::OpenOptions::new().write(true).open(&stray).unwrap();
616        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(7200)).unwrap();
617        check();
618        assert!(file.exists(), "a file only an unreadable row names is not an orphan");
619        assert!(!stray.exists(), "the check still runs: a file no row names is swept");
620    }
621
622    #[test]
623    fn a_plain_copy_in_a_download_folder_opens_though_it_isnt_held() {
624        let (_tmp, _guard) = init_test_db();
625        let downloads = tempfile::tempdir().unwrap();
626        crate::db::set_download_dir(downloads.path().to_path_buf());
627        let bytes = b"a picture kept unencrypted".to_vec();
628        let hash = crate::simd::hex::hex_to_bytes_32(&crate::crypto::sha256_hex(&bytes));
629        let path = downloads.path().join("plain.png");
630        std::fs::write(&path, &bytes).unwrap();
631        let conn = crate::db::get_write_connection_guard_static().unwrap();
632        conn.execute_batch("PRAGMA foreign_keys = OFF").unwrap();
633        conn.execute(
634            "INSERT INTO attachments (event_id, att_index, hash, path, downloaded) VALUES ('plain', 0, ?1, ?2, 1)",
635            rusqlite::params![crate::simd::hex::bytes_to_hex_32(&hash), path.to_string_lossy()],
636        )
637        .unwrap();
638        conn.execute_batch("PRAGMA foreign_keys = ON").unwrap();
639        drop(conn);
640
641        assert!(!crate::media::resident(&hash) && crate::media::openable(&hash), "opens from the plain copy");
642        std::fs::remove_file(&path).unwrap();
643        assert!(!crate::media::openable(&hash), "and not once that is gone");
644    }
645
646    #[test]
647    fn every_kept_file_counts_and_goes_whatever_its_type() {
648        let (_dir, _guard) = init_test_db();
649        let (picture, archive) = (b"a kept picture".to_vec(), b"a kept archive".to_vec());
650        let (p, a) = (
651            crate::simd::hex::hex_to_bytes_32(&crate::crypto::sha256_hex(&picture)),
652            crate::simd::hex::hex_to_bytes_32(&crate::crypto::sha256_hex(&archive)),
653        );
654        keep_sealed(&picture, p, "image/png", Origin::Sealed).unwrap();
655        keep_sealed(&archive, a, "application/zip", Origin::Sealed).unwrap();
656        assert_eq!(kept_files(), (2, (picture.len() + archive.len()) as u64));
657
658        let mut gone = forget_where(|_| true);
659        gone.sort();
660        let mut both = vec![p, a];
661        both.sort();
662        assert_eq!(gone, both);
663        assert!(!holds(&p) && !holds(&a));
664        assert_eq!(kept_files(), (0, 0));
665    }
666
667    #[test]
668    fn plaintext_with_no_blob_is_sealed_before_it_is_kept() {
669        let (_tmp, _guard) = init_test_db();
670        let plain = b"an unencrypted picture".to_vec();
671        let hash = crate::simd::hex::hex_to_bytes_32(&crate::crypto::sha256_hex(&plain));
672        keep_sealed(&plain, hash, "image/png", Origin::Sealed).unwrap();
673        let on_disk = std::fs::read(std::fs::read_dir(dir().unwrap()).unwrap().next().unwrap().unwrap().path()).unwrap();
674        assert!(on_disk.windows(plain.len()).all(|w| w != plain.as_slice()));
675        assert_eq!(crate::media::read_all(&*crate::media::open(&hash).unwrap()).unwrap(), plain);
676    }
677}