diff --git a/crates/dizey-core/migrations/0008_sender_is_settings.sql b/crates/dizey-core/migrations/0008_sender_is_settings.sql new file mode 100644 index 0000000..c9f33f6 --- /dev/null +++ b/crates/dizey-core/migrations/0008_sender_is_settings.sql @@ -0,0 +1,31 @@ +-- The sender comes back into the table, because the admin sets it from the +-- Settings screen and not from the server's environment. +-- +-- Migration 0006 moved these columns out on the argument that a password in a +-- row is a password a handler can be made to return. That argument is sound +-- and the mitigations survive: the password has no field on `Workspace`, so +-- no query that loads a workspace can carry it; it is written by +-- `Store::set_sender` and read by `Store::smtp_password`, which only the +-- mailer calls; and nothing that reaches a page ever holds it. +-- +-- What it cost was the artboard's own screen: `SMTP HOST`, `PORT`, +-- `USERNAME`, `PASSWORD`, `FROM NAME`, `FROM ADDRESS` and a Save button, with +-- the sender changed by whoever runs the workspace rather than by whoever has +-- a shell on the box. A three-person team has those be different people, and +-- the second one is not always awake. +-- +-- The password is stored as it is typed. It has to be: the server presents it +-- to the mail host on every send, so a one-way hash would make sending +-- impossible, and encrypting it under a key that also lives on this disk moves +-- the problem without shrinking it. The consequence is stated rather than +-- dressed up — whoever holds a copy of this file holds the sender's password, +-- so it belongs to a sending account and to nothing else. +-- +-- Added rather than rebuilt: `ALTER TABLE ... ADD COLUMN` works in place, and +-- every one of these is nullable, which is what a workspace with no sender is. +ALTER TABLE workspace ADD COLUMN smtp_host TEXT; +ALTER TABLE workspace ADD COLUMN smtp_port INTEGER; +ALTER TABLE workspace ADD COLUMN smtp_username TEXT; +ALTER TABLE workspace ADD COLUMN smtp_password TEXT; +ALTER TABLE workspace ADD COLUMN smtp_from_name TEXT; +ALTER TABLE workspace ADD COLUMN smtp_from_address TEXT; diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index fd9a2dd..5d074cd 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -35,20 +35,48 @@ pub enum StoreError { pub type Result = std::result::Result; -/// A workspace and the settings that ride on it. The sender is not here at -/// all: host, port, username, password and from-address come from the -/// environment, so no query can return them and no backup of this file carries -/// the password. +/// A workspace and the settings that ride on it. +/// +/// The sender is here except for its password, which has no field on purpose: +/// this record is what handlers load and what pages serialise, so a password +/// with a field here is a password one careless response away from the wire. +/// It is written by [`Store::set_sender`] and read by [`Store::smtp_password`], +/// which only the mailer calls. What a screen gets instead is +/// `smtp_password_set` — enough to say "set" and nothing more. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Workspace { pub id: String, pub name: String, pub created_at: OffsetDateTime, + pub smtp_host: Option, + pub smtp_port: Option, + pub smtp_username: Option, + pub smtp_from_name: Option, + pub smtp_from_address: Option, + /// Whether a password is stored, never the password. Derived in the query + /// so that the value itself does not travel even this far. + pub smtp_password_set: bool, pub attachment_limit_bytes: u64, pub photo_limit_bytes: u64, pub allowed_file_types: Vec, } +/// A sender as an admin typed it, on its way to the table. +/// +/// `password` is `None` when the admin left the field untouched, which is what +/// the screen sends when a password is already stored: the field is write-only, +/// so an edit to the port must not blank the password just because the form had +/// nothing to put in it. +#[derive(Debug, Clone, PartialEq)] +pub struct NewSender { + pub host: String, + pub port: u32, + pub username: String, + pub password: Option, + pub from_name: String, + pub from_address: String, +} + /// An account. `password_hash` is `None` for an invited member who has not /// signed in yet — the admin creates the account with a name and an address and /// can never read or set the password. @@ -289,6 +317,15 @@ pub trait Store: BoardReads + DetailReads + 'static { async fn workspace(&self) -> Result>; + /// Writes the sender. A `password` of `None` leaves the stored one alone, + /// which is how an admin changes the port without retyping a secret the + /// screen was never allowed to show them. + async fn set_sender(&self, workspace_id: &str, sender: NewSender) -> Result<()>; + + /// Reads the sender's password. Only the mailer calls this, and nothing it + /// returns reaches a response body. + async fn smtp_password(&self, workspace_id: &str) -> Result>; + async fn set_limits( &self, workspace_id: &str, diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index 0915abd..e85c81a 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -13,7 +13,8 @@ use turso::{Builder, Connection, Row, Value, params}; use uuid::Uuid; use super::{ - Audience, Deletion, Event, Freeing, MailRule, MailSend, NewTask, NewUser, Recipient, Result, + Audience, Deletion, Event, Freeing, MailRule, MailSend, NewSender, NewTask, NewUser, Recipient, + Result, SendState, Session, SigninLink, Store, StoreError, Trigger, User, Workspace, }; use crate::Role; @@ -34,6 +35,7 @@ const MIGRATIONS: &[(i64, &str)] = &[ (5, include_str!("../../migrations/0005_freeing.sql")), (6, include_str!("../../migrations/0006_sender_is_config.sql")), (7, include_str!("../../migrations/0007_who_invited.sql")), + (8, include_str!("../../migrations/0008_sender_is_settings.sql")), ]; /// The board a fresh workspace gets, and its columns. `Done` is the column @@ -343,11 +345,22 @@ fn workspace_from(row: &Row) -> Result { attachment_limit_bytes: row.get::(3).map_err(backend)?.max(0) as u64, allowed_file_types, photo_limit_bytes: row.get::(5).map_err(backend)?.max(0) as u64, + smtp_host: opt_text(row, 6)?, + smtp_port: row.get::>(7).map_err(backend)?, + smtp_username: opt_text(row, 8)?, + smtp_from_name: opt_text(row, 9)?, + smtp_from_address: opt_text(row, 10)?, + smtp_password_set: row.get::(11).map_err(backend)? != 0, }) } -const WORKSPACE_COLUMNS: &str = - "id, name, created_at, attachment_limit_bytes, allowed_file_types, photo_limit_bytes"; +// The password is not among these, and the last entry is why: the query asks +// the database whether a password exists and carries back a 0 or a 1. The value +// never leaves the row, so no caller can pass it on by accident. +const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \ + allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \ + smtp_from_name, smtp_from_address, \ + (smtp_password IS NOT NULL AND smtp_password <> '')"; fn user_from(row: &Row) -> Result { Ok(User { @@ -517,6 +530,44 @@ impl Store for TursoStore { } } + async fn set_sender(&self, workspace_id: &str, sender: NewSender) -> Result<()> { + // `COALESCE(?4, smtp_password)` is the write-only field made real: the + // screen sends no password when the admin did not type one, and the + // stored secret survives an edit to the port. Passing an empty string + // is not a way to blank it either — the form sends `None` for empty. + self.conn + .execute( + "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ + smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \ + smtp_from_address = ?6 WHERE id = ?7", + params![ + sender.host, + sender.port as i64, + sender.username, + sender.password, + sender.from_name, + sender.from_address, + workspace_id + ], + ) + .await + .map_err(backend)?; + Ok(()) + } + + async fn smtp_password(&self, workspace_id: &str) -> Result> { + 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), + } + } + async fn set_limits( &self, workspace_id: &str, @@ -2445,12 +2496,13 @@ mod probe { let _ = std::fs::remove_dir_all(&dir); } - /// The sender's columns are gone from the schema, password included. This - /// is the property the config-only decision rests on: no handler can be - /// made to return a password the table does not have, and a copy of the - /// database file carries none. + /// The password has a column but never a way out. The table holds it, + /// because the server must present it to the mail host on every send; the + /// read path does not, because `WORKSPACE_COLUMNS` asks only whether one + /// exists. This is the property the whole write-only field rests on, so it + /// is asserted against the real query rather than against a comment. #[tokio::test] - async fn the_workspace_table_has_no_sender_columns_left() { + async fn the_workspace_read_path_cannot_carry_the_password() { let dir = std::env::temp_dir().join(format!("dizey-sender-{}", Uuid::new_v4())); std::fs::create_dir_all(&dir).unwrap(); let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap()) @@ -2458,24 +2510,41 @@ mod probe { .unwrap(); use crate::store::Store as _; - let row = store - .one_row( - "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'workspace'", - (), - ) + let (ws, _admin) = store + .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "hash") .await - .unwrap() - .expect("the workspace table exists"); - let schema = text(&row, 0).unwrap(); - assert!(!schema.contains("smtp"), "{schema}"); - - // The rebuild put the name back, so everything that references the - // workspace still lands on this table. + .unwrap(); store - .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "hash") + .set_sender( + &ws.id, + NewSender { + host: "smtp.fastmail.com".into(), + port: 587, + username: "dizey".into(), + password: Some("hunter2-and-then-some".into()), + from_name: "Dizey".into(), + from_address: "dizey@dizey.sh".into(), + }, + ) .await .unwrap(); - assert!(store.workspace().await.unwrap().is_some()); + + // The column exists and holds what was written — the mailer needs it. + assert_eq!( + store.smtp_password(&ws.id).await.unwrap().as_deref(), + Some("hunter2-and-then-some") + ); + + // And the record a page would be handed does not contain it, anywhere, + // under any field name. + let loaded = store.workspace().await.unwrap().unwrap(); + assert!(loaded.smtp_password_set, "a password was stored"); + let serialised = serde_json::to_string(&loaded).unwrap(); + assert!( + !serialised.contains("hunter2"), + "the workspace record carried the password: {serialised}" + ); + assert_eq!(loaded.smtp_host.as_deref(), Some("smtp.fastmail.com")); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index e0d8dc9..048f358 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -9,7 +9,7 @@ use std::path::PathBuf; use dizey_core::Role; use dizey_core::auth::{Token, hash_password}; use dizey_core::store::{ - Audience, MailRule, NewUser, SendState, Store, StoreError, Trigger, TursoStore, User, + Audience, MailRule, NewSender, NewUser, SendState, Store, StoreError, Trigger, TursoStore, User, }; use time::{Duration, OffsetDateTime}; use uuid::Uuid; @@ -89,14 +89,14 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("dizey.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 7); + assert_eq!(first.schema_version().await.unwrap(), 8); claim(&first).await; drop(first); // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and // must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 7); + assert_eq!(second.schema_version().await.unwrap(), 8); assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); drop(second); let _ = std::fs::remove_dir_all(&dir); @@ -218,16 +218,97 @@ async fn workspace_defaults_match_the_settings_screen() { ); } +/// An admin edits the sender from Settings, so the record carries host, port, +/// username and from-address. It never carries the password: that field does +/// not exist on the struct, and what a screen gets is the fact that one is set. #[tokio::test] -async fn the_sender_is_not_in_the_workspace_record_at_all() { - let (scratch, _, _) = workspace_with_admin().await; +async fn the_workspace_record_carries_the_sender_but_never_its_password() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let fresh = scratch.store.workspace().await.unwrap().unwrap(); + assert_eq!(fresh.smtp_host, None, "a new workspace has no sender"); + assert!(!fresh.smtp_password_set); + + 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 ws = scratch.store.workspace().await.unwrap().unwrap(); + assert_eq!(ws.smtp_host.as_deref(), Some("smtp.fastmail.com")); + assert_eq!(ws.smtp_port, Some(587)); + assert_eq!(ws.smtp_username.as_deref(), Some("dizey")); + assert_eq!(ws.smtp_from_name.as_deref(), Some("Dizey")); + assert_eq!(ws.smtp_from_address.as_deref(), Some("dizey@dizey.sh")); + assert!(ws.smtp_password_set, "the screen must be able to say 'set'"); - // Host, port, username, password and from-address come from the - // environment. There is no column for any of them, so no response body - // that carries a workspace can carry a sender by accident. let serialised = serde_json::to_string(&ws).unwrap(); - assert!(!serialised.contains("smtp"), "{serialised}"); + assert!( + !serialised.contains("a-very-secret-string"), + "the password rode along in the workspace record: {serialised}" + ); +} + +/// Changing the port must not blank the password. The field is write-only, so +/// the screen has nothing to send back for it, and a save that took the empty +/// field literally would silently stop the workspace sending mail. +#[tokio::test] +async fn a_save_with_no_password_typed_keeps_the_stored_one() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let mut sender = NewSender { + host: "smtp.fastmail.com".into(), + port: 587, + username: "dizey".into(), + password: Some("keep-me".into()), + from_name: "Dizey".into(), + from_address: "dizey@dizey.sh".into(), + }; + scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap(); + + sender.port = 465; + sender.password = None; + scratch.store.set_sender(&ws_id, sender).await.unwrap(); + + let ws = scratch.store.workspace().await.unwrap().unwrap(); + assert_eq!(ws.smtp_port, Some(465), "the edit did not land"); + assert!(ws.smtp_password_set, "the password was blanked by an edit"); + assert_eq!( + scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + Some("keep-me") + ); +} + +/// And a password that is typed replaces the old one, which is the other half: +/// rotation has to work without a shell on the box. +#[tokio::test] +async fn a_typed_password_replaces_the_stored_one() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let mut sender = NewSender { + host: "smtp.fastmail.com".into(), + port: 587, + username: "dizey".into(), + password: Some("the-old-one".into()), + from_name: "Dizey".into(), + from_address: "dizey@dizey.sh".into(), + }; + scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap(); + sender.password = Some("the-new-one".into()); + scratch.store.set_sender(&ws_id, sender).await.unwrap(); + + assert_eq!( + scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + Some("the-new-one") + ); } #[tokio::test]