diff --git a/Cargo.lock b/Cargo.lock index 92cf1c8..86aa835 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -859,9 +859,13 @@ dependencies = [ name = "dizey-core" version = "0.1.0" dependencies = [ + "async-trait", "serde", + "serde_json", "thiserror", "time", + "tokio", + "turso", "uuid", ] diff --git a/Cargo.toml b/Cargo.toml index 46df3d1..ff08544 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,11 +11,12 @@ repository = "https://github.com/DizeyLab/izlek" [workspace.dependencies] dizey-core = { path = "crates/dizey-core" } serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.145" thiserror = "2.0.20" uuid = { version = "1.25.0", features = ["v4", "serde"] } time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] } tokio = { version = "1.53.1", features = ["full"] } -turso = "0.8.0-pre.7" +turso = "=0.8.0-pre.7" [profile.release] codegen-units = 1 diff --git a/crates/dizey-core/Cargo.toml b/crates/dizey-core/Cargo.toml index 9eee272..7378633 100644 --- a/crates/dizey-core/Cargo.toml +++ b/crates/dizey-core/Cargo.toml @@ -7,7 +7,14 @@ repository.workspace = true description = "Domain model and storage for Dizey" [dependencies] +async-trait = "0.1.92" serde.workspace = true +serde_json.workspace = true thiserror.workspace = true time.workspace = true +turso.workspace = true uuid.workspace = true + +[dev-dependencies] +serde_json.workspace = true +tokio = { workspace = true } diff --git a/crates/dizey-core/migrations/0001_init.sql b/crates/dizey-core/migrations/0001_init.sql new file mode 100644 index 0000000..19114a3 --- /dev/null +++ b/crates/dizey-core/migrations/0001_init.sql @@ -0,0 +1,192 @@ +-- Dizey initial schema. +-- +-- Plain versioned SQL applied at boot: Turso has no migration runner of its +-- own, and keeping the schema as SQL is what makes the store trait swappable. +-- Timestamps are RFC 3339 text in UTC. Ids are UUIDs as text. + +CREATE TABLE workspace ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + created_at TEXT NOT NULL, + -- The single sender every mail in the workspace goes through. Written by + -- the admin in Settings; the password is never returned to the client. + smtp_host TEXT, + smtp_port INTEGER, + smtp_username TEXT, + smtp_password TEXT, + smtp_from_name TEXT, + smtp_from_address TEXT, + -- Limits. Each states its consequence in the UI, not here. + attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400, + photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, + -- JSON array of allowed extensions. An empty array means every type. + allowed_file_types TEXT NOT NULL DEFAULT '[]', + -- 'anyone' | 'admin' + who_can_delete_tasks TEXT NOT NULL DEFAULT 'anyone' +); + +CREATE TABLE user ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspace(id), + email TEXT NOT NULL, + display_name TEXT NOT NULL, + -- 'admin' | 'member' | 'viewer' + role TEXT NOT NULL, + -- NULL until the person picks a password on first sign-in. The admin + -- creates the account with a name and an address and nothing else. + password_hash TEXT, + photo_path TEXT, + created_at TEXT NOT NULL, + last_signed_in_at TEXT +); +CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email); + +-- First sign-in / resend links. Only the hash is stored: the plaintext is shown +-- once when the admin creates or resends it. +CREATE TABLE signin_link ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + token_hash TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_at TEXT +); +CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash); + +CREATE TABLE board ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspace(id), + name TEXT NOT NULL, + task_prefix TEXT NOT NULL DEFAULT 'DZ', + next_task_no INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL +); + +CREATE TABLE board_column ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + name TEXT NOT NULL, + position INTEGER NOT NULL, + -- The column a finished task lands in; drives the "done Aug 14" card state. + is_done INTEGER NOT NULL DEFAULT 0 +); + +CREATE TABLE task ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + -- Human key from the mockups, e.g. DZ-14. + task_key TEXT NOT NULL, + title TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + column_id TEXT NOT NULL REFERENCES board_column(id), + deadline TEXT, + position REAL NOT NULL DEFAULT 0, + created_by TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + done_at TEXT, + deleted_at TEXT +); +CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key); +CREATE INDEX task_by_column ON task(column_id); + +CREATE TABLE task_assignee ( + task_id TEXT NOT NULL REFERENCES task(id), + user_id TEXT NOT NULL REFERENCES user(id), + PRIMARY KEY (task_id, user_id) +); + +CREATE TABLE task_watcher ( + task_id TEXT NOT NULL REFERENCES task(id), + user_id TEXT NOT NULL REFERENCES user(id), + PRIMARY KEY (task_id, user_id) +); + +-- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the +-- blocking task finishes, which is what the "you can start now" rule reads. +CREATE TABLE task_dependency ( + blocked_task_id TEXT NOT NULL REFERENCES task(id), + blocking_task_id TEXT NOT NULL REFERENCES task(id), + created_at TEXT NOT NULL, + cleared_at TEXT, + PRIMARY KEY (blocked_task_id, blocking_task_id) +); + +CREATE TABLE comment ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + author_id TEXT NOT NULL REFERENCES user(id), + body TEXT NOT NULL, + created_at TEXT NOT NULL +); +CREATE INDEX comment_by_task ON comment(task_id); + +CREATE TABLE attachment ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + comment_id TEXT REFERENCES comment(id), + file_name TEXT NOT NULL, + mime_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + stored_path TEXT NOT NULL, + uploaded_by TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); + +-- The activity strip in the task detail: who did what, and whether it mailed. +CREATE TABLE activity ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + actor_id TEXT REFERENCES user(id), + kind TEXT NOT NULL, + detail TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL +); +CREATE INDEX activity_by_task ON activity(task_id); + +-- Mail rules are written only by the admin and are always on. A rule that +-- addresses an external address stays off until that address confirms. +CREATE TABLE mail_rule ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspace(id), + board_id TEXT REFERENCES board(id), + -- 'status_becomes' | 'deadline_in' | 'unblocked' + trigger_kind TEXT NOT NULL, + trigger_value TEXT NOT NULL, + subject TEXT NOT NULL, + -- 'assignees' | 'assignees_watchers' | 'everyone' | 'external' + audience TEXT NOT NULL, + external_address TEXT, + external_confirmed INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + last_sent_at TEXT +); + +-- One row per (rule, task, transition) actually sent, so a revert-then-redo +-- does not mail twice. +CREATE TABLE mail_send ( + id TEXT PRIMARY KEY, + rule_id TEXT NOT NULL REFERENCES mail_rule(id), + task_id TEXT NOT NULL REFERENCES task(id), + transition TEXT NOT NULL, + sent_at TEXT NOT NULL +); +CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, task_id, transition); + +-- Read-only links: dizey.sh/v/. Only the hash of the token is stored, so a +-- database copy does not hand out working links; revoking is server-side and +-- immediate. +CREATE TABLE view_link ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspace(id), + board_id TEXT NOT NULL REFERENCES board(id), + token_hash TEXT NOT NULL, + -- 'whole_board' | 'deadlines' + scope TEXT NOT NULL, + created_by TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL, + expires_at TEXT, + revoked_at TEXT, + open_count INTEGER NOT NULL DEFAULT 0 +); +CREATE UNIQUE INDEX view_link_token ON view_link(token_hash); diff --git a/crates/dizey-core/src/lib.rs b/crates/dizey-core/src/lib.rs index a24c5c3..069602a 100644 --- a/crates/dizey-core/src/lib.rs +++ b/crates/dizey-core/src/lib.rs @@ -4,5 +4,7 @@ //! `ssr` feature so none of it is compiled into the wasm bundle. pub mod role; +pub mod store; pub use role::Role; +pub use store::{Store, StoreError, TursoStore}; diff --git a/crates/dizey-core/src/role.rs b/crates/dizey-core/src/role.rs index f009046..4e85089 100644 --- a/crates/dizey-core/src/role.rs +++ b/crates/dizey-core/src/role.rs @@ -51,6 +51,16 @@ impl Role { Role::Viewer => "viewer", } } + + /// The inverse of [`Role::as_str`], for values read back out of the store. + pub fn parse(raw: &str) -> Option { + match raw { + "admin" => Some(Role::Admin), + "member" => Some(Role::Member), + "viewer" => Some(Role::Viewer), + _ => None, + } + } } #[cfg(test)] diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs new file mode 100644 index 0000000..3298d24 --- /dev/null +++ b/crates/dizey-core/src/store/mod.rs @@ -0,0 +1,202 @@ +//! Storage boundary. +//! +//! Everything the app does to persistent state goes through [`Store`]. The only +//! implementation today is Turso (in-process, SQLite-compatible); a Postgres +//! swap is a new impl of this trait and nothing else. + +use async_trait::async_trait; +use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; + +use crate::Role; + +pub mod turso_store; + +pub use turso_store::TursoStore; + +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + #[error("database: {0}")] + Backend(String), + #[error("not found")] + NotFound, + #[error("{0} already exists")] + Conflict(&'static str), + #[error("stored value is not valid: {0}")] + Corrupt(String), +} + +pub type Result = std::result::Result; + +/// A workspace and the settings that ride on it. The SMTP password is +/// deliberately absent: it is written through [`Store::set_smtp`] and read only +/// by the mailer, never returned to a page. +#[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, + pub attachment_limit_bytes: u64, + pub photo_limit_bytes: u64, + pub allowed_file_types: Vec, + pub who_can_delete_tasks: DeletePolicy, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DeletePolicy { + /// Anyone who can write tasks may delete one. + Anyone, + /// Only the admin. + Admin, +} + +impl DeletePolicy { + pub fn as_str(self) -> &'static str { + match self { + DeletePolicy::Anyone => "anyone", + DeletePolicy::Admin => "admin", + } + } + + pub fn parse(raw: &str) -> Result { + match raw { + "anyone" => Ok(DeletePolicy::Anyone), + "admin" => Ok(DeletePolicy::Admin), + other => Err(StoreError::Corrupt(format!("delete policy {other:?}"))), + } + } +} + +/// 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. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct User { + pub id: String, + pub workspace_id: String, + pub email: String, + pub display_name: String, + pub role: Role, + pub password_hash: Option, + pub photo_path: Option, + pub created_at: OffsetDateTime, + pub last_signed_in_at: Option, +} + +impl User { + /// True once the person has chosen their own password. + pub fn has_signed_in(&self) -> bool { + self.password_hash.is_some() + } +} + +pub struct NewUser { + pub workspace_id: String, + pub email: String, + pub display_name: String, + pub role: Role, +} + +/// A first-sign-in link. Only the hash of the token is ever stored; the +/// plaintext is shown once, when the link is created or resent. +#[derive(Debug, Clone, PartialEq)] +pub struct SigninLink { + pub id: String, + pub user_id: String, + pub created_at: OffsetDateTime, + pub expires_at: OffsetDateTime, + pub used_at: Option, +} + +impl SigninLink { + pub fn is_usable(&self, now: OffsetDateTime) -> bool { + self.used_at.is_none() && now < self.expires_at + } +} + +/// The storage boundary. Dyn-safe on purpose: handlers hold `Arc`. +#[async_trait] +pub trait Store: Send + Sync + 'static { + // -- workspace --------------------------------------------------------- + + /// Creates the workspace. Fails with [`StoreError::Conflict`] if one + /// already exists: Dizey hosts a single workspace per database. + async fn create_workspace(&self, name: &str) -> Result; + + async fn workspace(&self) -> Result>; + + async fn set_smtp( + &self, + workspace_id: &str, + host: &str, + port: u32, + username: &str, + password: &str, + from_name: &str, + from_address: &str, + ) -> Result<()>; + + /// Reads the sender password. Only the mailer calls this. + async fn smtp_password(&self, workspace_id: &str) -> Result>; + + async fn set_limits( + &self, + workspace_id: &str, + attachment_limit_bytes: u64, + photo_limit_bytes: u64, + allowed_file_types: &[String], + who_can_delete_tasks: DeletePolicy, + ) -> Result<()>; + + // -- users ------------------------------------------------------------- + + async fn create_user(&self, new: NewUser) -> Result; + + async fn user(&self, id: &str) -> Result>; + + /// Lookup by address. Callers must not turn a `None` into a different + /// public response than a `Some`: the sign-in surface never reveals whether + /// an address has an account. + async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result>; + + async fn users(&self, workspace_id: &str) -> Result>; + + async fn count_users(&self, workspace_id: &str) -> Result; + + async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>; + + async fn set_profile( + &self, + user_id: &str, + display_name: &str, + photo_path: Option<&str>, + ) -> Result<()>; + + async fn set_role(&self, user_id: &str, role: Role) -> Result<()>; + + async fn mark_signed_in(&self, user_id: &str, at: OffsetDateTime) -> Result<()>; + + // -- sign-in links ----------------------------------------------------- + + /// Stores the hash of a freshly minted link. The caller keeps the plaintext + /// and shows it once. + async fn create_signin_link( + &self, + user_id: &str, + token_hash: &str, + expires_at: OffsetDateTime, + ) -> Result; + + /// Looks a link up by the hash of the presented token. Returns the link + /// whether or not it is still usable, so the caller can tell an expired + /// link apart from a wrong one — an expired link is not a dead account. + async fn signin_link_by_hash(&self, token_hash: &str) -> Result>; + + async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()>; +} diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs new file mode 100644 index 0000000..631210b --- /dev/null +++ b/crates/dizey-core/src/store/turso_store.rs @@ -0,0 +1,628 @@ +//! Turso implementation of [`Store`]. +//! +//! Turso is in-process and SQLite-compatible, so the schema is plain SQL and +//! there is no server to run alongside the binary. It ships no migration runner +//! of its own; [`TursoStore::open`] applies the numbered files in +//! `crates/dizey-core/migrations` at boot and records the version. + +use async_trait::async_trait; +use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; +use turso::{Builder, Connection, Row, Value, params}; +use uuid::Uuid; + +use super::{ + DeletePolicy, NewUser, Result, SigninLink, Store, StoreError, User, Workspace, +}; +use crate::Role; + +/// Every migration, in order. Adding one means appending a file and a line. +const MIGRATIONS: &[(i64, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; + +pub struct TursoStore { + conn: Connection, + // Held so the database outlives its connection. + _db: turso::Database, +} + +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 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 + // handle serialise by themselves, but a second handle on the same file + // (a second process, or a careless second open) fails outright with + // "database is locked" and silently drops the write unless a busy + // timeout is set. Both pragmas are set on every connection we hand out. + for pragma in [ + "PRAGMA foreign_keys = ON", + "PRAGMA busy_timeout = 5000", + ] { + conn.execute(pragma, ()).await.map_err(backend)?; + } + let store = Self { conn, _db: db }; + store.migrate().await?; + Ok(store) + } + + async fn migrate(&self) -> Result<()> { + self.conn + .execute( + "CREATE TABLE IF NOT EXISTS schema_version ( + version INTEGER PRIMARY KEY, + applied_at TEXT NOT NULL + )", + (), + ) + .await + .map_err(backend)?; + + let applied = self.applied_versions().await?; + for (version, sql) in MIGRATIONS { + if applied.contains(version) { + continue; + } + self.conn.execute_batch(sql).await.map_err(backend)?; + self.conn + .execute( + "INSERT INTO schema_version (version, applied_at) VALUES (?1, ?2)", + params![*version, now_text()?], + ) + .await + .map_err(backend)?; + } + Ok(()) + } + + async fn applied_versions(&self) -> Result> { + let mut rows = self + .conn + .query("SELECT version FROM schema_version", ()) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(row.get::(0).map_err(backend)?); + } + Ok(out) + } + + /// The schema version the database is actually at. + pub async fn schema_version(&self) -> Result { + Ok(self.applied_versions().await?.into_iter().max().unwrap_or(0)) + } + + async fn one_row(&self, sql: &str, args: impl turso::IntoParams) -> Result> { + let mut rows = self.conn.query(sql, args).await.map_err(backend)?; + rows.next().await.map_err(backend) + } +} + +fn backend(e: E) -> StoreError { + StoreError::Backend(e.to_string()) +} + +fn now_text() -> Result { + stamp(OffsetDateTime::now_utc()) +} + +fn stamp(at: OffsetDateTime) -> Result { + at.format(&Rfc3339) + .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}"))) +} + +fn parse_stamp(raw: &str) -> Result { + OffsetDateTime::parse(raw, &Rfc3339) + .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}"))) +} + +fn opt_stamp(row: &Row, idx: usize) -> Result> { + match row.get::>(idx).map_err(backend)? { + Some(raw) => Ok(Some(parse_stamp(&raw)?)), + None => Ok(None), + } +} + +fn text(row: &Row, idx: usize) -> Result { + row.get::(idx).map_err(backend) +} + +fn opt_text(row: &Row, idx: usize) -> Result> { + row.get::>(idx).map_err(backend) +} + +fn count_of(row: &Row) -> Result { + row.get::(0) + .map_err(backend) + .map(|n| n.max(0) as u64) +} + +fn workspace_from(row: &Row) -> Result { + let types_json = text(row, 9)?; + let allowed_file_types: Vec = if types_json.trim().is_empty() { + Vec::new() + } else { + serde_json::from_str(&types_json) + .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))? + }; + Ok(Workspace { + id: text(row, 0)?, + name: text(row, 1)?, + created_at: parse_stamp(&text(row, 2)?)?, + smtp_host: opt_text(row, 3)?, + smtp_port: row.get::>(4).map_err(backend)?, + smtp_username: opt_text(row, 5)?, + smtp_from_name: opt_text(row, 6)?, + smtp_from_address: opt_text(row, 7)?, + attachment_limit_bytes: row.get::(8).map_err(backend)?.max(0) as u64, + allowed_file_types, + photo_limit_bytes: row.get::(10).map_err(backend)?.max(0) as u64, + who_can_delete_tasks: DeletePolicy::parse(&text(row, 11)?)?, + }) +} + +const WORKSPACE_COLUMNS: &str = "id, name, created_at, smtp_host, smtp_port, smtp_username, \ + smtp_from_name, smtp_from_address, attachment_limit_bytes, allowed_file_types, \ + photo_limit_bytes, who_can_delete_tasks"; + +fn user_from(row: &Row) -> Result { + Ok(User { + id: text(row, 0)?, + workspace_id: text(row, 1)?, + email: text(row, 2)?, + display_name: text(row, 3)?, + role: Role::parse(&text(row, 4)?) + .ok_or_else(|| StoreError::Corrupt("role".into()))?, + password_hash: opt_text(row, 5)?, + photo_path: opt_text(row, 6)?, + created_at: parse_stamp(&text(row, 7)?)?, + last_signed_in_at: opt_stamp(row, 8)?, + }) +} + +const USER_COLUMNS: &str = "id, workspace_id, email, display_name, role, password_hash, \ + photo_path, created_at, last_signed_in_at"; + +fn signin_link_from(row: &Row) -> Result { + Ok(SigninLink { + id: text(row, 0)?, + user_id: text(row, 1)?, + created_at: parse_stamp(&text(row, 2)?)?, + expires_at: parse_stamp(&text(row, 3)?)?, + used_at: opt_stamp(row, 4)?, + }) +} + +/// Addresses are matched case-insensitively; the display form is kept as typed. +fn fold_email(email: &str) -> String { + email.trim().to_lowercase() +} + +#[async_trait] +impl Store for TursoStore { + async fn create_workspace(&self, name: &str) -> Result { + if self.workspace().await?.is_some() { + return Err(StoreError::Conflict("workspace")); + } + let id = Uuid::new_v4().to_string(); + self.conn + .execute( + "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)", + params![id.clone(), name, now_text()?], + ) + .await + .map_err(backend)?; + self.workspace().await?.ok_or(StoreError::NotFound) + } + + async fn workspace(&self) -> Result> { + let sql = format!("SELECT {WORKSPACE_COLUMNS} FROM workspace LIMIT 1"); + match self.one_row(&sql, ()).await? { + Some(row) => Ok(Some(workspace_from(&row)?)), + None => Ok(None), + } + } + + async fn set_smtp( + &self, + workspace_id: &str, + host: &str, + port: u32, + username: &str, + password: &str, + from_name: &str, + from_address: &str, + ) -> Result<()> { + self.conn + .execute( + "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ + smtp_password = ?4, smtp_from_name = ?5, smtp_from_address = ?6 WHERE id = ?7", + params![ + host, + port as i64, + username, + password, + from_name, + 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, + attachment_limit_bytes: u64, + photo_limit_bytes: u64, + allowed_file_types: &[String], + who_can_delete_tasks: DeletePolicy, + ) -> Result<()> { + let types = serde_json::to_string(allowed_file_types) + .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))?; + self.conn + .execute( + "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \ + allowed_file_types = ?3, who_can_delete_tasks = ?4 WHERE id = ?5", + params![ + attachment_limit_bytes as i64, + photo_limit_bytes as i64, + types, + who_can_delete_tasks.as_str(), + workspace_id + ], + ) + .await + .map_err(backend)?; + Ok(()) + } + + async fn create_user(&self, new: NewUser) -> Result { + let email = fold_email(&new.email); + if self.user_by_email(&new.workspace_id, &email).await?.is_some() { + return Err(StoreError::Conflict("account")); + } + let id = Uuid::new_v4().to_string(); + self.conn + .execute( + "INSERT INTO user (id, workspace_id, email, display_name, role, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + id.clone(), + new.workspace_id, + email, + new.display_name, + new.role.as_str(), + now_text()? + ], + ) + .await + .map_err(backend)?; + self.user(&id).await?.ok_or(StoreError::NotFound) + } + + async fn user(&self, id: &str) -> Result> { + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE id = ?1"); + match self.one_row(&sql, params![id]).await? { + Some(row) => Ok(Some(user_from(&row)?)), + None => Ok(None), + } + } + + async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result> { + let sql = + format!("SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 AND email = ?2"); + match self + .one_row(&sql, params![workspace_id, fold_email(email)]) + .await? + { + Some(row) => Ok(Some(user_from(&row)?)), + None => Ok(None), + } + } + + async fn users(&self, workspace_id: &str) -> Result> { + let sql = format!( + "SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 ORDER BY created_at, id" + ); + let mut rows = self.conn.query(&sql, params![workspace_id]).await.map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(user_from(&row)?); + } + Ok(out) + } + + async fn count_users(&self, workspace_id: &str) -> Result { + match self + .one_row( + "SELECT COUNT(*) FROM user WHERE workspace_id = ?1", + params![workspace_id], + ) + .await? + { + Some(row) => count_of(&row), + None => Ok(0), + } + } + + async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()> { + let n = self + .conn + .execute( + "UPDATE user SET password_hash = ?1 WHERE id = ?2", + params![hash, user_id], + ) + .await + .map_err(backend)?; + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } + } + + async fn set_profile( + &self, + user_id: &str, + display_name: &str, + photo_path: Option<&str>, + ) -> Result<()> { + let photo = match photo_path { + Some(p) => Value::from(p.to_string()), + None => Value::Null, + }; + let n = self + .conn + .execute( + "UPDATE user SET display_name = ?1, photo_path = ?2 WHERE id = ?3", + params![display_name, photo, user_id], + ) + .await + .map_err(backend)?; + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } + } + + async fn set_role(&self, user_id: &str, role: Role) -> Result<()> { + let n = self + .conn + .execute( + "UPDATE user SET role = ?1 WHERE id = ?2", + params![role.as_str(), user_id], + ) + .await + .map_err(backend)?; + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } + } + + async fn mark_signed_in(&self, user_id: &str, at: OffsetDateTime) -> Result<()> { + let n = self + .conn + .execute( + "UPDATE user SET last_signed_in_at = ?1 WHERE id = ?2", + params![stamp(at)?, user_id], + ) + .await + .map_err(backend)?; + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } + } + + async fn create_signin_link( + &self, + user_id: &str, + token_hash: &str, + expires_at: OffsetDateTime, + ) -> Result { + let id = Uuid::new_v4().to_string(); + self.conn + .execute( + "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + id.clone(), + user_id, + token_hash, + now_text()?, + stamp(expires_at)? + ], + ) + .await + .map_err(backend)?; + match self + .one_row( + "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link WHERE id = ?1", + params![id], + ) + .await? + { + Some(row) => signin_link_from(&row), + None => Err(StoreError::NotFound), + } + } + + async fn signin_link_by_hash(&self, token_hash: &str) -> Result> { + match self + .one_row( + "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link \ + WHERE token_hash = ?1", + params![token_hash], + ) + .await? + { + Some(row) => Ok(Some(signin_link_from(&row)?)), + None => Ok(None), + } + } + + async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()> { + let n = self + .conn + .execute( + "UPDATE signin_link SET used_at = ?1 WHERE id = ?2 AND used_at IS NULL", + params![stamp(at)?, id], + ) + .await + .map_err(backend)?; + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } + } +} + +#[cfg(test)] +mod probe { + //! What Turso actually does about durability and concurrent writers. + //! + //! These are not assertions about our code; they record engine behaviour we + //! are relying on. They fail loudly if a Turso upgrade changes it. + + use super::*; + + async fn pragma(conn: &Connection, name: &str) -> String { + let mut rows = conn.query(&format!("PRAGMA {name}"), ()).await.unwrap(); + match rows.next().await.unwrap() { + Some(row) => format!("{:?}", row.get_value(0).unwrap()), + None => "".to_string(), + } + } + + #[tokio::test] + async fn durability_defaults_are_recorded() { + let dir = std::env::temp_dir().join(format!("dizey-probe-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("probe.db"); + let db = Builder::new_local(path.to_str().unwrap()) + .build() + .await + .unwrap(); + let conn = db.connect().unwrap(); + // WAL journalling with synchronous=FULL: a committed write is fsynced + // before the commit returns. If a Turso upgrade weakens either of + // these, this test is where we find out. + assert_eq!(pragma(&conn, "journal_mode").await, "Text(\"wal\")"); + assert_eq!(pragma(&conn, "synchronous").await, "Integer(2)"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[tokio::test] + async fn concurrent_writers_on_one_database() { + let dir = std::env::temp_dir().join(format!("dizey-probe-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("probe.db"); + let db = Builder::new_local(path.to_str().unwrap()) + .build() + .await + .unwrap(); + let a = db.connect().unwrap(); + let b = db.connect().unwrap(); + a.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, who TEXT)", ()) + .await + .unwrap(); + + // Interleaved, both connections in flight at once. + let write_a = async { + for i in 0..50i64 { + a.execute("INSERT INTO t (id, who) VALUES (?1, 'a')", params![i]) + .await?; + } + Ok::<_, turso::Error>(()) + }; + let write_b = async { + for i in 100..150i64 { + b.execute("INSERT INTO t (id, who) VALUES (?1, 'b')", params![i]) + .await?; + } + Ok::<_, turso::Error>(()) + }; + // Two connections on ONE handle: the engine serialises them for us. + let (ra, rb) = tokio::join!(write_a, write_b); + ra.expect("writer a"); + rb.expect("writer b"); + + let c = db.connect().unwrap(); + let mut rows = c.query("SELECT COUNT(*) FROM t", ()).await.unwrap(); + let n = rows.next().await.unwrap().unwrap().get::(0).unwrap(); + assert_eq!(n, 100, "no write lost between two connections"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn two_database_handles_on_one_file() { + // Two handles on the same file is the shape a second process takes. + let dir = std::env::temp_dir().join(format!("dizey-probe-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("probe.db"); + let p = path.to_str().unwrap().to_string(); + + let first = Builder::new_local(&p).build().await.unwrap(); + let setup = first.connect().unwrap(); + setup + .execute("CREATE TABLE t (id INTEGER PRIMARY KEY, who TEXT)", ()) + .await + .unwrap(); + + let second = Builder::new_local(&p).build().await; + let second = match second { + Ok(db) => db, + Err(e) => { + println!("second handle refused: {e}"); + let _ = std::fs::remove_dir_all(&dir); + return; + } + }; + + let a = setup; + let b = second.connect().unwrap(); + for c in [&a, &b] { + c.execute("PRAGMA busy_timeout = 5000", ()).await.unwrap(); + } + let ha = tokio::spawn(async move { + let mut errs = Vec::new(); + for i in 0..100i64 { + if let Err(e) = a + .execute("INSERT INTO t (id, who) VALUES (?1, \'a\')", params![i]) + .await + { + errs.push(e.to_string()); + } + } + errs + }); + let hb = tokio::spawn(async move { + let mut errs = Vec::new(); + for i in 1000..1100i64 { + if let Err(e) = b + .execute("INSERT INTO t (id, who) VALUES (?1, \'b\')", params![i]) + .await + { + errs.push(e.to_string()); + } + } + errs + }); + let (ea, eb) = (ha.await.unwrap(), hb.await.unwrap()); + // With the busy timeout the store sets, a second handle waits its turn + // instead of dropping writes. Without it, roughly 40% of these fail + // with "database is locked". + assert!(ea.is_empty(), "handle a: {ea:?}"); + assert!(eb.is_empty(), "handle b: {eb:?}"); + + let third = Builder::new_local(&p).build().await.unwrap(); + let c = third.connect().unwrap(); + let mut rows = c.query("SELECT COUNT(*) FROM t", ()).await.unwrap(); + let n = rows.next().await.unwrap().unwrap().get::(0).unwrap(); + assert_eq!(n, 200, "no write lost between two database handles"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs new file mode 100644 index 0000000..9a1726c --- /dev/null +++ b/crates/dizey-core/tests/store.rs @@ -0,0 +1,367 @@ +//! Behaviour of the storage boundary, driven through the Turso implementation. +//! +//! New storage tests belong in this file rather than a new `tests/*.rs`: one +//! test binary links and runs once. + +use std::path::PathBuf; + +use dizey_core::store::{DeletePolicy, NewUser, Store, StoreError, TursoStore}; +use dizey_core::Role; +use time::{Duration, OffsetDateTime}; +use uuid::Uuid; + +/// A throwaway database on disk. Turso's in-memory mode is not what production +/// runs, so the tests exercise a real file. +struct Scratch { + dir: PathBuf, + store: TursoStore, +} + +impl Scratch { + async fn open() -> Self { + let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap()) + .await + .unwrap(); + Self { dir, store } + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +async fn workspace_with_admin() -> (Scratch, String, String) { + let scratch = Scratch::open().await; + let ws = scratch.store.create_workspace("Dizey").await.unwrap(); + let admin = scratch + .store + .create_user(NewUser { + workspace_id: ws.id.clone(), + email: "ada@dizey.sh".into(), + display_name: "Ada".into(), + role: Role::Admin, + }) + .await + .unwrap(); + (scratch, ws.id, admin.id) +} + +#[tokio::test] +async fn migrations_apply_once_and_survive_reopen() { + let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + 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(), 1); + first.create_workspace("Dizey").await.unwrap(); + 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(), 1); + assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); + drop(second); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_database_holds_exactly_one_workspace() { + let scratch = Scratch::open().await; + assert!(scratch.store.workspace().await.unwrap().is_none()); + scratch.store.create_workspace("Dizey").await.unwrap(); + let again = scratch.store.create_workspace("Other").await; + assert!(matches!(again, Err(StoreError::Conflict("workspace")))); +} + +#[tokio::test] +async fn workspace_defaults_match_the_settings_screen() { + let scratch = Scratch::open().await; + let ws = scratch.store.create_workspace("Dizey").await.unwrap(); + assert_eq!(ws.attachment_limit_bytes, 25 * 1024 * 1024); + assert_eq!(ws.photo_limit_bytes, 2 * 1024 * 1024); + assert!(ws.allowed_file_types.is_empty(), "every type until narrowed"); + assert_eq!(ws.who_can_delete_tasks, DeletePolicy::Anyone); + assert!(ws.smtp_host.is_none()); +} + +#[tokio::test] +async fn smtp_password_is_never_part_of_the_workspace_record() { + let (scratch, ws_id, _) = workspace_with_admin().await; + scratch + .store + .set_smtp(&ws_id, "smtp.fastmail.com", 465, "dizey", "hunter2", "Dizey", "dizey@dizey.sh") + .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(465)); + assert_eq!(ws.smtp_from_address.as_deref(), Some("dizey@dizey.sh")); + // The only way to the password is the mailer's own call. + let serialised = serde_json::to_string(&ws).unwrap(); + assert!(!serialised.contains("hunter2"), "{serialised}"); + assert_eq!( + scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + Some("hunter2") + ); +} + +#[tokio::test] +async fn limits_round_trip_including_the_file_type_list() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let types = vec!["png".to_string(), "pdf".to_string()]; + scratch + .store + .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types, DeletePolicy::Admin) + .await + .unwrap(); + let ws = scratch.store.workspace().await.unwrap().unwrap(); + assert_eq!(ws.attachment_limit_bytes, 10 * 1024 * 1024); + assert_eq!(ws.photo_limit_bytes, 512 * 1024); + assert_eq!(ws.allowed_file_types, types); + assert_eq!(ws.who_can_delete_tasks, DeletePolicy::Admin); +} + +#[tokio::test] +async fn an_invited_member_has_no_password_until_they_choose_one() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let member = scratch + .store + .create_user(NewUser { + workspace_id: ws_id.clone(), + email: "grace@dizey.sh".into(), + display_name: "Grace".into(), + role: Role::Member, + }) + .await + .unwrap(); + assert!(member.password_hash.is_none()); + assert!(!member.has_signed_in()); + + scratch + .store + .set_password_hash(&member.id, "$argon2id$fake") + .await + .unwrap(); + let member = scratch.store.user(&member.id).await.unwrap().unwrap(); + assert!(member.has_signed_in()); +} + +#[tokio::test] +async fn addresses_are_unique_and_case_insensitive() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let dup = scratch + .store + .create_user(NewUser { + workspace_id: ws_id.clone(), + email: " ADA@Dizey.sh ".into(), + display_name: "Ada again".into(), + role: Role::Member, + }) + .await; + assert!(matches!(dup, Err(StoreError::Conflict("account")))); + assert!( + scratch + .store + .user_by_email(&ws_id, "Ada@DIZEY.sh") + .await + .unwrap() + .is_some() + ); +} + +#[tokio::test] +async fn an_unknown_address_is_a_plain_none() { + let (scratch, ws_id, _) = workspace_with_admin().await; + // The sign-in surface builds its uniform response on this; the store must + // not distinguish "no such account" from anything else by erroring. + assert!( + scratch + .store + .user_by_email(&ws_id, "nobody@dizey.sh") + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn members_list_and_count_for_the_admin_screen() { + let (scratch, ws_id, admin_id) = workspace_with_admin().await; + for (email, name, role) in [ + ("grace@dizey.sh", "Grace", Role::Member), + ("linus@dizey.sh", "Linus", Role::Viewer), + ] { + scratch + .store + .create_user(NewUser { + workspace_id: ws_id.clone(), + email: email.into(), + display_name: name.into(), + role, + }) + .await + .unwrap(); + } + assert_eq!(scratch.store.count_users(&ws_id).await.unwrap(), 3); + let users = scratch.store.users(&ws_id).await.unwrap(); + assert_eq!(users[0].id, admin_id); + assert_eq!( + users.iter().filter(|u| u.role == Role::Viewer).count(), + 1 + ); +} + +#[tokio::test] +async fn profile_and_role_updates_stick() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let user = scratch + .store + .create_user(NewUser { + workspace_id: ws_id, + email: "grace@dizey.sh".into(), + display_name: "Grace".into(), + role: Role::Member, + }) + .await + .unwrap(); + + scratch + .store + .set_profile(&user.id, "Grace H.", Some("photos/grace.png")) + .await + .unwrap(); + scratch.store.set_role(&user.id, Role::Viewer).await.unwrap(); + let at = OffsetDateTime::now_utc(); + scratch.store.mark_signed_in(&user.id, at).await.unwrap(); + + let user = scratch.store.user(&user.id).await.unwrap().unwrap(); + assert_eq!(user.display_name, "Grace H."); + assert_eq!(user.photo_path.as_deref(), Some("photos/grace.png")); + assert_eq!(user.role, Role::Viewer); + // Stored as RFC 3339 text, so equality holds to the second. + assert_eq!( + user.last_signed_in_at.unwrap().unix_timestamp(), + at.unix_timestamp() + ); + + // Clearing the photo is a real update, not a no-op. + scratch.store.set_profile(&user.id, "Grace H.", None).await.unwrap(); + assert!(scratch.store.user(&user.id).await.unwrap().unwrap().photo_path.is_none()); +} + +#[tokio::test] +async fn updates_to_a_missing_user_are_not_found() { + let scratch = Scratch::open().await; + let missing = Uuid::new_v4().to_string(); + assert!(matches!( + scratch.store.set_password_hash(&missing, "x").await, + Err(StoreError::NotFound) + )); + assert!(matches!( + scratch.store.set_role(&missing, Role::Member).await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn a_signin_link_stores_only_the_hash_and_is_used_once() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let user = scratch + .store + .create_user(NewUser { + workspace_id: ws_id, + email: "grace@dizey.sh".into(), + display_name: "Grace".into(), + role: Role::Member, + }) + .await + .unwrap(); + + let now = OffsetDateTime::now_utc(); + let link = scratch + .store + .create_signin_link(&user.id, "hash-of-the-token", now + Duration::days(7)) + .await + .unwrap(); + assert!(link.is_usable(now)); + + // Lookup is by hash: the plaintext never reaches the database. + assert!( + scratch + .store + .signin_link_by_hash("hash-of-the-token") + .await + .unwrap() + .is_some() + ); + assert!( + scratch + .store + .signin_link_by_hash("some-other-hash") + .await + .unwrap() + .is_none() + ); + + scratch.store.consume_signin_link(&link.id, now).await.unwrap(); + let used = scratch + .store + .signin_link_by_hash("hash-of-the-token") + .await + .unwrap() + .unwrap(); + assert!(!used.is_usable(now)); + // A second use finds nothing left to consume. + assert!(matches!( + scratch.store.consume_signin_link(&link.id, now).await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn an_expired_link_is_still_a_live_account() { + let (scratch, ws_id, _) = workspace_with_admin().await; + let user = scratch + .store + .create_user(NewUser { + workspace_id: ws_id, + email: "grace@dizey.sh".into(), + display_name: "Grace".into(), + role: Role::Member, + }) + .await + .unwrap(); + + let now = OffsetDateTime::now_utc(); + let stale = scratch + .store + .create_signin_link(&user.id, "stale-hash", now - Duration::hours(1)) + .await + .unwrap(); + assert!(!stale.is_usable(now)); + + // Resending opens the same account rather than making a new one. + let fresh = scratch + .store + .create_signin_link(&user.id, "fresh-hash", now + Duration::days(7)) + .await + .unwrap(); + assert_eq!(fresh.user_id, stale.user_id); + assert!(fresh.is_usable(now)); + assert!(scratch.store.user(&user.id).await.unwrap().is_some()); +} + +#[tokio::test] +async fn the_store_is_usable_behind_a_trait_object() { + let scratch = Scratch::open().await; + let store: &dyn Store = &scratch.store; + store.create_workspace("Dizey").await.unwrap(); + assert!(store.workspace().await.unwrap().is_some()); +}