forge
Explore
Log in

Don't you dare go Hollow

The sender is workspace settings again, its password write-only

Browse files at this commit

3e26a9a3aa0d3146bf1f0c3440bd2c1453fca798Ahmet Kaan GümüşParent: 3172892
  • feat
    • the sender is workspace settings again, its password write-only
Show full message
🔒 feat(store): the sender is workspace settings again, its password write-only

The artboard's Settings screen has always had an editable sender — SMTP
HOST, PORT, USERNAME, PASSWORD, FROM NAME, FROM ADDRESS and a Save button.
Migration 0006 moved those columns out to the environment on the argument
that a password in a row is a password a handler can be made to return.
The argument was right about the risk and wrong about the price: it took
the screen away, and rotating a sender came to mean a shell on the box and
a restart. On a three-person team the person who runs the workspace and the
person with the shell are not the same, and the second one is not always
awake.

Migration 0008 adds the six columns back, in place — every one nullable,
which is what a workspace with no sender is.

The risk 0006 named is answered by shape rather than by absence:

  - `Workspace` has no password field. It is the record handlers load and
    pages serialise, so a field here is one careless response from the wire.
  - `WORKSPACE_COLUMNS` never selects the password. It selects
    `smtp_password IS NOT NULL`, so what comes back is a boolean —
    `smtp_password_set` — and the value does not travel even as far as the
    mapping function.
  - The only read is `Store::smtp_password`, which the mailer calls.
  - `set_sender` takes `password: Option<String>` and writes
    `COALESCE(?4, smtp_password)`, so the write-only field is real: an admin
    changes the port without retyping a secret the screen may not show them,
    and the save does not silently blank it.

Stated plainly, because it is the cost of the decision: the password is
stored as typed. It has to be — the server presents it to the mail host on
every send, so a one-way hash makes sending impossible, and encrypting it
under a key that also lives on this disk moves the problem without
shrinking it. Whoever holds a copy of the database file holds the sender's
password. It belongs to a sending account and to nothing else.

