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 | 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 | 60 | ```sh |
| 60 | 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 | 63 | --post-logout-uri https://in.example.com/ \ |
| 63 | 64 | --backchannel-uri https://in.example.com/auth/backchannel-logout \ |
| 64 | 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 | 68 | im --config /etc/im/im.toml client add --name "iz" \ |
| 68 | 69 | --redirect-uri https://iz.example.com/auth/callback \ |
| 69 | 70 | --post-logout-uri https://iz.example.com/ \ |
| 70 | 71 | --backchannel-uri https://iz.example.com/auth/backchannel-logout \ |
| 71 | 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 | 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 | 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 | 94 | `from_name`, and, when the relay needs a login, `username` and `password_file` (first line only, not readable |
| 93 | 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 | 18 | use image::metadata::Orientation; |
| 19 | 19 | use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; |
| 20 | +use tokio::sync::{Semaphore, SemaphorePermit}; | |
| 20 | 21 | |
| 21 | 22 | use crate::error::{Error, Result}; |
| 22 | 23 | |
| @@ -26,11 +27,20 @@ pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; | ||
| 26 | 27 | /// Longest side of the stored picture, in pixels. The picture is a square of this size at most. |
| 27 | 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 | -const MAX_INPUT_SIDE: u32 = 8000; | |
| 30 | +/// Longest side an input may have, in pixels. Larger inputs are refused from the header, before any | |
| 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). | |
| 33 | -const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024; | |
| 34 | +/// Most memory the decoder may allocate for one input, in bytes (64 MiB). A 4096 x 4096 RGBA picture | |
| 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 | 45 | /// MIME type of every stored photo. Lossless WebP keeps transparency and needs no quality choice. |
| 36 | 46 | pub const STORED_MIME: &str = "image/webp"; |
| @@ -64,7 +74,12 @@ pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> { | ||
| 64 | 74 | limits.max_alloc = Some(MAX_DECODE_ALLOC); |
| 65 | 75 | let mut reader = ImageReader::with_format(Cursor::new(input), format); |
| 66 | 76 | reader.limits(limits); |
| 77 | + // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded. | |
| 67 | 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 | 83 | // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping. |
| 69 | 84 | let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); |
| 70 | 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 | 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 | 128 | /// Every decode failure is the uploader's problem: the bytes are not an image this build reads. |
| 93 | 129 | fn decode_error(_: image::ImageError) -> Error { |
| 94 | 130 | refused() |
crates/im-core/src/store/backchannel.rsmodified+35 -4
| @@ -10,6 +10,7 @@ use turso::Connection; | ||
| 10 | 10 | |
| 11 | 11 | use crate::error::Result; |
| 12 | 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 | 15 | /// Why a session, or every session of a person, ended. The stored text is the `reason` column. |
| 15 | 16 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -60,6 +61,8 @@ pub struct Delivery { | ||
| 60 | 61 | pub attempts: i64, |
| 61 | 62 | /// When the row was queued. The retry window counts from here. |
| 62 | 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 | 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 | 111 | async fn insert_row( |
| 108 | 112 | conn: &Connection, |
| 109 | 113 | client_id: &str, |
| @@ -114,8 +118,8 @@ async fn insert_row( | ||
| 114 | 118 | ) -> Result<()> { |
| 115 | 119 | conn.execute( |
| 116 | 120 | "INSERT INTO backchannel_outbox (id, client_id, sid, sub, reason, state, attempts, \ |
| 117 | - next_attempt_at, created_at) \ | |
| 118 | - VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", | |
| 121 | + next_attempt_at, created_at, jti) \ | |
| 122 | + VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6, ?7)", | |
| 119 | 123 | ( |
| 120 | 124 | new_id(), |
| 121 | 125 | client_id.to_string(), |
| @@ -123,6 +127,7 @@ async fn insert_row( | ||
| 123 | 127 | sub.to_string(), |
| 124 | 128 | reason.as_str().to_string(), |
| 125 | 129 | now.to_string(), |
| 130 | + generate_token(), | |
| 126 | 131 | ), |
| 127 | 132 | ) |
| 128 | 133 | .await |
| @@ -208,7 +213,7 @@ impl Store { | ||
| 208 | 213 | let conn = self.read_conn().await; |
| 209 | 214 | fetch_all( |
| 210 | 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 | 217 | WHERE state = 'pending' AND next_attempt_at <= ?1 \ |
| 213 | 218 | ORDER BY next_attempt_at ASC, id ASC LIMIT ?2", |
| 214 | 219 | (now.to_string(), limit), |
| @@ -220,6 +225,7 @@ impl Store { | ||
| 220 | 225 | sub: col_text(row, 3)?, |
| 221 | 226 | attempts: col_int(row, 4)?, |
| 222 | 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 | 455 | #[tokio::test] |
| 425 | 456 | async fn disabling_an_account_queues_one_sub_only_row_per_client_and_ends_its_sessions() { |
| 426 | 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 | 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 | 451 | #[tokio::test] |
| 424 | 452 | async fn an_email_change_is_refused_when_the_address_was_taken_before_confirm() { |
| 425 | 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 | 24 | 4, |
| 25 | 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 | 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 | 354 | .await |
| 355 | 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 | 18 | use crate::model::User; |
| 19 | 19 | use crate::store::backchannel::{self, EndReason}; |
| 20 | 20 | use crate::store::directory::{ChangeKind, record_change}; |
| 21 | +use crate::store::links::invalidate_links; | |
| 21 | 22 | use crate::store::sessions::{end_rows, live_session_ids}; |
| 22 | 23 | use crate::store::{ |
| 23 | 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 | 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 | - /// with their back-channel logouts. One transaction: the old password never stays in force for a | |
| 324 | - /// session that the new one has ended, and nothing changes unless both happen. The caller has checked | |
| 325 | - /// the policy and the current password. Returns the ids of the sessions ended. | |
| 323 | + /// Stores a new argon2id hash, ends every live session of the person except `keep_session_id`, | |
| 324 | + /// with their back-channel logouts, and invalidates every pending account link (password reset and | |
| 325 | + /// email change), so a link issued for the old password cannot set or change anything. One | |
| 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 | 329 | pub async fn change_password( |
| 327 | 330 | &self, |
| 328 | 331 | id: &str, |
| @@ -343,6 +346,7 @@ impl Store { | ||
| 343 | 346 | if changed == 0 { |
| 344 | 347 | return Err(Error::NotFound); |
| 345 | 348 | } |
| 349 | + invalidate_links(&tx, id, &now).await?; | |
| 346 | 350 | let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?; |
| 347 | 351 | end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?; |
| 348 | 352 | Ok(ids) |
crates/im-web/src/backchannel.rsmodified+5 -4
| @@ -10,8 +10,10 @@ | ||
| 10 | 10 | //! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up |
| 11 | 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 | |
| 14 | -//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. | |
| 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`. 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 | 18 | use std::sync::Arc; |
| 17 | 19 | use std::time::Duration; |
| @@ -21,7 +23,6 @@ use im_core::model::Client; | ||
| 21 | 23 | use im_core::store::Store; |
| 22 | 24 | use im_core::store::backchannel::{Attempt, Delivery}; |
| 23 | 25 | use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; |
| 24 | -use im_core::token::generate_token; | |
| 25 | 26 | use serde_json::{Value, json}; |
| 26 | 27 | use tokio::sync::watch; |
| 27 | 28 | |
| @@ -217,7 +218,7 @@ async fn logout_token( | ||
| 217 | 218 | "aud": client.id, |
| 218 | 219 | "iat": now, |
| 219 | 220 | "exp": now + LOGOUT_TOKEN_TTL, |
| 220 | - "jti": generate_token(), | |
| 221 | + "jti": job.jti, | |
| 221 | 222 | "events": { LOGOUT_EVENT: {} }, |
| 222 | 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 | 151 | key: Arc::new(key), |
| 152 | 152 | live: Arc::new(LiveHub::default()), |
| 153 | 153 | throttle: Arc::new(Throttle::default()), |
| 154 | + photo_uploads: Arc::new(Throttle::photo_uploads()), | |
| 154 | 155 | stream_slots: Arc::new(StreamSlots::default()), |
| 155 | 156 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), |
| 156 | 157 | // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. |
| @@ -265,6 +266,7 @@ mod tests { | ||
| 265 | 266 | key: Arc::new(key), |
| 266 | 267 | live: Arc::new(LiveHub::default()), |
| 267 | 268 | throttle: Arc::new(Throttle::default()), |
| 269 | + photo_uploads: Arc::new(Throttle::photo_uploads()), | |
| 268 | 270 | stream_slots: Arc::new(StreamSlots::default()), |
| 269 | 271 | anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), |
| 270 | 272 | stop: watch::channel(false).1, |
crates/im-web/src/i18n/account.rsmodified+8 -0
| @@ -210,6 +210,8 @@ pub enum Txt { | ||
| 210 | 210 | ErrPhotoTooLarge, |
| 211 | 211 | /// Shown when the upload form was sent without a file. |
| 212 | 212 | ErrPhotoMissing, |
| 213 | + /// Shown when the account has used its photo uploads for the hour. | |
| 214 | + ErrPhotoRateLimited, | |
| 213 | 215 | /// The title of the preferences page, and the menu item that opens it. |
| 214 | 216 | PreferencesTitle, |
| 215 | 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 | 501 | (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.", |
| 500 | 502 | (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", |
| 501 | 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 | 510 | (Txt::ErrPhotoMissing, Lang::En) => "Choose a picture first.", |
| 503 | 511 | (Txt::ErrPhotoMissing, Lang::Tr) => "Önce bir resim seçin.", |
| 504 | 512 | (Txt::PreferencesTitle, Lang::En) => "Preferences", |
crates/im-web/src/pages/profile.rsmodified+22 -8
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | //! picture, so an upload from another site is refused before it is read at all. What is read is |
| 7 | 7 | //! decoded and re-encoded by `im_core::photo` before anything is written. |
| 8 | 8 | |
| 9 | +use std::time::Instant; | |
| 10 | + | |
| 9 | 11 | use im_core::model::AuditAction; |
| 10 | 12 | use im_core::names::parse_display_name; |
| 11 | 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 | 29 | use crate::live::Topic; |
| 28 | 30 | use crate::pages::login::CsrfForm; |
| 29 | 31 | use crate::state::AppState; |
| 32 | +use crate::throttle::{PHOTO_UPLOAD_LIMIT, photo_upload_key}; | |
| 30 | 33 | use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; |
| 31 | 34 | |
| 32 | 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 | 130 | let mut checked: Option<Viewer> = None; |
| 128 | 131 | let mut picture: Option<Vec<u8>> = None; |
| 129 | 132 | let mut too_large = false; |
| 133 | + let mut limited = false; | |
| 130 | 134 | |
| 131 | 135 | while let Some(mut part) = multipart.next_field().await? { |
| 132 | 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 | 138 | "csrf" => token = part.text().await?, |
| 135 | 139 | "photo" => { |
| 136 | 140 | // Refused before any byte of the picture is read, unless the token is right. |
| 137 | - if checked.is_none() { | |
| 138 | - checked = Some(require_csrf(cx, &token).await?); | |
| 141 | + let viewer = match checked.take() { | |
| 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 | 155 | let mut bytes = Vec::new(); |
| 141 | 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 | 176 | None => require_csrf(cx, &token).await?, |
| 162 | 177 | }; |
| 163 | 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 | 182 | Some(text(lang, Txt::ErrPhotoTooLarge)) |
| 166 | 183 | } else { |
| 167 | 184 | None |
| @@ -171,11 +188,8 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | ||
| 171 | 188 | return Ok(upload_problem(cx, lang, viewer, message)); |
| 172 | 189 | }; |
| 173 | 190 | |
| 174 | - // Decoding is CPU work and runs off the request threads. | |
| 175 | - let stored = tokio::task::spawn_blocking(move || photo::normalize_photo(&bytes)) | |
| 176 | - .await | |
| 177 | - .map_err(|error| topcoat::Error::msg(error.to_string()))?; | |
| 178 | - let stored = match stored { | |
| 191 | + // Decoding is CPU work: it runs on the blocking pool, behind the decode gate. | |
| 192 | + let stored = match photo::normalize_photo_async(bytes).await { | |
| 179 | 193 | Ok(stored) => stored, |
| 180 | 194 | Err(im_core::Error::Invalid(_)) => { |
| 181 | 195 | return Ok(upload_problem( |
crates/im-web/src/state.rsmodified+2 -0
| @@ -27,6 +27,8 @@ pub struct AppState { | ||
| 27 | 27 | pub live: Arc<LiveHub>, |
| 28 | 28 | /// Failed sign-in and second-factor counters. |
| 29 | 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 | 32 | /// The open directory streams of each machine client. |
| 31 | 33 | pub stream_slots: Arc<StreamSlots>, |
| 32 | 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 | 43 | /// Reset-link requests allowed per client address inside [`WINDOW`]. |
| 44 | 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 | 54 | /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past |
| 47 | 55 | /// this. |
| 48 | 56 | const MAX_KEYS: usize = 100_000; |
| @@ -80,6 +88,11 @@ impl Default for Throttle { | ||
| 80 | 88 | } |
| 81 | 89 | |
| 82 | 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 | 96 | /// Counters with a custom window and key cap. Tests use short windows. |
| 84 | 97 | pub fn with_limits(window: Duration, max_keys: usize) -> Self { |
| 85 | 98 | Self { |
| @@ -260,6 +273,11 @@ pub fn forgot_email_key(email: &str) -> String { | ||
| 260 | 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 | 281 | /// Throttle key for the second factor of one user, by user id. |
| 264 | 282 | pub fn two_factor_key(user_id: &str) -> String { |
| 265 | 283 | format!("2fa:{user_id}") |