Password change kills pending reset and email links, photo decode capped and rate-limited, back-channel retries keep their jti
Browse files at this commit1fb6cc20db90a9a0662ebbfbf4c67c02daef413fParent: e787bb2- fix
- password change kills pending reset and email links, photo decode capped and rate-limited, back-channel retries keep their jti
- README registration and SMTP notes
14 changed files +188 -29
- README.md +6 -4
- crates/im-core/migrations/0005_outbox_jti.sql +8 -0
- crates/im-core/src/photo.rs +40 -4
- crates/im-core/src/store/backchannel.rs +35 -4
- crates/im-core/src/store/links.rs +28 -0
- crates/im-core/src/store/migrate.rs +1 -0
- crates/im-core/src/store/mod.rs +5 -1
- crates/im-core/src/store/users.rs +8 -4
- crates/im-web/src/backchannel.rs +5 -4
- crates/im-web/src/boot.rs +2 -0
- crates/im-web/src/i18n/account.rs +8 -0
- crates/im-web/src/pages/profile.rs +22 -8
- crates/im-web/src/state.rs +2 -0
- crates/im-web/src/throttle.rs +18 -0
README.mdmodified+6 -4
| @@ -54,7 +54,8 @@ saved there overrides the file, and the settings page shows where each value com | |||
| 54 | 54 | ||
| 55 | ## Registering the family services | 55 | ## Registering the family services |
| 56 | 56 | ||
| 57 | -Each service that signs people in is an OpenID client. Register it from the shell on the server: | 57 | +Each service that signs people in is an OpenID client. Register it from the shell on the server. The CLI |
| 58 | +opens the database itself, so run it while `im serve` is stopped (or use the admin UI under Services): | ||
| 58 | 59 | ||
| 59 | ```sh | 60 | ```sh |
| 60 | im --config /etc/im/im.toml client add --name "in" \ | 61 | im --config /etc/im/im.toml client add --name "in" \ |
| @@ -62,14 +63,14 @@ im --config /etc/im/im.toml client add --name "in" \ | |||
| 62 | --post-logout-uri https://in.example.com/ \ | 63 | --post-logout-uri https://in.example.com/ \ |
| 63 | --backchannel-uri https://in.example.com/auth/backchannel-logout \ | 64 | --backchannel-uri https://in.example.com/auth/backchannel-logout \ |
| 64 | --family-key in --public-url https://in.example.com \ | 65 | --family-key in --public-url https://in.example.com \ |
| 65 | - --scopes "openid profile email" | 66 | + --scopes "openid profile email directory.read" |
| 66 | 67 | ||
| 67 | im --config /etc/im/im.toml client add --name "iz" \ | 68 | im --config /etc/im/im.toml client add --name "iz" \ |
| 68 | --redirect-uri https://iz.example.com/auth/callback \ | 69 | --redirect-uri https://iz.example.com/auth/callback \ |
| 69 | --post-logout-uri https://iz.example.com/ \ | 70 | --post-logout-uri https://iz.example.com/ \ |
| 70 | --backchannel-uri https://iz.example.com/auth/backchannel-logout \ | 71 | --backchannel-uri https://iz.example.com/auth/backchannel-logout \ |
| 71 | --family-key iz --public-url https://iz.example.com \ | 72 | --family-key iz --public-url https://iz.example.com \ |
| 72 | - --scopes "openid profile email" | 73 | + --scopes "openid profile email directory.read files.service" |
| 73 | ``` | 74 | ``` |
| 74 | 75 | ||
| 75 | - The redirect URI is `{base}/auth/callback` of the service. | 76 | - The redirect URI is `{base}/auth/callback` of the service. |
| @@ -88,7 +89,8 @@ Clients are listed with `im client list`, and disabled with `im client disable < | |||
| 88 | 89 | ||
| 89 | 90 | ||
| 90 | Mail is always queued in the outbox and sent through `[smtp]`. With `host` empty no attempt is made, and mail | 91 | Mail is always queued in the outbox and sent through `[smtp]`. With `host` empty no attempt is made, and mail |
| 91 | -waits in the outbox. Set `host`, `port`, `tls` (`implicit` for port 465, `starttls` for 587), `from`, | 92 | +waits in the outbox. Set `host`, `port`, `tls` (`implicit` for port 465, `starttls` for 587, `none` only for a relay on |
| 93 | +loopback), `from`, | ||
| 92 | `from_name`, and, when the relay needs a login, `username` and `password_file` (first line only, not readable | 94 | `from_name`, and, when the relay needs a login, `username` and `password_file` (first line only, not readable |
| 93 | by group or others). | 95 | by group or others). |
| 94 | 96 | ||
crates/im-core/migrations/0005_outbox_jti.sqladded+8 -0
| @@ -0,0 +1,8 @@ | |||
| 1 | +-- 0005: the `jti` of each back-channel logout, stored with its outbox row when the row is queued. The | ||
| 2 | +-- worker signs every attempt of the row with this same jti, so a receiver that recognises a repeat by | ||
| 3 | +-- its jti (contracts.md 2.5) sees the retries as the one logout they are. A row queued before this | ||
| 4 | +-- migration gets its own id as its jti, which is unique per row. | ||
| 5 | + | ||
| 6 | +ALTER TABLE backchannel_outbox ADD COLUMN jti TEXT NOT NULL DEFAULT ''; | ||
| 7 | + | ||
| 8 | +UPDATE backchannel_outbox SET jti = id WHERE jti = ''; | ||
crates/im-core/src/photo.rsmodified+40 -4
| @@ -17,6 +17,7 @@ use std::path::{Path, PathBuf}; | |||
| 17 | 17 | ||
| 18 | use image::metadata::Orientation; | 18 | use image::metadata::Orientation; |
| 19 | use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; | 19 | use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; |
| 20 | +use tokio::sync::{Semaphore, SemaphorePermit}; | ||
| 20 | 21 | ||
| 21 | use crate::error::{Error, Result}; | 22 | use crate::error::{Error, Result}; |
| 22 | 23 | ||
| @@ -26,11 +27,20 @@ pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; | |||
| 26 | /// Longest side of the stored picture, in pixels. The picture is a square of this size at most. | 27 | /// Longest side of the stored picture, in pixels. The picture is a square of this size at most. |
| 27 | pub const MAX_SIDE: u32 = 512; | 28 | pub const MAX_SIDE: u32 = 512; |
| 28 | 29 | ||
| 29 | -/// Longest side an input may have, in pixels. Larger inputs are refused before any pixel is decoded. | 30 | +/// Longest side an input may have, in pixels. Larger inputs are refused from the header, before any |
| 30 | -const MAX_INPUT_SIDE: u32 = 8000; | 31 | +/// pixel is decoded. At this side an RGBA picture is exactly [`MAX_DECODE_ALLOC`]. |
| 32 | +const MAX_INPUT_SIDE: u32 = 4096; | ||
| 31 | 33 | ||
| 32 | -/// Most memory the decoder may allocate for one input, in bytes (256 MiB). | 34 | +/// Most memory the decoder may allocate for one input, in bytes (64 MiB). A 4096 x 4096 RGBA picture |
| 33 | -const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024; | 35 | +/// fills it exactly, so the side limit and the allocation limit agree. |
| 36 | +const MAX_DECODE_ALLOC: u64 = 64 * 1024 * 1024; | ||
| 37 | + | ||
| 38 | +/// Decodes that may run at once. Each one holds up to [`MAX_DECODE_ALLOC`], so a burst of uploads queues | ||
| 39 | +/// behind two permits instead of starting one blocking thread and one decode per request. | ||
| 40 | +const DECODE_PERMITS: usize = 2; | ||
| 41 | + | ||
| 42 | +/// The gate of every async decode. | ||
| 43 | +static DECODING: Semaphore = Semaphore::const_new(DECODE_PERMITS); | ||
| 34 | 44 | ||
| 35 | /// MIME type of every stored photo. Lossless WebP keeps transparency and needs no quality choice. | 45 | /// MIME type of every stored photo. Lossless WebP keeps transparency and needs no quality choice. |
| 36 | pub const STORED_MIME: &str = "image/webp"; | 46 | pub const STORED_MIME: &str = "image/webp"; |
| @@ -64,7 +74,12 @@ pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> { | |||
| 64 | limits.max_alloc = Some(MAX_DECODE_ALLOC); | 74 | limits.max_alloc = Some(MAX_DECODE_ALLOC); |
| 65 | let mut reader = ImageReader::with_format(Cursor::new(input), format); | 75 | let mut reader = ImageReader::with_format(Cursor::new(input), format); |
| 66 | reader.limits(limits); | 76 | reader.limits(limits); |
| 77 | + // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded. | ||
| 67 | let mut decoder = reader.into_decoder().map_err(decode_error)?; | 78 | let mut decoder = reader.into_decoder().map_err(decode_error)?; |
| 79 | + let (declared_width, declared_height) = decoder.dimensions(); | ||
| 80 | + if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE { | ||
| 81 | + return Err(refused()); | ||
| 82 | + } | ||
| 68 | // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping. | 83 | // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping. |
| 69 | let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); | 84 | let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); |
| 70 | let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?; | 85 | let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?; |
| @@ -89,6 +104,27 @@ pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> { | |||
| 89 | Ok(out.into_inner()) | 104 | Ok(out.into_inner()) |
| 90 | } | 105 | } |
| 91 | 106 | ||
| 107 | +/// [`normalize_photo`] on the blocking thread pool, behind the decode gate. A task that panics is logged | ||
| 108 | +/// and answered as a refused picture, so the upload gets the same answer as any broken file. | ||
| 109 | +pub async fn normalize_photo_async(input: Vec<u8>) -> Result<Vec<u8>> { | ||
| 110 | + let _permit = decode_gate().await?; | ||
| 111 | + match tokio::task::spawn_blocking(move || normalize_photo(&input)).await { | ||
| 112 | + Ok(result) => result, | ||
| 113 | + Err(error) => { | ||
| 114 | + tracing::error!(error = %error, "photo decode task failed"); | ||
| 115 | + Err(refused()) | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// Takes one of the [`DECODE_PERMITS`] slots. Held until the blocking work ends. | ||
| 121 | +async fn decode_gate() -> Result<SemaphorePermit<'static>> { | ||
| 122 | + DECODING | ||
| 123 | + .acquire() | ||
| 124 | + .await | ||
| 125 | + .map_err(|e| Error::Crypto(format!("decode gate closed: {e}"))) | ||
| 126 | +} | ||
| 127 | + | ||
| 92 | /// Every decode failure is the uploader's problem: the bytes are not an image this build reads. | 128 | /// Every decode failure is the uploader's problem: the bytes are not an image this build reads. |
| 93 | fn decode_error(_: image::ImageError) -> Error { | 129 | fn decode_error(_: image::ImageError) -> Error { |
| 94 | refused() | 130 | refused() |
crates/im-core/src/store/backchannel.rsmodified+35 -4
| @@ -10,6 +10,7 @@ use turso::Connection; | |||
| 10 | 10 | ||
| 11 | use crate::error::Result; | 11 | use crate::error::Result; |
| 12 | use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | 12 | use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; |
| 13 | +use crate::token::generate_token; | ||
| 13 | 14 | ||
| 14 | /// Why a session, or every session of a person, ended. The stored text is the `reason` column. | 15 | /// Why a session, or every session of a person, ended. The stored text is the `reason` column. |
| 15 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 16 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -60,6 +61,8 @@ pub struct Delivery { | |||
| 60 | pub attempts: i64, | 61 | pub attempts: i64, |
| 61 | /// When the row was queued. The retry window counts from here. | 62 | /// When the row was queued. The retry window counts from here. |
| 62 | pub created_at: String, | 63 | pub created_at: String, |
| 64 | + /// The `jti` of the logout token, fixed when the row was queued. Every attempt carries it. | ||
| 65 | + pub jti: String, | ||
| 63 | } | 66 | } |
| 64 | 67 | ||
| 65 | /// Every column of an outbox row, for inspection and tests. | 68 | /// Every column of an outbox row, for inspection and tests. |
| @@ -103,7 +106,8 @@ fn map_row(row: &turso::Row) -> Result<OutboxRow> { | |||
| 103 | }) | 106 | }) |
| 104 | } | 107 | } |
| 105 | 108 | ||
| 106 | -/// Inserts one pending row. Runs inside the caller's transaction. | 109 | +/// Inserts one pending row. The row gets its `jti` here, once, so every attempt of the logout carries the |
| 110 | +/// same one. Runs inside the caller's transaction. | ||
| 107 | async fn insert_row( | 111 | async fn insert_row( |
| 108 | conn: &Connection, | 112 | conn: &Connection, |
| 109 | client_id: &str, | 113 | client_id: &str, |
| @@ -114,8 +118,8 @@ async fn insert_row( | |||
| 114 | ) -> Result<()> { | 118 | ) -> Result<()> { |
| 115 | conn.execute( | 119 | conn.execute( |
| 116 | "INSERT INTO backchannel_outbox (id, client_id, sid, sub, reason, state, attempts, \ | 120 | "INSERT INTO backchannel_outbox (id, client_id, sid, sub, reason, state, attempts, \ |
| 117 | - next_attempt_at, created_at) \ | 121 | + next_attempt_at, created_at, jti) \ |
| 118 | - VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", | 122 | + VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6, ?7)", |
| 119 | ( | 123 | ( |
| 120 | new_id(), | 124 | new_id(), |
| 121 | client_id.to_string(), | 125 | client_id.to_string(), |
| @@ -123,6 +127,7 @@ async fn insert_row( | |||
| 123 | sub.to_string(), | 127 | sub.to_string(), |
| 124 | reason.as_str().to_string(), | 128 | reason.as_str().to_string(), |
| 125 | now.to_string(), | 129 | now.to_string(), |
| 130 | + generate_token(), | ||
| 126 | ), | 131 | ), |
| 127 | ) | 132 | ) |
| 128 | .await | 133 | .await |
| @@ -208,7 +213,7 @@ impl Store { | |||
| 208 | let conn = self.read_conn().await; | 213 | let conn = self.read_conn().await; |
| 209 | fetch_all( | 214 | fetch_all( |
| 210 | &conn, | 215 | &conn, |
| 211 | - "SELECT id, client_id, sid, sub, attempts, created_at FROM backchannel_outbox \ | 216 | + "SELECT id, client_id, sid, sub, attempts, created_at, jti FROM backchannel_outbox \ |
| 212 | WHERE state = 'pending' AND next_attempt_at <= ?1 \ | 217 | WHERE state = 'pending' AND next_attempt_at <= ?1 \ |
| 213 | ORDER BY next_attempt_at ASC, id ASC LIMIT ?2", | 218 | ORDER BY next_attempt_at ASC, id ASC LIMIT ?2", |
| 214 | (now.to_string(), limit), | 219 | (now.to_string(), limit), |
| @@ -220,6 +225,7 @@ impl Store { | |||
| 220 | sub: col_text(row, 3)?, | 225 | sub: col_text(row, 3)?, |
| 221 | attempts: col_int(row, 4)?, | 226 | attempts: col_int(row, 4)?, |
| 222 | created_at: col_text(row, 5)?, | 227 | created_at: col_text(row, 5)?, |
| 228 | + jti: col_text(row, 6)?, | ||
| 223 | }) | 229 | }) |
| 224 | }, | 230 | }, |
| 225 | ) | 231 | ) |
| @@ -421,6 +427,31 @@ mod tests { | |||
| 421 | ); | 427 | ); |
| 422 | } | 428 | } |
| 423 | 429 | ||
| 430 | + #[tokio::test] | ||
| 431 | + async fn every_attempt_of_a_row_carries_the_jti_it_was_queued_with() { | ||
| 432 | + let (_dir, store, user_id, _session_id, _clients) = fixture().await; | ||
| 433 | + store.disable_user(&user_id).await.expect("disable"); | ||
| 434 | + let later = stamp_after(Duration::from_secs(3600)); | ||
| 435 | + let first = store.due_deliveries(&later, 10).await.expect("due"); | ||
| 436 | + assert_eq!(first.len(), 2); | ||
| 437 | + assert_ne!(first[0].jti, first[1].jti, "each row has its own jti"); | ||
| 438 | + for job in &first { | ||
| 439 | + let retry = Attempt::Retry { | ||
| 440 | + attempts: 1, | ||
| 441 | + next: later.clone(), | ||
| 442 | + error: "unreachable".into(), | ||
| 443 | + }; | ||
| 444 | + store | ||
| 445 | + .record_attempt(&job.id, &retry, &crate::time::now_stamp()) | ||
| 446 | + .await | ||
| 447 | + .expect("retry"); | ||
| 448 | + } | ||
| 449 | + for job in store.due_deliveries(&later, 10).await.expect("due again") { | ||
| 450 | + let queued = first.iter().find(|f| f.id == job.id).expect("same row"); | ||
| 451 | + assert_eq!(job.jti, queued.jti); | ||
| 452 | + } | ||
| 453 | + } | ||
| 454 | + | ||
| 424 | #[tokio::test] | 455 | #[tokio::test] |
| 425 | async fn disabling_an_account_queues_one_sub_only_row_per_client_and_ends_its_sessions() { | 456 | async fn disabling_an_account_queues_one_sub_only_row_per_client_and_ends_its_sessions() { |
| 426 | let (_dir, store, user_id, session_id, _clients) = fixture().await; | 457 | let (_dir, store, user_id, session_id, _clients) = fixture().await; |
crates/im-core/src/store/links.rsmodified+28 -0
| @@ -420,6 +420,34 @@ mod tests { | |||
| 420 | assert_eq!(user.password_hash, "new-hash"); | 420 | assert_eq!(user.password_hash, "new-hash"); |
| 421 | } | 421 | } |
| 422 | 422 | ||
| 423 | + #[tokio::test] | ||
| 424 | + async fn a_reset_link_dies_when_the_password_changes() { | ||
| 425 | + let (_dir, store, user_id) = setup().await; | ||
| 426 | + store | ||
| 427 | + .create_reset_link( | ||
| 428 | + &user_id, | ||
| 429 | + "reset-hash", | ||
| 430 | + &stamp_after(Duration::from_secs(3600)), | ||
| 431 | + ) | ||
| 432 | + .await | ||
| 433 | + .unwrap(); | ||
| 434 | + store | ||
| 435 | + .change_password(&user_id, "new-hash", "kept-session") | ||
| 436 | + .await | ||
| 437 | + .unwrap(); | ||
| 438 | + assert!(store.live_reset_link("reset-hash").await.unwrap().is_none()); | ||
| 439 | + // A link from before the change cannot set the password again. | ||
| 440 | + assert_eq!( | ||
| 441 | + store | ||
| 442 | + .redeem_reset_link("reset-hash", "stale-hash") | ||
| 443 | + .await | ||
| 444 | + .unwrap(), | ||
| 445 | + None | ||
| 446 | + ); | ||
| 447 | + let user = store.user_by_id(&user_id).await.unwrap().unwrap(); | ||
| 448 | + assert_eq!(user.password_hash, "new-hash"); | ||
| 449 | + } | ||
| 450 | + | ||
| 423 | #[tokio::test] | 451 | #[tokio::test] |
| 424 | async fn an_email_change_is_refused_when_the_address_was_taken_before_confirm() { | 452 | async fn an_email_change_is_refused_when_the_address_was_taken_before_confirm() { |
| 425 | let (_dir, store, user_id) = setup().await; | 453 | let (_dir, store, user_id) = setup().await; |
crates/im-core/src/store/migrate.rsmodified+1 -0
| @@ -24,6 +24,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 24 | 4, | 24 | 4, |
| 25 | include_str!("../../migrations/0004_revoked_access_tokens.sql"), | 25 | include_str!("../../migrations/0004_revoked_access_tokens.sql"), |
| 26 | ), | 26 | ), |
| 27 | + (5, include_str!("../../migrations/0005_outbox_jti.sql")), | ||
| 27 | ]; | 28 | ]; |
| 28 | 29 | ||
| 29 | fn migration_err(e: turso::Error) -> Error { | 30 | fn migration_err(e: turso::Error) -> Error { |
crates/im-core/src/store/mod.rsmodified+5 -1
| @@ -353,6 +353,10 @@ mod tests { | |||
| 353 | }) | 353 | }) |
| 354 | .await | 354 | .await |
| 355 | .unwrap(); | 355 | .unwrap(); |
| 356 | - assert_eq!(applied, vec![1, 2, 3, 4]); | 356 | + let expected: Vec<i64> = migrate::MIGRATIONS |
| 357 | + .iter() | ||
| 358 | + .map(|&(version, _)| i64::from(version)) | ||
| 359 | + .collect(); | ||
| 360 | + assert_eq!(applied, expected); | ||
| 357 | } | 361 | } |
| 358 | } | 362 | } |
crates/im-core/src/store/users.rsmodified+8 -4
| @@ -18,6 +18,7 @@ use crate::error::{Error, Result}; | |||
| 18 | use crate::model::User; | 18 | use crate::model::User; |
| 19 | use crate::store::backchannel::{self, EndReason}; | 19 | use crate::store::backchannel::{self, EndReason}; |
| 20 | use crate::store::directory::{ChangeKind, record_change}; | 20 | use crate::store::directory::{ChangeKind, record_change}; |
| 21 | +use crate::store::links::invalidate_links; | ||
| 21 | use crate::store::sessions::{end_rows, live_session_ids}; | 22 | use crate::store::sessions::{end_rows, live_session_ids}; |
| 22 | use crate::store::{ | 23 | use crate::store::{ |
| 23 | Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, | 24 | Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, |
| @@ -319,10 +320,12 @@ impl Store { | |||
| 319 | result | 320 | result |
| 320 | } | 321 | } |
| 321 | 322 | ||
| 322 | - /// Stores a new argon2id hash and ends every live session of the person except `keep_session_id`, | 323 | + /// Stores a new argon2id hash, ends every live session of the person except `keep_session_id`, |
| 323 | - /// with their back-channel logouts. One transaction: the old password never stays in force for a | 324 | + /// with their back-channel logouts, and invalidates every pending account link (password reset and |
| 324 | - /// session that the new one has ended, and nothing changes unless both happen. The caller has checked | 325 | + /// email change), so a link issued for the old password cannot set or change anything. One |
| 325 | - /// the policy and the current password. Returns the ids of the sessions ended. | 326 | + /// transaction: the old password never stays in force for a session that the new one has ended, and |
| 327 | + /// nothing changes unless all of it happens. The caller has checked the policy and the current | ||
| 328 | + /// password. Returns the ids of the sessions ended. | ||
| 326 | pub async fn change_password( | 329 | pub async fn change_password( |
| 327 | &self, | 330 | &self, |
| 328 | id: &str, | 331 | id: &str, |
| @@ -343,6 +346,7 @@ impl Store { | |||
| 343 | if changed == 0 { | 346 | if changed == 0 { |
| 344 | return Err(Error::NotFound); | 347 | return Err(Error::NotFound); |
| 345 | } | 348 | } |
| 349 | + invalidate_links(&tx, id, &now).await?; | ||
| 346 | let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?; | 350 | let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?; |
| 347 | end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?; | 351 | end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?; |
| 348 | Ok(ids) | 352 | Ok(ids) |
crates/im-web/src/backchannel.rsmodified+5 -4
| @@ -10,8 +10,10 @@ | |||
| 10 | //! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up | 10 | //! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up |
| 11 | //! the others. Their outcomes are recorded in the order the rows were due. | 11 | //! the others. Their outcomes are recorded in the order the rows were due. |
| 12 | //! | 12 | //! |
| 13 | -//! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), a fresh `jti`, the logout | 13 | +//! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), the row's `jti`, the logout |
| 14 | -//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. | 14 | +//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. Every attempt of a |
| 15 | +//! row re-signs the token with fresh `iat` and `exp` but the same `jti`, so a repeat is recognisable as one | ||
| 16 | +//! logout (contracts.md 2.5). | ||
| 15 | 17 | ||
| 16 | use std::sync::Arc; | 18 | use std::sync::Arc; |
| 17 | use std::time::Duration; | 19 | use std::time::Duration; |
| @@ -21,7 +23,6 @@ use im_core::model::Client; | |||
| 21 | use im_core::store::Store; | 23 | use im_core::store::Store; |
| 22 | use im_core::store::backchannel::{Attempt, Delivery}; | 24 | use im_core::store::backchannel::{Attempt, Delivery}; |
| 23 | use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; | 25 | use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; |
| 24 | -use im_core::token::generate_token; | ||
| 25 | use serde_json::{Value, json}; | 26 | use serde_json::{Value, json}; |
| 26 | use tokio::sync::watch; | 27 | use tokio::sync::watch; |
| 27 | 28 | ||
| @@ -217,7 +218,7 @@ async fn logout_token( | |||
| 217 | "aud": client.id, | 218 | "aud": client.id, |
| 218 | "iat": now, | 219 | "iat": now, |
| 219 | "exp": now + LOGOUT_TOKEN_TTL, | 220 | "exp": now + LOGOUT_TOKEN_TTL, |
| 220 | - "jti": generate_token(), | 221 | + "jti": job.jti, |
| 221 | "events": { LOGOUT_EVENT: {} }, | 222 | "events": { LOGOUT_EVENT: {} }, |
| 222 | "sub": job.sub, | 223 | "sub": job.sub, |
| 223 | }); | 224 | }); |
crates/im-web/src/boot.rsmodified+2 -0
| @@ -151,6 +151,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> { | |||
| 151 | key: Arc::new(key), | 151 | key: Arc::new(key), |
| 152 | live: Arc::new(LiveHub::default()), | 152 | live: Arc::new(LiveHub::default()), |
| 153 | throttle: Arc::new(Throttle::default()), | 153 | throttle: Arc::new(Throttle::default()), |
| 154 | + photo_uploads: Arc::new(Throttle::photo_uploads()), | ||
| 154 | stream_slots: Arc::new(StreamSlots::default()), | 155 | stream_slots: Arc::new(StreamSlots::default()), |
| 155 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), | 156 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), |
| 156 | // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. | 157 | // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. |
| @@ -265,6 +266,7 @@ mod tests { | |||
| 265 | key: Arc::new(key), | 266 | key: Arc::new(key), |
| 266 | live: Arc::new(LiveHub::default()), | 267 | live: Arc::new(LiveHub::default()), |
| 267 | throttle: Arc::new(Throttle::default()), | 268 | throttle: Arc::new(Throttle::default()), |
| 269 | + photo_uploads: Arc::new(Throttle::photo_uploads()), | ||
| 268 | stream_slots: Arc::new(StreamSlots::default()), | 270 | stream_slots: Arc::new(StreamSlots::default()), |
| 269 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), | 271 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), |
| 270 | stop: watch::channel(false).1, | 272 | stop: watch::channel(false).1, |
crates/im-web/src/i18n/account.rsmodified+8 -0
| @@ -210,6 +210,8 @@ pub enum Txt { | |||
| 210 | ErrPhotoTooLarge, | 210 | ErrPhotoTooLarge, |
| 211 | /// Shown when the upload form was sent without a file. | 211 | /// Shown when the upload form was sent without a file. |
| 212 | ErrPhotoMissing, | 212 | ErrPhotoMissing, |
| 213 | + /// Shown when the account has used its photo uploads for the hour. | ||
| 214 | + ErrPhotoRateLimited, | ||
| 213 | /// The title of the preferences page, and the menu item that opens it. | 215 | /// The title of the preferences page, and the menu item that opens it. |
| 214 | PreferencesTitle, | 216 | PreferencesTitle, |
| 215 | /// The account home link text that opens the preferences page. | 217 | /// The account home link text that opens the preferences page. |
| @@ -499,6 +501,12 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { | |||
| 499 | (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.", | 501 | (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.", |
| 500 | (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", | 502 | (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", |
| 501 | (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", | 503 | (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", |
| 504 | + (Txt::ErrPhotoRateLimited, Lang::En) => { | ||
| 505 | + "Too many photos were uploaded. Try again in an hour." | ||
| 506 | + } | ||
| 507 | + (Txt::ErrPhotoRateLimited, Lang::Tr) => { | ||
| 508 | + "Çok fazla fotoğraf yüklediniz. Bir saat sonra tekrar deneyin." | ||
| 509 | + } | ||
| 502 | (Txt::ErrPhotoMissing, Lang::En) => "Choose a picture first.", | 510 | (Txt::ErrPhotoMissing, Lang::En) => "Choose a picture first.", |
| 503 | (Txt::ErrPhotoMissing, Lang::Tr) => "Önce bir resim seçin.", | 511 | (Txt::ErrPhotoMissing, Lang::Tr) => "Önce bir resim seçin.", |
| 504 | (Txt::PreferencesTitle, Lang::En) => "Preferences", | 512 | (Txt::PreferencesTitle, Lang::En) => "Preferences", |
crates/im-web/src/pages/profile.rsmodified+22 -8
| @@ -6,6 +6,8 @@ | |||
| 6 | //! picture, so an upload from another site is refused before it is read at all. What is read is | 6 | //! picture, so an upload from another site is refused before it is read at all. What is read is |
| 7 | //! decoded and re-encoded by `im_core::photo` before anything is written. | 7 | //! decoded and re-encoded by `im_core::photo` before anything is written. |
| 8 | 8 | ||
| 9 | +use std::time::Instant; | ||
| 10 | + | ||
| 9 | use im_core::model::AuditAction; | 11 | use im_core::model::AuditAction; |
| 10 | use im_core::names::parse_display_name; | 12 | use im_core::names::parse_display_name; |
| 11 | use im_core::photo::{self, MAX_UPLOAD_BYTES, STORED_MIME}; | 13 | use im_core::photo::{self, MAX_UPLOAD_BYTES, STORED_MIME}; |
| @@ -27,6 +29,7 @@ use crate::i18n::flows::{Flow, text as flow_text}; | |||
| 27 | use crate::live::Topic; | 29 | use crate::live::Topic; |
| 28 | use crate::pages::login::CsrfForm; | 30 | use crate::pages::login::CsrfForm; |
| 29 | use crate::state::AppState; | 31 | use crate::state::AppState; |
| 32 | +use crate::throttle::{PHOTO_UPLOAD_LIMIT, photo_upload_key}; | ||
| 30 | use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; | 33 | use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; |
| 31 | 34 | ||
| 32 | /// Path of the photo upload. The router raises the body limit for this path (see `boot.rs`). | 35 | /// Path of the photo upload. The router raises the body limit for this path (see `boot.rs`). |
| @@ -127,6 +130,7 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | |||
| 127 | let mut checked: Option<Viewer> = None; | 130 | let mut checked: Option<Viewer> = None; |
| 128 | let mut picture: Option<Vec<u8>> = None; | 131 | let mut picture: Option<Vec<u8>> = None; |
| 129 | let mut too_large = false; | 132 | let mut too_large = false; |
| 133 | + let mut limited = false; | ||
| 130 | 134 | ||
| 131 | while let Some(mut part) = multipart.next_field().await? { | 135 | while let Some(mut part) = multipart.next_field().await? { |
| 132 | let name = part.name().unwrap_or_default().to_owned(); | 136 | let name = part.name().unwrap_or_default().to_owned(); |
| @@ -134,8 +138,19 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | |||
| 134 | "csrf" => token = part.text().await?, | 138 | "csrf" => token = part.text().await?, |
| 135 | "photo" => { | 139 | "photo" => { |
| 136 | // Refused before any byte of the picture is read, unless the token is right. | 140 | // Refused before any byte of the picture is read, unless the token is right. |
| 137 | - if checked.is_none() { | 141 | + let viewer = match checked.take() { |
| 138 | - checked = Some(require_csrf(cx, &token).await?); | 142 | + Some(viewer) => viewer, |
| 143 | + None => require_csrf(cx, &token).await?, | ||
| 144 | + }; | ||
| 145 | + // Each upload is counted before its bytes are read, so a limited upload reads nothing. | ||
| 146 | + let key = photo_upload_key(&viewer.user.id); | ||
| 147 | + limited = state | ||
| 148 | + .photo_uploads | ||
| 149 | + .reserve(&key, PHOTO_UPLOAD_LIMIT, Instant::now()) | ||
| 150 | + .is_err(); | ||
| 151 | + checked = Some(viewer); | ||
| 152 | + if limited { | ||
| 153 | + break; | ||
| 139 | } | 154 | } |
| 140 | let mut bytes = Vec::new(); | 155 | let mut bytes = Vec::new(); |
| 141 | while let Some(chunk) = part.chunk().await? { | 156 | while let Some(chunk) = part.chunk().await? { |
| @@ -161,7 +176,9 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | |||
| 161 | None => require_csrf(cx, &token).await?, | 176 | None => require_csrf(cx, &token).await?, |
| 162 | }; | 177 | }; |
| 163 | let lang = page_lang(cx, Some(&viewer)); | 178 | let lang = page_lang(cx, Some(&viewer)); |
| 164 | - let problem = if too_large { | 179 | + let problem = if limited { |
| 180 | + Some(text(lang, Txt::ErrPhotoRateLimited)) | ||
| 181 | + } else if too_large { | ||
| 165 | Some(text(lang, Txt::ErrPhotoTooLarge)) | 182 | Some(text(lang, Txt::ErrPhotoTooLarge)) |
| 166 | } else { | 183 | } else { |
| 167 | None | 184 | None |
| @@ -171,11 +188,8 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | |||
| 171 | return Ok(upload_problem(cx, lang, viewer, message)); | 188 | return Ok(upload_problem(cx, lang, viewer, message)); |
| 172 | }; | 189 | }; |
| 173 | 190 | ||
| 174 | - // Decoding is CPU work and runs off the request threads. | 191 | + // Decoding is CPU work: it runs on the blocking pool, behind the decode gate. |
| 175 | - let stored = tokio::task::spawn_blocking(move || photo::normalize_photo(&bytes)) | 192 | + let stored = match photo::normalize_photo_async(bytes).await { |
| 176 | - .await | ||
| 177 | - .map_err(|error| topcoat::Error::msg(error.to_string()))?; | ||
| 178 | - let stored = match stored { | ||
| 179 | Ok(stored) => stored, | 193 | Ok(stored) => stored, |
| 180 | Err(im_core::Error::Invalid(_)) => { | 194 | Err(im_core::Error::Invalid(_)) => { |
| 181 | return Ok(upload_problem( | 195 | return Ok(upload_problem( |
crates/im-web/src/state.rsmodified+2 -0
| @@ -27,6 +27,8 @@ pub struct AppState { | |||
| 27 | pub live: Arc<LiveHub>, | 27 | pub live: Arc<LiveHub>, |
| 28 | /// Failed sign-in and second-factor counters. | 28 | /// Failed sign-in and second-factor counters. |
| 29 | pub throttle: Arc<Throttle>, | 29 | pub throttle: Arc<Throttle>, |
| 30 | + /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`). | ||
| 31 | + pub photo_uploads: Arc<Throttle>, | ||
| 30 | /// The open directory streams of each machine client. | 32 | /// The open directory streams of each machine client. |
| 31 | pub stream_slots: Arc<StreamSlots>, | 33 | pub stream_slots: Arc<StreamSlots>, |
| 32 | /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`]. | 34 | /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`]. |
crates/im-web/src/throttle.rsmodified+18 -0
| @@ -43,6 +43,14 @@ pub const FORGOT_EMAIL_LIMIT: usize = 3; | |||
| 43 | /// Reset-link requests allowed per client address inside [`WINDOW`]. | 43 | /// Reset-link requests allowed per client address inside [`WINDOW`]. |
| 44 | pub const FORGOT_IP_LIMIT: usize = 20; | 44 | pub const FORGOT_IP_LIMIT: usize = 20; |
| 45 | 45 | ||
| 46 | +/// Profile photo uploads allowed per account inside [`PHOTO_UPLOAD_WINDOW`]. Every upload counts, whether | ||
| 47 | +/// or not its picture is accepted, because each one costs a decode. | ||
| 48 | +pub const PHOTO_UPLOAD_LIMIT: usize = 10; | ||
| 49 | + | ||
| 50 | +/// Length of the photo upload window: one hour. Kept on its own [`Throttle`] (see | ||
| 51 | +/// [`Throttle::photo_uploads`]), because a throttle has one window for all its keys. | ||
| 52 | +pub const PHOTO_UPLOAD_WINDOW: Duration = Duration::from_secs(60 * 60); | ||
| 53 | + | ||
| 46 | /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past | 54 | /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past |
| 47 | /// this. | 55 | /// this. |
| 48 | const MAX_KEYS: usize = 100_000; | 56 | const MAX_KEYS: usize = 100_000; |
| @@ -80,6 +88,11 @@ impl Default for Throttle { | |||
| 80 | } | 88 | } |
| 81 | 89 | ||
| 82 | impl Throttle { | 90 | impl Throttle { |
| 91 | + /// The counters of profile photo uploads: one hour window, the same key cap. | ||
| 92 | + pub fn photo_uploads() -> Self { | ||
| 93 | + Self::with_limits(PHOTO_UPLOAD_WINDOW, MAX_KEYS) | ||
| 94 | + } | ||
| 95 | + | ||
| 83 | /// Counters with a custom window and key cap. Tests use short windows. | 96 | /// Counters with a custom window and key cap. Tests use short windows. |
| 84 | pub fn with_limits(window: Duration, max_keys: usize) -> Self { | 97 | pub fn with_limits(window: Duration, max_keys: usize) -> Self { |
| 85 | Self { | 98 | Self { |
| @@ -260,6 +273,11 @@ pub fn forgot_email_key(email: &str) -> String { | |||
| 260 | format!("forgot:{}", address_part(email)) | 273 | format!("forgot:{}", address_part(email)) |
| 261 | } | 274 | } |
| 262 | 275 | ||
| 276 | +/// Throttle key for the photo uploads of one user, by user id. | ||
| 277 | +pub fn photo_upload_key(user_id: &str) -> String { | ||
| 278 | + format!("photo:{user_id}") | ||
| 279 | +} | ||
| 280 | + | ||
| 263 | /// Throttle key for the second factor of one user, by user id. | 281 | /// Throttle key for the second factor of one user, by user id. |
| 264 | pub fn two_factor_key(user_id: &str) -> String { | 282 | pub fn two_factor_key(user_id: &str) -> String { |
| 265 | format!("2fa:{user_id}") | 283 | format!("2fa:{user_id}") |