forge
Explore
Log in

Don't you dare go Hollow

Password change kills pending reset and email links, photo decode capped and rate-limited, back-channel retries keep their jti

Browse files at this commit

1fb6cc20db90a9a0662ebbfbf4c67c02daef413fAhmet Kaan GümüşParent: 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
Show full message
🔒 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
README.mdmodified+6 -4
@@ -54,7 +54,8 @@ saved there overrides the file, and the settings page shows where each value com
5454
5555 ## Registering the family services
5656
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):
5859
5960 ```sh
6061 im --config /etc/im/im.toml client add --name "in" \
@@ -62,14 +63,14 @@ im --config /etc/im/im.toml client add --name "in" \
6263 --post-logout-uri https://in.example.com/ \
6364 --backchannel-uri https://in.example.com/auth/backchannel-logout \
6465 --family-key in --public-url https://in.example.com \
65- --scopes "openid profile email"
66+ --scopes "openid profile email directory.read"
6667
6768 im --config /etc/im/im.toml client add --name "iz" \
6869 --redirect-uri https://iz.example.com/auth/callback \
6970 --post-logout-uri https://iz.example.com/ \
7071 --backchannel-uri https://iz.example.com/auth/backchannel-logout \
7172 --family-key iz --public-url https://iz.example.com \
72- --scopes "openid profile email"
73+ --scopes "openid profile email directory.read files.service"
7374 ```
7475
7576 - 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 <
8889 ## Mail
8990
9091 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`,
9294 `from_name`, and, when the relay needs a login, `username` and `password_file` (first line only, not readable
9395 by group or others).
9496
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};
1717
1818 use image::metadata::Orientation;
1919 use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits};
20+use tokio::sync::{Semaphore, SemaphorePermit};
2021
2122 use crate::error::{Error, Result};
2223
@@ -26,11 +27,20 @@ pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024;
2627 /// Longest side of the stored picture, in pixels. The picture is a square of this size at most.
2728 pub const MAX_SIDE: u32 = 512;
2829
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;
3133
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);
3444
3545 /// MIME type of every stored photo. Lossless WebP keeps transparency and needs no quality choice.
3646 pub const STORED_MIME: &str = "image/webp";
@@ -64,7 +74,12 @@ pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> {
6474 limits.max_alloc = Some(MAX_DECODE_ALLOC);
6575 let mut reader = ImageReader::with_format(Cursor::new(input), format);
6676 reader.limits(limits);
77+ // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded.
6778 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+ }
6883 // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping.
6984 let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
7085 let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?;
@@ -89,6 +104,27 @@ pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> {
89104 Ok(out.into_inner())
90105 }
91106
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+
92128 /// Every decode failure is the uploader's problem: the bytes are not an image this build reads.
93129 fn decode_error(_: image::ImageError) -> Error {
94130 refused()
crates/im-core/src/store/backchannel.rsmodified+35 -4
@@ -10,6 +10,7 @@ use turso::Connection;
1010
1111 use crate::error::Result;
1212 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;
1314
1415 /// Why a session, or every session of a person, ended. The stored text is the `reason` column.
1516 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -60,6 +61,8 @@ pub struct Delivery {
6061 pub attempts: i64,
6162 /// When the row was queued. The retry window counts from here.
6263 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,
6366 }
6467
6568 /// Every column of an outbox row, for inspection and tests.
@@ -103,7 +106,8 @@ fn map_row(row: &turso::Row) -> Result<OutboxRow> {
103106 })
104107 }
105108
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.
107111 async fn insert_row(
108112 conn: &Connection,
109113 client_id: &str,
@@ -114,8 +118,8 @@ async fn insert_row(
114118 ) -> Result<()> {
115119 conn.execute(
116120 "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)",
119123 (
120124 new_id(),
121125 client_id.to_string(),
@@ -123,6 +127,7 @@ async fn insert_row(
123127 sub.to_string(),
124128 reason.as_str().to_string(),
125129 now.to_string(),
130+ generate_token(),
126131 ),
127132 )
128133 .await
@@ -208,7 +213,7 @@ impl Store {
208213 let conn = self.read_conn().await;
209214 fetch_all(
210215 &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 \
212217 WHERE state = 'pending' AND next_attempt_at <= ?1 \
213218 ORDER BY next_attempt_at ASC, id ASC LIMIT ?2",
214219 (now.to_string(), limit),
@@ -220,6 +225,7 @@ impl Store {
220225 sub: col_text(row, 3)?,
221226 attempts: col_int(row, 4)?,
222227 created_at: col_text(row, 5)?,
228+ jti: col_text(row, 6)?,
223229 })
224230 },
225231 )
@@ -421,6 +427,31 @@ mod tests {
421427 );
422428 }
423429
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+
424455 #[tokio::test]
425456 async fn disabling_an_account_queues_one_sub_only_row_per_client_and_ends_its_sessions() {
426457 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 {
420420 assert_eq!(user.password_hash, "new-hash");
421421 }
422422
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+
423451 #[tokio::test]
424452 async fn an_email_change_is_refused_when_the_address_was_taken_before_confirm() {
425453 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)] = &[
2424 4,
2525 include_str!("../../migrations/0004_revoked_access_tokens.sql"),
2626 ),
27+ (5, include_str!("../../migrations/0005_outbox_jti.sql")),
2728 ];
2829
2930 fn migration_err(e: turso::Error) -> Error {
crates/im-core/src/store/mod.rsmodified+5 -1
@@ -353,6 +353,10 @@ mod tests {
353353 })
354354 .await
355355 .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);
357361 }
358362 }
crates/im-core/src/store/users.rsmodified+8 -4
@@ -18,6 +18,7 @@ use crate::error::{Error, Result};
1818 use crate::model::User;
1919 use crate::store::backchannel::{self, EndReason};
2020 use crate::store::directory::{ChangeKind, record_change};
21+use crate::store::links::invalidate_links;
2122 use crate::store::sessions::{end_rows, live_session_ids};
2223 use crate::store::{
2324 Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id,
@@ -319,10 +320,12 @@ impl Store {
319320 result
320321 }
321322
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.
326329 pub async fn change_password(
327330 &self,
328331 id: &str,
@@ -343,6 +346,7 @@ impl Store {
343346 if changed == 0 {
344347 return Err(Error::NotFound);
345348 }
349+ invalidate_links(&tx, id, &now).await?;
346350 let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?;
347351 end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?;
348352 Ok(ids)
crates/im-web/src/backchannel.rsmodified+5 -4
@@ -10,8 +10,10 @@
1010 //! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up
1111 //! the others. Their outcomes are recorded in the order the rows were due.
1212 //!
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).
1517
1618 use std::sync::Arc;
1719 use std::time::Duration;
@@ -21,7 +23,6 @@ use im_core::model::Client;
2123 use im_core::store::Store;
2224 use im_core::store::backchannel::{Attempt, Delivery};
2325 use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now};
24-use im_core::token::generate_token;
2526 use serde_json::{Value, json};
2627 use tokio::sync::watch;
2728
@@ -217,7 +218,7 @@ async fn logout_token(
217218 "aud": client.id,
218219 "iat": now,
219220 "exp": now + LOGOUT_TOKEN_TTL,
220- "jti": generate_token(),
221+ "jti": job.jti,
221222 "events": { LOGOUT_EVENT: {} },
222223 "sub": job.sub,
223224 });
crates/im-web/src/boot.rsmodified+2 -0
@@ -151,6 +151,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> {
151151 key: Arc::new(key),
152152 live: Arc::new(LiveHub::default()),
153153 throttle: Arc::new(Throttle::default()),
154+ photo_uploads: Arc::new(Throttle::photo_uploads()),
154155 stream_slots: Arc::new(StreamSlots::default()),
155156 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
156157 // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves.
@@ -265,6 +266,7 @@ mod tests {
265266 key: Arc::new(key),
266267 live: Arc::new(LiveHub::default()),
267268 throttle: Arc::new(Throttle::default()),
269+ photo_uploads: Arc::new(Throttle::photo_uploads()),
268270 stream_slots: Arc::new(StreamSlots::default()),
269271 anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)),
270272 stop: watch::channel(false).1,
crates/im-web/src/i18n/account.rsmodified+8 -0
@@ -210,6 +210,8 @@ pub enum Txt {
210210 ErrPhotoTooLarge,
211211 /// Shown when the upload form was sent without a file.
212212 ErrPhotoMissing,
213+ /// Shown when the account has used its photo uploads for the hour.
214+ ErrPhotoRateLimited,
213215 /// The title of the preferences page, and the menu item that opens it.
214216 PreferencesTitle,
215217 /// The account home link text that opens the preferences page.
@@ -499,6 +501,12 @@ pub fn text(lang: Lang, key: Txt) -> &'static str {
499501 (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.",
500502 (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.",
501503 (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+ }
502510 (Txt::ErrPhotoMissing, Lang::En) => "Choose a picture first.",
503511 (Txt::ErrPhotoMissing, Lang::Tr) => "Önce bir resim seçin.",
504512 (Txt::PreferencesTitle, Lang::En) => "Preferences",
crates/im-web/src/pages/profile.rsmodified+22 -8
@@ -6,6 +6,8 @@
66 //! picture, so an upload from another site is refused before it is read at all. What is read is
77 //! decoded and re-encoded by `im_core::photo` before anything is written.
88
9+use std::time::Instant;
10+
911 use im_core::model::AuditAction;
1012 use im_core::names::parse_display_name;
1113 use im_core::photo::{self, MAX_UPLOAD_BYTES, STORED_MIME};
@@ -27,6 +29,7 @@ use crate::i18n::flows::{Flow, text as flow_text};
2729 use crate::live::Topic;
2830 use crate::pages::login::CsrfForm;
2931 use crate::state::AppState;
32+use crate::throttle::{PHOTO_UPLOAD_LIMIT, photo_upload_key};
3033 use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
3134
3235 /// 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> {
127130 let mut checked: Option<Viewer> = None;
128131 let mut picture: Option<Vec<u8>> = None;
129132 let mut too_large = false;
133+ let mut limited = false;
130134
131135 while let Some(mut part) = multipart.next_field().await? {
132136 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> {
134138 "csrf" => token = part.text().await?,
135139 "photo" => {
136140 // 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;
139154 }
140155 let mut bytes = Vec::new();
141156 while let Some(chunk) = part.chunk().await? {
@@ -161,7 +176,9 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> {
161176 None => require_csrf(cx, &token).await?,
162177 };
163178 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 {
165182 Some(text(lang, Txt::ErrPhotoTooLarge))
166183 } else {
167184 None
@@ -171,11 +188,8 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> {
171188 return Ok(upload_problem(cx, lang, viewer, message));
172189 };
173190
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 {
179193 Ok(stored) => stored,
180194 Err(im_core::Error::Invalid(_)) => {
181195 return Ok(upload_problem(
crates/im-web/src/state.rsmodified+2 -0
@@ -27,6 +27,8 @@ pub struct AppState {
2727 pub live: Arc<LiveHub>,
2828 /// Failed sign-in and second-factor counters.
2929 pub throttle: Arc<Throttle>,
30+ /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`).
31+ pub photo_uploads: Arc<Throttle>,
3032 /// The open directory streams of each machine client.
3133 pub stream_slots: Arc<StreamSlots>,
3234 /// 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;
4343 /// Reset-link requests allowed per client address inside [`WINDOW`].
4444 pub const FORGOT_IP_LIMIT: usize = 20;
4545
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+
4654 /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past
4755 /// this.
4856 const MAX_KEYS: usize = 100_000;
@@ -80,6 +88,11 @@ impl Default for Throttle {
8088 }
8189
8290 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+
8396 /// Counters with a custom window and key cap. Tests use short windows.
8497 pub fn with_limits(window: Duration, max_keys: usize) -> Self {
8598 Self {
@@ -260,6 +273,11 @@ pub fn forgot_email_key(email: &str) -> String {
260273 format!("forgot:{}", address_part(email))
261274 }
262275
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+
263281 /// Throttle key for the second factor of one user, by user id.
264282 pub fn two_factor_key(user_id: &str) -> String {
265283 format!("2fa:{user_id}")