diff --git a/Cargo.lock b/Cargo.lock index ba80504..6bdc0af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -537,6 +537,17 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + [[package]] name = "chacha20" version = "0.10.1" @@ -548,6 +559,19 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.45" @@ -569,6 +593,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common 0.1.7", "inout", + "zeroize", ] [[package]] @@ -945,6 +970,8 @@ version = "0.1.0" dependencies = [ "argon2", "async-trait", + "base64 0.22.1", + "chacha20poly1305", "rand 0.10.2", "serde", "serde_json", @@ -2711,6 +2738,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "polyval" version = "0.6.2" @@ -2929,7 +2967,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" dependencies = [ - "chacha20", + "chacha20 0.10.1", "getrandom 0.4.3", "rand_core 0.10.1", ] diff --git a/Cargo.toml b/Cargo.toml index 310fa56..4df1bba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,8 @@ argon2 = "0.6.0-rc.8" rand = "0.10.2" sha2 = "0.11.0" subtle = "2.6.1" +chacha20poly1305 = "0.10.1" +base64 = "0.22.1" [profile.release] codegen-units = 1 diff --git a/crates/dizey-core/Cargo.toml b/crates/dizey-core/Cargo.toml index 9f21eae..10c2d24 100644 --- a/crates/dizey-core/Cargo.toml +++ b/crates/dizey-core/Cargo.toml @@ -14,6 +14,8 @@ default = ["server"] server = [ "dep:argon2", "dep:async-trait", + "dep:base64", + "dep:chacha20poly1305", "dep:rand", "dep:sha2", "dep:subtle", @@ -24,6 +26,8 @@ server = [ [dependencies] argon2 = { workspace = true, optional = true } async-trait = { version = "0.1.92", optional = true } +base64 = { workspace = true, optional = true } +chacha20poly1305 = { workspace = true, optional = true } rand = { workspace = true, optional = true } sha2 = { workspace = true, optional = true } subtle = { workspace = true, optional = true } diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index 7070656..692b656 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -12,6 +12,8 @@ use crate::Role; use crate::board::{BoardReads, Moved, TaskRow}; use crate::detail::{ActivityKind, DeletionCost, DetailReads}; +#[cfg(feature = "server")] +pub mod secret; pub mod turso_store; pub use turso_store::TursoStore; diff --git a/crates/dizey-core/src/store/secret.rs b/crates/dizey-core/src/store/secret.rs new file mode 100644 index 0000000..1005bda --- /dev/null +++ b/crates/dizey-core/src/store/secret.rs @@ -0,0 +1,199 @@ +//! The SMTP password's second lock. +//! +//! File permissions on the database (see [`TursoStore::open`]) stop a casual +//! `ls` on the server from reading the password, but a copy of the database +//! file — a backup, a snapshot, an `scp` by someone who should not have had +//! it — carries the plaintext right along with it. This module is the fix: +//! the column holds ciphertext, and the key that opens it lives in a second +//! file (`dizey.key`, beside the database) that a database backup does not +//! automatically include. +//! +//! The envelope is `v1:` followed by base64 of a 24-byte XChaCha20-Poly1305 +//! nonce and the sealed bytes it protects. The prefix is what lets +//! [`TursoStore::open`] tell a value we sealed apart from a plaintext +//! password left behind by a deployment from before this module existed — +//! see the migration note there. There is deliberately no `v2` yet; add one +//! the day the algorithm changes, and keep `open` accepting both prefixes for +//! as long as ciphertext under the old one might still be sitting in a row. +//! +//! Losing the key file — a backup restored without its sibling, most likely — +//! is not a crash. [`open`] returns `None` on anything it cannot make sense +//! of: wrong key, damaged ciphertext, a value that never was one of ours. +//! The caller in [`TursoStore::smtp_password`] turns that into "no password +//! set", which is the same screen an admin sees on a workspace that never had +//! a sender configured, and the same fix: type the password in again. + +use std::io; +use std::path::Path; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD as base64; +use chacha20poly1305::aead::Aead; +use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; +use rand::Rng; + +/// A key is 32 raw bytes; nothing here derives it from a password, because +/// there is no password to derive it from — it is the thing that protects +/// one. +pub const KEY_BYTES: usize = 32; +pub type Key = [u8; KEY_BYTES]; + +const PREFIX: &str = "v1:"; +const NONCE_BYTES: usize = 24; + +/// True for a value already in our envelope — the test the migration-at-open +/// logic uses to skip a row it has already sealed. +pub fn is_sealed(value: &str) -> bool { + value.starts_with(PREFIX) +} + +/// Encrypts `plaintext` under `key`, returning the envelope ready to store. +/// +/// A fresh random nonce is drawn every call, so sealing the same password +/// twice gives two different strings. XChaCha20-Poly1305's 24-byte nonce is +/// wide enough that "draw at random and never track reuse" is safe for the +/// volume of writes a settings panel produces in a workspace's lifetime. +pub fn seal(key: &Key, plaintext: &str) -> String { + let cipher = XChaCha20Poly1305::new(key.into()); + let mut nonce_bytes = [0u8; NONCE_BYTES]; + rand::rng().fill_bytes(&mut nonce_bytes); + let nonce = XNonce::from_slice(&nonce_bytes); + let ciphertext = cipher + .encrypt(nonce, plaintext.as_bytes()) + .expect("XChaCha20-Poly1305 cannot fail to encrypt a plaintext this small"); + let mut payload = Vec::with_capacity(NONCE_BYTES + ciphertext.len()); + payload.extend_from_slice(&nonce_bytes); + payload.extend_from_slice(&ciphertext); + format!("{PREFIX}{}", base64.encode(payload)) +} + +/// Reverses [`seal`]. `None` covers every way this can fail to come back — +/// not our prefix, not valid base64, too short to hold a nonce, wrong key, +/// or a tampered/truncated ciphertext that fails the Poly1305 tag check — +/// and every one of those is meant to degrade to "no password", never panic +/// or bubble an error past the mailer. +pub fn open(key: &Key, sealed: &str) -> Option { + let body = sealed.strip_prefix(PREFIX)?; + let payload = base64.decode(body).ok()?; + if payload.len() < NONCE_BYTES { + return None; + } + let (nonce_bytes, ciphertext) = payload.split_at(NONCE_BYTES); + let cipher = XChaCha20Poly1305::new(key.into()); + let nonce = XNonce::from_slice(nonce_bytes); + let plaintext = cipher.decrypt(nonce, ciphertext).ok()?; + String::from_utf8(plaintext).ok() +} + +/// Reads the key at `path`, generating and writing a fresh one (mode 0600, +/// where the platform has modes) if the file is not there yet. +/// +/// Called once, at [`TursoStore::open`] — the key is loaded, not re-read per +/// query, so a corrupted key file is a boot-time failure, not a per-send one. +pub fn load_or_create_key(path: &Path) -> io::Result { + match std::fs::read(path) { + Ok(bytes) => { + let key: Key = bytes.try_into().map_err(|bytes: Vec| { + io::Error::new( + io::ErrorKind::InvalidData, + format!( + "{} holds {} bytes, not the {KEY_BYTES} of a key", + path.display(), + bytes.len() + ), + ) + })?; + Ok(key) + } + Err(e) if e.kind() == io::ErrorKind::NotFound => { + let mut key = [0u8; KEY_BYTES]; + rand::rng().fill_bytes(&mut key); + std::fs::write(path, key)?; + restrict(path)?; + Ok(key) + } + Err(e) => Err(e), + } +} + +/// 0600 on a freshly written file holding key material or a live credential. +#[cfg(unix)] +pub fn restrict(path: &Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) +} + +#[cfg(not(unix))] +pub fn restrict(_path: &Path) -> io::Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key() -> Key { + let mut k = [0u8; KEY_BYTES]; + rand::rng().fill_bytes(&mut k); + k + } + + #[test] + fn roundtrip() { + let k = key(); + let sealed = seal(&k, "hunter2"); + assert!(is_sealed(&sealed)); + assert_eq!(open(&k, &sealed).as_deref(), Some("hunter2")); + } + + #[test] + fn tamper_fails() { + let k = key(); + let mut sealed = seal(&k, "hunter2").into_bytes(); + let last = sealed.len() - 1; + sealed[last] ^= 0x01; + let sealed = String::from_utf8(sealed).unwrap(); + assert_eq!(open(&k, &sealed), None); + } + + #[test] + fn wrong_key_fails() { + let sealed = seal(&key(), "hunter2"); + assert_eq!(open(&key(), &sealed), None); + } + + #[test] + fn non_envelope_fails() { + let k = key(); + assert_eq!(open(&k, "hunter2"), None); + assert_eq!(open(&k, ""), None); + assert_eq!(open(&k, "v1:not-base64!!"), None); + } + + #[test] + fn load_or_create_key_persists_and_restricts() { + let dir = std::env::temp_dir().join(format!("dizey-key-test-{}", uuid_lite())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("dizey.key"); + let first = load_or_create_key(&path).unwrap(); + let second = load_or_create_key(&path).unwrap(); + assert_eq!(first, second, "a second open reuses the same key"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + } + let _ = std::fs::remove_dir_all(&dir); + } + + // A tiny stand-in so this module does not reach for the `uuid` crate just + // to name a scratch directory. + fn uuid_lite() -> u64 { + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() as u64 + } +} diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index ea8cde2..687bafd 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -6,12 +6,14 @@ //! `crates/dizey-core/migrations` at boot and records the version. use async_trait::async_trait; +use rand::Rng; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; use turso::transaction::TransactionBehavior; use turso::{Builder, Connection, Row, Value, params}; use uuid::Uuid; +use super::secret; use super::{ Attachment, Audience, Deletion, Event, Freeing, MailRule, MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, @@ -60,12 +62,17 @@ pub struct TursoStore { /// connection of their own. conn: Connection, db: turso::Database, + /// Seals and opens `smtp_password`; see [`crate::store::secret`]. Never + /// exposed through the `Store` trait — callers keep passing and receiving + /// plaintext, this field is the detail that makes the row not be one. + key: secret::Key, } impl TursoStore { /// Opens (creating if needed) the database at `path` and brings the schema /// up to date. `:memory:` gives a throwaway database for tests. pub async fn open(path: &str) -> Result { + let existed = path != ":memory:" && std::path::Path::new(path).exists(); let db = Builder::new_local(path).build().await.map_err(backend)?; let conn = db.connect().map_err(backend)?; // Turso is a single-writer engine. Two connections on one Database @@ -76,11 +83,65 @@ impl TursoStore { for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] { conn.execute(pragma, ()).await.map_err(backend)?; } - let store = Self { conn, db }; + // The database file holds a live SMTP credential (encrypted below, but + // still worth not handing to every local user via umask default). 0600 + // right after creation closes the window between "file exists" and + // "file is ours alone" — a WAL file, if this engine leaves one beside + // the main file, gets the same restriction while it's still there to + // restrict; if it does not exist yet, there is nothing to chmod and + // nothing unprotected either, since it does not hold rows until a + // write happens on a connection that already applied this. + if !existed && path != ":memory:" { + restrict_if_present(std::path::Path::new(path))?; + restrict_if_present(&sibling(path, "-wal"))?; + restrict_if_present(&sibling(path, "-shm"))?; + } + let key = load_key(path)?; + let store = Self { conn, db, key }; store.migrate().await?; + store.encrypt_plaintext_passwords().await?; Ok(store) } + /// Migration 0011 could not live in `migrations/`: encrypting a column in + /// place needs the key, and the key is application state, not something + /// SQL can reach. So the upgrade happens here instead, once per boot, + /// idempotently — a value already carrying [`secret::is_sealed`]'s prefix + /// is left alone, which is what makes running this every boot free after + /// the first one. A deployment that predates this module has a plaintext + /// password sitting in `workspace.smtp_password`; this is the one time it + /// is read as plaintext, and only to seal it before anything else touches + /// the row. + async fn encrypt_plaintext_passwords(&self) -> Result<()> { + let mut rows = self + .conn + .query( + "SELECT id, smtp_password FROM workspace WHERE smtp_password IS NOT NULL AND smtp_password <> ''", + (), + ) + .await + .map_err(backend)?; + let mut pending = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let id = text(&row, 0)?; + let password = text(&row, 1)?; + if !secret::is_sealed(&password) { + pending.push((id, password)); + } + } + for (id, plaintext) in pending { + let sealed = secret::seal(&self.key, &plaintext); + self.conn + .execute( + "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2", + params![sealed, id], + ) + .await + .map_err(backend)?; + } + Ok(()) + } + async fn migrate(&self) -> Result<()> { self.conn .execute( @@ -266,6 +327,45 @@ async fn recipients_from(rows: &mut turso::Rows) -> Result> { Ok(out) } +/// `path` with its file name suffixed, for the WAL/SHM files Turso may leave +/// beside the main one (`dizey.db-wal`, `dizey.db-shm`). +fn sibling(path: &str, suffix: &str) -> std::path::PathBuf { + let mut name = std::path::Path::new(path) + .file_name() + .map(|n| n.to_os_string()) + .unwrap_or_default(); + name.push(suffix); + std::path::Path::new(path).with_file_name(name) +} + +/// 0600 on `path` if it exists, a no-op if it does not — chmodding a file +/// into existence would be worse than leaving it be, since it would exist +/// with no rows in it yet regardless. +fn restrict_if_present(path: &std::path::Path) -> Result<()> { + if path.exists() { + secret::restrict(path).map_err(backend)?; + } + Ok(()) +} + +/// The key for `path`'s database. `:memory:` has no directory to anchor a +/// sibling file to and does not survive the process anyway, so it gets a +/// key generated fresh in memory — every in-memory store in the test suite +/// is its own, unrelated encryption domain, which is exactly right for a +/// database that is gone the moment the handle is dropped. +fn load_key(path: &str) -> Result { + if path == ":memory:" { + let mut key = [0u8; secret::KEY_BYTES]; + rand::rng().fill_bytes(&mut key); + return Ok(key); + } + let dir = std::path::Path::new(path) + .parent() + .filter(|d| !d.as_os_str().is_empty()) + .unwrap_or_else(|| std::path::Path::new(".")); + secret::load_or_create_key(&dir.join("dizey.key")).map_err(backend) +} + fn backend(e: E) -> StoreError { StoreError::Backend(e.to_string()) } @@ -568,6 +668,10 @@ impl Store for TursoStore { // The last test result is cleared by the same statement. It was about // the settings that have just been replaced, and a green "delivered" // line under a host nobody has tried yet is worse than no line at all. + // Sealed here, not by the caller — the `Store` trait keeps passing + // plaintext so nothing outside this file needs to know a cipher + // exists. See `crate::store::secret`. + let sealed_password = sender.password.as_deref().map(|p| secret::seal(&self.key, p)); self.conn .execute( "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ @@ -578,7 +682,7 @@ impl Store for TursoStore { sender.host, sender.port as i64, sender.username, - sender.password, + sealed_password, sender.from_name, sender.from_address, workspace_id @@ -607,16 +711,24 @@ impl Store for TursoStore { } async fn smtp_password(&self, workspace_id: &str) -> Result> { - match self + let sealed = match self .one_row( "SELECT smtp_password FROM workspace WHERE id = ?1", params![workspace_id], ) .await? { - Some(row) => opt_text(&row, 0), - None => Err(StoreError::NotFound), - } + Some(row) => opt_text(&row, 0)?, + None => return Err(StoreError::NotFound), + }; + // A decrypt failure — wrong key, damaged ciphertext, a restored + // backup missing its `dizey.key` — comes back as `None` rather than + // an error. To every caller that is indistinguishable from a + // workspace that never had a sender, which is the intended + // degradation: mail send falls back to the no-sender path instead of + // crashing or poisoning the settings screen, and the admin retypes + // the password once through the existing write-only field to heal it. + Ok(sealed.as_deref().and_then(|s| secret::open(&self.key, s))) } async fn set_limits( diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 69e7e4c..7eb04c2 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -33,6 +33,17 @@ impl Scratch { } } +/// A second, independent connection to the scratch database, for tests that +/// need to see a column the way it actually sits on disk rather than through +/// [`Store`]'s API. +async fn raw_conn(scratch: &Scratch) -> turso::Connection { + let db = turso::Builder::new_local(scratch.dir.join("dizey.db").to_str().unwrap()) + .build() + .await + .unwrap(); + db.connect().unwrap() +} + impl Drop for Scratch { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.dir); @@ -312,6 +323,130 @@ async fn a_typed_password_replaces_the_stored_one() { ); } +/// The point of encrypting the column: what actually sits on disk is not the +/// password. A raw read of the row must not turn it up even in ciphertext +/// form recognisable as the plaintext. +#[tokio::test] +async fn the_stored_password_is_not_the_plaintext_on_disk() { + let (scratch, ws_id, _) = workspace_with_admin().await; + scratch + .store + .set_sender( + &ws_id, + NewSender { + host: "smtp.fastmail.com".into(), + port: 587, + username: "dizey".into(), + password: Some("a-very-secret-string".into()), + from_name: "Dizey".into(), + from_address: "dizey@dizey.sh".into(), + }, + ) + .await + .unwrap(); + + let conn = raw_conn(&scratch).await; + let mut rows = conn + .query("SELECT smtp_password FROM workspace WHERE id = ?1", turso::params![ws_id.clone()]) + .await + .unwrap(); + let row = rows.next().await.unwrap().unwrap(); + let column: String = row.get(0).unwrap(); + assert!( + !column.contains("a-very-secret-string"), + "the plaintext is sitting in the column: {column}" + ); + assert!(column.starts_with("v1:"), "expected the sealed envelope, got: {column}"); + + // And the read path still gets the real password back. + assert_eq!( + scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + Some("a-very-secret-string") + ); +} + +/// A backup restored without its sibling `dizey.key`, or a key file damaged +/// in place, must not crash mail sending or the settings screen — it has to +/// degrade to "no password set", exactly like a workspace that never had a +/// sender, so the admin can heal it by retyping the password once. +#[tokio::test] +async fn a_password_that_will_not_decrypt_reads_back_as_none() { + let (scratch, ws_id, _) = workspace_with_admin().await; + scratch + .store + .set_sender( + &ws_id, + NewSender { + host: "smtp.fastmail.com".into(), + port: 587, + username: "dizey".into(), + password: Some("a-very-secret-string".into()), + from_name: "Dizey".into(), + from_address: "dizey@dizey.sh".into(), + }, + ) + .await + .unwrap(); + + // Simulate a lost key / corrupted ciphertext: overwrite the column with + // garbage that still carries the envelope prefix, the way a truncated or + // bit-flipped backup would. + let conn = raw_conn(&scratch).await; + conn.execute( + "UPDATE workspace SET smtp_password = 'v1:not-actually-sealed' WHERE id = ?1", + turso::params![ws_id.clone()], + ) + .await + .unwrap(); + + // Reading degrades to None, not an error. + assert_eq!(scratch.store.smtp_password(&ws_id).await.unwrap(), None); + + // The screen still says "set" — a value is present — but retyping heals it. + let ws = scratch.store.workspace().await.unwrap().unwrap(); + assert!(ws.smtp_password_set); + + scratch + .store + .set_sender( + &ws_id, + NewSender { + host: "smtp.fastmail.com".into(), + port: 587, + username: "dizey".into(), + password: Some("a-fresh-password".into()), + from_name: "Dizey".into(), + from_address: "dizey@dizey.sh".into(), + }, + ) + .await + .unwrap(); + assert_eq!( + scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + Some("a-fresh-password"), + "retyping the password heals a store that could not decrypt it" + ); +} + +/// `TursoStore::open` closes the world-readable window: the database file and +/// its key file come out at 0600, not whatever umask the process inherited. +#[tokio::test] +#[cfg(unix)] +async fn the_database_and_key_file_are_owner_only() { + use std::os::unix::fs::PermissionsExt; + let scratch = Scratch::open().await; + let db_path = scratch.dir.join("dizey.db"); + let key_path = scratch.dir.join("dizey.key"); + for path in [&db_path, &key_path] { + let mode = std::fs::metadata(path) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())) + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600, "{} is not owner-only: {mode:o}", path.display()); + } +} + #[tokio::test] async fn limits_round_trip_including_the_file_type_list() { let (scratch, ws_id, _) = workspace_with_admin().await;