use std::fs; use std::io::Read; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use ed25519_dalek::SigningKey; use rand::RngCore; use rand::rngs::OsRng; use rusqlite::{Connection, OptionalExtension, params}; use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; use zeroize::Zeroizing; pub type Result = std::result::Result; #[derive(Debug)] pub struct Error(String); impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl std::error::Error for Error {} impl From for Error { fn from(e: rusqlite::Error) -> Self { Self(e.to_string()) } } impl From for Error { fn from(e: std::io::Error) -> Self { Self(e.to_string()) } } impl From for Error { fn from(e: String) -> Self { Self(e) } } /// The store error is a message and nothing else, and the rest of the crate /// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the /// outbox boundary — no per-call `map_err`. impl From for String { fn from(e: Error) -> Self { e.0 } } pub struct Store { conn: Connection, msg_key: Zeroizing<[u8; 32]>, } /// The identity row. Secret halves wipe when this is dropped. pub struct SelfIdentity { pub identity_sk: Zeroizing>, pub identity_pk: Vec, pub onion: String, pub prekey_sk: Zeroizing>, pub prekey_pk: Vec, } pub struct Friend { pub pubkey: Vec, pub fingerprint: String, pub petname: Option, pub onion: String, pub last_connect_ok: bool, pub prekey: Vec, } pub struct FriendProfile { pub display_name: String, pub bio: String, pub xmr_addr: String, pub updated_at: i64, } #[derive(Debug)] pub struct Message { /// `messages.id` row id. The outbox row for a send carries the same /// `message_id`, so the UI can join exactly instead of matching bodies. pub id: i64, pub dir: String, pub plaintext: Vec, } #[derive(Debug)] pub struct Payment { pub id: i64, pub dir: String, pub kind: String, pub amount_atomic: String, pub address: String, pub memo: String, pub txid: Option, pub verified: bool, pub created_at: i64, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum OutboxStatus { Queued, Sending, Sent, /// Terminal: transport or protocol failure that will not be retried. Failed(String), } impl OutboxStatus { pub fn is_terminal(&self) -> bool { matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_)) } /// Column encoding for the `outbox.status` CHECK constraint. pub fn as_db_str(&self) -> &'static str { match self { OutboxStatus::Queued => "queued", OutboxStatus::Sending => "sending", OutboxStatus::Sent => "sent", OutboxStatus::Failed(_) => "failed", } } pub fn from_db(status: &str, last_error: Option<&str>) -> Self { match status { "sending" => OutboxStatus::Sending, "sent" => OutboxStatus::Sent, "failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()), _ => OutboxStatus::Queued, } } } impl std::fmt::Display for OutboxStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { OutboxStatus::Failed(why) => write!(f, "failed: {why}"), other => f.write_str(other.as_db_str()), } } } /// One queued chat send. The body is not copied: it lives in the `messages` /// row the outbox row points at, under that row's own AEAD. #[derive(Debug, Clone)] pub struct OutboxEntry { pub id: i64, pub friend_pk: Vec, pub message_id: i64, pub body: Vec, pub attempts: u32, pub next_attempt_at: i64, pub created_at: i64, pub status: OutboxStatus, pub last_error: Option, } pub struct PaymentWrite<'a> { pub dir: &'a str, pub kind: &'a str, pub amount_atomic: &'a str, pub address: &'a str, pub memo: &'a str, pub txid: Option<&'a str>, pub verified: bool, } impl Store { pub fn open() -> Result { Self::open_at(&home_dir()?) } pub fn home_dir() -> Result { home_dir() } pub fn open_at(home: &Path) -> Result { let passphrase = passphrase_from_env()?; Self::open_at_with_passphrase(home, passphrase.as_str()) } pub fn open_at_with_passphrase(home: &Path, passphrase: &str) -> Result { if passphrase.is_empty() { return Err(Error("empty passphrase".into())); } mkdir_700(home)?; mkdir_700(&home.join("arti"))?; mkdir_700(&home.join("cache"))?; let db_path = home.join("onionwire.db"); let conn = open_store_db(home, &db_path, passphrase)?; let journal: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?; if !journal.eq_ignore_ascii_case("wal") { return Err(Error(format!("journal_mode WAL failed: {journal}"))); } // Overwrite freed pages on DELETE. Flash wear-leveling can still keep copies; // this is not a forensic / SSD crypto-shred. conn.pragma_update(None, "secure_delete", "ON")?; conn.execute_batch( " PRAGMA foreign_keys = ON; CREATE TABLE IF NOT EXISTS friends ( id INTEGER PRIMARY KEY, pubkey BLOB NOT NULL UNIQUE, fingerprint TEXT NOT NULL, petname TEXT, onion TEXT NOT NULL, onion_updated_at INTEGER NOT NULL, added_at INTEGER NOT NULL, last_connect_ok INTEGER NOT NULL DEFAULT 1, prekey BLOB NOT NULL DEFAULT x'' ); CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), dir TEXT NOT NULL CHECK(dir IN ('in','out')), plaintext BLOB NOT NULL, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS self ( id INTEGER PRIMARY KEY CHECK (id = 1), identity_sk BLOB NOT NULL, identity_pk BLOB NOT NULL, onion TEXT NOT NULL, onion_rotated_at INTEGER NOT NULL, prekey_sk BLOB NOT NULL, prekey_pk BLOB NOT NULL, hs_nickname TEXT NOT NULL DEFAULT 'ow0' ); CREATE TABLE IF NOT EXISTS self_profile ( id INTEGER PRIMARY KEY CHECK (id = 1), display_name TEXT NOT NULL DEFAULT '', bio TEXT NOT NULL DEFAULT '', xmr_addr TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS friend_profiles ( pubkey BLOB PRIMARY KEY, display_name TEXT NOT NULL, bio TEXT NOT NULL, xmr_addr TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS store_meta ( id INTEGER PRIMARY KEY CHECK (id = 1), kdf_salt BLOB NOT NULL, wrapped_key BLOB NOT NULL ); CREATE TABLE IF NOT EXISTS payments ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), dir TEXT NOT NULL CHECK(dir IN ('in','out')), kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt')), amount_atomic TEXT NOT NULL, address TEXT NOT NULL, memo TEXT NOT NULL DEFAULT '', txid TEXT, verified INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS outbox ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), message_id INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL, status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')), last_error TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at); INSERT OR IGNORE INTO self_profile (id) VALUES (1); ", )?; let check: String = conn.query_row("PRAGMA integrity_check", [], |row| row.get(0))?; if check != "ok" { return Err(Error(format!("integrity_check: {check}"))); } let mut store = Self { conn, msg_key: Zeroizing::new([0u8; 32]), }; store.migrate()?; store.ensure_self()?; store.unlock_messages(passphrase)?; Ok(store) } pub fn journal_mode(&self) -> Result { self.conn .query_row("PRAGMA journal_mode", [], |row| row.get(0)) .map_err(Into::into) } pub fn replace_identity_keys( &self, identity_sk: &[u8], identity_pk: &[u8], prekey_sk: &[u8], prekey_pk: &[u8], ) -> Result<()> { if identity_sk.len() != 32 || identity_pk.len() != 32 || prekey_sk.len() != 32 || prekey_pk.len() != 32 { return Err(Error("identity key length".into())); } self.conn.execute( "UPDATE self SET identity_sk = ?1, identity_pk = ?2, prekey_sk = ?3, prekey_pk = ?4 WHERE id = 1", params![identity_sk, identity_pk, prekey_sk, prekey_pk], )?; Ok(()) } fn migrate(&self) -> Result<()> { self.add_column_if_missing( "friends", "last_connect_ok", "ALTER TABLE friends ADD COLUMN last_connect_ok INTEGER NOT NULL DEFAULT 1", )?; self.add_column_if_missing( "friends", "prekey", "ALTER TABLE friends ADD COLUMN prekey BLOB NOT NULL DEFAULT x''", )?; self.add_column_if_missing( "self", "prekey_sk", "ALTER TABLE self ADD COLUMN prekey_sk BLOB NOT NULL DEFAULT x''", )?; self.add_column_if_missing( "self", "prekey_pk", "ALTER TABLE self ADD COLUMN prekey_pk BLOB NOT NULL DEFAULT x''", )?; self.add_column_if_missing( "self", "hs_nickname", "ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'", )?; Ok(()) } fn unlock_messages(&mut self, passphrase: &str) -> Result<()> { let row: Option<(Vec, Vec)> = self .conn .query_row( "SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1", [], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?; match row { Some((salt, wrapped)) => { let wrap_key = crate::backup::kdf(passphrase, &salt)?; // The unwrapped data key lands in a Zeroizing buffer immediately. let raw = Zeroizing::new( crate::backup::aead_decrypt(&wrap_key, &wrapped, b"") .map_err(|_| Error("wrong passphrase".into()))?, ); if raw.len() != 32 { return Err(Error("wrapped message key length".into())); } self.msg_key.copy_from_slice(&raw); self.rewrap_empty_aad_messages()?; Ok(()) } None => { let mut data_key = Zeroizing::new([0u8; 32]); OsRng.fill_bytes(&mut data_key[..]); let mut salt = [0u8; 16]; OsRng.fill_bytes(&mut salt); let wrap_key = crate::backup::kdf(passphrase, &salt)?; let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?; self.conn.execute( "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", params![salt.as_slice(), wrapped], )?; self.msg_key = data_key; self.reencrypt_legacy_messages()?; Ok(()) } } } fn reencrypt_legacy_messages(&self) -> Result<()> { let mut stmt = self .conn .prepare("SELECT id, friend_id, dir, plaintext FROM messages")?; let rows: Vec<(i64, i64, String, Vec)> = stmt .query_map([], |row| { Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)) })? .collect::>()?; drop(stmt); if rows.is_empty() { return Ok(()); } let tx = self.conn.unchecked_transaction()?; for (id, friend_id, dir, plain) in rows { let aad = message_aad(friend_id, &dir, id); let blob = crate::backup::aead_encrypt(&self.msg_key, &plain, &aad)?; tx.execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![blob, id], )?; } tx.commit()?; let _ = self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); Ok(()) } /// One-shot: empty-AAD v0.2 blobs → row-bound AAD. list_messages never falls back. fn rewrap_empty_aad_messages(&self) -> Result<()> { let mut stmt = self .conn .prepare("SELECT id, friend_id, dir, plaintext FROM messages")?; let rows: Vec<(i64, i64, String, Vec)> = stmt .query_map([], |row| { Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)) })? .collect::>()?; drop(stmt); let mut updates = Vec::new(); for (id, friend_id, dir, blob) in rows { let aad = message_aad(friend_id, &dir, id); if crate::backup::aead_decrypt(&self.msg_key, &blob, &aad).is_ok() { continue; } if let Ok(pt) = crate::backup::aead_decrypt(&self.msg_key, &blob, b"") { let new_blob = crate::backup::aead_encrypt(&self.msg_key, &pt, &aad)?; updates.push((id, new_blob)); } } if updates.is_empty() { return Ok(()); } let tx = self.conn.unchecked_transaction()?; for (id, blob) in updates { tx.execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![blob, id], )?; } tx.commit()?; let _ = self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); Ok(()) } fn add_column_if_missing(&self, table: &str, column: &str, ddl: &str) -> Result<()> { let sql = format!("SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{column}'"); let has: i64 = self.conn.query_row(&sql, [], |row| row.get(0))?; if has == 0 { self.conn.execute(ddl, [])?; } Ok(()) } fn ensure_self(&self) -> Result<()> { let exists: i64 = self.conn .query_row("SELECT COUNT(*) FROM self WHERE id = 1", [], |row| { row.get(0) })?; if exists == 0 { let signing = SigningKey::generate(&mut OsRng); let sk = Zeroizing::new(signing.to_bytes().to_vec()); let pk = signing.verifying_key().to_bytes().to_vec(); let (psk, ppk) = gen_prekey(); self.conn.execute( "INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname) VALUES (1, ?1, ?2, '', 0, ?3, ?4, 'ow0')", params![&sk[..], pk, &psk[..], ppk], )?; } else { let empty: i64 = self.conn.query_row( "SELECT CASE WHEN length(prekey_sk) = 32 AND length(prekey_pk) = 32 THEN 0 ELSE 1 END FROM self WHERE id = 1", [], |row| row.get(0), )?; if empty != 0 { let (psk, ppk) = gen_prekey(); self.conn.execute( "UPDATE self SET prekey_sk = ?1, prekey_pk = ?2 WHERE id = 1", params![&psk[..], ppk], )?; } } Ok(()) } pub fn self_identity(&self) -> Result { self.conn .query_row( "SELECT identity_sk, identity_pk, onion, prekey_sk, prekey_pk FROM self WHERE id = 1", [], |row| { Ok(SelfIdentity { identity_sk: Zeroizing::new(row.get(0)?), identity_pk: row.get(1)?, onion: row.get(2)?, prekey_sk: Zeroizing::new(row.get(3)?), prekey_pk: row.get(4)?, }) }, ) .map_err(Into::into) } pub fn friend_count(&self) -> Result { self.conn .query_row("SELECT COUNT(*) FROM friends", [], |row| row.get(0)) .map_err(Into::into) } /// Display fingerprint of our own identity key (identity = pubkey). pub fn self_fingerprint(&self) -> Result { Ok(fingerprint(&self.self_identity()?.identity_pk)) } /// Local petname only. Never part of the wire protocol. pub fn set_petname(&self, pubkey: &[u8], petname: Option<&str>) -> Result<()> { let n = self.conn.execute( "UPDATE friends SET petname = ?1 WHERE pubkey = ?2", params![petname, pubkey], )?; if n == 0 { return Err(Error("friend not found".into())); } Ok(()) } pub fn upsert_friend(&self, pubkey: &[u8], onion: &str, petname: Option<&str>) -> Result<()> { let now = unix_now(); let fp = fingerprint(pubkey); self.conn.execute( "INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at) VALUES (?1, ?2, ?3, ?4, ?5, ?5) ON CONFLICT(pubkey) DO UPDATE SET onion = excluded.onion, onion_updated_at = excluded.onion_updated_at, petname = COALESCE(excluded.petname, friends.petname)", params![pubkey, fp, petname, onion, now], )?; Ok(()) } pub fn get_friend(&self, pubkey: &[u8]) -> Result> { self.conn .query_row( "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE pubkey = ?1", params![pubkey], friend_from_row, ) .optional() .map_err(Into::into) } /// Locator → friend. Onions are not unique in the schema (a stale row can /// hold a rotated address), so the first match wins; the outbox uses this /// only to pick which queue to flush early. pub fn friend_by_onion(&self, onion: &str) -> Result> { self.conn .query_row( "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1", params![onion], friend_from_row, ) .optional() .map_err(Into::into) } pub fn list_friends(&self) -> Result> { let mut stmt = self.conn.prepare( "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends ORDER BY COALESCE(petname, fingerprint) COLLATE NOCASE", )?; let rows = stmt.query_map([], friend_from_row)?; let mut out = Vec::new(); for row in rows { out.push(row?); } Ok(out) } pub fn hs_nickname(&self) -> Result { self.conn .query_row("SELECT hs_nickname FROM self WHERE id = 1", [], |row| { row.get(0) }) .map_err(Into::into) } pub fn set_hs_nickname(&self, nickname: &str) -> Result<()> { self.conn.execute( "UPDATE self SET hs_nickname = ?1 WHERE id = 1", params![nickname], )?; Ok(()) } pub fn set_onion(&self, onion: &str) -> Result<()> { let now = unix_now(); self.conn.execute( "UPDATE self SET onion = ?1, onion_rotated_at = ?2 WHERE id = 1", params![onion, now], )?; Ok(()) } /// Apply a signed locator update. Bad sig / stale ts / unknown friend → no change. pub fn apply_loc(&self, pubkey: &[u8], onion: &str, ts: i64, sig: &[u8]) -> Result { let loc = crate::loc::Loc { onion: onion.to_string(), ts, sig: sig.to_vec(), }; if !crate::loc::verify(pubkey, &loc) { return Ok(false); } let Some(updated_at) = self .conn .query_row( "SELECT onion_updated_at FROM friends WHERE pubkey = ?1", params![pubkey], |row| row.get::<_, i64>(0), ) .optional()? else { return Ok(false); }; if ts <= updated_at { return Ok(false); } let n = self.conn.execute( "UPDATE friends SET onion = ?1, onion_updated_at = ?2 WHERE pubkey = ?3", params![onion, ts, pubkey], )?; Ok(n > 0) } pub fn set_self_profile(&self, display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> { crate::profile::validate(display_name, bio, xmr_addr).map_err(|e| Error(e.to_string()))?; let prev: i64 = self.conn.query_row( "SELECT updated_at FROM self_profile WHERE id = 1", [], |row| row.get(0), )?; let now = unix_now().max(prev + 1); self.conn.execute( "UPDATE self_profile SET display_name = ?1, bio = ?2, xmr_addr = ?3, updated_at = ?4 WHERE id = 1", params![display_name, bio, xmr_addr, now], )?; Ok(()) } pub fn self_profile(&self) -> Result { self.conn .query_row( "SELECT display_name, bio, xmr_addr, updated_at FROM self_profile WHERE id = 1", [], profile_from_row, ) .map_err(Into::into) } /// Apply a signed profile. Unknown friend / bad sig / stale ts → no change, no insert. pub fn apply_profile(&self, pubkey: &[u8], prf: &crate::profile::Profile) -> Result { if !crate::profile::verify(pubkey, prf) { return Ok(false); } let exists: i64 = self.conn.query_row( "SELECT COUNT(*) FROM friends WHERE pubkey = ?1", params![pubkey], |row| row.get(0), )?; if exists == 0 { return Ok(false); } let prev: Option = self .conn .query_row( "SELECT updated_at FROM friend_profiles WHERE pubkey = ?1", params![pubkey], |row| row.get(0), ) .optional()?; if prev.is_some_and(|t| prf.ts <= t) { return Ok(false); } self.conn.execute( "INSERT INTO friend_profiles (pubkey, display_name, bio, xmr_addr, updated_at) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(pubkey) DO UPDATE SET display_name = excluded.display_name, bio = excluded.bio, xmr_addr = excluded.xmr_addr, updated_at = excluded.updated_at", params![pubkey, prf.display_name, prf.bio, prf.xmr_addr, prf.ts], )?; Ok(true) } pub fn friend_profile(&self, pubkey: &[u8]) -> Result> { self.conn .query_row( "SELECT display_name, bio, xmr_addr, updated_at FROM friend_profiles WHERE pubkey = ?1", params![pubkey], profile_from_row, ) .optional() .map_err(Into::into) } pub fn set_friend_prekey(&self, pubkey: &[u8], prekey: &[u8]) -> Result<()> { let n = self.conn.execute( "UPDATE friends SET prekey = ?1 WHERE pubkey = ?2", params![prekey, pubkey], )?; if n == 0 { return Err(Error("friend not found".into())); } Ok(()) } pub fn get_friend_by_prekey(&self, prekey: &[u8]) -> Result> { self.conn .query_row( "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE prekey = ?1", params![prekey], friend_from_row, ) .optional() .map_err(Into::into) } pub fn insert_payment(&self, friend_pk: &[u8], p: PaymentWrite<'_>) -> Result { if p.dir != "in" && p.dir != "out" { return Err(Error("dir must be in or out".into())); } if p.kind != "invoice" && p.kind != "receipt" { return Err(Error("kind must be invoice or receipt".into())); } crate::pay::parse_atomic(p.amount_atomic).map_err(|e| Error(e.to_string()))?; crate::pay::check_address(p.address).map_err(|e| Error(e.to_string()))?; let friend_id: i64 = self .conn .query_row( "SELECT id FROM friends WHERE pubkey = ?1", params![friend_pk], |row| row.get(0), ) .map_err(|_| Error("friend not found".into()))?; self.conn.execute( "INSERT INTO payments (friend_id, dir, kind, amount_atomic, address, memo, txid, verified, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", params![ friend_id, p.dir, p.kind, p.amount_atomic, p.address, p.memo, p.txid, i64::from(p.verified), unix_now() ], )?; Ok(self.conn.last_insert_rowid()) } pub fn list_payments(&self, friend_pk: &[u8]) -> Result> { let mut stmt = self.conn.prepare( "SELECT p.id, p.dir, p.kind, p.amount_atomic, p.address, p.memo, p.txid, p.verified, p.created_at FROM payments p JOIN friends f ON f.id = p.friend_id WHERE f.pubkey = ?1 ORDER BY p.id", )?; let rows = stmt.query_map(params![friend_pk], payment_from_row)?; let mut out = Vec::new(); for row in rows { out.push(row?); } Ok(out) } pub fn mark_verified(&self, id: i64) -> Result { let n = self.conn.execute( "UPDATE payments SET verified = 1 WHERE id = ?1", params![id], )?; Ok(n > 0) } pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> { self.append_message_id(friend_pk, dir, plaintext).map(|_| ()) } /// Same as `append_message`, returning the row id so an outbox row can /// point at the body instead of storing a second copy. pub fn append_message_id( &self, friend_pk: &[u8], dir: &str, plaintext: &[u8], ) -> Result { if dir != "in" && dir != "out" { return Err(Error("dir must be in or out".into())); } let friend_id: i64 = self .conn .query_row( "SELECT id FROM friends WHERE pubkey = ?1", params![friend_pk], |row| row.get(0), ) .map_err(|_| Error("friend not found".into()))?; let tx = self.conn.unchecked_transaction()?; tx.execute( "INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (?1, ?2, x'', ?3)", params![friend_id, dir, unix_now()], )?; let row_id = tx.last_insert_rowid(); let aad = message_aad(friend_id, dir, row_id); let blob = crate::backup::aead_encrypt(&self.msg_key, plaintext, &aad)?; tx.execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![blob, row_id], )?; tx.commit()?; Ok(row_id) } pub fn list_messages(&self, friend_pk: &[u8]) -> Result> { let mut stmt = self.conn.prepare( "SELECT m.id, m.friend_id, m.dir, m.plaintext FROM messages m JOIN friends f ON f.id = m.friend_id WHERE f.pubkey = ?1 ORDER BY m.id", )?; let rows = stmt.query_map(params![friend_pk], |row| { Ok(( row.get::<_, i64>(0)?, row.get::<_, i64>(1)?, row.get::<_, String>(2)?, row.get::<_, Vec>(3)?, )) })?; let mut out = Vec::new(); for row in rows { let (id, friend_id, dir, blob) = row?; let aad = message_aad(friend_id, &dir, id); let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) .map_err(|_| Error("message decrypt failed".into()))?; out.push(Message { id, dir, plaintext, }); } Ok(out) } /// Queue one already-stored chat message for retry. `next_attempt_at` is an /// absolute unix second; `now` is used for created_at/updated_at so the /// caller and the row agree on the clock. pub fn enqueue_outbox( &self, friend_pk: &[u8], message_id: i64, attempts: u32, next_attempt_at: i64, last_error: &str, now: i64, ) -> Result { let friend_id: i64 = self .conn .query_row( "SELECT id FROM friends WHERE pubkey = ?1", params![friend_pk], |row| row.get(0), ) .map_err(|_| Error("friend not found".into()))?; self.conn.execute( "INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)", params![friend_id, message_id, attempts, next_attempt_at, last_error, now], )?; Ok(self.conn.last_insert_rowid()) } /// Rows whose backoff has elapsed: the timer trigger for the worker. pub fn due_outbox(&self, now: i64, limit: i64) -> Result> { self.outbox_query( &format!( "{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1 ORDER BY o.next_attempt_at, o.id LIMIT ?2" ), params![now, limit], ) } /// Unscheduleable rows for one friend (queued or mid-attempt): the /// "we just heard from this peer" trigger, which ignores the backoff. pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result> { self.outbox_query( &format!( "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending') ORDER BY o.id" ), params![friend_pk], ) } /// Every row the worker may still try: the unlock/foreground trigger. pub fn all_pending_outbox(&self, limit: i64) -> Result> { self.outbox_query( &format!( "{OUTBOX_SELECT} WHERE o.status IN ('queued','sending') ORDER BY o.next_attempt_at, o.id LIMIT ?1" ), params![limit], ) } /// Pending and failed rows for one friend — what a UI shows as not-yet-sent. /// Delivered rows are deleted, so absence means "sent". pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result> { self.outbox_query( &format!( "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed') ORDER BY o.id" ), params![friend_pk], ) } pub fn outbox_status_of_message(&self, message_id: i64) -> Result> { let row: Option<(String, Option)> = self .conn .query_row( "SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1", params![message_id], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?; Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref()))) } pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> { self.conn.execute( "UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2", params![now, id], )?; Ok(()) } /// Delivered. The row is dropped — the chat history is the record, and a /// per-message status table would grow without bound. pub fn mark_outbox_sent(&self, id: i64) -> Result<()> { self.conn .execute("DELETE FROM outbox WHERE id = ?1", params![id])?; Ok(()) } pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> { self.conn.execute( "UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3", params![why, now, id], )?; Ok(()) } pub fn mark_outbox_retry( &self, id: i64, attempts: u32, next_attempt_at: i64, now: i64, why: &str, ) -> Result<()> { self.conn.execute( "UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5", params![attempts, next_attempt_at, why, now, id], )?; Ok(()) } /// A row left in 'sending' means we died mid-attempt. Requeue on unlock. pub fn reset_sending_outbox(&self) -> Result { let n = self.conn.execute( "UPDATE outbox SET status = 'queued' WHERE status = 'sending'", [], )?; Ok(n) } fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { let mut stmt = self.conn.prepare(sql)?; let rows = stmt.query_map(args, |row| { Ok(( row.get::<_, i64>(0)?, row.get::<_, Vec>(1)?, row.get::<_, i64>(2)?, row.get::<_, i64>(3)?, row.get::<_, i64>(4)?, row.get::<_, String>(5)?, row.get::<_, Option>(6)?, row.get::<_, i64>(7)?, row.get::<_, i64>(8)?, row.get::<_, String>(9)?, row.get::<_, Vec>(10)?, )) })?; let mut out = Vec::new(); for row in rows { let ( id, friend_pk, message_id, attempts, next_attempt_at, status, last_error, created_at, m_friend_id, dir, blob, ) = row?; let aad = message_aad(m_friend_id, &dir, message_id); let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) .map_err(|_| Error("outbox body decrypt failed".into()))?; out.push(OutboxEntry { id, friend_pk, message_id, body, attempts: attempts as u32, next_attempt_at, created_at, status: OutboxStatus::from_db(&status, last_error.as_deref()), last_error, }); } Ok(out) } /// Fold the WAL into the main db file and truncate it. /// /// Runs on this store's own keyed connection: a second, unkeyed connection /// cannot even read a SQLCipher store (`SQLITE_NOTADB`), so the checkpoint /// has to happen here, not from `node.rs`. /// /// Best effort on purpose: WAL replay on open recovers everything committed, /// so this is about leaving less to replay (and less on disk) if the process /// is killed right after teardown — not about correctness. pub fn checkpoint_wal(&self) -> Result<()> { let (busy, log, checkpointed): (i64, i64, i64) = self.conn .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { Ok((row.get(0)?, row.get(1)?, row.get(2)?)) })?; if busy != 0 { // Another connection is reading/writing: pages are still safe in the // WAL, they just were not moved this time. return Err(Error(format!( "busy ({checkpointed}/{log} pages moved, another connection active)" ))); } Ok(()) } /// Drop chat + payments history. Identity + friends stay. /// Not a forensic erase: SSD wear-leveling can keep copies. pub fn wipe_messages(&self) -> Result<()> { self.conn.execute("DELETE FROM outbox", [])?; self.conn.execute( "UPDATE messages SET plaintext = zeroblob(length(plaintext))", [], )?; self.conn.execute("DELETE FROM messages", [])?; self.conn.execute("DELETE FROM payments", [])?; self.conn.execute_batch("VACUUM")?; self.checkpoint_wal()?; Ok(()) } /// Delete the data dir. Next `open_at` is a new identity. Caller must drop Store first. pub fn wipe_all(home: &Path) -> Result<()> { if home.exists() { fs::remove_dir_all(home)?; } Ok(()) } } fn payment_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { Ok(Payment { id: row.get(0)?, dir: row.get(1)?, kind: row.get(2)?, amount_atomic: row.get(3)?, address: row.get(4)?, memo: row.get(5)?, txid: row.get(6)?, verified: row.get::<_, i64>(7)? != 0, created_at: row.get(8)?, }) } fn profile_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { Ok(FriendProfile { display_name: row.get(0)?, bio: row.get(1)?, xmr_addr: row.get(2)?, updated_at: row.get(3)?, }) } fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { Ok(Friend { pubkey: row.get(0)?, fingerprint: row.get(1)?, petname: row.get(2)?, onion: row.get(3)?, last_connect_ok: row.get::<_, i64>(4)? != 0, prekey: row.get(5)?, }) } fn gen_prekey() -> (Zeroizing>, Vec) { let sk = StaticSecret::random_from_rng(OsRng); let pk = X25519Public::from(&sk); (Zeroizing::new(sk.to_bytes().to_vec()), pk.to_bytes().to_vec()) } /// Per-install KDF salt for the whole-database key. Not secret (a salt never /// is); kept in the data dir so the db key never has to live inside the db it /// opens. const SALT_FILE: &str = "store_salt"; const SQLITE_HEADER: &[u8] = b"SQLite format 3\0"; enum DbState { Missing, Empty, Plaintext, Encrypted, } fn db_state(path: &Path) -> Result { let meta = match fs::metadata(path) { Ok(m) => m, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(DbState::Missing), Err(e) => return Err(e.into()), }; if meta.len() == 0 { return Ok(DbState::Empty); } let mut head = [0u8; 16]; let mut f = fs::File::open(path)?; match f.read_exact(&mut head) { Ok(()) if head.as_slice() == SQLITE_HEADER => Ok(DbState::Plaintext), Ok(()) => Ok(DbState::Encrypted), Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(DbState::Encrypted), Err(e) => Err(e.into()), } } fn read_salt(path: &Path) -> Result> { match fs::read(path) { Ok(b) if b.len() == 16 => Ok(Some(b.try_into().expect("len checked"))), Ok(b) => Err(Error(format!("{SALT_FILE} has {} bytes, want 16", b.len()))), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e.into()), } } fn write_salt(path: &Path, salt: &[u8; 16]) -> Result<()> { fs::write(path, salt)?; let mut perms = fs::metadata(path)?.permissions(); perms.set_mode(0o600); fs::set_permissions(path, perms)?; Ok(()) } fn random_salt() -> [u8; 16] { let mut salt = [0u8; 16]; OsRng.fill_bytes(&mut salt); salt } /// Opens the store, creating it encrypted and upgrading a v0.2.1 plaintext /// file in place. Any failure before the swap leaves the old file untouched. fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result { let salt_path = home.join(SALT_FILE); let mut salt = read_salt(&salt_path)?; match db_state(db_path)? { DbState::Plaintext => { let conn = Connection::open(db_path)?; let ok = wrapped_key_opens(&conn, passphrase)?; drop(conn); if !ok { return Err(Error("wrong passphrase".into())); } let s = salt.unwrap_or_else(random_salt); let key = crate::backup::kdf(passphrase, &s)?; write_salt(&salt_path, &s)?; migrate_plaintext_to_encrypted(db_path, &key, passphrase)?; salt = Some(s); } DbState::Missing | DbState::Empty => { if salt.is_none() { let s = random_salt(); write_salt(&salt_path, &s)?; salt = Some(s); } } DbState::Encrypted => {} } let Some(salt) = salt else { return Err(Error(format!( "{SALT_FILE} is missing next to an encrypted onionwire.db; restore it from \ your backup, or restore the db from backup and re-import" ))); }; let key = crate::backup::kdf(passphrase, &salt)?; open_keyed(db_path, &key) } /// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is /// the key, with no second KDF pass over it. fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result { let conn = Connection::open(db_path)?; conn.execute_batch(pragma_key(key).as_str())?; // A rejected key otherwise logs SQLCipher's internal "hmac check failed" // at ERROR to stderr. A wrong passphrase is a normal user error here. let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE"); // Force a read so a wrong key fails here, not on the first later query. conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| { r.get::<_, i64>(0) }) .map_err(|_| Error("wrong passphrase or corrupt store".into()))?; Ok(conn) } /// SQLCipher's key material as hex inside the pragma text. The `String` holds /// the database key, so it wipes on drop. fn pragma_key(key: &[u8; 32]) -> Zeroizing { Zeroizing::new(format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key))) } /// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh /// store) accepts any passphrase, matching the v0.2.1 behaviour. fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result { let row: Option<(Vec, Vec)> = conn .query_row( "SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1", [], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?; let Some((salt, wrapped)) = row else { return Ok(true); }; let wrap_key = crate::backup::kdf(passphrase, &salt)?; Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok()) } /// Rewrites a plaintext sqlite store as an encrypted one and swaps it in. /// The source file is only replaced after the new file opens, passes /// `integrity_check` and unlocks with this passphrase. fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &str) -> Result<()> { let mut tmp_name = db_path.as_os_str().to_owned(); tmp_name.push(".migrating"); let tmp = PathBuf::from(tmp_name); let _ = fs::remove_file(&tmp); let mode = fs::metadata(db_path)?.permissions().mode() & 0o777; { // Fold the WAL in so the export sees every committed row. let conn = Connection::open(db_path)?; let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); let target = tmp.to_string_lossy().replace('\'', "''"); let attach = Zeroizing::new(format!( "ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";", hex = fingerprint(key) )); conn.execute_batch(attach.as_str())?; conn.execute_batch("SELECT sqlcipher_export('enc');")?; conn.execute_batch("DETACH DATABASE enc;")?; } let verified = (|| -> Result<()> { let conn = open_keyed(&tmp, key)?; let check: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; if check != "ok" { return Err(Error(format!("migration integrity_check: {check}"))); } if !wrapped_key_opens(&conn, passphrase)? { return Err(Error("migrated store failed to unlock".into())); } Ok(()) })(); if let Err(e) = verified { let _ = fs::remove_file(&tmp); return Err(e); } fs::rename(&tmp, db_path)?; let mut perms = fs::metadata(db_path)?.permissions(); perms.set_mode(mode); fs::set_permissions(db_path, perms)?; for suffix in ["-wal", "-shm"] { let mut stale = db_path.as_os_str().to_owned(); stale.push(suffix); let _ = fs::remove_file(PathBuf::from(stale)); } Ok(()) } fn home_dir() -> Result { if let Some(p) = std::env::var_os("ONIONWIRE_HOME") { return Ok(PathBuf::from(p)); } let home = std::env::var_os("HOME").ok_or_else(|| Error("HOME not set".into()))?; Ok(PathBuf::from(home).join(".local/share/onionwire")) } fn passphrase_from_env() -> Result> { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())), Ok(p) => Ok(Zeroizing::new(p)), Err(_) => Err(Error("ONIONWIRE_STORE_PASSPHRASE required".into())), } } /// Env `ONIONWIRE_STORE_PASSPHRASE` if set (non-empty). Otherwise `read_secret` /// (TTY, no echo). Empty values fail closed. The passphrase is wiped on drop. pub fn resolve_store_passphrase( read_secret: impl FnOnce(&str) -> std::io::Result, ) -> Result> { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())), Ok(p) => Ok(Zeroizing::new(p)), Err(_) => { let s = read_secret("onionwire: store passphrase: ")?; let s = s.trim_end_matches(['\n', '\r']).to_string(); if s.is_empty() { Err(Error("empty passphrase".into())) } else { Ok(Zeroizing::new(s)) } } } } fn mkdir_700(path: &Path) -> Result<()> { fs::create_dir_all(path)?; let mut perms = fs::metadata(path)?.permissions(); perms.set_mode(0o700); fs::set_permissions(path, perms)?; Ok(()) } /// Base projection for outbox rows: the body comes from the `messages` row the /// outbox row points at, so it stays under that row's AEAD + AAD. const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \ o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \ FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id"; /// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64 fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec { let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8); aad.extend_from_slice(b"owmsg1"); aad.extend_from_slice(&friend_id.to_le_bytes()); aad.extend_from_slice(dir.as_bytes()); aad.push(0); aad.extend_from_slice(&row_id.to_le_bytes()); aad } fn unix_now() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs() as i64) .unwrap_or(0) } fn fingerprint(pubkey: &[u8]) -> String { pubkey.iter().map(|b| format!("{b:02x}")).collect() } #[cfg(test)] mod at_rest { use super::*; use zeroize::Zeroize; /// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has /// to run on the store's own keyed connection: a second, unkeyed one cannot /// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently /// never happened. #[test] fn checkpoint_wal_truncates_an_encrypted_store_wal() { let dir = tempfile::tempdir().unwrap(); let store = Store::open_at_with_passphrase(dir.path(), "checkpoint-pass").unwrap(); let pk = [3u8; 32]; store.upsert_friend(&pk, "peer.onion", None).unwrap(); for _ in 0..64 { store.append_message(&pk, "out", &[7u8; 512]).unwrap(); } let wal = dir.path().join("onionwire.db-wal"); let before = std::fs::metadata(&wal).expect("wal file").len(); assert!(before > 0, "expected pending WAL frames, got {before}"); store.checkpoint_wal().expect("checkpoint"); let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); // A checkpoint moves pages into the db; it never drops committed data. assert_eq!(store.list_messages(&pk).unwrap().len(), 64); } #[test] fn store_data_key_is_a_zeroizing_wrapper_that_wipes() { let dir = tempfile::tempdir().unwrap(); let mut store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").unwrap(); // Type-level: the field is `Zeroizing<[u8; 32]>`, so its Drop wipes it. let _: &Zeroizing<[u8; 32]> = &store.msg_key; let before = *store.msg_key; assert_ne!(before, [0u8; 32], "store has no data key"); store.msg_key.zeroize(); assert_eq!(*store.msg_key, [0u8; 32], "store data key not wiped"); } #[test] fn swapped_ciphertext_does_not_show_other_friends_body() { let dir = tempfile::tempdir().unwrap(); let store = Store::open_at_with_passphrase(dir.path(), "aad-pass").unwrap(); let alice = [1u8; 32]; let bob = [2u8; 32]; store.upsert_friend(&alice, "a.onion", None).unwrap(); store.upsert_friend(&bob, "b.onion", None).unwrap(); store .append_message(&alice, "out", b"secret-for-alice") .unwrap(); store .append_message(&bob, "out", b"secret-for-bob") .unwrap(); let blobs: Vec<(i64, Vec)> = { let mut stmt = store .conn .prepare("SELECT id, plaintext FROM messages ORDER BY id") .unwrap(); stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))) .unwrap() .collect::>>() .unwrap() }; assert_eq!(blobs.len(), 2); store .conn .execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![&blobs[1].1, blobs[0].0], ) .unwrap(); store .conn .execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![&blobs[0].1, blobs[1].0], ) .unwrap(); if let Ok(msgs) = store.list_messages(&alice) { assert!( msgs.iter() .all(|m| m.plaintext.as_slice() != b"secret-for-bob"), "alice saw bob's body after ciphertext swap" ); } if let Ok(msgs) = store.list_messages(&bob) { assert!( msgs.iter() .all(|m| m.plaintext.as_slice() != b"secret-for-alice"), "bob saw alice's body after ciphertext swap" ); } } #[test] fn empty_aad_rows_rewrap_on_unlock_then_swap_fails() { let dir = tempfile::tempdir().unwrap(); let store = Store::open_at_with_passphrase(dir.path(), "rewrap-pass").unwrap(); let alice = [1u8; 32]; let bob = [2u8; 32]; store.upsert_friend(&alice, "a.onion", None).unwrap(); store.upsert_friend(&bob, "b.onion", None).unwrap(); store .append_message(&alice, "out", b"secret-for-alice") .unwrap(); store .append_message(&bob, "out", b"secret-for-bob") .unwrap(); let ids: Vec = { let mut stmt = store .conn .prepare("SELECT id FROM messages ORDER BY id") .unwrap(); stmt.query_map([], |r| r.get(0)) .unwrap() .collect::>>() .unwrap() }; let a_blob = crate::backup::aead_encrypt(&store.msg_key, b"secret-for-alice", b"").unwrap(); let b_blob = crate::backup::aead_encrypt(&store.msg_key, b"secret-for-bob", b"").unwrap(); store .conn .execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![a_blob, ids[0]], ) .unwrap(); store .conn .execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![b_blob, ids[1]], ) .unwrap(); drop(store); let store = Store::open_at_with_passphrase(dir.path(), "rewrap-pass").unwrap(); assert_eq!( store.list_messages(&alice).unwrap()[0].plaintext, b"secret-for-alice" ); assert_eq!( store.list_messages(&bob).unwrap()[0].plaintext, b"secret-for-bob" ); let blobs: Vec<(i64, Vec)> = { let mut stmt = store .conn .prepare("SELECT id, plaintext FROM messages ORDER BY id") .unwrap(); stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))) .unwrap() .collect::>>() .unwrap() }; store .conn .execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![&blobs[1].1, blobs[0].0], ) .unwrap(); store .conn .execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![&blobs[0].1, blobs[1].0], ) .unwrap(); if let Ok(msgs) = store.list_messages(&alice) { assert!( msgs.iter() .all(|m| m.plaintext.as_slice() != b"secret-for-bob"), "alice saw bob's body after post-rewrap swap" ); } } /// The exact v0.2.1 on-disk layout, hand-built: a plaintext sqlite file with /// the identity row in the clear, a `store_meta` row holding the /// Argon2id-wrapped message key and ChaCha20-Poly1305 message rows bound to /// their row AAD. Pin it here so the migration test cannot drift with the /// production schema. const LEGACY_SCHEMA: &str = " CREATE TABLE friends ( id INTEGER PRIMARY KEY, pubkey BLOB NOT NULL UNIQUE, fingerprint TEXT NOT NULL, petname TEXT, onion TEXT NOT NULL, onion_updated_at INTEGER NOT NULL, added_at INTEGER NOT NULL, last_connect_ok INTEGER NOT NULL DEFAULT 1, prekey BLOB NOT NULL DEFAULT x'' ); CREATE TABLE messages ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), dir TEXT NOT NULL CHECK(dir IN ('in','out')), plaintext BLOB NOT NULL, created_at INTEGER NOT NULL ); CREATE TABLE self ( id INTEGER PRIMARY KEY CHECK (id = 1), identity_sk BLOB NOT NULL, identity_pk BLOB NOT NULL, onion TEXT NOT NULL, onion_rotated_at INTEGER NOT NULL, prekey_sk BLOB NOT NULL, prekey_pk BLOB NOT NULL, hs_nickname TEXT NOT NULL DEFAULT 'ow0' ); CREATE TABLE self_profile ( id INTEGER PRIMARY KEY CHECK (id = 1), display_name TEXT NOT NULL DEFAULT '', bio TEXT NOT NULL DEFAULT '', xmr_addr TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE friend_profiles ( pubkey BLOB PRIMARY KEY, display_name TEXT NOT NULL, bio TEXT NOT NULL, xmr_addr TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL ); CREATE TABLE store_meta ( id INTEGER PRIMARY KEY CHECK (id = 1), kdf_salt BLOB NOT NULL, wrapped_key BLOB NOT NULL ); CREATE TABLE payments ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), dir TEXT NOT NULL CHECK(dir IN ('in','out')), kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt')), amount_atomic TEXT NOT NULL, address TEXT NOT NULL, memo TEXT NOT NULL DEFAULT '', txid TEXT, verified INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL ); INSERT OR IGNORE INTO self_profile (id) VALUES (1); "; const LEGACY_IDENTITY_SK: [u8; 32] = [0x11; 32]; const LEGACY_FRIEND_PK: [u8; 32] = [0x55; 32]; /// Writes a v0.2.1 store at `db_path` with no encryption at all. fn write_legacy_plaintext_store(db_path: &Path, passphrase: &str) { let conn = Connection::open(db_path).unwrap(); conn.execute_batch(LEGACY_SCHEMA).unwrap(); conn.execute( "INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname) VALUES (1, ?1, ?2, 'legacy.onion', 7, ?3, ?4, 'ow0')", params![ LEGACY_IDENTITY_SK.to_vec(), vec![0x22u8; 32], vec![0x33u8; 32], vec![0x44u8; 32] ], ) .unwrap(); conn.execute( "INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at, last_connect_ok, prekey) VALUES (?1, ?2, 'legacy-friend', 'legacy-friend.onion', 7, 7, 1, x'')", params![LEGACY_FRIEND_PK.as_slice(), fingerprint(&LEGACY_FRIEND_PK)], ) .unwrap(); let mut salt = [0u8; 16]; OsRng.fill_bytes(&mut salt); let mut data_key = Zeroizing::new([0u8; 32]); OsRng.fill_bytes(&mut data_key[..]); let wrap = crate::backup::kdf(passphrase, &salt).unwrap(); let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap(); conn.execute( "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", params![salt.as_slice(), wrapped], ) .unwrap(); for (dir, body) in [ ("in", "legacy-body-xyz"), ("out", "legacy-reply-xyz"), ] { conn.execute( "INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)", params![dir], ) .unwrap(); let id = conn.last_insert_rowid(); let blob = crate::backup::aead_encrypt( &data_key, body.as_bytes(), &message_aad(1, dir, id), ) .unwrap(); conn.execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![blob, id], ) .unwrap(); } conn.close().unwrap(); } fn file_has(path: &Path, needle: &[u8]) -> bool { let Ok(bytes) = std::fs::read(path) else { return false; }; bytes.windows(needle.len()).any(|w| w == needle) } #[test] fn plaintext_v0_2_1_store_is_encrypted_in_place_and_keeps_history() { let dir = tempfile::tempdir().unwrap(); let db_path = dir.path().join("onionwire.db"); write_legacy_plaintext_store(&db_path, "legacy-pass"); let raw = std::fs::read(&db_path).unwrap(); assert!( raw.starts_with(b"SQLite format 3\0"), "fixture must be a plaintext sqlite file" ); let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade"); assert_eq!( store.self_identity().unwrap().identity_sk[..], LEGACY_IDENTITY_SK[..] ); let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap(); assert_eq!(msgs.len(), 2, "history must survive the upgrade"); assert_eq!(msgs[0].plaintext, b"legacy-body-xyz"); assert_eq!(msgs[1].plaintext, b"legacy-reply-xyz"); assert_eq!( store.get_friend(&LEGACY_FRIEND_PK).unwrap().unwrap().onion, "legacy-friend.onion" ); drop(store); let enc = std::fs::read(&db_path).unwrap(); assert!( !enc.starts_with(b"SQLite format 3\0"), "db header must be encrypted after the in-place upgrade" ); for (needle, what) in [ (b"legacy-body-xyz".to_vec(), "message body"), (fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"), (LEGACY_IDENTITY_SK.to_vec(), "identity secret"), (b"legacy-friend.onion".to_vec(), "locator"), ] { assert!( !file_has(&db_path, &needle), "upgraded db still contains the {what}" ); } let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("reopen"); assert_eq!(store.list_messages(&LEGACY_FRIEND_PK).unwrap().len(), 2); } #[test] fn legacy_plaintext_store_with_wrong_passphrase_is_left_untouched() { let dir = tempfile::tempdir().unwrap(); let db_path = dir.path().join("onionwire.db"); write_legacy_plaintext_store(&db_path, "legacy-pass"); let before = std::fs::read(&db_path).unwrap(); let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") { Ok(_) => panic!("wrong passphrase must not open a legacy store"), Err(e) => e, }; assert!( err.to_string().to_ascii_lowercase().contains("passphrase"), "got {err}" ); assert_eq!( std::fs::read(&db_path).unwrap(), before, "a failed legacy upgrade must not modify the plaintext db" ); assert!( !dir.path().join("store_salt").exists(), "a failed legacy upgrade must not leave a salt file behind" ); } #[test] fn first_unlock_reencrypts_legacy_plaintext_rows() { let dir = tempfile::tempdir().unwrap(); let store = Store::open_at_with_passphrase(dir.path(), "migrate-pass").unwrap(); let pk = [1u8; 32]; store.upsert_friend(&pk, "a.onion", None).unwrap(); store .append_message(&pk, "out", b"legacy-plain-xyz") .unwrap(); store.conn.execute("DELETE FROM store_meta", []).unwrap(); store .conn .execute( "UPDATE messages SET plaintext = ?1", params![b"legacy-plain-xyz".as_slice()], ) .unwrap(); let _ = store.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); drop(store); let store = Store::open_at_with_passphrase(dir.path(), "migrate-pass").unwrap(); let msgs = store.list_messages(&pk).unwrap(); assert_eq!(msgs[0].plaintext, b"legacy-plain-xyz"); drop(store); let needle = b"legacy-plain-xyz"; for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] { let path = dir.path().join(name); let Ok(bytes) = std::fs::read(&path) else { continue; }; assert!( !bytes.windows(needle.len()).any(|w| w == needle), "{name} still contains legacy plaintext" ); } } }