diff --git a/README.md b/README.md index 34ae7bf..330ca2b 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,8 @@ saved there overrides the file, and the settings page shows where each value com ## Registering the family services -Each service that signs people in is an OpenID client. Register it from the shell on the server: +Each service that signs people in is an OpenID client. Register it from the shell on the server. The CLI +opens the database itself, so run it while `im serve` is stopped (or use the admin UI under Services): ```sh im --config /etc/im/im.toml client add --name "in" \ @@ -62,14 +63,14 @@ im --config /etc/im/im.toml client add --name "in" \ --post-logout-uri https://in.example.com/ \ --backchannel-uri https://in.example.com/auth/backchannel-logout \ --family-key in --public-url https://in.example.com \ - --scopes "openid profile email" + --scopes "openid profile email directory.read" im --config /etc/im/im.toml client add --name "iz" \ --redirect-uri https://iz.example.com/auth/callback \ --post-logout-uri https://iz.example.com/ \ --backchannel-uri https://iz.example.com/auth/backchannel-logout \ --family-key iz --public-url https://iz.example.com \ - --scopes "openid profile email" + --scopes "openid profile email directory.read files.service" ``` - 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 < ## Mail Mail is always queued in the outbox and sent through `[smtp]`. With `host` empty no attempt is made, and mail -waits in the outbox. Set `host`, `port`, `tls` (`implicit` for port 465, `starttls` for 587), `from`, +waits in the outbox. Set `host`, `port`, `tls` (`implicit` for port 465, `starttls` for 587, `none` only for a relay on +loopback), `from`, `from_name`, and, when the relay needs a login, `username` and `password_file` (first line only, not readable by group or others). diff --git a/crates/im-core/migrations/0005_outbox_jti.sql b/crates/im-core/migrations/0005_outbox_jti.sql new file mode 100644 index 0000000..eb240f3 --- /dev/null +++ b/crates/im-core/migrations/0005_outbox_jti.sql @@ -0,0 +1,8 @@ +-- 0005: the `jti` of each back-channel logout, stored with its outbox row when the row is queued. The +-- worker signs every attempt of the row with this same jti, so a receiver that recognises a repeat by +-- its jti (contracts.md 2.5) sees the retries as the one logout they are. A row queued before this +-- migration gets its own id as its jti, which is unique per row. + +ALTER TABLE backchannel_outbox ADD COLUMN jti TEXT NOT NULL DEFAULT ''; + +UPDATE backchannel_outbox SET jti = id WHERE jti = ''; diff --git a/crates/im-core/src/photo.rs b/crates/im-core/src/photo.rs index 9240612..0e8f554 100644 --- a/crates/im-core/src/photo.rs +++ b/crates/im-core/src/photo.rs @@ -17,6 +17,7 @@ use std::path::{Path, PathBuf}; use image::metadata::Orientation; use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; +use tokio::sync::{Semaphore, SemaphorePermit}; use crate::error::{Error, Result}; @@ -26,11 +27,20 @@ pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; /// Longest side of the stored picture, in pixels. The picture is a square of this size at most. pub const MAX_SIDE: u32 = 512; -/// Longest side an input may have, in pixels. Larger inputs are refused before any pixel is decoded. -const MAX_INPUT_SIDE: u32 = 8000; +/// Longest side an input may have, in pixels. Larger inputs are refused from the header, before any +/// pixel is decoded. At this side an RGBA picture is exactly [`MAX_DECODE_ALLOC`]. +const MAX_INPUT_SIDE: u32 = 4096; -/// Most memory the decoder may allocate for one input, in bytes (256 MiB). -const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024; +/// Most memory the decoder may allocate for one input, in bytes (64 MiB). A 4096 x 4096 RGBA picture +/// fills it exactly, so the side limit and the allocation limit agree. +const MAX_DECODE_ALLOC: u64 = 64 * 1024 * 1024; + +/// Decodes that may run at once. Each one holds up to [`MAX_DECODE_ALLOC`], so a burst of uploads queues +/// behind two permits instead of starting one blocking thread and one decode per request. +const DECODE_PERMITS: usize = 2; + +/// The gate of every async decode. +static DECODING: Semaphore = Semaphore::const_new(DECODE_PERMITS); /// MIME type of every stored photo. Lossless WebP keeps transparency and needs no quality choice. pub const STORED_MIME: &str = "image/webp"; @@ -64,7 +74,12 @@ pub fn normalize_photo(input: &[u8]) -> Result> { limits.max_alloc = Some(MAX_DECODE_ALLOC); let mut reader = ImageReader::with_format(Cursor::new(input), format); reader.limits(limits); + // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded. let mut decoder = reader.into_decoder().map_err(decode_error)?; + let (declared_width, declared_height) = decoder.dimensions(); + if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE { + return Err(refused()); + } // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping. let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?; @@ -89,6 +104,27 @@ pub fn normalize_photo(input: &[u8]) -> Result> { Ok(out.into_inner()) } +/// [`normalize_photo`] on the blocking thread pool, behind the decode gate. A task that panics is logged +/// and answered as a refused picture, so the upload gets the same answer as any broken file. +pub async fn normalize_photo_async(input: Vec) -> Result> { + let _permit = decode_gate().await?; + match tokio::task::spawn_blocking(move || normalize_photo(&input)).await { + Ok(result) => result, + Err(error) => { + tracing::error!(error = %error, "photo decode task failed"); + Err(refused()) + } + } +} + +/// Takes one of the [`DECODE_PERMITS`] slots. Held until the blocking work ends. +async fn decode_gate() -> Result> { + DECODING + .acquire() + .await + .map_err(|e| Error::Crypto(format!("decode gate closed: {e}"))) +} + /// Every decode failure is the uploader's problem: the bytes are not an image this build reads. fn decode_error(_: image::ImageError) -> Error { refused() diff --git a/crates/im-core/src/store/backchannel.rs b/crates/im-core/src/store/backchannel.rs index f53eaa7..49b0817 100644 --- a/crates/im-core/src/store/backchannel.rs +++ b/crates/im-core/src/store/backchannel.rs @@ -10,6 +10,7 @@ use turso::Connection; use crate::error::Result; use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::token::generate_token; /// Why a session, or every session of a person, ended. The stored text is the `reason` column. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -60,6 +61,8 @@ pub struct Delivery { pub attempts: i64, /// When the row was queued. The retry window counts from here. pub created_at: String, + /// The `jti` of the logout token, fixed when the row was queued. Every attempt carries it. + pub jti: String, } /// Every column of an outbox row, for inspection and tests. @@ -103,7 +106,8 @@ fn map_row(row: &turso::Row) -> Result { }) } -/// Inserts one pending row. Runs inside the caller's transaction. +/// Inserts one pending row. The row gets its `jti` here, once, so every attempt of the logout carries the +/// same one. Runs inside the caller's transaction. async fn insert_row( conn: &Connection, client_id: &str, @@ -114,8 +118,8 @@ async fn insert_row( ) -> Result<()> { conn.execute( "INSERT INTO backchannel_outbox (id, client_id, sid, sub, reason, state, attempts, \ - next_attempt_at, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", + next_attempt_at, created_at, jti) \ + VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6, ?7)", ( new_id(), client_id.to_string(), @@ -123,6 +127,7 @@ async fn insert_row( sub.to_string(), reason.as_str().to_string(), now.to_string(), + generate_token(), ), ) .await @@ -208,7 +213,7 @@ impl Store { let conn = self.read_conn().await; fetch_all( &conn, - "SELECT id, client_id, sid, sub, attempts, created_at FROM backchannel_outbox \ + "SELECT id, client_id, sid, sub, attempts, created_at, jti FROM backchannel_outbox \ WHERE state = 'pending' AND next_attempt_at <= ?1 \ ORDER BY next_attempt_at ASC, id ASC LIMIT ?2", (now.to_string(), limit), @@ -220,6 +225,7 @@ impl Store { sub: col_text(row, 3)?, attempts: col_int(row, 4)?, created_at: col_text(row, 5)?, + jti: col_text(row, 6)?, }) }, ) @@ -421,6 +427,31 @@ mod tests { ); } + #[tokio::test] + async fn every_attempt_of_a_row_carries_the_jti_it_was_queued_with() { + let (_dir, store, user_id, _session_id, _clients) = fixture().await; + store.disable_user(&user_id).await.expect("disable"); + let later = stamp_after(Duration::from_secs(3600)); + let first = store.due_deliveries(&later, 10).await.expect("due"); + assert_eq!(first.len(), 2); + assert_ne!(first[0].jti, first[1].jti, "each row has its own jti"); + for job in &first { + let retry = Attempt::Retry { + attempts: 1, + next: later.clone(), + error: "unreachable".into(), + }; + store + .record_attempt(&job.id, &retry, &crate::time::now_stamp()) + .await + .expect("retry"); + } + for job in store.due_deliveries(&later, 10).await.expect("due again") { + let queued = first.iter().find(|f| f.id == job.id).expect("same row"); + assert_eq!(job.jti, queued.jti); + } + } + #[tokio::test] async fn disabling_an_account_queues_one_sub_only_row_per_client_and_ends_its_sessions() { let (_dir, store, user_id, session_id, _clients) = fixture().await; diff --git a/crates/im-core/src/store/links.rs b/crates/im-core/src/store/links.rs index c5920d5..c938c46 100644 --- a/crates/im-core/src/store/links.rs +++ b/crates/im-core/src/store/links.rs @@ -420,6 +420,34 @@ mod tests { assert_eq!(user.password_hash, "new-hash"); } + #[tokio::test] + async fn a_reset_link_dies_when_the_password_changes() { + let (_dir, store, user_id) = setup().await; + store + .create_reset_link( + &user_id, + "reset-hash", + &stamp_after(Duration::from_secs(3600)), + ) + .await + .unwrap(); + store + .change_password(&user_id, "new-hash", "kept-session") + .await + .unwrap(); + assert!(store.live_reset_link("reset-hash").await.unwrap().is_none()); + // A link from before the change cannot set the password again. + assert_eq!( + store + .redeem_reset_link("reset-hash", "stale-hash") + .await + .unwrap(), + None + ); + let user = store.user_by_id(&user_id).await.unwrap().unwrap(); + assert_eq!(user.password_hash, "new-hash"); + } + #[tokio::test] async fn an_email_change_is_refused_when_the_address_was_taken_before_confirm() { let (_dir, store, user_id) = setup().await; diff --git a/crates/im-core/src/store/migrate.rs b/crates/im-core/src/store/migrate.rs index 153e420..bc847c8 100644 --- a/crates/im-core/src/store/migrate.rs +++ b/crates/im-core/src/store/migrate.rs @@ -24,6 +24,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 4, include_str!("../../migrations/0004_revoked_access_tokens.sql"), ), + (5, include_str!("../../migrations/0005_outbox_jti.sql")), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 7199d5d..d593e02 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -353,6 +353,10 @@ mod tests { }) .await .unwrap(); - assert_eq!(applied, vec![1, 2, 3, 4]); + let expected: Vec = migrate::MIGRATIONS + .iter() + .map(|&(version, _)| i64::from(version)) + .collect(); + assert_eq!(applied, expected); } } diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index 195a780..8c94c3e 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -18,6 +18,7 @@ use crate::error::{Error, Result}; use crate::model::User; use crate::store::backchannel::{self, EndReason}; use crate::store::directory::{ChangeKind, record_change}; +use crate::store::links::invalidate_links; use crate::store::sessions::{end_rows, live_session_ids}; use crate::store::{ Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, @@ -319,10 +320,12 @@ impl Store { result } - /// Stores a new argon2id hash and ends every live session of the person except `keep_session_id`, - /// with their back-channel logouts. One transaction: the old password never stays in force for a - /// session that the new one has ended, and nothing changes unless both happen. The caller has checked - /// the policy and the current password. Returns the ids of the sessions ended. + /// Stores a new argon2id hash, ends every live session of the person except `keep_session_id`, + /// with their back-channel logouts, and invalidates every pending account link (password reset and + /// email change), so a link issued for the old password cannot set or change anything. One + /// transaction: the old password never stays in force for a session that the new one has ended, and + /// nothing changes unless all of it happens. The caller has checked the policy and the current + /// password. Returns the ids of the sessions ended. pub async fn change_password( &self, id: &str, @@ -343,6 +346,7 @@ impl Store { if changed == 0 { return Err(Error::NotFound); } + invalidate_links(&tx, id, &now).await?; let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?; end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?; Ok(ids) diff --git a/crates/im-web/src/backchannel.rs b/crates/im-web/src/backchannel.rs index be2b76a..1913230 100644 --- a/crates/im-web/src/backchannel.rs +++ b/crates/im-web/src/backchannel.rs @@ -10,8 +10,10 @@ //! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up //! the others. Their outcomes are recorded in the order the rows were due. //! -//! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), a fresh `jti`, the logout -//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. +//! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), the row's `jti`, the logout +//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. Every attempt of a +//! row re-signs the token with fresh `iat` and `exp` but the same `jti`, so a repeat is recognisable as one +//! logout (contracts.md 2.5). use std::sync::Arc; use std::time::Duration; @@ -21,7 +23,6 @@ use im_core::model::Client; use im_core::store::Store; use im_core::store::backchannel::{Attempt, Delivery}; use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; -use im_core::token::generate_token; use serde_json::{Value, json}; use tokio::sync::watch; @@ -217,7 +218,7 @@ async fn logout_token( "aud": client.id, "iat": now, "exp": now + LOGOUT_TOKEN_TTL, - "jti": generate_token(), + "jti": job.jti, "events": { LOGOUT_EVENT: {} }, "sub": job.sub, }); diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index dadc205..8787497 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -151,6 +151,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { key: Arc::new(key), live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), + photo_uploads: Arc::new(Throttle::photo_uploads()), stream_slots: Arc::new(StreamSlots::default()), anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. @@ -265,6 +266,7 @@ mod tests { key: Arc::new(key), live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), + photo_uploads: Arc::new(Throttle::photo_uploads()), stream_slots: Arc::new(StreamSlots::default()), anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), stop: watch::channel(false).1, diff --git a/crates/im-web/src/i18n/account.rs b/crates/im-web/src/i18n/account.rs index df98268..ed9db8f 100644 --- a/crates/im-web/src/i18n/account.rs +++ b/crates/im-web/src/i18n/account.rs @@ -210,6 +210,8 @@ pub enum Txt { ErrPhotoTooLarge, /// Shown when the upload form was sent without a file. ErrPhotoMissing, + /// Shown when the account has used its photo uploads for the hour. + ErrPhotoRateLimited, /// The title of the preferences page, and the menu item that opens it. PreferencesTitle, /// The account home link text that opens the preferences page. @@ -499,6 +501,12 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.", (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", + (Txt::ErrPhotoRateLimited, Lang::En) => { + "Too many photos were uploaded. Try again in an hour." + } + (Txt::ErrPhotoRateLimited, Lang::Tr) => { + "Çok fazla fotoğraf yüklediniz. Bir saat sonra tekrar deneyin." + } (Txt::ErrPhotoMissing, Lang::En) => "Choose a picture first.", (Txt::ErrPhotoMissing, Lang::Tr) => "Önce bir resim seçin.", (Txt::PreferencesTitle, Lang::En) => "Preferences", diff --git a/crates/im-web/src/pages/profile.rs b/crates/im-web/src/pages/profile.rs index bfda032..eda5ab3 100644 --- a/crates/im-web/src/pages/profile.rs +++ b/crates/im-web/src/pages/profile.rs @@ -6,6 +6,8 @@ //! picture, so an upload from another site is refused before it is read at all. What is read is //! decoded and re-encoded by `im_core::photo` before anything is written. +use std::time::Instant; + use im_core::model::AuditAction; use im_core::names::parse_display_name; use im_core::photo::{self, MAX_UPLOAD_BYTES, STORED_MIME}; @@ -27,6 +29,7 @@ use crate::i18n::flows::{Flow, text as flow_text}; use crate::live::Topic; use crate::pages::login::CsrfForm; use crate::state::AppState; +use crate::throttle::{PHOTO_UPLOAD_LIMIT, photo_upload_key}; use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; /// 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 { let mut checked: Option = None; let mut picture: Option> = None; let mut too_large = false; + let mut limited = false; while let Some(mut part) = multipart.next_field().await? { let name = part.name().unwrap_or_default().to_owned(); @@ -134,8 +138,19 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result { "csrf" => token = part.text().await?, "photo" => { // Refused before any byte of the picture is read, unless the token is right. - if checked.is_none() { - checked = Some(require_csrf(cx, &token).await?); + let viewer = match checked.take() { + Some(viewer) => viewer, + None => require_csrf(cx, &token).await?, + }; + // Each upload is counted before its bytes are read, so a limited upload reads nothing. + let key = photo_upload_key(&viewer.user.id); + limited = state + .photo_uploads + .reserve(&key, PHOTO_UPLOAD_LIMIT, Instant::now()) + .is_err(); + checked = Some(viewer); + if limited { + break; } let mut bytes = Vec::new(); while let Some(chunk) = part.chunk().await? { @@ -161,7 +176,9 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result { None => require_csrf(cx, &token).await?, }; let lang = page_lang(cx, Some(&viewer)); - let problem = if too_large { + let problem = if limited { + Some(text(lang, Txt::ErrPhotoRateLimited)) + } else if too_large { Some(text(lang, Txt::ErrPhotoTooLarge)) } else { None @@ -171,11 +188,8 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result { return Ok(upload_problem(cx, lang, viewer, message)); }; - // Decoding is CPU work and runs off the request threads. - let stored = tokio::task::spawn_blocking(move || photo::normalize_photo(&bytes)) - .await - .map_err(|error| topcoat::Error::msg(error.to_string()))?; - let stored = match stored { + // Decoding is CPU work: it runs on the blocking pool, behind the decode gate. + let stored = match photo::normalize_photo_async(bytes).await { Ok(stored) => stored, Err(im_core::Error::Invalid(_)) => { return Ok(upload_problem( diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index a95857f..a7e9f09 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -27,6 +27,8 @@ pub struct AppState { pub live: Arc, /// Failed sign-in and second-factor counters. pub throttle: Arc, + /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`). + pub photo_uploads: Arc, /// The open directory streams of each machine client. pub stream_slots: Arc, /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`]. diff --git a/crates/im-web/src/throttle.rs b/crates/im-web/src/throttle.rs index 1955c69..1845c0f 100644 --- a/crates/im-web/src/throttle.rs +++ b/crates/im-web/src/throttle.rs @@ -43,6 +43,14 @@ pub const FORGOT_EMAIL_LIMIT: usize = 3; /// Reset-link requests allowed per client address inside [`WINDOW`]. pub const FORGOT_IP_LIMIT: usize = 20; +/// Profile photo uploads allowed per account inside [`PHOTO_UPLOAD_WINDOW`]. Every upload counts, whether +/// or not its picture is accepted, because each one costs a decode. +pub const PHOTO_UPLOAD_LIMIT: usize = 10; + +/// Length of the photo upload window: one hour. Kept on its own [`Throttle`] (see +/// [`Throttle::photo_uploads`]), because a throttle has one window for all its keys. +pub const PHOTO_UPLOAD_WINDOW: Duration = Duration::from_secs(60 * 60); + /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past /// this. const MAX_KEYS: usize = 100_000; @@ -80,6 +88,11 @@ impl Default for Throttle { } impl Throttle { + /// The counters of profile photo uploads: one hour window, the same key cap. + pub fn photo_uploads() -> Self { + Self::with_limits(PHOTO_UPLOAD_WINDOW, MAX_KEYS) + } + /// Counters with a custom window and key cap. Tests use short windows. pub fn with_limits(window: Duration, max_keys: usize) -> Self { Self { @@ -260,6 +273,11 @@ pub fn forgot_email_key(email: &str) -> String { format!("forgot:{}", address_part(email)) } +/// Throttle key for the photo uploads of one user, by user id. +pub fn photo_upload_key(user_id: &str) -> String { + format!("photo:{user_id}") +} + /// Throttle key for the second factor of one user, by user id. pub fn two_factor_key(user_id: &str) -> String { format!("2fa:{user_id}")