forge
Explore
Log in

Don't you dare go Hollow

The SMTP password is sealed under a key beside the file

Browse files at this commit

9410be82f689cd3c63712fdb1a1de68587d7b13fAhmet Kaan GümüşParent: 297c919
  • feat
    • the SMTP password is sealed under a key beside the file
Show full message
🔒 feat(settings): the SMTP password is sealed under a key beside the file

The one live credential in the database file is now XChaCha20-Poly1305
ciphertext (v1: envelope), sealed under a 32-byte key the app generates
into dizey.key next to the database — never typed, never shown. The
database and key files come out 0600, a plaintext password from an older
deployment is sealed once at boot, and a value that will not decrypt —
a backup restored without its key — reads back as no password at all,
so mail degrades to the no-sender path and retyping once heals it. The
Store trait still speaks plaintext; the cipher is turso_store's detail.
Cargo.lockmodified+39 -1
@@ -537,6 +537,17 @@ version = "0.1.1"
537 source = "registry+https://github.com/rust-lang/crates.io-index"537 source = "registry+https://github.com/rust-lang/crates.io-index"
538 checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487"538 checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487"
539 539
540+[[package]]
541+name = "chacha20"
542+version = "0.9.1"
543+source = "registry+https://github.com/rust-lang/crates.io-index"
544+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
545+dependencies = [
546+ "cfg-if",
547+ "cipher",
548+ "cpufeatures 0.2.17",
549+]
550+
540 [[package]]551 [[package]]
541 name = "chacha20"552 name = "chacha20"
542 version = "0.10.1"553 version = "0.10.1"
@@ -548,6 +559,19 @@ dependencies = [
548 "rand_core 0.10.1",559 "rand_core 0.10.1",
549 ]560 ]
550 561
562+[[package]]
563+name = "chacha20poly1305"
564+version = "0.10.1"
565+source = "registry+https://github.com/rust-lang/crates.io-index"
566+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
567+dependencies = [
568+ "aead",
569+ "chacha20 0.9.1",
570+ "cipher",
571+ "poly1305",
572+ "zeroize",
573+]
574+
551 [[package]]575 [[package]]
552 name = "chrono"576 name = "chrono"
553 version = "0.4.45"577 version = "0.4.45"
@@ -569,6 +593,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
569 dependencies = [593 dependencies = [
570 "crypto-common 0.1.7",594 "crypto-common 0.1.7",
571 "inout",595 "inout",
596+ "zeroize",
572 ]597 ]
573 598
574 [[package]]599 [[package]]
@@ -945,6 +970,8 @@ version = "0.1.0"
945 dependencies = [970 dependencies = [
946 "argon2",971 "argon2",
947 "async-trait",972 "async-trait",
973+ "base64 0.22.1",
974+ "chacha20poly1305",
948 "rand 0.10.2",975 "rand 0.10.2",
949 "serde",976 "serde",
950 "serde_json",977 "serde_json",
@@ -2711,6 +2738,17 @@ dependencies = [
2711 "windows-sys 0.61.2",2738 "windows-sys 0.61.2",
2712 ]2739 ]
2713 2740
2741+[[package]]
2742+name = "poly1305"
2743+version = "0.8.0"
2744+source = "registry+https://github.com/rust-lang/crates.io-index"
2745+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
2746+dependencies = [
2747+ "cpufeatures 0.2.17",
2748+ "opaque-debug",
2749+ "universal-hash",
2750+]
2751+
2714 [[package]]2752 [[package]]
2715 name = "polyval"2753 name = "polyval"
2716 version = "0.6.2"2754 version = "0.6.2"
@@ -2929,7 +2967,7 @@ version = "0.10.2"
2929 source = "registry+https://github.com/rust-lang/crates.io-index"2967 source = "registry+https://github.com/rust-lang/crates.io-index"
2930 checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"2968 checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
2931 dependencies = [2969 dependencies = [
2932- "chacha20",2970+ "chacha20 0.10.1",
2933 "getrandom 0.4.3",2971 "getrandom 0.4.3",
2934 "rand_core 0.10.1",2972 "rand_core 0.10.1",
2935 ]2973 ]
Cargo.tomlmodified+2 -0
@@ -21,6 +21,8 @@ argon2 = "0.6.0-rc.8"
21 rand = "0.10.2"21 rand = "0.10.2"
22 sha2 = "0.11.0"22 sha2 = "0.11.0"
23 subtle = "2.6.1"23 subtle = "2.6.1"
24+chacha20poly1305 = "0.10.1"
25+base64 = "0.22.1"
24 26
25 [profile.release]27 [profile.release]
26 codegen-units = 128 codegen-units = 1
crates/dizey-core/Cargo.tomlmodified+4 -0
@@ -14,6 +14,8 @@ default = ["server"]
14 server = [14 server = [
15 "dep:argon2",15 "dep:argon2",
16 "dep:async-trait",16 "dep:async-trait",
17+ "dep:base64",
18+ "dep:chacha20poly1305",
17 "dep:rand",19 "dep:rand",
18 "dep:sha2",20 "dep:sha2",
19 "dep:subtle",21 "dep:subtle",
@@ -24,6 +26,8 @@ server = [
24 [dependencies]26 [dependencies]
25 argon2 = { workspace = true, optional = true }27 argon2 = { workspace = true, optional = true }
26 async-trait = { version = "0.1.92", optional = true }28 async-trait = { version = "0.1.92", optional = true }
29+base64 = { workspace = true, optional = true }
30+chacha20poly1305 = { workspace = true, optional = true }
27 rand = { workspace = true, optional = true }31 rand = { workspace = true, optional = true }
28 sha2 = { workspace = true, optional = true }32 sha2 = { workspace = true, optional = true }
29 subtle = { workspace = true, optional = true }33 subtle = { workspace = true, optional = true }
crates/dizey-core/src/store/mod.rsmodified+2 -0
@@ -12,6 +12,8 @@ use crate::Role;
12 use crate::board::{BoardReads, Moved, TaskRow};12 use crate::board::{BoardReads, Moved, TaskRow};
13 use crate::detail::{ActivityKind, DeletionCost, DetailReads};13 use crate::detail::{ActivityKind, DeletionCost, DetailReads};
14 14
15+#[cfg(feature = "server")]
16+pub mod secret;
15 pub mod turso_store;17 pub mod turso_store;
16 18
17 pub use turso_store::TursoStore;19 pub use turso_store::TursoStore;
crates/dizey-core/src/store/secret.rsadded+199 -0
@@ -0,0 +1,199 @@
1+//! The SMTP password's second lock.
2+//!
3+//! File permissions on the database (see [`TursoStore::open`]) stop a casual
4+//! `ls` on the server from reading the password, but a copy of the database
5+//! file — a backup, a snapshot, an `scp` by someone who should not have had
6+//! it — carries the plaintext right along with it. This module is the fix:
7+//! the column holds ciphertext, and the key that opens it lives in a second
8+//! file (`dizey.key`, beside the database) that a database backup does not
9+//! automatically include.
10+//!
11+//! The envelope is `v1:` followed by base64 of a 24-byte XChaCha20-Poly1305
12+//! nonce and the sealed bytes it protects. The prefix is what lets
13+//! [`TursoStore::open`] tell a value we sealed apart from a plaintext
14+//! password left behind by a deployment from before this module existed —
15+//! see the migration note there. There is deliberately no `v2` yet; add one
16+//! the day the algorithm changes, and keep `open` accepting both prefixes for
17+//! as long as ciphertext under the old one might still be sitting in a row.
18+//!
19+//! Losing the key file — a backup restored without its sibling, most likely —
20+//! is not a crash. [`open`] returns `None` on anything it cannot make sense
21+//! of: wrong key, damaged ciphertext, a value that never was one of ours.
22+//! The caller in [`TursoStore::smtp_password`] turns that into "no password
23+//! set", which is the same screen an admin sees on a workspace that never had
24+//! a sender configured, and the same fix: type the password in again.
25+
26+use std::io;
27+use std::path::Path;
28+
29+use base64::Engine;
30+use base64::engine::general_purpose::STANDARD as base64;
31+use chacha20poly1305::aead::Aead;
32+use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
33+use rand::Rng;
34+
35+/// A key is 32 raw bytes; nothing here derives it from a password, because
36+/// there is no password to derive it from — it is the thing that protects
37+/// one.
38+pub const KEY_BYTES: usize = 32;
39+pub type Key = [u8; KEY_BYTES];
40+
41+const PREFIX: &str = "v1:";
42+const NONCE_BYTES: usize = 24;
43+
44+/// True for a value already in our envelope — the test the migration-at-open
45+/// logic uses to skip a row it has already sealed.
46+pub fn is_sealed(value: &str) -> bool {
47+ value.starts_with(PREFIX)
48+}
49+
50+/// Encrypts `plaintext` under `key`, returning the envelope ready to store.
51+///
52+/// A fresh random nonce is drawn every call, so sealing the same password
53+/// twice gives two different strings. XChaCha20-Poly1305's 24-byte nonce is
54+/// wide enough that "draw at random and never track reuse" is safe for the
55+/// volume of writes a settings panel produces in a workspace's lifetime.
56+pub fn seal(key: &Key, plaintext: &str) -> String {
57+ let cipher = XChaCha20Poly1305::new(key.into());
58+ let mut nonce_bytes = [0u8; NONCE_BYTES];
59+ rand::rng().fill_bytes(&mut nonce_bytes);
60+ let nonce = XNonce::from_slice(&nonce_bytes);
61+ let ciphertext = cipher
62+ .encrypt(nonce, plaintext.as_bytes())
63+ .expect("XChaCha20-Poly1305 cannot fail to encrypt a plaintext this small");
64+ let mut payload = Vec::with_capacity(NONCE_BYTES + ciphertext.len());
65+ payload.extend_from_slice(&nonce_bytes);
66+ payload.extend_from_slice(&ciphertext);
67+ format!("{PREFIX}{}", base64.encode(payload))
68+}
69+
70+/// Reverses [`seal`]. `None` covers every way this can fail to come back —
71+/// not our prefix, not valid base64, too short to hold a nonce, wrong key,
72+/// or a tampered/truncated ciphertext that fails the Poly1305 tag check —
73+/// and every one of those is meant to degrade to "no password", never panic
74+/// or bubble an error past the mailer.
75+pub fn open(key: &Key, sealed: &str) -> Option<String> {
76+ let body = sealed.strip_prefix(PREFIX)?;
77+ let payload = base64.decode(body).ok()?;
78+ if payload.len() < NONCE_BYTES {
79+ return None;
80+ }
81+ let (nonce_bytes, ciphertext) = payload.split_at(NONCE_BYTES);
82+ let cipher = XChaCha20Poly1305::new(key.into());
83+ let nonce = XNonce::from_slice(nonce_bytes);
84+ let plaintext = cipher.decrypt(nonce, ciphertext).ok()?;
85+ String::from_utf8(plaintext).ok()
86+}
87+
88+/// Reads the key at `path`, generating and writing a fresh one (mode 0600,
89+/// where the platform has modes) if the file is not there yet.
90+///
91+/// Called once, at [`TursoStore::open`] — the key is loaded, not re-read per
92+/// query, so a corrupted key file is a boot-time failure, not a per-send one.
93+pub fn load_or_create_key(path: &Path) -> io::Result<Key> {
94+ match std::fs::read(path) {
95+ Ok(bytes) => {
96+ let key: Key = bytes.try_into().map_err(|bytes: Vec<u8>| {
97+ io::Error::new(
98+ io::ErrorKind::InvalidData,
99+ format!(
100+ "{} holds {} bytes, not the {KEY_BYTES} of a key",
101+ path.display(),
102+ bytes.len()
103+ ),
104+ )
105+ })?;
106+ Ok(key)
107+ }
108+ Err(e) if e.kind() == io::ErrorKind::NotFound => {
109+ let mut key = [0u8; KEY_BYTES];
110+ rand::rng().fill_bytes(&mut key);
111+ std::fs::write(path, key)?;
112+ restrict(path)?;
113+ Ok(key)
114+ }
115+ Err(e) => Err(e),
116+ }
117+}
118+
119+/// 0600 on a freshly written file holding key material or a live credential.
120+#[cfg(unix)]
121+pub fn restrict(path: &Path) -> io::Result<()> {
122+ use std::os::unix::fs::PermissionsExt;
123+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
124+}
125+
126+#[cfg(not(unix))]
127+pub fn restrict(_path: &Path) -> io::Result<()> {
128+ Ok(())
129+}
130+
131+#[cfg(test)]
132+mod tests {
133+ use super::*;
134+
135+ fn key() -> Key {
136+ let mut k = [0u8; KEY_BYTES];
137+ rand::rng().fill_bytes(&mut k);
138+ k
139+ }
140+
141+ #[test]
142+ fn roundtrip() {
143+ let k = key();
144+ let sealed = seal(&k, "hunter2");
145+ assert!(is_sealed(&sealed));
146+ assert_eq!(open(&k, &sealed).as_deref(), Some("hunter2"));
147+ }
148+
149+ #[test]
150+ fn tamper_fails() {
151+ let k = key();
152+ let mut sealed = seal(&k, "hunter2").into_bytes();
153+ let last = sealed.len() - 1;
154+ sealed[last] ^= 0x01;
155+ let sealed = String::from_utf8(sealed).unwrap();
156+ assert_eq!(open(&k, &sealed), None);
157+ }
158+
159+ #[test]
160+ fn wrong_key_fails() {
161+ let sealed = seal(&key(), "hunter2");
162+ assert_eq!(open(&key(), &sealed), None);
163+ }
164+
165+ #[test]
166+ fn non_envelope_fails() {
167+ let k = key();
168+ assert_eq!(open(&k, "hunter2"), None);
169+ assert_eq!(open(&k, ""), None);
170+ assert_eq!(open(&k, "v1:not-base64!!"), None);
171+ }
172+
173+ #[test]
174+ fn load_or_create_key_persists_and_restricts() {
175+ let dir = std::env::temp_dir().join(format!("dizey-key-test-{}", uuid_lite()));
176+ std::fs::create_dir_all(&dir).unwrap();
177+ let path = dir.join("dizey.key");
178+ let first = load_or_create_key(&path).unwrap();
179+ let second = load_or_create_key(&path).unwrap();
180+ assert_eq!(first, second, "a second open reuses the same key");
181+ #[cfg(unix)]
182+ {
183+ use std::os::unix::fs::PermissionsExt;
184+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
185+ assert_eq!(mode, 0o600);
186+ }
187+ let _ = std::fs::remove_dir_all(&dir);
188+ }
189+
190+ // A tiny stand-in so this module does not reach for the `uuid` crate just
191+ // to name a scratch directory.
192+ fn uuid_lite() -> u64 {
193+ use std::time::{SystemTime, UNIX_EPOCH};
194+ SystemTime::now()
195+ .duration_since(UNIX_EPOCH)
196+ .unwrap()
197+ .as_nanos() as u64
198+ }
199+}
crates/dizey-core/src/store/turso_store.rsmodified+118 -6
@@ -6,12 +6,14 @@
6 //! `crates/dizey-core/migrations` at boot and records the version.6 //! `crates/dizey-core/migrations` at boot and records the version.
7 7
8 use async_trait::async_trait;8 use async_trait::async_trait;
9+use rand::Rng;
9 use time::OffsetDateTime;10 use time::OffsetDateTime;
10 use time::format_description::well_known::Rfc3339;11 use time::format_description::well_known::Rfc3339;
11 use turso::transaction::TransactionBehavior;12 use turso::transaction::TransactionBehavior;
12 use turso::{Builder, Connection, Row, Value, params};13 use turso::{Builder, Connection, Row, Value, params};
13 use uuid::Uuid;14 use uuid::Uuid;
14 15
16+use super::secret;
15 use super::{17 use super::{
16 Attachment, Audience, Deletion, Event, Freeing, MailRule, MailSend, NewAttachment, NewSender,18 Attachment, Audience, Deletion, Event, Freeing, MailRule, MailSend, NewAttachment, NewSender,
17 NewTask, NewUser, Recipient, Result,19 NewTask, NewUser, Recipient, Result,
@@ -60,12 +62,17 @@ pub struct TursoStore {
60 /// connection of their own.62 /// connection of their own.
61 conn: Connection,63 conn: Connection,
62 db: turso::Database,64 db: turso::Database,
65+ /// Seals and opens `smtp_password`; see [`crate::store::secret`]. Never
66+ /// exposed through the `Store` trait — callers keep passing and receiving
67+ /// plaintext, this field is the detail that makes the row not be one.
68+ key: secret::Key,
63 }69 }
64 70
65 impl TursoStore {71 impl TursoStore {
66 /// Opens (creating if needed) the database at `path` and brings the schema72 /// Opens (creating if needed) the database at `path` and brings the schema
67 /// up to date. `:memory:` gives a throwaway database for tests.73 /// up to date. `:memory:` gives a throwaway database for tests.
68 pub async fn open(path: &str) -> Result<Self> {74 pub async fn open(path: &str) -> Result<Self> {
75+ let existed = path != ":memory:" && std::path::Path::new(path).exists();
69 let db = Builder::new_local(path).build().await.map_err(backend)?;76 let db = Builder::new_local(path).build().await.map_err(backend)?;
70 let conn = db.connect().map_err(backend)?;77 let conn = db.connect().map_err(backend)?;
71 // Turso is a single-writer engine. Two connections on one Database78 // Turso is a single-writer engine. Two connections on one Database
@@ -76,11 +83,65 @@ impl TursoStore {
76 for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] {83 for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] {
77 conn.execute(pragma, ()).await.map_err(backend)?;84 conn.execute(pragma, ()).await.map_err(backend)?;
78 }85 }
79- let store = Self { conn, db };86+ // The database file holds a live SMTP credential (encrypted below, but
87+ // still worth not handing to every local user via umask default). 0600
88+ // right after creation closes the window between "file exists" and
89+ // "file is ours alone" — a WAL file, if this engine leaves one beside
90+ // the main file, gets the same restriction while it's still there to
91+ // restrict; if it does not exist yet, there is nothing to chmod and
92+ // nothing unprotected either, since it does not hold rows until a
93+ // write happens on a connection that already applied this.
94+ if !existed && path != ":memory:" {
95+ restrict_if_present(std::path::Path::new(path))?;
96+ restrict_if_present(&sibling(path, "-wal"))?;
97+ restrict_if_present(&sibling(path, "-shm"))?;
98+ }
99+ let key = load_key(path)?;
100+ let store = Self { conn, db, key };
80 store.migrate().await?;101 store.migrate().await?;
102+ store.encrypt_plaintext_passwords().await?;
81 Ok(store)103 Ok(store)
82 }104 }
83 105
106+ /// Migration 0011 could not live in `migrations/`: encrypting a column in
107+ /// place needs the key, and the key is application state, not something
108+ /// SQL can reach. So the upgrade happens here instead, once per boot,
109+ /// idempotently — a value already carrying [`secret::is_sealed`]'s prefix
110+ /// is left alone, which is what makes running this every boot free after
111+ /// the first one. A deployment that predates this module has a plaintext
112+ /// password sitting in `workspace.smtp_password`; this is the one time it
113+ /// is read as plaintext, and only to seal it before anything else touches
114+ /// the row.
115+ async fn encrypt_plaintext_passwords(&self) -> Result<()> {
116+ let mut rows = self
117+ .conn
118+ .query(
119+ "SELECT id, smtp_password FROM workspace WHERE smtp_password IS NOT NULL AND smtp_password <> ''",
120+ (),
121+ )
122+ .await
123+ .map_err(backend)?;
124+ let mut pending = Vec::new();
125+ while let Some(row) = rows.next().await.map_err(backend)? {
126+ let id = text(&row, 0)?;
127+ let password = text(&row, 1)?;
128+ if !secret::is_sealed(&password) {
129+ pending.push((id, password));
130+ }
131+ }
132+ for (id, plaintext) in pending {
133+ let sealed = secret::seal(&self.key, &plaintext);
134+ self.conn
135+ .execute(
136+ "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2",
137+ params![sealed, id],
138+ )
139+ .await
140+ .map_err(backend)?;
141+ }
142+ Ok(())
143+ }
144+
84 async fn migrate(&self) -> Result<()> {145 async fn migrate(&self) -> Result<()> {
85 self.conn146 self.conn
86 .execute(147 .execute(
@@ -266,6 +327,45 @@ async fn recipients_from(rows: &mut turso::Rows) -> Result<Vec<Recipient>> {
266 Ok(out)327 Ok(out)
267 }328 }
268 329
330+/// `path` with its file name suffixed, for the WAL/SHM files Turso may leave
331+/// beside the main one (`dizey.db-wal`, `dizey.db-shm`).
332+fn sibling(path: &str, suffix: &str) -> std::path::PathBuf {
333+ let mut name = std::path::Path::new(path)
334+ .file_name()
335+ .map(|n| n.to_os_string())
336+ .unwrap_or_default();
337+ name.push(suffix);
338+ std::path::Path::new(path).with_file_name(name)
339+}
340+
341+/// 0600 on `path` if it exists, a no-op if it does not — chmodding a file
342+/// into existence would be worse than leaving it be, since it would exist
343+/// with no rows in it yet regardless.
344+fn restrict_if_present(path: &std::path::Path) -> Result<()> {
345+ if path.exists() {
346+ secret::restrict(path).map_err(backend)?;
347+ }
348+ Ok(())
349+}
350+
351+/// The key for `path`'s database. `:memory:` has no directory to anchor a
352+/// sibling file to and does not survive the process anyway, so it gets a
353+/// key generated fresh in memory — every in-memory store in the test suite
354+/// is its own, unrelated encryption domain, which is exactly right for a
355+/// database that is gone the moment the handle is dropped.
356+fn load_key(path: &str) -> Result<secret::Key> {
357+ if path == ":memory:" {
358+ let mut key = [0u8; secret::KEY_BYTES];
359+ rand::rng().fill_bytes(&mut key);
360+ return Ok(key);
361+ }
362+ let dir = std::path::Path::new(path)
363+ .parent()
364+ .filter(|d| !d.as_os_str().is_empty())
365+ .unwrap_or_else(|| std::path::Path::new("."));
366+ secret::load_or_create_key(&dir.join("dizey.key")).map_err(backend)
367+}
368+
269 fn backend<E: std::fmt::Display>(e: E) -> StoreError {369 fn backend<E: std::fmt::Display>(e: E) -> StoreError {
270 StoreError::Backend(e.to_string())370 StoreError::Backend(e.to_string())
271 }371 }
@@ -568,6 +668,10 @@ impl Store for TursoStore {
568 // The last test result is cleared by the same statement. It was about668 // The last test result is cleared by the same statement. It was about
569 // the settings that have just been replaced, and a green "delivered"669 // the settings that have just been replaced, and a green "delivered"
570 // line under a host nobody has tried yet is worse than no line at all.670 // line under a host nobody has tried yet is worse than no line at all.
671+ // Sealed here, not by the caller — the `Store` trait keeps passing
672+ // plaintext so nothing outside this file needs to know a cipher
673+ // exists. See `crate::store::secret`.
674+ let sealed_password = sender.password.as_deref().map(|p| secret::seal(&self.key, p));
571 self.conn675 self.conn
572 .execute(676 .execute(
573 "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \677 "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \
@@ -578,7 +682,7 @@ impl Store for TursoStore {
578 sender.host,682 sender.host,
579 sender.port as i64,683 sender.port as i64,
580 sender.username,684 sender.username,
581- sender.password,685+ sealed_password,
582 sender.from_name,686 sender.from_name,
583 sender.from_address,687 sender.from_address,
584 workspace_id688 workspace_id
@@ -607,16 +711,24 @@ impl Store for TursoStore {
607 }711 }
608 712
609 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>> {713 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>> {
610- match self714+ let sealed = match self
611 .one_row(715 .one_row(
612 "SELECT smtp_password FROM workspace WHERE id = ?1",716 "SELECT smtp_password FROM workspace WHERE id = ?1",
613 params![workspace_id],717 params![workspace_id],
614 )718 )
615 .await?719 .await?
616 {720 {
617- Some(row) => opt_text(&row, 0),721+ Some(row) => opt_text(&row, 0)?,
618- None => Err(StoreError::NotFound),722+ None => return Err(StoreError::NotFound),
619- }723+ };
724+ // A decrypt failure — wrong key, damaged ciphertext, a restored
725+ // backup missing its `dizey.key` — comes back as `None` rather than
726+ // an error. To every caller that is indistinguishable from a
727+ // workspace that never had a sender, which is the intended
728+ // degradation: mail send falls back to the no-sender path instead of
729+ // crashing or poisoning the settings screen, and the admin retypes
730+ // the password once through the existing write-only field to heal it.
731+ Ok(sealed.as_deref().and_then(|s| secret::open(&self.key, s)))
620 }732 }
621 733
622 async fn set_limits(734 async fn set_limits(
crates/dizey-core/tests/store.rsmodified+135 -0
@@ -33,6 +33,17 @@ impl Scratch {
33 }33 }
34 }34 }
35 35
36+/// A second, independent connection to the scratch database, for tests that
37+/// need to see a column the way it actually sits on disk rather than through
38+/// [`Store`]'s API.
39+async fn raw_conn(scratch: &Scratch) -> turso::Connection {
40+ let db = turso::Builder::new_local(scratch.dir.join("dizey.db").to_str().unwrap())
41+ .build()
42+ .await
43+ .unwrap();
44+ db.connect().unwrap()
45+}
46+
36 impl Drop for Scratch {47 impl Drop for Scratch {
37 fn drop(&mut self) {48 fn drop(&mut self) {
38 let _ = std::fs::remove_dir_all(&self.dir);49 let _ = std::fs::remove_dir_all(&self.dir);
@@ -312,6 +323,130 @@ async fn a_typed_password_replaces_the_stored_one() {
312 );323 );
313 }324 }
314 325
326+/// The point of encrypting the column: what actually sits on disk is not the
327+/// password. A raw read of the row must not turn it up even in ciphertext
328+/// form recognisable as the plaintext.
329+#[tokio::test]
330+async fn the_stored_password_is_not_the_plaintext_on_disk() {
331+ let (scratch, ws_id, _) = workspace_with_admin().await;
332+ scratch
333+ .store
334+ .set_sender(
335+ &ws_id,
336+ NewSender {
337+ host: "smtp.fastmail.com".into(),
338+ port: 587,
339+ username: "dizey".into(),
340+ password: Some("a-very-secret-string".into()),
341+ from_name: "Dizey".into(),
342+ from_address: "dizey@dizey.sh".into(),
343+ },
344+ )
345+ .await
346+ .unwrap();
347+
348+ let conn = raw_conn(&scratch).await;
349+ let mut rows = conn
350+ .query("SELECT smtp_password FROM workspace WHERE id = ?1", turso::params![ws_id.clone()])
351+ .await
352+ .unwrap();
353+ let row = rows.next().await.unwrap().unwrap();
354+ let column: String = row.get(0).unwrap();
355+ assert!(
356+ !column.contains("a-very-secret-string"),
357+ "the plaintext is sitting in the column: {column}"
358+ );
359+ assert!(column.starts_with("v1:"), "expected the sealed envelope, got: {column}");
360+
361+ // And the read path still gets the real password back.
362+ assert_eq!(
363+ scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
364+ Some("a-very-secret-string")
365+ );
366+}
367+
368+/// A backup restored without its sibling `dizey.key`, or a key file damaged
369+/// in place, must not crash mail sending or the settings screen — it has to
370+/// degrade to "no password set", exactly like a workspace that never had a
371+/// sender, so the admin can heal it by retyping the password once.
372+#[tokio::test]
373+async fn a_password_that_will_not_decrypt_reads_back_as_none() {
374+ let (scratch, ws_id, _) = workspace_with_admin().await;
375+ scratch
376+ .store
377+ .set_sender(
378+ &ws_id,
379+ NewSender {
380+ host: "smtp.fastmail.com".into(),
381+ port: 587,
382+ username: "dizey".into(),
383+ password: Some("a-very-secret-string".into()),
384+ from_name: "Dizey".into(),
385+ from_address: "dizey@dizey.sh".into(),
386+ },
387+ )
388+ .await
389+ .unwrap();
390+
391+ // Simulate a lost key / corrupted ciphertext: overwrite the column with
392+ // garbage that still carries the envelope prefix, the way a truncated or
393+ // bit-flipped backup would.
394+ let conn = raw_conn(&scratch).await;
395+ conn.execute(
396+ "UPDATE workspace SET smtp_password = 'v1:not-actually-sealed' WHERE id = ?1",
397+ turso::params![ws_id.clone()],
398+ )
399+ .await
400+ .unwrap();
401+
402+ // Reading degrades to None, not an error.
403+ assert_eq!(scratch.store.smtp_password(&ws_id).await.unwrap(), None);
404+
405+ // The screen still says "set" — a value is present — but retyping heals it.
406+ let ws = scratch.store.workspace().await.unwrap().unwrap();
407+ assert!(ws.smtp_password_set);
408+
409+ scratch
410+ .store
411+ .set_sender(
412+ &ws_id,
413+ NewSender {
414+ host: "smtp.fastmail.com".into(),
415+ port: 587,
416+ username: "dizey".into(),
417+ password: Some("a-fresh-password".into()),
418+ from_name: "Dizey".into(),
419+ from_address: "dizey@dizey.sh".into(),
420+ },
421+ )
422+ .await
423+ .unwrap();
424+ assert_eq!(
425+ scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
426+ Some("a-fresh-password"),
427+ "retyping the password heals a store that could not decrypt it"
428+ );
429+}
430+
431+/// `TursoStore::open` closes the world-readable window: the database file and
432+/// its key file come out at 0600, not whatever umask the process inherited.
433+#[tokio::test]
434+#[cfg(unix)]
435+async fn the_database_and_key_file_are_owner_only() {
436+ use std::os::unix::fs::PermissionsExt;
437+ let scratch = Scratch::open().await;
438+ let db_path = scratch.dir.join("dizey.db");
439+ let key_path = scratch.dir.join("dizey.key");
440+ for path in [&db_path, &key_path] {
441+ let mode = std::fs::metadata(path)
442+ .unwrap_or_else(|e| panic!("{}: {e}", path.display()))
443+ .permissions()
444+ .mode()
445+ & 0o777;
446+ assert_eq!(mode, 0o600, "{} is not owner-only: {mode:o}", path.display());
447+ }
448+}
449+
315 #[tokio::test]450 #[tokio::test]
316 async fn limits_round_trip_including_the_file_type_list() {451 async fn limits_round_trip_including_the_file_type_list() {
317 let (scratch, ws_id, _) = workspace_with_admin().await;452 let (scratch, ws_id, _) = workspace_with_admin().await;