//! Writes and listings that only the administrator pages make: admin rights, enabling and deleting //! accounts, the user search, clients and their services, the mail outbox, signing keys and the policy //! overrides. //! //! The rules that must hold under concurrency are single conditional statements, so two requests cannot //! both succeed: //! //! - the last enabled administrator cannot be demoted, disabled or deleted (`set_admin`, `delete_user`, //! and the same guard in `users::disable_user`); //! - the signing key that is current cannot be retired (`retire_signing_key`); //! - a mail row is retried or abandoned only in the states that allow it (`retry_mail`, `abandon_mail`). //! //! Who may call these is decided by the web layer. Nothing here knows about the session. use turso::Row; use crate::error::{Error, Result}; use crate::model::User; use crate::store::backchannel::{self, EndReason}; use crate::store::clients::{CLIENT_COLS, map_client, upsert_service_link}; use crate::store::directory::{ChangeKind, record_change}; use crate::store::invites::{Invite, map_invite}; use crate::store::users::{USER_COLS, map_user}; use crate::store::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; use crate::time::now_stamp; /// The result of [`Store::set_admin`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AdminChange { /// The flag was changed. Changed, /// The account already had that flag. Unchanged, /// The change would leave no enabled administrator, so it was refused. LastAdmin, } /// One row of the mail outbox, as the administrator sees it. The body is never included. #[derive(Debug, Clone, PartialEq, Eq)] pub struct OutboxRow { /// ULID. Newer rows have larger ids. pub id: String, /// The mail kind. pub kind: String, /// The recipient address. pub to_addr: String, /// The subject. pub subject: String, /// `pending`, `sent`, `failed` or `abandoned`. pub state: String, /// Attempts made so far. pub attempts: i64, /// When the row is next due. pub next_attempt_at: String, /// The last failure, without secrets. pub last_error: Option, /// When the row was queued. pub created_at: String, } /// The fields of a client that an administrator can edit. The URIs must already be checked. #[derive(Debug, Clone)] pub struct ClientEdit<'a> { /// Display name. pub name: &'a str, /// Exact redirect URIs. pub redirect_uris: &'a [String], /// Exact post-logout redirect URIs. pub post_logout_redirect_uris: &'a [String], /// Back-channel logout endpoint, if any. pub backchannel_logout_uri: Option<&'a str>, /// Space-separated scopes. pub allowed_scopes: &'a str, /// Family key, if the client is a family service. Unique. pub service_key: Option<&'a str>, } impl Store { /// Grants or removes instance administration. Removing it from the last enabled administrator is /// refused by the same statement that would do it, so two parallel demotions cannot both succeed. pub async fn set_admin(&self, user_id: &str, is_admin: bool) -> Result { let flag = i64::from(is_admin); let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE users SET is_admin = ?2, updated_at = ?3 \ WHERE id = ?1 AND is_admin <> ?2 \ AND (?2 = 1 OR disabled_at IS NOT NULL \ OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", (user_id.to_string(), flag, now_stamp()), ) .await .map_err(db_err)?; if changed == 1 { return Ok(AdminChange::Changed); } let current = fetch_opt( &conn, "SELECT is_admin FROM users WHERE id = ?1", (user_id.to_string(),), |row| col_int(row, 0), ) .await?; match current { None => Err(Error::NotFound), Some(value) if value == flag => Ok(AdminChange::Unchanged), Some(_) => Ok(AdminChange::LastAdmin), } } /// Number of enabled administrators. The admin pages show it and refuse to leave none. pub async fn enabled_admin_count(&self) -> Result { let conn = self.read_conn().await; let count = fetch_opt( &conn, "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL", (), |row| col_int(row, 0), ) .await? .unwrap_or(0); u64::try_from(count).map_err(|_| Error::Database("negative count".into())) } /// Clears the disabled mark of an account. The directory feed records the change. Returns false when /// the account is missing or was not disabled. pub async fn enable_user(&self, user_id: &str) -> Result { let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let changed = tx .execute( "UPDATE users SET disabled_at = NULL, updated_at = ?2 \ WHERE id = ?1 AND disabled_at IS NOT NULL", (user_id.to_string(), now), ) .await .map_err(db_err)?; if changed != 1 { return Ok(false); } record_change(&tx, user_id, ChangeKind::Member).await?; Ok(true) } .await; let result = finish(tx, outcome).await; if matches!(result, Ok(true)) { self.announce_directory(); } result } /// Deletes an account and everything that belonged to it: sessions and their client links, recovery /// codes, reset and email-change links, and a pending two-factor enrolment. The rows that remain /// name the person only by id (audit entries and invitations that person sent). Back-channel logouts /// are queued first, and the directory feed records a `deleted` change. The last enabled /// administrator cannot be deleted. Returns false when there was no such account. /// /// The caller removes the profile photo file after this returns. pub async fn delete_user(&self, user_id: &str) -> Result { let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let exists = fetch_opt( &tx, "SELECT id FROM users WHERE id = ?1", (user_id.to_string(),), |row| col_text(row, 0), ) .await?; if exists.is_none() { return Ok(false); } // Queued before the sessions go, because the client links are read from them. backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; let removed = tx .execute( "DELETE FROM users WHERE id = ?1 \ AND (is_admin = 0 OR disabled_at IS NOT NULL \ OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)", (user_id.to_string(),), ) .await .map_err(db_err)?; if removed != 1 { // Returned as an error so the transaction, with its queued logouts, is rolled back. return Err(Error::Conflict( "the last enabled administrator cannot be deleted".into(), )); } // Revoked explicitly, not only by the cascade below, so no refresh can succeed for this account // after the delete, whatever the foreign keys do. tx.execute( "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", (user_id.to_string(), now.clone()), ) .await .map_err(db_err)?; tx.execute( "DELETE FROM settings WHERE key = ?1", (format!("totp_pending:{user_id}"),), ) .await .map_err(db_err)?; record_change(&tx, user_id, ChangeKind::Deleted).await?; Ok(true) } .await; let result = finish(tx, outcome).await; if matches!(result, Ok(true)) { self.announce_directory(); } result } /// A page of accounts, newest first. `search` matches a part of the address or the name, in any /// case. `after` is the `(created_at, id)` of the last account of the previous page. Returns up to /// `limit` accounts. pub async fn list_users( &self, search: Option<&str>, after: Option<(&str, &str)>, limit: u32, ) -> Result> { let term = search .map(|s| s.trim().to_lowercase()) .filter(|s| !s.is_empty()); let (after_at, after_id) = match after { Some((at, id)) => (Some(at.to_owned()), Some(id.to_owned())), None => (None, None), }; let conn = self.read_conn().await; fetch_all( &conn, &format!( "SELECT {USER_COLS} FROM users \ WHERE (?1 IS NULL OR instr(email_folded, ?1) > 0 OR instr(lower(name), ?1) > 0) \ AND (?2 IS NULL OR created_at < ?2 OR (created_at = ?2 AND id < ?3)) \ ORDER BY created_at DESC, id DESC LIMIT ?4" ), (term, after_at, after_id, i64::from(limit)), map_user, ) .await } /// Invitations that can still be used, newest first. pub async fn pending_invites(&self) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \ WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at DESC, token_hash", (now_stamp(),), map_invite, ) .await } /// The invitation with this token hash, while it can still be used. pub async fn pending_invite(&self, token_hash: &str) -> Result> { let conn = self.read_conn().await; fetch_opt( &conn, "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \ WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2", (token_hash.to_string(), now_stamp()), map_invite, ) .await } /// Deletes an invitation that was not used. Returns false when it was used or is unknown. pub async fn revoke_invite(&self, token_hash: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute( "DELETE FROM invites WHERE token_hash = ?1 AND accepted_at IS NULL", (token_hash.to_string(),), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Ends every live session of a person, with their back-channel logouts. Returns the ids ended. pub async fn end_all_sessions(&self, user_id: &str, reason: EndReason) -> Result> { self.end_matching(user_id, None, reason).await } /// Updates the editable fields of a client. A family key that another client holds is a conflict. /// Services that pointed to this client under another key are unlinked in the same transaction. /// Returns false when there is no such client. pub async fn update_client(&self, id: &str, edit: &ClientEdit<'_>) -> Result { let redirect_uris = serde_json::to_string(edit.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?; let post_logout = serde_json::to_string(edit.post_logout_redirect_uris) .map_err(|e| Error::Invalid(e.to_string()))?; let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let changed = tx .execute( "UPDATE clients SET name = ?2, redirect_uris = ?3, post_logout_redirect_uris = ?4, \ backchannel_logout_uri = ?5, allowed_scopes = ?6, service_key = ?7 \ WHERE id = ?1", ( id.to_string(), edit.name.to_string(), redirect_uris, post_logout, edit.backchannel_logout_uri.map(str::to_owned), edit.allowed_scopes.to_string(), edit.service_key.map(str::to_owned), ), ) .await .map_err(|e| { if e.to_string().contains("UNIQUE") { Error::Conflict("that family key is already used by another client".into()) } else { db_err(e) } })?; if changed != 1 { return Ok(false); } tx.execute( "UPDATE services SET client_id = NULL WHERE client_id = ?1 AND key IS NOT ?2", (id.to_string(), edit.service_key.map(str::to_owned)), ) .await .map_err(db_err)?; Ok(true) } .await; finish(tx, outcome).await } /// Replaces the secret hash of a client. The old secret stops working at once. pub async fn rotate_client_secret(&self, id: &str, secret_hash: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE clients SET secret_hash = ?2, secret_rotated_at = ?3 WHERE id = ?1", (id.to_string(), secret_hash.to_string(), now_stamp()), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Creates or updates the switcher row of a family service and links it to its client. pub async fn link_service( &self, key: &str, name: &str, url: &str, client_id: &str, ) -> Result<()> { let conn = self.inner.conn.lock().await; upsert_service_link(&conn, key, name, url, client_id).await } /// The client with this id, enabled or not. Used by the admin client pages. pub async fn client_row(&self, id: &str) -> Result> { let conn = self.read_conn().await; fetch_opt( &conn, &format!("SELECT {} FROM clients WHERE id = ?1", CLIENT_COLS), (id.to_string(),), map_client, ) .await } /// One page of the mail outbox, newest first, optionally only one state. `after` is the id of the /// last row of the previous page. pub async fn outbox_page( &self, state: Option<&str>, after: Option<&str>, limit: u32, ) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, "SELECT id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error, created_at \ FROM mail_outbox \ WHERE (?1 IS NULL OR state = ?1) AND (?2 IS NULL OR id < ?2) \ ORDER BY id DESC LIMIT ?3", ( state.map(str::to_owned), after.map(str::to_owned), i64::from(limit), ), map_outbox, ) .await } /// How many rows the outbox holds in each state. pub async fn outbox_counts(&self) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, "SELECT state, COUNT(*) FROM mail_outbox GROUP BY state ORDER BY state", (), |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), ) .await } /// Sends a failed row again now. Only a `failed` row whose body is still held can be retried. pub async fn retry_mail(&self, id: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE mail_outbox SET state = 'pending', next_attempt_at = ?2 \ WHERE id = ?1 AND state = 'failed' AND body_text <> ''", (id.to_string(), now_stamp()), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Gives up on a row that is not yet sent: its body is blanked, as the worker does on abandonment. pub async fn abandon_mail(&self, id: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE mail_outbox SET state = 'abandoned', body_text = '', \ last_error = 'abandoned by an administrator' \ WHERE id = ?1 AND state IN ('pending', 'failed')", (id.to_string(),), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Retires a published signing key that is not the current one. Its public key stays published for /// the usual overlap, so tokens it signed still verify. Its sealed seed is blanked in the same write, /// because a retired key never signs again. The current key cannot be retired: the statement excludes /// it, so a token can always be signed. pub async fn retire_signing_key(&self, kid: &str) -> Result { let now = now_stamp(); let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE signing_keys SET retires_at = ?2, private_sealed = '' \ WHERE kid = ?1 AND retires_at IS NULL AND activates_at <= ?2 \ AND kid <> (SELECT kid FROM signing_keys WHERE retires_at IS NULL AND activates_at <= ?2 \ ORDER BY activates_at DESC, kid DESC LIMIT 1)", (kid.to_string(), now), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Reads the saved `policy.` values, lets `change` decide which of them to write, and writes those in one /// transaction. `change` gets the saved values as they are inside the transaction, so a read-modify-write /// of the policy cannot lose an update made by another request in between. An error from `change` rolls /// the transaction back and is returned unchanged. pub async fn update_policy_settings( &self, change: impl FnOnce(&[(String, String)]) -> Result>, ) -> Result<()> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<()> = async { let saved = fetch_all( &tx, "SELECT key, value FROM settings WHERE substr(key, 1, length('policy.')) = 'policy.' ORDER BY key", (), |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)), ) .await?; let writes = change(&saved)?; for (key, value) in writes { tx.execute( "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", (key, value, now_stamp()), ) .await .map_err(db_err)?; } Ok(()) } .await; finish(tx, outcome).await } /// Removes a setting. Returns false when there was no such setting. pub async fn delete_setting(&self, key: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute("DELETE FROM settings WHERE key = ?1", (key.to_string(),)) .await .map_err(db_err)?; Ok(changed == 1) } /// The settings whose key starts with `prefix`, in key order. pub async fn settings_with_prefix(&self, prefix: &str) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, "SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1 ORDER BY key", (prefix.to_string(),), |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)), ) .await } } /// Maps a row selected as `id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error, /// created_at`. fn map_outbox(row: &Row) -> Result { Ok(OutboxRow { id: col_text(row, 0)?, kind: col_text(row, 1)?, to_addr: col_text(row, 2)?, subject: col_text(row, 3)?, state: col_text(row, 4)?, attempts: col_int(row, 5)?, next_attempt_at: col_text(row, 6)?, last_error: crate::store::col_opt_text(row, 7)?, created_at: col_text(row, 8)?, }) } #[cfg(test)] mod tests { use super::*; async fn store_with_users() -> (tempfile::TempDir, Store, String, String) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("im.db")).await.unwrap(); let first = store .create_first_admin("ada@example.com", "Ada", "h") .await .unwrap(); let second = store .create_user("bob@example.com", "Bob", "h", true) .await .unwrap(); (dir, store, first.id, second.id) } #[tokio::test] async fn the_last_enabled_admin_cannot_be_demoted_disabled_or_deleted() { let (_dir, store, first, second) = store_with_users().await; // Two admins: one may go. assert!(store.disable_user(&second).await.unwrap()); // `second` is disabled now, so `first` is the last enabled admin. assert_eq!( store.set_admin(&first, false).await.unwrap(), AdminChange::LastAdmin ); assert!(!store.disable_user(&first).await.unwrap()); assert!(store.delete_user(&first).await.is_err()); assert_eq!(store.enabled_admin_count().await.unwrap(), 1); assert!(store.user_by_id(&first).await.unwrap().is_some()); } }