forge
Explore
Log in

Don't you dare go Hollow

Audit findings: share password throttle reserves attempts, no-cache member bytes, folder depth, quota headroom before staging, object staging budget, open-upload cap, bidi names, thumbnail size precheck, sign-in respects newer directory data

Browse files at this commit

6e8ecae557a7f8503dd899ca974e6c8bf88b7d90Ahmet Kaan GümüşParent: 0f1ee24
  • fix
    • audit findings: share password throttle reserves attempts, no-cache member bytes, folder depth, quota headroom before staging, object staging budget, open-upload cap, bidi names, thumbnail size precheck, sign-in respects newer directory data
Show full message
🔒 fix: audit findings: share password throttle reserves attempts, no-cache member bytes, folder depth, quota headroom before staging, object staging budget, open-upload cap, bidi names, thumbnail size precheck, sign-in respects newer directory data
crates/in-core/src/names.rsmodified+33 -3
@@ -18,6 +18,24 @@ pub const MAX_NAME_BYTES: usize = 255;
18 /// Name given to an item whose input has no usable characters left.18 /// Name given to an item whose input has no usable characters left.
19 pub const UNTITLED: &str = "Untitled";19 pub const UNTITLED: &str = "Untitled";
20 20
21+/// Whether `c` is a Unicode format character (category Cf) that changes how a name is shown, or a line or
22+/// paragraph separator. Bidi overrides such as U+202E make `invoice\u{202E}fdp.exe` read as `invoice exe.pdf`,
23+/// so these are refused in typed names and stripped from upload names.
24+fn is_invisible_or_bidi(c: char) -> bool {
25+ matches!(
26+ c,
27+ // U+200D (zero-width joiner) is allowed: emoji sequences need it and it cannot reorder text.
28+ '\u{200B}'..='\u{200C}'
29+ | '\u{200E}'..='\u{200F}'
30+ | '\u{202A}'..='\u{202E}'
31+ | '\u{2060}'..='\u{2064}'
32+ | '\u{2066}'..='\u{2069}'
33+ | '\u{FEFF}'
34+ | '\u{2028}'
35+ | '\u{2029}'
36+ )
37+}
38+
21 /// Checks a name typed by a person and returns it trimmed and in NFC. Refusals are39 /// Checks a name typed by a person and returns it trimmed and in NFC. Refusals are
22 /// `Invalid` with a fixed reason word: `name_empty`, `name_reserved` (`.` or `..`), `name_too_long`40 /// `Invalid` with a fixed reason word: `name_empty`, `name_reserved` (`.` or `..`), `name_too_long`
23 /// (over [`MAX_NAME_BYTES`]) or `name_bad_char` (a `/`, a `\`, a NUL or any other control character).41 /// (over [`MAX_NAME_BYTES`]) or `name_bad_char` (a `/`, a `\`, a NUL or any other control character).
@@ -34,7 +52,7 @@ pub fn validate_name(input: &str) -> Result<String> {
34 }52 }
35 if name53 if name
36 .chars()54 .chars()
37- .any(|c| matches!(c, '/' | '\\') || c.is_control())55+ .any(|c| matches!(c, '/' | '\\') || c.is_control() || is_invisible_or_bidi(c))
38 {56 {
39 return Err(Error::Invalid("name_bad_char".into()));57 return Err(Error::Invalid("name_bad_char".into()));
40 }58 }
@@ -60,7 +78,7 @@ pub fn upload_name(client_name: &str) -> String {
60 }78 }
61 79
62 /// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt`80 /// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt`
63-/// becomes `c.txt`. Control characters are dropped, surrounding spaces are trimmed, and input with81+/// becomes `c.txt`. Control and format characters are dropped, surrounding spaces are trimmed, and input with
64 /// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`].82 /// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`].
65 pub fn display_name(input: &str) -> String {83 pub fn display_name(input: &str) -> String {
66 // Path separators come from both Unix and Windows clients, so split on both.84 // Path separators come from both Unix and Windows clients, so split on both.
@@ -68,7 +86,10 @@ pub fn display_name(input: &str) -> String {
68 .rsplit(['/', '\\'])86 .rsplit(['/', '\\'])
69 .find(|part| !part.trim().is_empty())87 .find(|part| !part.trim().is_empty())
70 .unwrap_or("");88 .unwrap_or("");
71- let cleaned: String = leaf.chars().filter(|c| !c.is_control()).collect();89+ let cleaned: String = leaf
90+ .chars()
91+ .filter(|c| !c.is_control() && !is_invisible_or_bidi(*c))
92+ .collect();
72 let trimmed = cleaned.trim();93 let trimmed = cleaned.trim();
73 if trimmed.is_empty() || trimmed == "." || trimmed == ".." {94 if trimmed.is_empty() || trimmed == "." || trimmed == ".." {
74 return UNTITLED.to_string();95 return UNTITLED.to_string();
@@ -161,6 +182,15 @@ mod tests {
161 assert!(validate_name(&cut).is_ok());182 assert!(validate_name(&cut).is_ok());
162 }183 }
163 184
185+ /// A right-to-left override hides the real extension. A typed name is refused, an upload name is stripped.
186+ #[test]
187+ fn bidi_override_cannot_disguise_an_extension() {
188+ let disguised = "invoice\u{202E}fdp.exe";
189+ assert!(matches!(validate_name(disguised), Err(Error::Invalid(m)) if m == "name_bad_char"));
190+ assert_eq!(upload_name(disguised), "invoicefdp.exe");
191+ assert_eq!(display_name("\u{FEFF}zero\u{200B}width"), "zerowidth");
192+ }
193+
164 #[test]194 #[test]
165 fn display_name_cuts_long_names_by_characters() {195 fn display_name_cuts_long_names_by_characters() {
166 let long = "é".repeat(300);196 let long = "é".repeat(300);
crates/in-core/src/store/folders.rsmodified+24 -4
@@ -112,6 +112,21 @@ pub(crate) async fn has_trashed_chain(conn: &Connection, folder: Option<&str>) -
112 Err(Error::Database("folder tree is too deep".into()))112 Err(Error::Database("folder tree is too deep".into()))
113 }113 }
114 114
115+/// How many folders lie on the chain from `folder` up to the top level, `folder` included. A chain that
116+/// is longer than [`MAX_DEPTH`] is an error, so a walk never passes its limit silently.
117+async fn chain_depth(conn: &Connection, folder: &str) -> Result<usize> {
118+ let mut depth = 0;
119+ let mut cur = Some(folder.to_string());
120+ while let Some(id) = cur {
121+ depth += 1;
122+ if depth > MAX_DEPTH {
123+ return Err(Error::Database("folder tree is too deep".into()));
124+ }
125+ cur = folder_by_id(conn, &id).await?.and_then(|f| f.parent_id);
126+ }
127+ Ok(depth)
128+}
129+
115 /// Inserts a folder with the first free postfix. The partial unique index decides each attempt.130 /// Inserts a folder with the first free postfix. The partial unique index decides each attempt.
116 async fn insert_folder_postfixed(131 async fn insert_folder_postfixed(
117 conn: &Connection,132 conn: &Connection,
@@ -181,6 +196,10 @@ impl Store {
181 let conn = self.inner.conn.lock().await;196 let conn = self.inner.conn.lock().await;
182 if let Some(p) = parent {197 if let Some(p) = parent {
183 live_folder(&conn, owner, p).await?;198 live_folder(&conn, owner, p).await?;
199+ // The new folder sits one level below its parent, so the parent's chain must leave room.
200+ if chain_depth(&conn, p).await? >= MAX_DEPTH {
201+ return Err(Error::Invalid("folder_too_deep".into()));
202+ }
184 }203 }
185 insert_folder_postfixed(&conn, owner, parent, &base).await204 insert_folder_postfixed(&conn, owner, parent, &base).await
186 }205 }
@@ -211,11 +230,12 @@ impl Store {
211 live_folder(&tx, owner, id).await?;230 live_folder(&tx, owner, id).await?;
212 if let Some(p) = parent {231 if let Some(p) = parent {
213 live_folder(&tx, owner, p).await?;232 live_folder(&tx, owner, p).await?;
233+ // The moved folder sits one level below `p`, so `p`'s chain must leave room for it.
234+ if chain_depth(&tx, p).await? >= MAX_DEPTH {
235+ return Err(Error::Invalid("folder_too_deep".into()));
236+ }
214 let mut cur = Some(p.to_string());237 let mut cur = Some(p.to_string());
215- for _ in 0..MAX_DEPTH {238+ while let Some(c) = cur {
216- let Some(c) = cur else {
217- break;
218- };
219 if c == id {239 if c == id {
220 return Err(Error::Forbidden("cycle".into()));240 return Err(Error::Forbidden("cycle".into()));
221 }241 }
crates/in-core/src/store/members.rsmodified+22 -12
@@ -69,7 +69,8 @@ pub struct MemberFields {
69 pub zoneinfo: String,69 pub zoneinfo: String,
70 /// Photo version.70 /// Photo version.
71 pub picture_version: i64,71 pub picture_version: i64,
72- /// Directory timestamp of the change. Sign-in claims carry none, so the sign-in path ignores it.72+ /// Directory timestamp of the change, in the stamp format of `time.rs`. Sign-in passes the ID token's
73+ /// `iat`; an empty value means "now".
73 pub im_updated_at: String,74 pub im_updated_at: String,
74 }75 }
75 76
@@ -117,14 +118,21 @@ async fn fetch_member(conn: &turso::Connection, sub: &str) -> Result<Option<Memb
117 118
118 impl Store {119 impl Store {
119 /// Records a sign-in. Creates the member with `default_quota` when new; otherwise refreshes the120 /// Records a sign-in. Creates the member with `default_quota` when new; otherwise refreshes the
120- /// claim fields. Quota, theme and the disabled flag are left alone. A sign-in also stamps121+ /// claim fields, but only when the claims are not older than the stored directory change
121- /// `last_sign_in_at`.122+ /// (`im_updated_at`). A stale sign-in cannot roll back a newer directory edit. Quota, theme and the
123+ /// disabled flag are left alone. A sign-in always stamps `last_sign_in_at`.
122 pub async fn upsert_member_from_claims(124 pub async fn upsert_member_from_claims(
123 &self,125 &self,
124 fields: &MemberFields,126 fields: &MemberFields,
125 default_quota: i64,127 default_quota: i64,
126 ) -> Result<Member> {128 ) -> Result<Member> {
127 let now = now_stamp();129 let now = now_stamp();
130+ // The claims' own time: the caller's stamp, or now when it gave none.
131+ let claims_at = if fields.im_updated_at.is_empty() {
132+ now.clone()
133+ } else {
134+ fields.im_updated_at.clone()
135+ };
128 let conn = self.inner.conn.lock().await;136 let conn = self.inner.conn.lock().await;
129 conn.execute(137 conn.execute(
130 "INSERT INTO members (sub, email, name, is_admin, locale, zoneinfo, picture_version, \138 "INSERT INTO members (sub, email, name, is_admin, locale, zoneinfo, picture_version, \
@@ -132,7 +140,8 @@ impl Store {
132 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10) \140 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10) \
133 ON CONFLICT (sub) DO UPDATE SET email = excluded.email, name = excluded.name, \141 ON CONFLICT (sub) DO UPDATE SET email = excluded.email, name = excluded.name, \
134 is_admin = excluded.is_admin, locale = excluded.locale, zoneinfo = excluded.zoneinfo, \142 is_admin = excluded.is_admin, locale = excluded.locale, zoneinfo = excluded.zoneinfo, \
135- picture_version = excluded.picture_version, last_sign_in_at = excluded.last_sign_in_at",143+ picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at \
144+ WHERE excluded.im_updated_at >= members.im_updated_at",
136 (145 (
137 fields.sub.clone(),146 fields.sub.clone(),
138 fields.email.clone(),147 fields.email.clone(),
@@ -141,19 +150,20 @@ impl Store {
141 fields.locale.clone(),150 fields.locale.clone(),
142 fields.zoneinfo.clone(),151 fields.zoneinfo.clone(),
143 fields.picture_version,152 fields.picture_version,
144- // The insert needs a value; an existing row keeps its own im_updated_at because the153+ claims_at,
145- // conflict clause does not touch that column.154+ now.clone(),
146- if fields.im_updated_at.is_empty() {
147- now.clone()
148- } else {
149- fields.im_updated_at.clone()
150- },
151- now,
152 default_quota,155 default_quota,
153 ),156 ),
154 )157 )
155 .await158 .await
156 .map_err(db_err)?;159 .map_err(db_err)?;
160+ // Kept apart from the claim update: that one is skipped for a stale sign-in, this one never is.
161+ conn.execute(
162+ "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1",
163+ (fields.sub.clone(), now),
164+ )
165+ .await
166+ .map_err(db_err)?;
157 fetch_member(&conn, &fields.sub)167 fetch_member(&conn, &fields.sub)
158 .await?168 .await?
159 .ok_or(Error::NotFound)169 .ok_or(Error::NotFound)
crates/in-core/src/store/uploads.rsmodified+23 -1
@@ -16,6 +16,10 @@ use crate::store::folders::live_folder;
16 use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish};16 use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish};
17 use crate::time::now_stamp;17 use crate::time::now_stamp;
18 18
19+/// Most uploads one person may have open (active and not expired) at once. A create past it is
20+/// `Conflict("too_many_uploads")`, so an account cannot hold thousands of empty uploads at no cost.
21+pub const MAX_OPEN_UPLOADS: i64 = 64;
22+
19 /// Column list for [`map_upload`]. Keep the two in step.23 /// Column list for [`map_upload`]. Keep the two in step.
20 pub const UPLOAD_COLS: &str =24 pub const UPLOAD_COLS: &str =
21 "id, owner, folder_id, name, size, chunk_size, state, file_id, created_at, expires_at";25 "id, owner, folder_id, name, size, chunk_size, state, file_id, created_at, expires_at";
@@ -113,6 +117,12 @@ async fn declared_claims(conn: &Connection, owner: &str, now: &str, except: &str
113 }117 }
114 118
115 impl Store {119 impl Store {
120+ /// The bytes the owner's open uploads have declared. A new upload or a direct upload must leave them room.
121+ pub async fn declared_claims_of(&self, owner: &str) -> Result<i64> {
122+ let conn = self.read_conn().await;
123+ declared_claims(&conn, owner, &now_stamp(), "").await
124+ }
125+
116 /// An upload of `owner` by id, or `None` when there is no such upload for that person.126 /// An upload of `owner` by id, or `None` when there is no such upload for that person.
117 pub async fn upload(&self, owner: &str, id: &str) -> Result<Option<Upload>> {127 pub async fn upload(&self, owner: &str, id: &str) -> Result<Option<Upload>> {
118 let conn = self.read_conn().await;128 let conn = self.read_conn().await;
@@ -121,7 +131,8 @@ impl Store {
121 131
122 /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size132 /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size
123 /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared133 /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared
124- /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`.134+ /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`,
135+ /// and one for too many open uploads ([`MAX_OPEN_UPLOADS`]) is `Conflict("too_many_uploads")`.
125 pub async fn create_upload(&self, new: NewUpload, max_size: i64) -> Result<Upload> {136 pub async fn create_upload(&self, new: NewUpload, max_size: i64) -> Result<Upload> {
126 if new.size < 0 || new.size > max_size {137 if new.size < 0 || new.size > max_size {
127 return Err(Error::Invalid("too_large".into()));138 return Err(Error::Invalid("too_large".into()));
@@ -141,6 +152,17 @@ impl Store {
141 )152 )
142 .await?153 .await?
143 .ok_or(Error::NotFound)?;154 .ok_or(Error::NotFound)?;
155+ let open: i64 = fetch_opt(
156+ &tx,
157+ "SELECT COUNT(*) FROM uploads WHERE owner = ?1 AND state = 'active' AND expires_at > ?2",
158+ (new.owner.clone(), now.clone()),
159+ |row| col_int(row, 0),
160+ )
161+ .await?
162+ .unwrap_or(0);
163+ if open >= MAX_OPEN_UPLOADS {
164+ return Err(Error::Conflict("too_many_uploads".into()));
165+ }
144 let claims = declared_claims(&tx, &new.owner, &now, "").await?;166 let claims = declared_claims(&tx, &new.owner, &now, "").await?;
145 if !quota::fits(new.size, quota::headroom(quota, used, claims)) {167 if !quota::fits(new.size, quota::headroom(quota, used, claims)) {
146 return Err(Error::Conflict("quota_exceeded".into()));168 return Err(Error::Conflict("quota_exceeded".into()));
crates/in-core/src/thumbs.rsmodified+10 -0
@@ -43,6 +43,16 @@ pub fn make_thumbnail(source: &[u8]) -> Result<Vec<u8>> {
43 if !reader.format().is_some_and(|f| FORMATS.contains(&f)) {43 if !reader.format().is_some_and(|f| FORMATS.contains(&f)) {
44 return Err(bad());44 return Err(bad());
45 }45 }
46+ // The header alone gives the size of the decoded picture. A picture that would need more than the
47+ // allocation limit is refused here, before the decoder sizes any buffer, whatever its format.
48+ let (width, height) = ImageReader::new(Cursor::new(source))
49+ .with_guessed_format()
50+ .map_err(|_| bad())?
51+ .into_dimensions()
52+ .map_err(|_| bad())?;
53+ if u64::from(width) * u64::from(height) * 4 > MAX_ALLOC_BYTES {
54+ return Err(bad());
55+ }
46 let mut limits = Limits::default();56 let mut limits = Limits::default();
47 limits.max_image_width = Some(MAX_DIMENSION);57 limits.max_image_width = Some(MAX_DIMENSION);
48 limits.max_image_height = Some(MAX_DIMENSION);58 limits.max_image_height = Some(MAX_DIMENSION);
crates/in-core/src/time.rsmodified+7 -0
@@ -26,6 +26,13 @@ pub fn stamp_after(after: Duration) -> String {
26 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))26 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))
27 }27 }
28 28
29+/// The stamp of a Unix time in whole seconds (an ID token's `iat`), or `None` when it is out of range.
30+pub fn stamp_from_unix(secs: i64) -> Option<String> {
31+ OffsetDateTime::from_unix_timestamp(secs)
32+ .ok()
33+ .map(format_stamp)
34+}
35+
29 /// The stamp for `now - before`. Saturates at the smallest representable time instead of panicking.36 /// The stamp for `now - before`. Saturates at the smallest representable time instead of panicking.
30 pub fn stamp_before(before: Duration) -> String {37 pub fn stamp_before(before: Duration) -> String {
31 let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX);38 let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX);
crates/in-web/src/api/objects.rsmodified+21 -3
@@ -11,6 +11,8 @@
11 //! `If-None-Match: *` refuses an existing id with `409`.11 //! `If-None-Match: *` refuses an existing id with `409`.
12 //! - `GET` and `HEAD` send the bytes through `serve_bytes`, always as an attachment, with `Range` support.12 //! - `GET` and `HEAD` send the bytes through `serve_bytes`, always as an attachment, with `Range` support.
13 //! The cache policy is `private, no-cache`, because a replace changes what the id names.13 //! The cache policy is `private, no-cache`, because a replace changes what the id names.
14+//! - A write reserves the bytes it may stage for its service before it reads the body. A write that would
15+//! take the service past its headroom, together with the writes in flight, is `429 rate_limited`.
14 //! - `DELETE` removes the object. It answers `204` also when the object was already absent.16 //! - `DELETE` removes the object. It answers `204` also when the object was already absent.
15 //! - `GET /api/v1/usage` answers the quota, the bytes used and the number of objects.17 //! - `GET /api/v1/usage` answers the quota, the bytes used and the number of objects.
16 //!18 //!
@@ -18,8 +20,8 @@
18 //! write is storing right now, are never removed. A removal that is refused is left to the sweeper.20 //! write is storing right now, are never removed. A removal that is refused is left to the sweeper.
19 21
20 use futures_util::StreamExt;22 use futures_util::StreamExt;
21-use http::StatusCode;23+use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH, RETRY_AFTER};
22-use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH};24+use http::{HeaderValue, StatusCode};
23 use in_core::error::Error as CoreError;25 use in_core::error::Error as CoreError;
24 use in_core::names;26 use in_core::names;
25 use in_core::staging::StagedFile;27 use in_core::staging::StagedFile;
@@ -236,8 +238,24 @@ async fn put_object(cx: &Cx, body: Body) -> Result<Response> {
236 if request.declared.is_some_and(|length| length > headroom) {238 if request.declared.is_some_and(|length| length > headroom) {
237 return Ok(quota_refusal.answer());239 return Ok(quota_refusal.answer());
238 }240 }
241+ // The bytes this write may stage: its declared length, or the whole headroom when none was declared.
242+ // They are reserved for the service before a byte is read, so writes in flight together cannot stage
243+ // more than the headroom. The reservation is released when this handler returns, on every path.
244+ let reserve = request.declared.unwrap_or(headroom);
245+ let Some(_staging) = state.staging.reserve(&service, reserve, headroom) else {
246+ let mut response = Refusal {
247+ status: StatusCode::TOO_MANY_REQUESTS,
248+ error: "rate_limited",
249+ message: "other writes to this service are staging; retry shortly",
250+ }
251+ .answer();
252+ response
253+ .headers_mut()
254+ .insert(RETRY_AFTER, HeaderValue::from_static("1"));
255+ return Ok(response);
256+ };
239 257
240- let mut staged = StagedFile::create(&state.config.data_dir, headroom).await?;258+ let mut staged = StagedFile::create(&state.config.data_dir, reserve).await?;
241 let mut frames = body.into_data_stream();259 let mut frames = body.into_data_stream();
242 while let Some(frame) = frames.next().await {260 while let Some(frame) = frames.next().await {
243 let written = match frame {261 let written = match frame {
crates/in-web/src/api/upload.rsmodified+5 -1
@@ -5,7 +5,8 @@
5 //! The routes:5 //! The routes:
6 //! - `POST /api/uploads` `{folder_id?, name, size}` starts an upload → `201 {id, chunk_size}`. The size is6 //! - `POST /api/uploads` `{folder_id?, name, size}` starts an upload → `201 {id, chunk_size}`. The size is
7 //! reserved against the quota in the same transaction that creates the row, so two creates cannot7 //! reserved against the quota in the same transaction that creates the row, so two creates cannot
8-//! together promise more than the headroom.8+//! together promise more than the headroom. A person may hold 64 open uploads; the next one is `429`
9+//! `too_many_uploads`.
9 //! - `GET /api/uploads/{id}` → `{id, state, size, chunk_size, received}`, where `received` lists the chunk10 //! - `GET /api/uploads/{id}` → `{id, state, size, chunk_size, received}`, where `received` lists the chunk
10 //! indexes on disk. A client that lost its connection asks this, then sends only what is missing.11 //! indexes on disk. A client that lost its connection asks this, then sends only what is missing.
11 //! - `PUT /api/uploads/{id}/{index}` sends one chunk as the raw body. The index must be a chunk of the12 //! - `PUT /api/uploads/{id}/{index}` sends one chunk as the raw body. The index must be a chunk of the
@@ -213,6 +214,9 @@ async fn create_upload(cx: &Cx, body: Body) -> Result<Response> {
213 Err(CoreError::Conflict(word)) if word == "quota_exceeded" => {214 Err(CoreError::Conflict(word)) if word == "quota_exceeded" => {
214 return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer());215 return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer());
215 }216 }
217+ Err(CoreError::Conflict(word)) if word == "too_many_uploads" => {
218+ return Ok(refuse(StatusCode::TOO_MANY_REQUESTS, "too_many_uploads").answer());
219+ }
216 Err(error) => return Err(error.into()),220 Err(error) => return Err(error.into()),
217 };221 };
218 // The directory is made after the row commits. A crash in between leaves a row with no directory, which222 // The directory is made after the row commits. A crash in between leaves a row with no directory, which
crates/in-web/src/boot.rsmodified+3 -1
@@ -32,7 +32,7 @@ use crate::oidc::OidcClient;
32 use crate::pages::files;32 use crate::pages::files;
33 use crate::pages::not_found::NotFoundLayer;33 use crate::pages::not_found::NotFoundLayer;
34 use crate::security::{self, SecurityHeaders};34 use crate::security::{self, SecurityHeaders};
35-use crate::state::AppState;35+use crate::state::{AppState, ObjectStaging};
36 use crate::sweeper;36 use crate::sweeper;
37 use crate::throttle::ShareThrottles;37 use crate::throttle::ShareThrottles;
38 use crate::thumbs_worker;38 use crate::thumbs_worker;
@@ -182,6 +182,7 @@ async fn open_state(config: Config) -> Result<AppState> {
182 oidc,182 oidc,
183 throttles: Arc::new(ShareThrottles::default()),183 throttles: Arc::new(ShareThrottles::default()),
184 family: Arc::new(FamilyCache::default()),184 family: Arc::new(FamilyCache::default()),
185+ staging: Arc::new(ObjectStaging::default()),
185 })186 })
186 }187 }
187 188
@@ -314,6 +315,7 @@ mod tests {
314 oidc: None,315 oidc: None,
315 throttles: Arc::new(ShareThrottles::default()),316 throttles: Arc::new(ShareThrottles::default()),
316 family: Arc::new(FamilyCache::default()),317 family: Arc::new(FamilyCache::default()),
318+ staging: Arc::new(ObjectStaging::default()),
317 };319 };
318 (dir, state)320 (dir, state)
319 }321 }
crates/in-web/src/i18n/drive.rsmodified+8 -3
@@ -126,7 +126,7 @@ pub enum DK {
126 RefuseNameReserved,126 RefuseNameReserved,
127 /// Refusal: the name is too long.127 /// Refusal: the name is too long.
128 RefuseNameTooLong,128 RefuseNameTooLong,
129- /// Refusal: the name holds a slash, backslash or control character.129+ /// Refusal: the name holds a slash, backslash, control or hidden formatting character.
130 RefuseNameBadChar,130 RefuseNameBadChar,
131 /// Refusal: a folder would move into itself.131 /// Refusal: a folder would move into itself.
132 RefuseCycle,132 RefuseCycle,
@@ -134,6 +134,8 @@ pub enum DK {
134 RefuseNotInTrash,134 RefuseNotInTrash,
135 /// Refusal: no free postfix exists.135 /// Refusal: no free postfix exists.
136 RefuseTooManyNames,136 RefuseTooManyNames,
137+ /// Refusal: a folder would nest deeper than the tree allows.
138+ RefuseFolderTooDeep,
137 /// Refusal: nothing else is known.139 /// Refusal: nothing else is known.
138 RefuseGeneric,140 RefuseGeneric,
139 /// Refusal: the upload had no file in it.141 /// Refusal: the upload had no file in it.
@@ -272,10 +274,10 @@ pub fn d(lang: Lang, key: DK) -> &'static str {
272 (DK::RefuseNameTooLong, Lang::En) => "The name is too long (255 bytes at most).",274 (DK::RefuseNameTooLong, Lang::En) => "The name is too long (255 bytes at most).",
273 (DK::RefuseNameTooLong, Lang::Tr) => "Ad çok uzun (en fazla 255 bayt).",275 (DK::RefuseNameTooLong, Lang::Tr) => "Ad çok uzun (en fazla 255 bayt).",
274 (DK::RefuseNameBadChar, Lang::En) => {276 (DK::RefuseNameBadChar, Lang::En) => {
275- "The name contains a slash, a backslash or a control character."277+ "The name contains a slash, a backslash, a control character or a hidden formatting character."
276 }278 }
277 (DK::RefuseNameBadChar, Lang::Tr) => {279 (DK::RefuseNameBadChar, Lang::Tr) => {
278- "Ad eğik çizgi, ters eğik çizgi ya da denetim karakteri içeriyor."280+ "Ad eğik çizgi, ters eğik çizgi, denetim karakteri ya da gizli biçimlendirme karakteri içeriyor."
279 }281 }
280 (DK::RefuseCycle, Lang::En) => "A folder cannot be moved into itself.",282 (DK::RefuseCycle, Lang::En) => "A folder cannot be moved into itself.",
281 (DK::RefuseCycle, Lang::Tr) => "Bir klasör kendi içine taşınamaz.",283 (DK::RefuseCycle, Lang::Tr) => "Bir klasör kendi içine taşınamaz.",
@@ -283,6 +285,8 @@ pub fn d(lang: Lang, key: DK) -> &'static str {
283 (DK::RefuseNotInTrash, Lang::Tr) => "Bu öğe çöpte değil.",285 (DK::RefuseNotInTrash, Lang::Tr) => "Bu öğe çöpte değil.",
284 (DK::RefuseTooManyNames, Lang::En) => "Too many items already use this name.",286 (DK::RefuseTooManyNames, Lang::En) => "Too many items already use this name.",
285 (DK::RefuseTooManyNames, Lang::Tr) => "Bu adı kullanan çok fazla öğe var.",287 (DK::RefuseTooManyNames, Lang::Tr) => "Bu adı kullanan çok fazla öğe var.",
288+ (DK::RefuseFolderTooDeep, Lang::En) => "Folders cannot be nested any deeper.",
289+ (DK::RefuseFolderTooDeep, Lang::Tr) => "Klasörler daha fazla iç içe olamaz.",
286 (DK::RefuseGeneric, Lang::En) => "The change could not be made.",290 (DK::RefuseGeneric, Lang::En) => "The change could not be made.",
287 (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.",291 (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.",
288 (DK::RefuseNoFile, Lang::En) => "Choose at least one file.",292 (DK::RefuseNoFile, Lang::En) => "Choose at least one file.",
@@ -334,6 +338,7 @@ pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> {
334 "cycle" => d(lang, DK::RefuseCycle),338 "cycle" => d(lang, DK::RefuseCycle),
335 "not_in_trash" => d(lang, DK::RefuseNotInTrash),339 "not_in_trash" => d(lang, DK::RefuseNotInTrash),
336 "too_many_names" => d(lang, DK::RefuseTooManyNames),340 "too_many_names" => d(lang, DK::RefuseTooManyNames),
341+ "folder_too_deep" => d(lang, DK::RefuseFolderTooDeep),
337 "no_file" => d(lang, DK::RefuseNoFile),342 "no_file" => d(lang, DK::RefuseNoFile),
338 "generic" => d(lang, DK::RefuseGeneric),343 "generic" => d(lang, DK::RefuseGeneric),
339 _ => return super::share::refusal_text(lang, word),344 _ => return super::share::refusal_text(lang, word),
crates/in-web/src/oidc.rsmodified+6 -0
@@ -127,6 +127,8 @@ pub struct IdClaims {
127 pub zoneinfo: String,127 pub zoneinfo: String,
128 /// Photo version; bumps when the photo changes.128 /// Photo version; bumps when the photo changes.
129 pub picture_version: i64,129 pub picture_version: i64,
130+ /// When the token was issued, in Unix seconds. `check_iat` has already made sure it is present.
131+ pub iat: i64,
130 }132 }
131 133
132 /// The claims of a back-channel logout token that `in` uses.134 /// The claims of a back-channel logout token that `in` uses.
@@ -358,6 +360,10 @@ pub fn verify_id_token(
358 zoneinfo: optional_text_claim(&claims, "zoneinfo")360 zoneinfo: optional_text_claim(&claims, "zoneinfo")
359 .unwrap_or("UTC")361 .unwrap_or("UTC")
360 .to_owned(),362 .to_owned(),
363+ iat: claims
364+ .get("iat")
365+ .and_then(Value::as_i64)
366+ .unwrap_or_default(),
361 picture_version: claims367 picture_version: claims
362 .get("picture_version")368 .get("picture_version")
363 .and_then(Value::as_i64)369 .and_then(Value::as_i64)
crates/in-web/src/pages/drive.rsmodified+3 -2
@@ -599,13 +599,14 @@ async fn drive_live(cx: &Cx, query: Option<Form<LiveQuery>>) -> Result<Response>
599 if store.session_by_token_hash(&token_hash).await?.is_none() {599 if store.session_by_token_hash(&token_hash).await?.is_none() {
600 return Err(not_found().into());600 return Err(not_found().into());
601 }601 }
602- // A grant that was taken away ends the stream too, even though the folder still exists.602+ // A grant that was taken away ends the stream too, even though the folder still exists. The
603+ // owner has no grant on their own folders, so only a shared folder is checked for one.
603 if let Some(id) = folder.as_deref() {604 if let Some(id) = folder.as_deref() {
604 let access = store605 let access = store
605 .access_of(&me, ItemKind::Folder, id)606 .access_of(&me, ItemKind::Folder, id)
606 .await?607 .await?
607 .ok_or_else(not_found)?;608 .ok_or_else(not_found)?;
608- if access.trashed || access.grant == Grant::None {609+ if access.trashed || (access.grant == Grant::None && owner != me) {
609 return Err(not_found().into());610 return Err(not_found().into());
610 }611 }
611 }612 }
crates/in-web/src/pages/files.rsmodified+18 -7
@@ -84,8 +84,10 @@ async fn read_text(field: &mut Field<'_>, cap: usize) -> Result<String> {
84 String::from_utf8(bytes).map_err(|_| bad_request("field is not UTF-8").into())84 String::from_utf8(bytes).map_err(|_| bad_request("field is not UTF-8").into())
85 }85 }
86 86
87-/// Streams one file part into the store. `Ok(Err(word))` is a refusal the person can read (the quota, the87+/// Streams one file part into the store. `claims` is the declared size of the owner's other open uploads,
88-/// size limit); `Err` is a server failure. Nothing is left behind on either path.88+/// which the quota must leave room for. The headroom is worked out before a byte is staged, so the disk
89+/// never takes more than the quota allows. `Ok(Err(word))` is a refusal the person can read (the quota,
90+/// the size limit); `Err` is a server failure. Nothing is left behind on either path.
89 async fn store_one(91 async fn store_one(
90 state: &AppState,92 state: &AppState,
91 owner: &str,93 owner: &str,
@@ -93,8 +95,14 @@ async fn store_one(
93 client_name: &str,95 client_name: &str,
94 field: &mut Field<'_>,96 field: &mut Field<'_>,
95 limit: u64,97 limit: u64,
98+ claims: i64,
96 ) -> Result<std::result::Result<File, String>> {99 ) -> Result<std::result::Result<File, String>> {
97- let mut staged = StagedFile::create(&state.config.data_dir, limit).await?;100+ let member = state.store.member(owner).await?.ok_or_else(not_found)?;
101+ let room = quota::headroom(member.quota_bytes, member.used_bytes, claims);
102+ let room_bytes = u64::try_from(room).unwrap_or(0);
103+ // When the quota, not the per-file limit, is what stops the file, the refusal says so.
104+ let quota_binds = room_bytes < limit;
105+ let mut staged = StagedFile::create(&state.config.data_dir, limit.min(room_bytes)).await?;
98 let mut prefix: Vec<u8> = Vec::with_capacity(SNIFF_BYTES);106 let mut prefix: Vec<u8> = Vec::with_capacity(SNIFF_BYTES);
99 loop {107 loop {
100 let chunk = match field.chunk().await {108 let chunk = match field.chunk().await {
@@ -112,6 +120,9 @@ async fn store_one(
112 if let Err(error) = staged.write(&chunk).await {120 if let Err(error) = staged.write(&chunk).await {
113 staged.abort().await;121 staged.abort().await;
114 return match refusal_word(&error) {122 return match refusal_word(&error) {
123+ Some(word) if quota_binds && word == "too_large" => {
124+ Ok(Err("quota_exceeded".to_owned()))
125+ }
115 Some(word) => Ok(Err(word)),126 Some(word) => Ok(Err(word)),
116 None => Err(error.into()),127 None => Err(error.into()),
117 };128 };
@@ -119,9 +130,7 @@ async fn store_one(
119 }130 }
120 let Staged { path, size, sha256 } = staged.finish().await?;131 let Staged { path, size, sha256 } = staged.finish().await?;
121 let size = i64::try_from(size).unwrap_or(i64::MAX);132 let size = i64::try_from(size).unwrap_or(i64::MAX);
122- // The quota is checked before the bytes move, so a refused file never reaches the blob store.133+ // The quota is checked again before the bytes move, so a refused file never reaches the blob store.
123- let member = state.store.member(owner).await?.ok_or_else(not_found)?;
124- let room = quota::headroom(member.quota_bytes, member.used_bytes, 0);
125 if !quota::fits(size, room) {134 if !quota::fits(size, room) {
126 let _ = tokio::fs::remove_file(&path).await;135 let _ = tokio::fs::remove_file(&path).await;
127 return Ok(Err("quota_exceeded".to_owned()));136 return Ok(Err("quota_exceeded".to_owned()));
@@ -140,7 +149,7 @@ async fn store_one(
140 mime: sniff(&prefix),149 mime: sniff(&prefix),
141 size,150 size,
142 sha256,151 sha256,
143- staged_claims: 0,152+ staged_claims: claims,
144 };153 };
145 match state.store.insert_file(new).await {154 match state.store.insert_file(new).await {
146 Ok(file) => Ok(Ok(file)),155 Ok(file) => Ok(Ok(file)),
@@ -189,6 +198,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<SeeOther> {
189 folder = Some(optional_folder(state, owner, &folder_raw).await?);198 folder = Some(optional_folder(state, owner, &folder_raw).await?);
190 }199 }
191 let target = folder.clone().flatten();200 let target = folder.clone().flatten();
201+ let claims = state.store.declared_claims_of(&owner.member.sub).await?;
192 match store_one(202 match store_one(
193 state,203 state,
194 &owner.member.sub,204 &owner.member.sub,
@@ -196,6 +206,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<SeeOther> {
196 &client_name,206 &client_name,
197 &mut field,207 &mut field,
198 limit,208 limit,
209+ claims,
199 )210 )
200 .await?211 .await?
201 {212 {
crates/in-web/src/pages/public_share.rsmodified+19 -12
@@ -50,6 +50,10 @@ const GATE_CSRF_COOKIE: &str = "__Host-in_precsrf";
50 /// How long a successful password keeps a visitor unlocked: twelve hours.50 /// How long a successful password keeps a visitor unlocked: twelve hours.
51 const UNLOCK_HOURS: i64 = 12;51 const UNLOCK_HOURS: i64 = 12;
52 52
53+/// Longest password that is verified, in characters. A longer one is a wrong password without hashing,
54+/// so a huge submission costs nothing. The reason: no real share password comes near it.
55+const MAX_PASSWORD_CHARS: usize = 256;
56+
53 /// The unlock cookie name of a link. It is scoped to the link's own path, so the name only needs the id.57 /// The unlock cookie name of a link. It is scoped to the link's own path, so the name only needs the id.
54 fn unlock_cookie_name(link_id: &str) -> String {58 fn unlock_cookie_name(link_id: &str) -> String {
55 format!("in_link_{link_id}")59 format!("in_link_{link_id}")
@@ -427,8 +431,9 @@ async fn public_page(cx: &Cx) -> Result<impl View> {
427 })431 })
428 }432 }
429 433
430-/// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie; a wrong one is counted434+/// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie. Every attempt is counted
431-/// against the link and the client address. Both limits are checked before anything else.435+/// against the link and the client address before it is verified, and a right one takes its count back;
436+/// so parallel guesses cannot all be verified together. Refused attempts are `429`.
432 #[route(POST "/s/{token}")]437 #[route(POST "/s/{token}")]
433 async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> {438 async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> {
434 let state = app_context::<AppState>(cx);439 let state = app_context::<AppState>(cx);
@@ -436,13 +441,6 @@ async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> {
436 let token_hash = hash_token(&token);441 let token_hash = hash_token(&token);
437 let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default();442 let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default();
438 let throttles = &state.throttles;443 let throttles = &state.throttles;
439- if let Some(wait) = throttles
440- .per_link
441- .blocked(&token_hash)
442- .or_else(|| throttles.per_ip.blocked(&ip))
443- {
444- return Err(too_many_requests(wait).into());
445- }
446 let expected_csrf = cookie_value(cx, GATE_CSRF_COOKIE).unwrap_or_default();444 let expected_csrf = cookie_value(cx, GATE_CSRF_COOKIE).unwrap_or_default();
447 if expected_csrf.is_empty() || !constant_time_eq(expected_csrf.as_bytes(), form.csrf.as_bytes())445 if expected_csrf.is_empty() || !constant_time_eq(expected_csrf.as_bytes(), form.csrf.as_bytes())
448 {446 {
@@ -452,7 +450,18 @@ async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> {
452 let Some(hash) = link.password_hash.clone() else {450 let Some(hash) = link.password_hash.clone() else {
453 return Ok(see_other(format!("/s/{token}")));451 return Ok(see_other(format!("/s/{token}")));
454 };452 };
455- if verify_password_async(form.password, hash.clone()).await? {453+ if let Err(wait) = throttles.per_link.reserve(&token_hash) {
454+ return Err(too_many_requests(wait).into());
455+ }
456+ if let Err(wait) = throttles.per_ip.reserve(&ip) {
457+ throttles.per_link.refund(&token_hash);
458+ return Err(too_many_requests(wait).into());
459+ }
460+ let verified = form.password.chars().count() <= MAX_PASSWORD_CHARS
461+ && verify_password_async(form.password, hash.clone()).await?;
462+ if verified {
463+ throttles.per_link.refund(&token_hash);
464+ throttles.per_ip.refund(&ip);
456 let proof = unlock_proof(&state.key, &link.id, &hash);465 let proof = unlock_proof(&state.key, &link.id, &hash);
457 let cookie = Cookie::build((unlock_cookie_name(&link.id), proof))466 let cookie = Cookie::build((unlock_cookie_name(&link.id), proof))
458 .path(format!("/s/{token}"))467 .path(format!("/s/{token}"))
@@ -464,8 +473,6 @@ async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> {
464 cookies(cx).add(cookie);473 cookies(cx).add(cookie);
465 return Ok(see_other(format!("/s/{token}")));474 return Ok(see_other(format!("/s/{token}")));
466 }475 }
467- throttles.per_link.failure(&token_hash);
468- throttles.per_ip.failure(&ip);
469 Ok(see_other(format!("/s/{token}?wrong=1")))476 Ok(see_other(format!("/s/{token}?wrong=1")))
470 }477 }
471 478
crates/in-web/src/pages/sign_in.rsmodified+4 -3
@@ -14,7 +14,7 @@ use in_core::error::{Error as CoreError, Result as CoreResult};
14 use in_core::secret;14 use in_core::secret;
15 use in_core::store::members::MemberFields;15 use in_core::store::members::MemberFields;
16 use in_core::store::sessions::NewSession;16 use in_core::store::sessions::NewSession;
17-use in_core::time::stamp_after;17+use in_core::time::{stamp_after, stamp_from_unix};
18 use in_core::token::{constant_time_eq, generate_token, hash_token};18 use in_core::token::{constant_time_eq, generate_token, hash_token};
19 use serde::{Deserialize, Serialize};19 use serde::{Deserialize, Serialize};
20 use topcoat::Result;20 use topcoat::Result;
@@ -201,8 +201,9 @@ async fn callback(cx: &Cx, query: Option<Form<CallbackQuery>>) -> Result<SeeOthe
201 locale: claims.locale,201 locale: claims.locale,
202 zoneinfo: claims.zoneinfo,202 zoneinfo: claims.zoneinfo,
203 picture_version: claims.picture_version,203 picture_version: claims.picture_version,
204- // Sign-in claims carry no directory timestamp, so the store uses the sign-in time.204+ // The token's issue time orders these claims against directory changes. An `iat` that
205- im_updated_at: String::new(),205+ // cannot be converted leaves it empty, and the store then uses the sign-in time.
206+ im_updated_at: stamp_from_unix(claims.iat).unwrap_or_default(),
206 },207 },
207 default_quota,208 default_quota,
208 )209 )
crates/in-web/src/serve_bytes.rsmodified+4 -2
@@ -66,8 +66,10 @@ pub const BYTES_CSP: &str = "sandbox; default-src 'none'; img-src 'self'; media-
66 pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; \66 pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; \
67 style-src 'unsafe-inline'; frame-ancestors 'self'";67 style-src 'unsafe-inline'; frame-ancestors 'self'";
68 68
69-/// Cache policy of content addressed by id and hash: the bytes behind a URL never change.69+/// Cache policy of the member's own bytes (`/file` and `/thumb`). Access is revoked by a grant change, not by
70-const BYTES_CACHE: &str = "private, max-age=31536000, immutable";70+/// the URL, so a cached copy must not outlive the check: the browser revalidates, and the `ETag` turns that
71+/// into a cheap `304` while the bytes are unchanged.
72+const BYTES_CACHE: &str = "private, no-cache";
71 73
72 /// Cache policy of bytes behind a public share link. The link can be revoked or its password changed, so74 /// Cache policy of bytes behind a public share link. The link can be revoked or its password changed, so
73 /// a cached copy must not outlive the check: the browser asks again every time.75 /// a cached copy must not outlive the check: the browser asks again every time.
crates/in-web/src/state.rsmodified+59 -1
@@ -1,6 +1,7 @@
1 //! The state shared by every route. Topcoat hands it to each handler through the app context.1 //! The state shared by every route. Topcoat hands it to each handler through the app context.
2 2
3-use std::sync::Arc;3+use std::collections::HashMap;
4+use std::sync::{Arc, Mutex, PoisonError};
4 5
5 use in_core::blob::BlobStore;6 use in_core::blob::BlobStore;
6 use in_core::config::Config;7 use in_core::config::Config;
@@ -32,4 +33,61 @@ pub struct AppState {
32 pub throttles: Arc<ShareThrottles>,33 pub throttles: Arc<ShareThrottles>,
33 /// The switcher list of the family, refreshed by the family worker.34 /// The switcher list of the family, refreshed by the family worker.
34 pub family: Arc<FamilyCache>,35 pub family: Arc<FamilyCache>,
36+ /// The bytes object writes may stage right now, per service.
37+ pub staging: Arc<ObjectStaging>,
38+}
39+
40+/// Bytes of object writes that are being staged, per service. A write reserves the bytes it may stage before
41+/// it reads its body, and the reservation ends when the write does. So parallel writes of one service cannot
42+/// stage more than the service's headroom together.
43+#[derive(Default)]
44+pub struct ObjectStaging {
45+ /// Reserved bytes per service name. An entry is removed when its last reservation ends.
46+ reserved: Mutex<HashMap<String, u64>>,
47+}
48+
49+impl ObjectStaging {
50+ /// Reserves `bytes` for `service`, when the reservations it already holds plus `bytes` stay within
51+ /// `headroom`. The reservation ends when the guard is dropped. `None` when the budget is used up.
52+ pub fn reserve(
53+ self: &Arc<Self>,
54+ service: &str,
55+ bytes: u64,
56+ headroom: u64,
57+ ) -> Option<StagingGuard> {
58+ let mut map = self.reserved.lock().unwrap_or_else(PoisonError::into_inner);
59+ let held = map.get(service).copied().unwrap_or(0);
60+ if held.saturating_add(bytes) > headroom {
61+ return None;
62+ }
63+ map.insert(service.to_owned(), held.saturating_add(bytes));
64+ Some(StagingGuard {
65+ staging: Arc::clone(self),
66+ service: service.to_owned(),
67+ bytes,
68+ })
69+ }
70+}
71+
72+/// A reservation of [`ObjectStaging`]. Dropping it gives the bytes back, on success and on every failure.
73+pub struct StagingGuard {
74+ staging: Arc<ObjectStaging>,
75+ service: String,
76+ bytes: u64,
77+}
78+
79+impl Drop for StagingGuard {
80+ fn drop(&mut self) {
81+ let mut map = self
82+ .staging
83+ .reserved
84+ .lock()
85+ .unwrap_or_else(PoisonError::into_inner);
86+ if let Some(held) = map.get_mut(&self.service) {
87+ *held = held.saturating_sub(self.bytes);
88+ if *held == 0 {
89+ map.remove(&self.service);
90+ }
91+ }
92+ }
35 }93 }
crates/in-web/src/throttle.rsmodified+72 -23
@@ -1,8 +1,9 @@
1 //! Failure throttling in memory: a sliding window of failures per key, with a bounded number of keys.1 //! Failure throttling in memory: a sliding window of failures per key, with a bounded number of keys.
2 //!2 //!
3-//! A check asks [`Throttle::blocked`] before any lookup and answers `429` with `Retry-After` when the key3+//! An attempt first asks [`Throttle::reserve`], which counts it as a failure and answers `429` with
4-//! has reached its limit. A failure is recorded with [`Throttle::failure`]. Nothing is persisted, so a4+//! `Retry-After` when the key has reached its limit. A success gives the count back with
5-//! restart forgets the failures; that is accepted for a family instance and documented in the backlog.5+//! [`Throttle::refund`]. Check and count are one step, so parallel attempts cannot pass together.
6+//! Nothing is persisted, so a restart forgets the failures; that is accepted for a family instance and documented in the backlog.
6 //!7 //!
7 //! The key count is capped. When a new key would exceed the cap, the windows that have expired are8 //! The key count is capped. When a new key would exceed the cap, the windows that have expired are
8 //! dropped first, and then the key whose last failure is oldest. So an attacker who spreads guesses over9 //! dropped first, and then the key whose last failure is oldest. So an attacker who spreads guesses over
@@ -48,34 +49,52 @@ impl Throttle {
48 self.failures.lock().unwrap_or_else(PoisonError::into_inner)49 self.failures.lock().unwrap_or_else(PoisonError::into_inner)
49 }50 }
50 51
51- /// The seconds `key` must wait before it may try again, or `None` when it may try now. Only failures52+ /// Counts one attempt of `key` now, before the attempt is made. The check and the record are one step,
52- /// inside the window count.53+ /// so parallel attempts cannot all pass before any of them is counted. When the key already has `limit`
53- pub fn blocked(&self, key: &str) -> Option<u64> {54+ /// failures in the window, nothing is recorded and the seconds to wait come back (at least one).
55+ ///
56+ /// A reserved attempt counts as a failure until [`Throttle::refund`] takes it back, which a success does.
57+ pub fn reserve(&self, key: &str) -> std::result::Result<(), u64> {
54 let now = Instant::now();58 let now = Instant::now();
55 let mut map = self.map();59 let mut map = self.map();
56- let stamps = map.get_mut(key)?;60+ if let Some(stamps) = map.get_mut(key) {
57- stamps.retain(|at| now.duration_since(*at) < self.window);61+ stamps.retain(|at| now.duration_since(*at) < self.window);
58- if stamps.len() < self.limit {62+ if stamps.len() >= self.limit {
59- return None;63+ return Err(self.wait_seconds(stamps, now));
64+ }
65+ stamps.push(now);
66+ return Ok(());
67+ }
68+ if map.len() >= self.max_keys {
69+ self.make_room(&mut map, now);
60 }70 }
71+ map.entry(key.to_owned()).or_default().push(now);
72+ Ok(())
73+ }
74+
75+ /// Takes back the newest counted attempt of `key`, for an attempt that succeeded.
76+ pub fn refund(&self, key: &str) {
77+ let emptied = match self.map().get_mut(key) {
78+ Some(stamps) => {
79+ stamps.pop();
80+ stamps.is_empty()
81+ }
82+ None => false,
83+ };
84+ if emptied {
85+ self.map().remove(key);
86+ }
87+ }
88+
89+ /// The seconds until the oldest failure that must leave the window before `key` may try again. Rounded
90+ /// up, and at least one second, so `Retry-After` is never zero for a blocked key.
91+ fn wait_seconds(&self, stamps: &[Instant], now: Instant) -> u64 {
61 // The key may try again once enough failures have left the window: the one at this index is the92 // The key may try again once enough failures have left the window: the one at this index is the
62 // last to leave before the count drops below the limit.93 // last to leave before the count drops below the limit.
63 let index = stamps.len() - self.limit;94 let index = stamps.len() - self.limit;
64 let free_at = stamps[index] + self.window;95 let free_at = stamps[index] + self.window;
65 let wait = free_at.saturating_duration_since(now);96 let wait = free_at.saturating_duration_since(now);
66- // Rounded up, and at least one second, so `Retry-After` is never zero for a blocked key.97+ (wait.as_secs() + u64::from(wait.subsec_nanos() > 0)).max(1)
67- let seconds = wait.as_secs() + u64::from(wait.subsec_nanos() > 0);
68- Some(seconds.max(1))
69- }
70-
71- /// Records one failure of `key` now.
72- pub fn failure(&self, key: &str) {
73- let now = Instant::now();
74- let mut map = self.map();
75- if !map.contains_key(key) && map.len() >= self.max_keys {
76- self.make_room(&mut map, now);
77- }
78- map.entry(key.to_owned()).or_default().push(now);
79 }98 }
80 99
81 /// Frees one slot: expired windows go first, then the key with the oldest last failure.100 /// Frees one slot: expired windows go first, then the key with the oldest last failure.
@@ -113,3 +132,33 @@ impl Default for ShareThrottles {
113 }132 }
114 }133 }
115 }134 }
135+
136+#[cfg(test)]
137+mod tests {
138+ use super::*;
139+ use std::sync::Arc;
140+
141+ /// Ten parallel wrong guesses against one link: only the limit of them is counted and admitted, and the
142+ /// rest are refused with a wait. The check and the record are one step, so none can slip past.
143+ #[test]
144+ fn parallel_attempts_admit_no_more_than_the_limit() {
145+ let throttle = Arc::new(Throttle::new(
146+ PASSWORD_WINDOW,
147+ LINK_PASSWORD_LIMIT,
148+ MAX_KEYS,
149+ ));
150+ let handles: Vec<_> = (0..10)
151+ .map(|_| {
152+ let throttle = Arc::clone(&throttle);
153+ std::thread::spawn(move || throttle.reserve("link").is_ok())
154+ })
155+ .collect();
156+ let admitted = handles
157+ .into_iter()
158+ .map(|handle| handle.join().expect("attempt thread"))
159+ .filter(|ok| *ok)
160+ .count();
161+ assert_eq!(admitted, LINK_PASSWORD_LIMIT);
162+ assert!(throttle.reserve("link").is_err_and(|wait| wait >= 1));
163+ }
164+}