forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

admin.rs571 lines, 22.4 KiBHistoryRawDownload
1//! Writes and listings that only the administrator pages make: admin rights, enabling and deleting
2//! accounts, the user search, clients and their services, the mail outbox, signing keys and the policy
3//! overrides.
4//!
5//! The rules that must hold under concurrency are single conditional statements, so two requests cannot
6//! both succeed:
7//!
8//! - the last enabled administrator cannot be demoted, disabled or deleted (`set_admin`, `delete_user`,
9//! and the same guard in `users::disable_user`);
10//! - the signing key that is current cannot be retired (`retire_signing_key`);
11//! - a mail row is retried or abandoned only in the states that allow it (`retry_mail`, `abandon_mail`).
12//!
13//! Who may call these is decided by the web layer. Nothing here knows about the session.
14
15use turso::Row;
16
17use crate::error::{Error, Result};
18use crate::model::User;
19use crate::store::backchannel::{self, EndReason};
20use crate::store::clients::{CLIENT_COLS, map_client, upsert_service_link};
21use crate::store::directory::{ChangeKind, record_change};
22use crate::store::invites::{Invite, map_invite};
23use crate::store::users::{USER_COLS, map_user};
24use crate::store::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish};
25use crate::time::now_stamp;
26
27/// The result of [`Store::set_admin`].
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum AdminChange {
30 /// The flag was changed.
31 Changed,
32 /// The account already had that flag.
33 Unchanged,
34 /// The change would leave no enabled administrator, so it was refused.
35 LastAdmin,
36}
37
38/// One row of the mail outbox, as the administrator sees it. The body is never included.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct OutboxRow {
41 /// ULID. Newer rows have larger ids.
42 pub id: String,
43 /// The mail kind.
44 pub kind: String,
45 /// The recipient address.
46 pub to_addr: String,
47 /// The subject.
48 pub subject: String,
49 /// `pending`, `sent`, `failed` or `abandoned`.
50 pub state: String,
51 /// Attempts made so far.
52 pub attempts: i64,
53 /// When the row is next due.
54 pub next_attempt_at: String,
55 /// The last failure, without secrets.
56 pub last_error: Option<String>,
57 /// When the row was queued.
58 pub created_at: String,
59}
60
61/// The fields of a client that an administrator can edit. The URIs must already be checked.
62#[derive(Debug, Clone)]
63pub struct ClientEdit<'a> {
64 /// Display name.
65 pub name: &'a str,
66 /// Exact redirect URIs.
67 pub redirect_uris: &'a [String],
68 /// Exact post-logout redirect URIs.
69 pub post_logout_redirect_uris: &'a [String],
70 /// Back-channel logout endpoint, if any.
71 pub backchannel_logout_uri: Option<&'a str>,
72 /// Space-separated scopes.
73 pub allowed_scopes: &'a str,
74 /// Family key, if the client is a family service. Unique.
75 pub service_key: Option<&'a str>,
76}
77
78impl Store {
79 /// Grants or removes instance administration. Removing it from the last enabled administrator is
80 /// refused by the same statement that would do it, so two parallel demotions cannot both succeed.
81 pub async fn set_admin(&self, user_id: &str, is_admin: bool) -> Result<AdminChange> {
82 let flag = i64::from(is_admin);
83 let conn = self.inner.conn.lock().await;
84 let changed = conn
85 .execute(
86 "UPDATE users SET is_admin = ?2, updated_at = ?3 \
87 WHERE id = ?1 AND is_admin <> ?2 \
88 AND (?2 = 1 OR disabled_at IS NOT NULL \
89 OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)",
90 (user_id.to_string(), flag, now_stamp()),
91 )
92 .await
93 .map_err(db_err)?;
94 if changed == 1 {
95 return Ok(AdminChange::Changed);
96 }
97 let current = fetch_opt(
98 &conn,
99 "SELECT is_admin FROM users WHERE id = ?1",
100 (user_id.to_string(),),
101 |row| col_int(row, 0),
102 )
103 .await?;
104 match current {
105 None => Err(Error::NotFound),
106 Some(value) if value == flag => Ok(AdminChange::Unchanged),
107 Some(_) => Ok(AdminChange::LastAdmin),
108 }
109 }
110
111 /// Number of enabled administrators. The admin pages show it and refuse to leave none.
112 pub async fn enabled_admin_count(&self) -> Result<u64> {
113 let conn = self.read_conn().await;
114 let count = fetch_opt(
115 &conn,
116 "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL",
117 (),
118 |row| col_int(row, 0),
119 )
120 .await?
121 .unwrap_or(0);
122 u64::try_from(count).map_err(|_| Error::Database("negative count".into()))
123 }
124
125 /// Clears the disabled mark of an account. The directory feed records the change. Returns false when
126 /// the account is missing or was not disabled.
127 pub async fn enable_user(&self, user_id: &str) -> Result<bool> {
128 let now = now_stamp();
129 let conn = self.inner.conn.lock().await;
130 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
131 let outcome: Result<bool> = async {
132 let changed = tx
133 .execute(
134 "UPDATE users SET disabled_at = NULL, updated_at = ?2 \
135 WHERE id = ?1 AND disabled_at IS NOT NULL",
136 (user_id.to_string(), now),
137 )
138 .await
139 .map_err(db_err)?;
140 if changed != 1 {
141 return Ok(false);
142 }
143 record_change(&tx, user_id, ChangeKind::Member).await?;
144 Ok(true)
145 }
146 .await;
147 let result = finish(tx, outcome).await;
148 if matches!(result, Ok(true)) {
149 self.announce_directory();
150 }
151 result
152 }
153
154 /// Deletes an account and everything that belonged to it: sessions and their client links, recovery
155 /// codes, reset and email-change links, and a pending two-factor enrolment. The rows that remain
156 /// name the person only by id (audit entries and invitations that person sent). Back-channel logouts
157 /// are queued first, and the directory feed records a `deleted` change. The last enabled
158 /// administrator cannot be deleted. Returns false when there was no such account.
159 ///
160 /// The caller removes the profile photo file after this returns.
161 pub async fn delete_user(&self, user_id: &str) -> Result<bool> {
162 let now = now_stamp();
163 let conn = self.inner.conn.lock().await;
164 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
165 let outcome: Result<bool> = async {
166 let exists = fetch_opt(
167 &tx,
168 "SELECT id FROM users WHERE id = ?1",
169 (user_id.to_string(),),
170 |row| col_text(row, 0),
171 )
172 .await?;
173 if exists.is_none() {
174 return Ok(false);
175 }
176 // Queued before the sessions go, because the client links are read from them.
177 backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?;
178 let removed = tx
179 .execute(
180 "DELETE FROM users WHERE id = ?1 \
181 AND (is_admin = 0 OR disabled_at IS NOT NULL \
182 OR (SELECT COUNT(*) FROM users WHERE is_admin = 1 AND disabled_at IS NULL) > 1)",
183 (user_id.to_string(),),
184 )
185 .await
186 .map_err(db_err)?;
187 if removed != 1 {
188 // Returned as an error so the transaction, with its queued logouts, is rolled back.
189 return Err(Error::Conflict(
190 "the last enabled administrator cannot be deleted".into(),
191 ));
192 }
193 // Revoked explicitly, not only by the cascade below, so no refresh can succeed for this account
194 // after the delete, whatever the foreign keys do.
195 tx.execute(
196 "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL",
197 (user_id.to_string(), now.clone()),
198 )
199 .await
200 .map_err(db_err)?;
201 tx.execute(
202 "DELETE FROM settings WHERE key = ?1",
203 (format!("totp_pending:{user_id}"),),
204 )
205 .await
206 .map_err(db_err)?;
207 record_change(&tx, user_id, ChangeKind::Deleted).await?;
208 Ok(true)
209 }
210 .await;
211 let result = finish(tx, outcome).await;
212 if matches!(result, Ok(true)) {
213 self.announce_directory();
214 }
215 result
216 }
217
218 /// A page of accounts, newest first. `search` matches a part of the address or the name, in any
219 /// case. `after` is the `(created_at, id)` of the last account of the previous page. Returns up to
220 /// `limit` accounts.
221 pub async fn list_users(
222 &self,
223 search: Option<&str>,
224 after: Option<(&str, &str)>,
225 limit: u32,
226 ) -> Result<Vec<User>> {
227 let term = search
228 .map(|s| s.trim().to_lowercase())
229 .filter(|s| !s.is_empty());
230 let (after_at, after_id) = match after {
231 Some((at, id)) => (Some(at.to_owned()), Some(id.to_owned())),
232 None => (None, None),
233 };
234 let conn = self.read_conn().await;
235 fetch_all(
236 &conn,
237 &format!(
238 "SELECT {USER_COLS} FROM users \
239 WHERE (?1 IS NULL OR instr(email_folded, ?1) > 0 OR instr(lower(name), ?1) > 0) \
240 AND (?2 IS NULL OR created_at < ?2 OR (created_at = ?2 AND id < ?3)) \
241 ORDER BY created_at DESC, id DESC LIMIT ?4"
242 ),
243 (term, after_at, after_id, i64::from(limit)),
244 map_user,
245 )
246 .await
247 }
248
249 /// Invitations that can still be used, newest first.
250 pub async fn pending_invites(&self) -> Result<Vec<Invite>> {
251 let conn = self.read_conn().await;
252 fetch_all(
253 &conn,
254 "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \
255 WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at DESC, token_hash",
256 (now_stamp(),),
257 map_invite,
258 )
259 .await
260 }
261
262 /// The invitation with this token hash, while it can still be used.
263 pub async fn pending_invite(&self, token_hash: &str) -> Result<Option<Invite>> {
264 let conn = self.read_conn().await;
265 fetch_opt(
266 &conn,
267 "SELECT token_hash, email_folded, is_admin, expires_at, accepted_at FROM invites \
268 WHERE token_hash = ?1 AND accepted_at IS NULL AND expires_at > ?2",
269 (token_hash.to_string(), now_stamp()),
270 map_invite,
271 )
272 .await
273 }
274
275 /// Deletes an invitation that was not used. Returns false when it was used or is unknown.
276 pub async fn revoke_invite(&self, token_hash: &str) -> Result<bool> {
277 let conn = self.inner.conn.lock().await;
278 let changed = conn
279 .execute(
280 "DELETE FROM invites WHERE token_hash = ?1 AND accepted_at IS NULL",
281 (token_hash.to_string(),),
282 )
283 .await
284 .map_err(db_err)?;
285 Ok(changed == 1)
286 }
287
288 /// Ends every live session of a person, with their back-channel logouts. Returns the ids ended.
289 pub async fn end_all_sessions(&self, user_id: &str, reason: EndReason) -> Result<Vec<String>> {
290 self.end_matching(user_id, None, reason).await
291 }
292
293 /// Updates the editable fields of a client. A family key that another client holds is a conflict.
294 /// Services that pointed to this client under another key are unlinked in the same transaction.
295 /// Returns false when there is no such client.
296 pub async fn update_client(&self, id: &str, edit: &ClientEdit<'_>) -> Result<bool> {
297 let redirect_uris =
298 serde_json::to_string(edit.redirect_uris).map_err(|e| Error::Invalid(e.to_string()))?;
299 let post_logout = serde_json::to_string(edit.post_logout_redirect_uris)
300 .map_err(|e| Error::Invalid(e.to_string()))?;
301 let conn = self.inner.conn.lock().await;
302 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
303 let outcome: Result<bool> = async {
304 let changed = tx
305 .execute(
306 "UPDATE clients SET name = ?2, redirect_uris = ?3, post_logout_redirect_uris = ?4, \
307 backchannel_logout_uri = ?5, allowed_scopes = ?6, service_key = ?7 \
308 WHERE id = ?1",
309 (
310 id.to_string(),
311 edit.name.to_string(),
312 redirect_uris,
313 post_logout,
314 edit.backchannel_logout_uri.map(str::to_owned),
315 edit.allowed_scopes.to_string(),
316 edit.service_key.map(str::to_owned),
317 ),
318 )
319 .await
320 .map_err(|e| {
321 if e.to_string().contains("UNIQUE") {
322 Error::Conflict("that family key is already used by another client".into())
323 } else {
324 db_err(e)
325 }
326 })?;
327 if changed != 1 {
328 return Ok(false);
329 }
330 tx.execute(
331 "UPDATE services SET client_id = NULL WHERE client_id = ?1 AND key IS NOT ?2",
332 (id.to_string(), edit.service_key.map(str::to_owned)),
333 )
334 .await
335 .map_err(db_err)?;
336 Ok(true)
337 }
338 .await;
339 finish(tx, outcome).await
340 }
341
342 /// Replaces the secret hash of a client. The old secret stops working at once.
343 pub async fn rotate_client_secret(&self, id: &str, secret_hash: &str) -> Result<bool> {
344 let conn = self.inner.conn.lock().await;
345 let changed = conn
346 .execute(
347 "UPDATE clients SET secret_hash = ?2, secret_rotated_at = ?3 WHERE id = ?1",
348 (id.to_string(), secret_hash.to_string(), now_stamp()),
349 )
350 .await
351 .map_err(db_err)?;
352 Ok(changed == 1)
353 }
354
355 /// Creates or updates the switcher row of a family service and links it to its client.
356 pub async fn link_service(
357 &self,
358 key: &str,
359 name: &str,
360 url: &str,
361 client_id: &str,
362 ) -> Result<()> {
363 let conn = self.inner.conn.lock().await;
364 upsert_service_link(&conn, key, name, url, client_id).await
365 }
366
367 /// The client with this id, enabled or not. Used by the admin client pages.
368 pub async fn client_row(&self, id: &str) -> Result<Option<crate::model::Client>> {
369 let conn = self.read_conn().await;
370 fetch_opt(
371 &conn,
372 &format!("SELECT {} FROM clients WHERE id = ?1", CLIENT_COLS),
373 (id.to_string(),),
374 map_client,
375 )
376 .await
377 }
378
379 /// One page of the mail outbox, newest first, optionally only one state. `after` is the id of the
380 /// last row of the previous page.
381 pub async fn outbox_page(
382 &self,
383 state: Option<&str>,
384 after: Option<&str>,
385 limit: u32,
386 ) -> Result<Vec<OutboxRow>> {
387 let conn = self.read_conn().await;
388 fetch_all(
389 &conn,
390 "SELECT id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error, created_at \
391 FROM mail_outbox \
392 WHERE (?1 IS NULL OR state = ?1) AND (?2 IS NULL OR id < ?2) \
393 ORDER BY id DESC LIMIT ?3",
394 (
395 state.map(str::to_owned),
396 after.map(str::to_owned),
397 i64::from(limit),
398 ),
399 map_outbox,
400 )
401 .await
402 }
403
404 /// How many rows the outbox holds in each state.
405 pub async fn outbox_counts(&self) -> Result<Vec<(String, i64)>> {
406 let conn = self.read_conn().await;
407 fetch_all(
408 &conn,
409 "SELECT state, COUNT(*) FROM mail_outbox GROUP BY state ORDER BY state",
410 (),
411 |row| Ok((col_text(row, 0)?, col_int(row, 1)?)),
412 )
413 .await
414 }
415
416 /// Sends a failed row again now. Only a `failed` row whose body is still held can be retried.
417 pub async fn retry_mail(&self, id: &str) -> Result<bool> {
418 let conn = self.inner.conn.lock().await;
419 let changed = conn
420 .execute(
421 "UPDATE mail_outbox SET state = 'pending', next_attempt_at = ?2 \
422 WHERE id = ?1 AND state = 'failed' AND body_text <> ''",
423 (id.to_string(), now_stamp()),
424 )
425 .await
426 .map_err(db_err)?;
427 Ok(changed == 1)
428 }
429
430 /// Gives up on a row that is not yet sent: its body is blanked, as the worker does on abandonment.
431 pub async fn abandon_mail(&self, id: &str) -> Result<bool> {
432 let conn = self.inner.conn.lock().await;
433 let changed = conn
434 .execute(
435 "UPDATE mail_outbox SET state = 'abandoned', body_text = '', \
436 last_error = 'abandoned by an administrator' \
437 WHERE id = ?1 AND state IN ('pending', 'failed')",
438 (id.to_string(),),
439 )
440 .await
441 .map_err(db_err)?;
442 Ok(changed == 1)
443 }
444
445 /// Retires a published signing key that is not the current one. Its public key stays published for
446 /// the usual overlap, so tokens it signed still verify. Its sealed seed is blanked in the same write,
447 /// because a retired key never signs again. The current key cannot be retired: the statement excludes
448 /// it, so a token can always be signed.
449 pub async fn retire_signing_key(&self, kid: &str) -> Result<bool> {
450 let now = now_stamp();
451 let conn = self.inner.conn.lock().await;
452 let changed = conn
453 .execute(
454 "UPDATE signing_keys SET retires_at = ?2, private_sealed = '' \
455 WHERE kid = ?1 AND retires_at IS NULL AND activates_at <= ?2 \
456 AND kid <> (SELECT kid FROM signing_keys WHERE retires_at IS NULL AND activates_at <= ?2 \
457 ORDER BY activates_at DESC, kid DESC LIMIT 1)",
458 (kid.to_string(), now),
459 )
460 .await
461 .map_err(db_err)?;
462 Ok(changed == 1)
463 }
464
465 /// Reads the saved `policy.` values, lets `change` decide which of them to write, and writes those in one
466 /// transaction. `change` gets the saved values as they are inside the transaction, so a read-modify-write
467 /// of the policy cannot lose an update made by another request in between. An error from `change` rolls
468 /// the transaction back and is returned unchanged.
469 pub async fn update_policy_settings(
470 &self,
471 change: impl FnOnce(&[(String, String)]) -> Result<Vec<(String, String)>>,
472 ) -> Result<()> {
473 let conn = self.inner.conn.lock().await;
474 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
475 let outcome: Result<()> = async {
476 let saved = fetch_all(
477 &tx,
478 "SELECT key, value FROM settings WHERE substr(key, 1, length('policy.')) = 'policy.' ORDER BY key",
479 (),
480 |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
481 )
482 .await?;
483 let writes = change(&saved)?;
484 for (key, value) in writes {
485 tx.execute(
486 "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
487 ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
488 (key, value, now_stamp()),
489 )
490 .await
491 .map_err(db_err)?;
492 }
493 Ok(())
494 }
495 .await;
496 finish(tx, outcome).await
497 }
498
499 /// Removes a setting. Returns false when there was no such setting.
500 pub async fn delete_setting(&self, key: &str) -> Result<bool> {
501 let conn = self.inner.conn.lock().await;
502 let changed = conn
503 .execute("DELETE FROM settings WHERE key = ?1", (key.to_string(),))
504 .await
505 .map_err(db_err)?;
506 Ok(changed == 1)
507 }
508
509 /// The settings whose key starts with `prefix`, in key order.
510 pub async fn settings_with_prefix(&self, prefix: &str) -> Result<Vec<(String, String)>> {
511 let conn = self.read_conn().await;
512 fetch_all(
513 &conn,
514 "SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1 ORDER BY key",
515 (prefix.to_string(),),
516 |row: &Row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
517 )
518 .await
519 }
520}
521
522/// Maps a row selected as `id, kind, to_addr, subject, state, attempts, next_attempt_at, last_error,
523/// created_at`.
524fn map_outbox(row: &Row) -> Result<OutboxRow> {
525 Ok(OutboxRow {
526 id: col_text(row, 0)?,
527 kind: col_text(row, 1)?,
528 to_addr: col_text(row, 2)?,
529 subject: col_text(row, 3)?,
530 state: col_text(row, 4)?,
531 attempts: col_int(row, 5)?,
532 next_attempt_at: col_text(row, 6)?,
533 last_error: crate::store::col_opt_text(row, 7)?,
534 created_at: col_text(row, 8)?,
535 })
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541
542 async fn store_with_users() -> (tempfile::TempDir, Store, String, String) {
543 let dir = tempfile::tempdir().unwrap();
544 let store = Store::open(&dir.path().join("im.db")).await.unwrap();
545 let first = store
546 .create_first_admin("ada@example.com", "Ada", "h")
547 .await
548 .unwrap();
549 let second = store
550 .create_user("bob@example.com", "Bob", "h", true)
551 .await
552 .unwrap();
553 (dir, store, first.id, second.id)
554 }
555
556 #[tokio::test]
557 async fn the_last_enabled_admin_cannot_be_demoted_disabled_or_deleted() {
558 let (_dir, store, first, second) = store_with_users().await;
559 // Two admins: one may go.
560 assert!(store.disable_user(&second).await.unwrap());
561 // `second` is disabled now, so `first` is the last enabled admin.
562 assert_eq!(
563 store.set_admin(&first, false).await.unwrap(),
564 AdminChange::LastAdmin
565 );
566 assert!(!store.disable_user(&first).await.unwrap());
567 assert!(store.delete_user(&first).await.is_err());
568 assert_eq!(store.enabled_admin_count().await.unwrap(), 1);
569 assert!(store.user_by_id(&first).await.unwrap().is_some());
570 }
571}