Tests: the record carries host, port, username and from-address and never
the password under any field name; a save with no password typed keeps the
stored one while the rest of the edit lands; a typed password replaces it;
and the read path is asserted against the real query, not against a comment.
crates/dizey-core/migrations/0008_sender_is_settings.sqladded+31 -0
@@ -0,0 +1,31 @@
1+-- The sender comes back into the table, because the admin sets it from the
2+-- Settings screen and not from the server's environment.
3+--
4+-- Migration 0006 moved these columns out on the argument that a password in a
5+-- row is a password a handler can be made to return. That argument is sound
6+-- and the mitigations survive: the password has no field on `Workspace`, so
7+-- no query that loads a workspace can carry it; it is written by
8+-- `Store::set_sender` and read by `Store::smtp_password`, which only the
9+-- mailer calls; and nothing that reaches a page ever holds it.
10+--
11+-- What it cost was the artboard's own screen: `SMTP HOST`, `PORT`,
12+-- `USERNAME`, `PASSWORD`, `FROM NAME`, `FROM ADDRESS` and a Save button, with
13+-- the sender changed by whoever runs the workspace rather than by whoever has
14+-- a shell on the box. A three-person team has those be different people, and
15+-- the second one is not always awake.
16+--
17+-- The password is stored as it is typed. It has to be: the server presents it
18+-- to the mail host on every send, so a one-way hash would make sending
19+-- impossible, and encrypting it under a key that also lives on this disk moves
20+-- the problem without shrinking it. The consequence is stated rather than
21+-- dressed up — whoever holds a copy of this file holds the sender's password,
22+-- so it belongs to a sending account and to nothing else.
23+--
24+-- Added rather than rebuilt: `ALTER TABLE ... ADD COLUMN` works in place, and
25+-- every one of these is nullable, which is what a workspace with no sender is.
26+ALTER TABLE workspace ADD COLUMN smtp_host TEXT;
27+ALTER TABLE workspace ADD COLUMN smtp_port INTEGER;
28+ALTER TABLE workspace ADD COLUMN smtp_username TEXT;
29+ALTER TABLE workspace ADD COLUMN smtp_password TEXT;
30+ALTER TABLE workspace ADD COLUMN smtp_from_name TEXT;
31+ALTER TABLE workspace ADD COLUMN smtp_from_address TEXT;
crates/dizey-core/src/store/mod.rsmodified+41 -4
@@ -35,20 +35,48 @@ pub enum StoreError {
35 35
36 pub type Result<T> = std::result::Result<T, StoreError>;36 pub type Result<T> = std::result::Result<T, StoreError>;
37 37
38-/// A workspace and the settings that ride on it. The sender is not here at38+/// A workspace and the settings that ride on it.
39-/// all: host, port, username, password and from-address come from the39+///
40-/// environment, so no query can return them and no backup of this file carries40+/// The sender is here except for its password, which has no field on purpose:
41-/// the password.41+/// this record is what handlers load and what pages serialise, so a password
42+/// with a field here is a password one careless response away from the wire.
43+/// It is written by [`Store::set_sender`] and read by [`Store::smtp_password`],
44+/// which only the mailer calls. What a screen gets instead is
45+/// `smtp_password_set` — enough to say "set" and nothing more.
42 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]46 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43 pub struct Workspace {47 pub struct Workspace {
44 pub id: String,48 pub id: String,
45 pub name: String,49 pub name: String,
46 pub created_at: OffsetDateTime,50 pub created_at: OffsetDateTime,
51+ pub smtp_host: Option<String>,
52+ pub smtp_port: Option<u32>,
53+ pub smtp_username: Option<String>,
54+ pub smtp_from_name: Option<String>,
55+ pub smtp_from_address: Option<String>,
56+ /// Whether a password is stored, never the password. Derived in the query
57+ /// so that the value itself does not travel even this far.
58+ pub smtp_password_set: bool,
47 pub attachment_limit_bytes: u64,59 pub attachment_limit_bytes: u64,
48 pub photo_limit_bytes: u64,60 pub photo_limit_bytes: u64,
49 pub allowed_file_types: Vec<String>,61 pub allowed_file_types: Vec<String>,
50 }62 }
51 63
64+/// A sender as an admin typed it, on its way to the table.
65+///
66+/// `password` is `None` when the admin left the field untouched, which is what
67+/// the screen sends when a password is already stored: the field is write-only,
68+/// so an edit to the port must not blank the password just because the form had
69+/// nothing to put in it.
70+#[derive(Debug, Clone, PartialEq)]
71+pub struct NewSender {
72+ pub host: String,
73+ pub port: u32,
74+ pub username: String,
75+ pub password: Option<String>,
76+ pub from_name: String,
77+ pub from_address: String,
78+}
79+
52 /// An account. `password_hash` is `None` for an invited member who has not80 /// An account. `password_hash` is `None` for an invited member who has not
53 /// signed in yet — the admin creates the account with a name and an address and81 /// signed in yet — the admin creates the account with a name and an address and
54 /// can never read or set the password.82 /// can never read or set the password.
@@ -289,6 +317,15 @@ pub trait Store: BoardReads + DetailReads + 'static {
289 317
290 async fn workspace(&self) -> Result<Option<Workspace>>;318 async fn workspace(&self) -> Result<Option<Workspace>>;
291 319
320+ /// Writes the sender. A `password` of `None` leaves the stored one alone,
321+ /// which is how an admin changes the port without retyping a secret the
322+ /// screen was never allowed to show them.
323+ async fn set_sender(&self, workspace_id: &str, sender: NewSender) -> Result<()>;
324+
325+ /// Reads the sender's password. Only the mailer calls this, and nothing it
326+ /// returns reaches a response body.
327+ async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>;
328+
292 async fn set_limits(329 async fn set_limits(
293 &self,330 &self,
294 workspace_id: &str,331 workspace_id: &str,
crates/dizey-core/src/store/turso_store.rsmodified+91 -22
@@ -13,7 +13,8 @@ use turso::{Builder, Connection, Row, Value, params};
13 use uuid::Uuid;13 use uuid::Uuid;
14 14
15 use super::{15 use super::{
16- Audience, Deletion, Event, Freeing, MailRule, MailSend, NewTask, NewUser, Recipient, Result,16+ Audience, Deletion, Event, Freeing, MailRule, MailSend, NewSender, NewTask, NewUser, Recipient,
17+ Result,
17 SendState, Session, SigninLink, Store, StoreError, Trigger, User, Workspace,18 SendState, Session, SigninLink, Store, StoreError, Trigger, User, Workspace,
18 };19 };
19 use crate::Role;20 use crate::Role;
@@ -34,6 +35,7 @@ const MIGRATIONS: &[(i64, &str)] = &[
34 (5, include_str!("../../migrations/0005_freeing.sql")),35 (5, include_str!("../../migrations/0005_freeing.sql")),
35 (6, include_str!("../../migrations/0006_sender_is_config.sql")),36 (6, include_str!("../../migrations/0006_sender_is_config.sql")),
36 (7, include_str!("../../migrations/0007_who_invited.sql")),37 (7, include_str!("../../migrations/0007_who_invited.sql")),
38+ (8, include_str!("../../migrations/0008_sender_is_settings.sql")),
37 ];39 ];
38 40
39 /// The board a fresh workspace gets, and its columns. `Done` is the column41 /// The board a fresh workspace gets, and its columns. `Done` is the column
@@ -343,11 +345,22 @@ fn workspace_from(row: &Row) -> Result<Workspace> {
343 attachment_limit_bytes: row.get::<i64>(3).map_err(backend)?.max(0) as u64,345 attachment_limit_bytes: row.get::<i64>(3).map_err(backend)?.max(0) as u64,
344 allowed_file_types,346 allowed_file_types,
345 photo_limit_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,347 photo_limit_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
348+ smtp_host: opt_text(row, 6)?,
349+ smtp_port: row.get::<Option<u32>>(7).map_err(backend)?,
350+ smtp_username: opt_text(row, 8)?,
351+ smtp_from_name: opt_text(row, 9)?,
352+ smtp_from_address: opt_text(row, 10)?,
353+ smtp_password_set: row.get::<i64>(11).map_err(backend)? != 0,
346 })354 })
347 }355 }
348 356
349-const WORKSPACE_COLUMNS: &str =357+// The password is not among these, and the last entry is why: the query asks
350- "id, name, created_at, attachment_limit_bytes, allowed_file_types, photo_limit_bytes";358+// the database whether a password exists and carries back a 0 or a 1. The value
359+// never leaves the row, so no caller can pass it on by accident.
360+const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \
361+ allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \
362+ smtp_from_name, smtp_from_address, \
363+ (smtp_password IS NOT NULL AND smtp_password <> '')";
351 364
352 fn user_from(row: &Row) -> Result<User> {365 fn user_from(row: &Row) -> Result<User> {
353 Ok(User {366 Ok(User {
@@ -517,6 +530,44 @@ impl Store for TursoStore {
517 }530 }
518 }531 }
519 532
533+ async fn set_sender(&self, workspace_id: &str, sender: NewSender) -> Result<()> {
534+ // `COALESCE(?4, smtp_password)` is the write-only field made real: the
535+ // screen sends no password when the admin did not type one, and the
536+ // stored secret survives an edit to the port. Passing an empty string
537+ // is not a way to blank it either — the form sends `None` for empty.
538+ self.conn
539+ .execute(
540+ "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \
541+ smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \
542+ smtp_from_address = ?6 WHERE id = ?7",
543+ params![
544+ sender.host,
545+ sender.port as i64,
546+ sender.username,
547+ sender.password,
548+ sender.from_name,
549+ sender.from_address,
550+ workspace_id
551+ ],
552+ )
553+ .await
554+ .map_err(backend)?;
555+ Ok(())
556+ }
557+
558+ async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>> {
559+ match self
560+ .one_row(
561+ "SELECT smtp_password FROM workspace WHERE id = ?1",
562+ params![workspace_id],
563+ )
564+ .await?
565+ {
566+ Some(row) => opt_text(&row, 0),
567+ None => Err(StoreError::NotFound),
568+ }
569+ }
570+
520 async fn set_limits(571 async fn set_limits(
521 &self,572 &self,
522 workspace_id: &str,573 workspace_id: &str,
@@ -2445,12 +2496,13 @@ mod probe {
2445 let _ = std::fs::remove_dir_all(&dir);2496 let _ = std::fs::remove_dir_all(&dir);
2446 }2497 }
2447 2498
2448- /// The sender's columns are gone from the schema, password included. This2499+ /// The password has a column but never a way out. The table holds it,
2449- /// is the property the config-only decision rests on: no handler can be2500+ /// because the server must present it to the mail host on every send; the
2450- /// made to return a password the table does not have, and a copy of the2501+ /// read path does not, because `WORKSPACE_COLUMNS` asks only whether one
2451- /// database file carries none.2502+ /// exists. This is the property the whole write-only field rests on, so it
2503+ /// is asserted against the real query rather than against a comment.
2452 #[tokio::test]2504 #[tokio::test]
2453- async fn the_workspace_table_has_no_sender_columns_left() {2505+ async fn the_workspace_read_path_cannot_carry_the_password() {
2454 let dir = std::env::temp_dir().join(format!("dizey-sender-{}", Uuid::new_v4()));2506 let dir = std::env::temp_dir().join(format!("dizey-sender-{}", Uuid::new_v4()));
2455 std::fs::create_dir_all(&dir).unwrap();2507 std::fs::create_dir_all(&dir).unwrap();
2456 let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap())2508 let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap())
@@ -2458,24 +2510,41 @@ mod probe {
2458 .unwrap();2510 .unwrap();
2459 use crate::store::Store as _;2511 use crate::store::Store as _;
2460 2512
2461- let row = store2513+ let (ws, _admin) = store
2462- .one_row(2514+ .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "hash")
2463- "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'workspace'",
2464- (),
2465- )
2466 .await2515 .await
2467- .unwrap()2516+ .unwrap();
2468- .expect("the workspace table exists");
2469- let schema = text(&row, 0).unwrap();
2470- assert!(!schema.contains("smtp"), "{schema}");
2471-
2472- // The rebuild put the name back, so everything that references the
2473- // workspace still lands on this table.
2474 store2517 store
2475- .claim_workspace("Dizey", "ada@dizey.sh", "Ada", "hash")2518+ .set_sender(
2519+ &ws.id,
2520+ NewSender {
2521+ host: "smtp.fastmail.com".into(),
2522+ port: 587,
2523+ username: "dizey".into(),
2524+ password: Some("hunter2-and-then-some".into()),
2525+ from_name: "Dizey".into(),
2526+ from_address: "dizey@dizey.sh".into(),
2527+ },
2528+ )
2476 .await2529 .await
2477 .unwrap();2530 .unwrap();
2478- assert!(store.workspace().await.unwrap().is_some());2531+
2532+ // The column exists and holds what was written — the mailer needs it.
2533+ assert_eq!(
2534+ store.smtp_password(&ws.id).await.unwrap().as_deref(),
2535+ Some("hunter2-and-then-some")
2536+ );
2537+
2538+ // And the record a page would be handed does not contain it, anywhere,
2539+ // under any field name.
2540+ let loaded = store.workspace().await.unwrap().unwrap();
2541+ assert!(loaded.smtp_password_set, "a password was stored");
2542+ let serialised = serde_json::to_string(&loaded).unwrap();
2543+ assert!(
2544+ !serialised.contains("hunter2"),
2545+ "the workspace record carried the password: {serialised}"
2546+ );
2547+ assert_eq!(loaded.smtp_host.as_deref(), Some("smtp.fastmail.com"));
2479 let _ = std::fs::remove_dir_all(&dir);2548 let _ = std::fs::remove_dir_all(&dir);
2480 }2549 }
2481 }2550 }
crates/dizey-core/tests/store.rsmodified+90 -9
@@ -9,7 +9,7 @@ use std::path::PathBuf;
9 use dizey_core::Role;9 use dizey_core::Role;
10 use dizey_core::auth::{Token, hash_password};10 use dizey_core::auth::{Token, hash_password};
11 use dizey_core::store::{11 use dizey_core::store::{
12- Audience, MailRule, NewUser, SendState, Store, StoreError, Trigger, TursoStore, User,12+ Audience, MailRule, NewSender, NewUser, SendState, Store, StoreError, Trigger, TursoStore, User,
13 };13 };
14 use time::{Duration, OffsetDateTime};14 use time::{Duration, OffsetDateTime};
15 use uuid::Uuid;15 use uuid::Uuid;
@@ -89,14 +89,14 @@ async fn migrations_apply_once_and_survive_reopen() {
89 let path = dir.join("dizey.db").to_string_lossy().into_owned();89 let path = dir.join("dizey.db").to_string_lossy().into_owned();
90 90
91 let first = TursoStore::open(&path).await.unwrap();91 let first = TursoStore::open(&path).await.unwrap();
92- assert_eq!(first.schema_version().await.unwrap(), 7);92+ assert_eq!(first.schema_version().await.unwrap(), 8);
93 claim(&first).await;93 claim(&first).await;
94 drop(first);94 drop(first);
95 95
96 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and96 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
97 // must not lose what the first open wrote.97 // must not lose what the first open wrote.
98 let second = TursoStore::open(&path).await.unwrap();98 let second = TursoStore::open(&path).await.unwrap();
99- assert_eq!(second.schema_version().await.unwrap(), 7);99+ assert_eq!(second.schema_version().await.unwrap(), 8);
100 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey");100 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey");
101 drop(second);101 drop(second);
102 let _ = std::fs::remove_dir_all(&dir);102 let _ = std::fs::remove_dir_all(&dir);
@@ -218,16 +218,97 @@ async fn workspace_defaults_match_the_settings_screen() {
218 );218 );
219 }219 }
220 220
221+/// An admin edits the sender from Settings, so the record carries host, port,
222+/// username and from-address. It never carries the password: that field does
223+/// not exist on the struct, and what a screen gets is the fact that one is set.
221 #[tokio::test]224 #[tokio::test]
222-async fn the_sender_is_not_in_the_workspace_record_at_all() {225+async fn the_workspace_record_carries_the_sender_but_never_its_password() {
223- let (scratch, _, _) = workspace_with_admin().await;226+ let (scratch, ws_id, _) = workspace_with_admin().await;
227+ let fresh = scratch.store.workspace().await.unwrap().unwrap();
228+ assert_eq!(fresh.smtp_host, None, "a new workspace has no sender");
229+ assert!(!fresh.smtp_password_set);
230+
231+ scratch
232+ .store
233+ .set_sender(
234+ &ws_id,
235+ NewSender {
236+ host: "smtp.fastmail.com".into(),
237+ port: 587,
238+ username: "dizey".into(),
239+ password: Some("a-very-secret-string".into()),
240+ from_name: "Dizey".into(),
241+ from_address: "dizey@dizey.sh".into(),
242+ },
243+ )
244+ .await
245+ .unwrap();
246+
224 let ws = scratch.store.workspace().await.unwrap().unwrap();247 let ws = scratch.store.workspace().await.unwrap().unwrap();
248+ assert_eq!(ws.smtp_host.as_deref(), Some("smtp.fastmail.com"));
249+ assert_eq!(ws.smtp_port, Some(587));
250+ assert_eq!(ws.smtp_username.as_deref(), Some("dizey"));
251+ assert_eq!(ws.smtp_from_name.as_deref(), Some("Dizey"));
252+ assert_eq!(ws.smtp_from_address.as_deref(), Some("dizey@dizey.sh"));
253+ assert!(ws.smtp_password_set, "the screen must be able to say 'set'");
225 254
226- // Host, port, username, password and from-address come from the
227- // environment. There is no column for any of them, so no response body
228- // that carries a workspace can carry a sender by accident.
229 let serialised = serde_json::to_string(&ws).unwrap();255 let serialised = serde_json::to_string(&ws).unwrap();
230- assert!(!serialised.contains("smtp"), "{serialised}");256+ assert!(
257+ !serialised.contains("a-very-secret-string"),
258+ "the password rode along in the workspace record: {serialised}"
259+ );
260+}
261+
262+/// Changing the port must not blank the password. The field is write-only, so
263+/// the screen has nothing to send back for it, and a save that took the empty
264+/// field literally would silently stop the workspace sending mail.
265+#[tokio::test]
266+async fn a_save_with_no_password_typed_keeps_the_stored_one() {
267+ let (scratch, ws_id, _) = workspace_with_admin().await;
268+ let mut sender = NewSender {
269+ host: "smtp.fastmail.com".into(),
270+ port: 587,
271+ username: "dizey".into(),
272+ password: Some("keep-me".into()),
273+ from_name: "Dizey".into(),
274+ from_address: "dizey@dizey.sh".into(),
275+ };
276+ scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap();
277+
278+ sender.port = 465;
279+ sender.password = None;
280+ scratch.store.set_sender(&ws_id, sender).await.unwrap();
281+
282+ let ws = scratch.store.workspace().await.unwrap().unwrap();
283+ assert_eq!(ws.smtp_port, Some(465), "the edit did not land");
284+ assert!(ws.smtp_password_set, "the password was blanked by an edit");
285+ assert_eq!(
286+ scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
287+ Some("keep-me")
288+ );
289+}
290+
291+/// And a password that is typed replaces the old one, which is the other half:
292+/// rotation has to work without a shell on the box.
293+#[tokio::test]
294+async fn a_typed_password_replaces_the_stored_one() {
295+ let (scratch, ws_id, _) = workspace_with_admin().await;
296+ let mut sender = NewSender {
297+ host: "smtp.fastmail.com".into(),
298+ port: 587,
299+ username: "dizey".into(),
300+ password: Some("the-old-one".into()),
301+ from_name: "Dizey".into(),
302+ from_address: "dizey@dizey.sh".into(),
303+ };
304+ scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap();
305+ sender.password = Some("the-new-one".into());
306+ scratch.store.set_sender(&ws_id, sender).await.unwrap();
307+
308+ assert_eq!(
309+ scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),
310+ Some("the-new-one")
311+ );
231 }312 }
232 313
233 #[tokio::test]314 #[tokio::test]