use std::collections::HashMap; use std::path::{Path, PathBuf}; use meow_core::contact::Contact; use meow_core::server::{ServerInfo, ServerKeys}; use meow_crypto::password::KdfParams; use meow_store::blocks::BLOCK_SIZE; use meow_store::{Batch, Content, Error, HistoryEntry, PendingAck, SpaceId, State, Store}; const KDF: KdfParams = KdfParams::INSECURE_TEST; const MAIN: SpaceId = SpaceId::MAIN; fn tmp() -> (PathBuf, PathBuf) { let dir = std::env::temp_dir().join(format!( "meow-store-{}", meow_crypto::random_bytes::<8>() .iter() .map(|b| format!("{b:02x}")) .collect::() )); std::fs::create_dir_all(&dir).unwrap(); (dir.join("id.mwid2"), dir) } fn server() -> ServerInfo { ServerInfo::from_card(&ServerKeys::generate().card("http://s", "s", "", 1)).unwrap() } fn contact(name: &str, s: &ServerInfo) -> Contact { meow_core::invitation::create_offer(name, "me", vec![s.clone()], "", 1000, 3600) .unwrap() .contact } fn text(c: &Contact, t: &str) -> HistoryEntry { HistoryEntry { id: meow_crypto::random_bytes::<16>().to_vec(), contact: c.id.clone(), outbound: false, sent_at_ms: 1, received_at: 2, content: Content::Text(t.into()), } } fn texts(entries: &[HistoryEntry]) -> Vec { entries .iter() .map(|e| match &e.content { Content::Text(t) => t.clone(), Content::File { name, .. } => format!("file:{name}"), }) .collect() } /// Every block of the file, as an attacker without password sees it. fn blocks(path: &Path) -> HashMap, Vec> { let c = rusqlite::Connection::open(path).unwrap(); let mut stmt = c.prepare("SELECT id, data FROM blocks").unwrap(); let rows = stmt .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) .unwrap() .collect::>() .unwrap(); rows } #[test] fn lifecycle_password_and_lock() { let (path, dir) = tmp(); let store = Store::create(&path, "alice", "pw", KDF, false).unwrap(); assert!(matches!(Store::open(&path, "pw"), Err(Error::Locked(_)))); assert!(matches!( Store::create(&path, "x", "pw", KDF, true), Err(Error::Locked(_)) )); drop(store); assert!(matches!( Store::create(&path, "x", "pw", KDF, false), Err(Error::Exists(_)) )); assert!(matches!(Store::open(&path, "nope"), Err(Error::BadPassword))); let mut store = Store::open(&path, "pw").unwrap(); assert_eq!(store.load(MAIN).unwrap().nickname, "alice"); store.change_password(MAIN, "new").unwrap(); drop(store); assert!(matches!(Store::open(&path, "pw"), Err(Error::BadPassword))); let mut store = Store::open(&path, "new").unwrap(); assert_eq!(store.load(MAIN).unwrap().nickname, "alice"); drop(store); let mut store = Store::create(&path, "bob", "pw2", KDF, true).unwrap(); assert_eq!(store.load(MAIN).unwrap().nickname, "bob"); drop(store); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = std::fs::metadata(&path).unwrap().permissions().mode(); assert_eq!(mode & 0o077, 0, "store must not be readable by others"); } let _ = std::fs::remove_dir_all(dir); } #[test] fn state_segments_and_files() { let (path, dir) = tmp(); let s = server(); let bob = contact("bob", &s); let carol = contact("carol", &s); let mut store = Store::create(&path, "alice", "pw", KDF, false).unwrap(); let mut state = store.load(MAIN).unwrap(); state.servers.push(s.clone()); state.contacts = vec![bob.clone(), carol.clone()]; state.pending_acks.push(PendingAck { server: s.sign_key, mailbox: vec![7; 32], id: b"1-0".to_vec(), }); // ~1 KiB messages: several segments. let filler = "x".repeat(1000); let mut batch = Batch::default(); for i in 0..30 { batch.history.push(text(&bob, &format!("m{i:02}{filler}"))); } let dup = batch.history[29].clone(); batch.history.push(dup); // same id: ignored let file = HistoryEntry { content: Content::File { name: "a.bin".into(), size: 3, }, ..text(&carol, "") }; batch.files.push((carol.id.clone(), file.id.clone(), vec![1, 2, 3])); batch.history.push(file.clone()); store.save(MAIN, &state, batch).unwrap(); // A later append goes to the same conversation. let later = Batch { history: vec![text(&bob, "last")], files: vec![], }; store.save(MAIN, &state, later).unwrap(); drop(store); let mut store = Store::open(&path, "pw").unwrap(); let loaded = store.load(MAIN).unwrap(); assert_eq!(loaded.servers, state.servers); assert_eq!(loaded.pending_acks, state.pending_acks); assert_eq!( loaded.contacts.iter().map(|c| c.name.as_str()).collect::>(), vec!["bob", "carol"] ); let all = texts(&store.full_history(MAIN, &bob.id).unwrap()); assert_eq!(all.len(), 31); assert!(all[0].starts_with("m00") && all[29].starts_with("m29") && all[30] == "last"); // Walk the segments from the latest one back. let mut page = store.history(MAIN, &bob.id, None).unwrap(); assert!(page.prev.is_some(), "30 KiB of messages must span several segments"); assert_eq!(texts(&page.entries).last().unwrap(), "last"); let mut walked = page.entries.len(); while let Some(prev) = page.prev { page = store.history(MAIN, &bob.id, Some(prev)).unwrap(); walked += page.entries.len(); } assert_eq!(walked, 31); assert!(texts(&page.entries)[0].starts_with("m00")); assert_eq!(texts(&store.full_history(MAIN, &carol.id).unwrap()), vec!["file:a.bin"]); assert_eq!(store.file(MAIN, &carol.id, &file.id).unwrap(), Some(vec![1, 2, 3])); assert_eq!(store.file(MAIN, &bob.id, &file.id).unwrap(), None); // Removing a contact removes its history and files; the blocks are recycled. let before = blocks(&path).len(); let mut state = loaded; state.contacts.retain(|c| c.name != "carol"); store.save(MAIN, &state, Batch::default()).unwrap(); assert!(store.full_history(MAIN, &carol.id).is_err()); assert_eq!(store.full_history(MAIN, &bob.id).unwrap().len(), 31); assert!(blocks(&path).len() <= before + 4, "freed blocks are reused, not leaked"); let _ = std::fs::remove_dir_all(dir); } #[test] fn hidden_spaces() { let (path, dir) = tmp(); let s = server(); let visible = contact("visible", &s); let secret = contact("secret", &s); let secret2 = contact("secret2", &s); let mut store = Store::create(&path, "alice", "main-pw", KDF, false).unwrap(); let mut main = store.load(MAIN).unwrap(); main.contacts.push(visible.clone()); store.save(MAIN, &main, Batch::default()).unwrap(); // One hidden space holding two contacts. let h = store.create_space("hidden-pw").unwrap(); assert_ne!(h, MAIN); let hidden = State { contacts: vec![secret.clone(), secret2.clone()], ..State::default() }; let batch = Batch { history: vec![text(&secret, "for your eyes only")], files: vec![], }; store.save(h, &hidden, batch).unwrap(); // A contact of another space cannot receive history here. let wrong = Batch { history: vec![text(&secret, "x")], files: vec![], }; assert!(store.save(MAIN, &main, wrong).is_err()); assert!(matches!( store.create_space("hidden-pw"), Err(Error::PasswordUnavailable) )); assert!(matches!(store.create_space("main-pw"), Err(Error::PasswordUnavailable))); drop(store); // The main password shows nothing of it. assert!(matches!(Store::open(&path, "hidden-pw"), Err(Error::BadPassword))); let mut store = Store::open(&path, "main-pw").unwrap(); assert_eq!(store.spaces(), vec![MAIN]); let names = |st: &State| st.contacts.iter().map(|c| c.name.clone()).collect::>(); assert_eq!(names(&store.load(MAIN).unwrap()), vec!["visible"]); assert!(store.full_history(MAIN, &secret.id).is_err()); // Unlocking: wrong password, main password, hidden password. assert_eq!(store.unlock("not-a-password").unwrap(), None); assert_eq!(store.unlock("main-pw").unwrap(), Some(MAIN)); let h = store.unlock("hidden-pw").unwrap().unwrap(); assert_eq!(store.unlock("hidden-pw").unwrap(), Some(h)); assert_eq!(names(&store.load(h).unwrap()), vec!["secret", "secret2"]); assert_eq!( texts(&store.full_history(h, &secret.id).unwrap()), vec!["for your eyes only"] ); // Changing the hidden password. store.change_password(h, "other-pw").unwrap(); drop(store); let mut store = Store::open(&path, "main-pw").unwrap(); assert_eq!(store.unlock("hidden-pw").unwrap(), None); let h = store.unlock("other-pw").unwrap().unwrap(); assert_eq!(names(&store.load(h).unwrap()), vec!["secret", "secret2"]); let _ = std::fs::remove_dir_all(dir); } #[test] fn an_attacker_without_password_sees_only_uniform_blocks() { let (path, dir) = tmp(); let s = server(); let bob = contact("bob", &s); let mut store = Store::create(&path, "alice-the-nickname", "pw", KDF, false).unwrap(); let state = State { nickname: "alice-the-nickname".into(), servers: vec![s], contacts: vec![bob.clone()], ..State::default() }; let batch = Batch { history: vec![text(&bob, "very secret text one"), text(&bob, "very secret text two")], files: vec![], }; store.save(MAIN, &state, batch).unwrap(); let h = store.create_space("hidden").unwrap(); store.save(h, &State::default(), Batch::default()).unwrap(); drop(store); // Only two tables: public parameters and blocks. let conn = rusqlite::Connection::open(&path).unwrap(); let mut stmt = conn .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name") .unwrap(); let tables: Vec = stmt .query_map([], |r| r.get(0)) .unwrap() .collect::>() .unwrap(); drop(stmt); drop(conn); assert_eq!(tables, vec!["blocks", "meta"]); let all = blocks(&path); assert!(all.len() > 128, "random filler is always present"); assert!(all.iter().all(|(id, data)| id.len() == 32 && data.len() == BLOCK_SIZE)); // No WAL left behind, and nothing readable in the file. let wal = std::fs::metadata(format!("{}-wal", path.display())).map_or(0, |m| m.len()); assert_eq!(wal, 0); let raw = std::fs::read(&path).unwrap(); for needle in ["alice-the-nickname", "very secret", "bob", "http://s"] { assert!( !raw.windows(needle.len()).any(|w| w == needle.as_bytes()), "{needle:?} found in clear" ); } // Swapping two blocks breaks authentication (contents are bound to their id). { let c = rusqlite::Connection::open(&path).unwrap(); let mut ids: Vec<&Vec> = all.keys().collect(); ids.sort(); for (a, b) in ids.iter().zip(ids.iter().skip(1)) { c.execute( "UPDATE blocks SET data = ?1 WHERE id = ?2", rusqlite::params![all[*b], a.as_slice()], ) .unwrap(); } } assert!(Store::open(&path, "pw").is_err()); let _ = std::fs::remove_dir_all(dir); } #[test] fn rewrites_move_objects_and_wipe_old_blocks() { let (path, dir) = tmp(); let s = server(); let bob = contact("bob", &s); let mut store = Store::create(&path, "alice", "pw", KDF, false).unwrap(); let mut state = store.load(MAIN).unwrap(); state.contacts.push(bob.clone()); store.save(MAIN, &state, Batch::default()).unwrap(); // An unchanged save touches very few blocks (root, index, churn, filler). let a = blocks(&path); store.save(MAIN, &state, Batch::default()).unwrap(); let b = blocks(&path); let changed = b.iter().filter(|(id, d)| a.get(*id) != Some(*d)).count(); assert!(changed <= 2 + 2 + 3 + 4, "{changed} blocks changed for a no-op save"); // Appending a message changes blocks at places unrelated to the previous write. store .save( MAIN, &state, Batch { history: vec![text(&bob, "hello")], files: vec![], }, ) .unwrap(); let c = blocks(&path); assert!(c.len() >= b.len(), "blocks are never deleted"); let _ = std::fs::remove_dir_all(dir); } #[test] fn schema_versions_and_foreign_files() { let (path, dir) = tmp(); drop(Store::create(&path, "alice", "pw", KDF, false).unwrap()); { let c = rusqlite::Connection::open(&path).unwrap(); let v: u32 = c.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap(); assert_eq!(v, meow_store::schema::VERSION); c.pragma_update(None, "user_version", 99).unwrap(); } assert!(matches!(Store::open(&path, "pw"), Err(Error::NewerSchema(99)))); let junk = dir.join("junk.mwid2"); std::fs::write(&junk, vec![0x42; 4096]).unwrap(); assert!(matches!(Store::open(&junk, "pw"), Err(Error::Corrupted(_)))); assert!(matches!( Store::open(&dir.join("missing.mwid2"), "pw"), Err(Error::Io(_)) )); let _ = std::fs::remove_dir_all(dir); }