diff --git a/migrations/0012_account_updated_at.sql b/migrations/0012_account_updated_at.sql new file mode 100644 index 0000000..2a93f6c --- /dev/null +++ b/migrations/0012_account_updated_at.sql @@ -0,0 +1,4 @@ +-- When an account's settings last changed. The sync manager compares it +-- with the version its running task started from, and restarts the task +-- after an edit (new password, host, …) — the task holds its own copy. +ALTER TABLE accounts ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); diff --git a/src/api/accounts.rs b/src/api/accounts.rs index e28abd7..91a2f37 100644 --- a/src/api/accounts.rs +++ b/src/api/accounts.rs @@ -63,23 +63,42 @@ pub async fn list( } /// Catches what would otherwise only fail later, in the sync task's log. -fn validate(req: &CreateAccountRequest) -> ApiResult<()> { +fn validate_settings( + name: &str, + imap_host: &str, + imap_port: i32, + smtp_host: &str, + smtp_port: i32, + username: &str, +) -> ApiResult<()> { let blank = |s: &str| s.trim().is_empty(); - if blank(&req.name) || blank(&req.imap_host) || blank(&req.smtp_host) || blank(&req.username) { + if blank(name) || blank(imap_host) || blank(smtp_host) || blank(username) { return Err(ApiError::BadRequest( "name, IMAP server, SMTP server and login are all required".into(), )); } + for (what, port) in [("IMAP", imap_port), ("SMTP", smtp_port)] { + if !(1..=65535).contains(&port) { + return Err(ApiError::BadRequest(format!("{what} port must be 1–65535"))); + } + } + Ok(()) +} + +fn validate(req: &CreateAccountRequest) -> ApiResult<()> { + validate_settings( + &req.name, + &req.imap_host, + req.imap_port, + &req.smtp_host, + req.smtp_port, + &req.username, + )?; if req.password.is_empty() { return Err(ApiError::BadRequest( "the mailbox password is required".into(), )); } - for (what, port) in [("IMAP", req.imap_port), ("SMTP", req.smtp_port)] { - if !(1..=65535).contains(&port) { - return Err(ApiError::BadRequest(format!("{what} port must be 1–65535"))); - } - } Ok(()) } @@ -127,6 +146,103 @@ pub async fn create( Ok(Json(account.into())) } +/// The account's settings, replaced as a whole — except the password, +/// which stays as it is unless a new one is given. +#[derive(Deserialize)] +pub struct UpdateAccountRequest { + pub name: String, + pub imap_host: String, + pub imap_port: i32, + pub smtp_host: String, + pub smtp_port: i32, + pub username: String, + /// Omitted or empty: keep the stored password. + pub password: Option, + pub email_address: Option, + pub display_name: Option, + /// Defaults by port, as when creating. + pub smtp_use_starttls: Option, +} + +/// Edits an account. Its sync task is restarted with the new settings. +/// Mail already synced stays when it's still the same mailbox (say, a new +/// password or a renamed host); pointing it at a different mailbox shows up +/// as a UIDVALIDITY change on the next connect, and that re-syncs it. +pub async fn update( + State(state): State, + user: CurrentUser, + axum::extract::Path(account_id): axum::extract::Path, + AppJson(req): AppJson, +) -> ApiResult> { + validate_settings( + &req.name, + &req.imap_host, + req.imap_port, + &req.smtp_host, + req.smtp_port, + &req.username, + )?; + let sealed = match req.password.as_deref().filter(|p| !p.is_empty()) { + Some(p) => Some(state.cipher.encrypt(p)?), + None => None, + }; + + let account: Option = sqlx::query_as( + "UPDATE accounts SET \ + name = $3, imap_host = $4, imap_port = $5, smtp_host = $6, smtp_port = $7, \ + username = $8, \ + email_address = COALESCE($9, CASE WHEN $8 LIKE '%@%' THEN $8 END), \ + display_name = $10, smtp_use_starttls = $11, \ + encrypted_password = COALESCE($12, encrypted_password), \ + password_nonce = COALESCE($13, password_nonce), \ + updated_at = now() \ + WHERE id = $1 AND user_id = $2 RETURNING *", + ) + .bind(account_id) + .bind(user.user_id) + .bind(req.name.trim()) + .bind(req.imap_host.trim()) + .bind(req.imap_port) + .bind(req.smtp_host.trim()) + .bind(req.smtp_port) + .bind(req.username.trim()) + .bind( + req.email_address + .as_deref() + .map(str::trim) + .filter(|e| !e.is_empty()), + ) + .bind( + req.display_name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty()), + ) + .bind(req.smtp_use_starttls.unwrap_or(req.smtp_port != 465)) + .bind(sealed.as_ref().map(|s| &s.ciphertext)) + .bind(sealed.as_ref().map(|s| &s.nonce)) + .fetch_optional(&state.pool) + .await?; + let account = account.ok_or(ApiError::NotFound)?; + + // The old status described the old settings. + sqlx::query( + "UPDATE sync_state SET status = 'pending', last_error = NULL, updated_at = now() \ + WHERE account_id = $1", + ) + .bind(account_id) + .execute(&state.pool) + .await?; + + // Restart its sync task now rather than at the manager's next poll. + state.sync_wake.notify_one(); + state + .events + .emit(user.user_id, Change::config(ConfigKind::Accounts)) + .await; + Ok(Json(account.into())) +} + pub async fn delete( State(state): State, user: CurrentUser, diff --git a/src/api/router.rs b/src/api/router.rs index 64cf14f..37ee916 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -3,7 +3,7 @@ use crate::api::{ accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads, }; use axum::http::header::{AUTHORIZATION, CONTENT_TYPE}; -use axum::routing::{delete, get, post, put}; +use axum::routing::{get, post, put}; use axum::Router; use tower_http::cors::{Any, CorsLayer}; use tower_http::trace::TraceLayer; @@ -13,7 +13,10 @@ pub fn build(state: AppState) -> Router { .route("/api/auth/register", post(auth::register)) .route("/api/auth/login", post(auth::login)) .route("/api/accounts", get(accounts::list).post(accounts::create)) - .route("/api/accounts/:id", delete(accounts::delete)) + .route( + "/api/accounts/:id", + put(accounts::update).delete(accounts::delete), + ) .route("/api/folders", get(folders::list).post(folders::create)) .route( "/api/folders/:id", diff --git a/src/imap_sync/manager.rs b/src/imap_sync/manager.rs index 42f5c77..a97d105 100644 --- a/src/imap_sync/manager.rs +++ b/src/imap_sync/manager.rs @@ -1,14 +1,16 @@ -//! Spawns and tracks one sync task per account, and stops the task of an -//! account that was removed. Woken by the API when accounts change, and -//! polls as a fallback. +//! Spawns and tracks one sync task per account; stops the task of an +//! account that was removed, and restarts the task of one that was edited +//! (it holds its own copy of the settings). Woken by the API when accounts +//! change, and polls as a fallback. use crate::crypto::CredentialCipher; use crate::events::EventHub; use crate::imap_sync::connection::AccountSyncer; use crate::models::account::Account; use crate::storage::BlobStore; +use chrono::{DateTime, Utc}; use sqlx::PgPool; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; use tokio::sync::Notify; @@ -23,10 +25,11 @@ pub async fn run( events: EventHub, wake: Arc, ) { - let mut running: HashMap> = HashMap::new(); + // Each task, with the account version (updated_at) it was started from. + let mut running: HashMap, DateTime)> = HashMap::new(); loop { - running.retain(|_, handle| !handle.is_finished()); + running.retain(|_, (handle, _)| !handle.is_finished()); match sqlx::query_as::<_, Account>("SELECT * FROM accounts") .fetch_all(&pool) @@ -35,14 +38,20 @@ pub async fn run( Ok(accounts) => { // A removed account's task would otherwise retry forever // against rows that no longer exist. - let present: HashSet = accounts.iter().map(|a| a.id).collect(); - running.retain(|id, handle| { - let keep = present.contains(id); - if !keep { + let present: HashMap> = + accounts.iter().map(|a| (a.id, a.updated_at)).collect(); + running.retain(|id, (handle, version)| match present.get(id) { + None => { tracing::info!(account_id = %id, "account removed; stopping sync task"); handle.abort(); + false } - keep + Some(current) if current != version => { + tracing::info!(account_id = %id, "account edited; restarting sync task"); + handle.abort(); + false + } + Some(_) => true, }); for account in accounts { if running.contains_key(&account.id) { @@ -56,9 +65,9 @@ pub async fn run( blobs: blobs.clone(), events: events.clone(), }; - let id = syncer.account.id; + let (id, version) = (syncer.account.id, syncer.account.updated_at); let handle = tokio::spawn(syncer.run()); - running.insert(id, handle); + running.insert(id, (handle, version)); } } Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"), diff --git a/src/models/account.rs b/src/models/account.rs index 493718d..1e7b769 100644 --- a/src/models/account.rs +++ b/src/models/account.rs @@ -20,6 +20,7 @@ pub struct Account { pub created_at: DateTime, pub email_address: Option, pub display_name: Option, + pub updated_at: DateTime, } impl Account { diff --git a/tests/routes.rs b/tests/routes.rs index 1d45179..ada42d0 100644 --- a/tests/routes.rs +++ b/tests/routes.rs @@ -70,6 +70,7 @@ async fn parameterised_routes_match() { ("GET", format!("/api/messages/{id}")), ("GET", format!("/api/threads/{id}")), ("DELETE", format!("/api/accounts/{id}")), + ("PUT", format!("/api/accounts/{id}")), ("POST", format!("/api/threads/{id}/read")), ("PUT", format!("/api/outbox/{id}")), ("DELETE", format!("/api/outbox/{id}")),