diff --git a/crates/in-core/src/names.rs b/crates/in-core/src/names.rs index 72542f7..6b31bd8 100644 --- a/crates/in-core/src/names.rs +++ b/crates/in-core/src/names.rs @@ -18,6 +18,24 @@ pub const MAX_NAME_BYTES: usize = 255; /// Name given to an item whose input has no usable characters left. pub const UNTITLED: &str = "Untitled"; +/// Whether `c` is a Unicode format character (category Cf) that changes how a name is shown, or a line or +/// paragraph separator. Bidi overrides such as U+202E make `invoice\u{202E}fdp.exe` read as `invoice exe.pdf`, +/// so these are refused in typed names and stripped from upload names. +fn is_invisible_or_bidi(c: char) -> bool { + matches!( + c, + // U+200D (zero-width joiner) is allowed: emoji sequences need it and it cannot reorder text. + '\u{200B}'..='\u{200C}' + | '\u{200E}'..='\u{200F}' + | '\u{202A}'..='\u{202E}' + | '\u{2060}'..='\u{2064}' + | '\u{2066}'..='\u{2069}' + | '\u{FEFF}' + | '\u{2028}' + | '\u{2029}' + ) +} + /// Checks a name typed by a person and returns it trimmed and in NFC. Refusals are /// `Invalid` with a fixed reason word: `name_empty`, `name_reserved` (`.` or `..`), `name_too_long` /// (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 { } if name .chars() - .any(|c| matches!(c, '/' | '\\') || c.is_control()) + .any(|c| matches!(c, '/' | '\\') || c.is_control() || is_invisible_or_bidi(c)) { return Err(Error::Invalid("name_bad_char".into())); } @@ -60,7 +78,7 @@ pub fn upload_name(client_name: &str) -> String { } /// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt` -/// becomes `c.txt`. Control characters are dropped, surrounding spaces are trimmed, and input with +/// becomes `c.txt`. Control and format characters are dropped, surrounding spaces are trimmed, and input with /// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`]. pub fn display_name(input: &str) -> String { // Path separators come from both Unix and Windows clients, so split on both. @@ -68,7 +86,10 @@ pub fn display_name(input: &str) -> String { .rsplit(['/', '\\']) .find(|part| !part.trim().is_empty()) .unwrap_or(""); - let cleaned: String = leaf.chars().filter(|c| !c.is_control()).collect(); + let cleaned: String = leaf + .chars() + .filter(|c| !c.is_control() && !is_invisible_or_bidi(*c)) + .collect(); let trimmed = cleaned.trim(); if trimmed.is_empty() || trimmed == "." || trimmed == ".." { return UNTITLED.to_string(); @@ -161,6 +182,15 @@ mod tests { assert!(validate_name(&cut).is_ok()); } + /// A right-to-left override hides the real extension. A typed name is refused, an upload name is stripped. + #[test] + fn bidi_override_cannot_disguise_an_extension() { + let disguised = "invoice\u{202E}fdp.exe"; + assert!(matches!(validate_name(disguised), Err(Error::Invalid(m)) if m == "name_bad_char")); + assert_eq!(upload_name(disguised), "invoicefdp.exe"); + assert_eq!(display_name("\u{FEFF}zero\u{200B}width"), "zerowidth"); + } + #[test] fn display_name_cuts_long_names_by_characters() { let long = "é".repeat(300); diff --git a/crates/in-core/src/store/folders.rs b/crates/in-core/src/store/folders.rs index d186246..53daddf 100644 --- a/crates/in-core/src/store/folders.rs +++ b/crates/in-core/src/store/folders.rs @@ -112,6 +112,21 @@ pub(crate) async fn has_trashed_chain(conn: &Connection, folder: Option<&str>) - Err(Error::Database("folder tree is too deep".into())) } +/// How many folders lie on the chain from `folder` up to the top level, `folder` included. A chain that +/// is longer than [`MAX_DEPTH`] is an error, so a walk never passes its limit silently. +async fn chain_depth(conn: &Connection, folder: &str) -> Result { + let mut depth = 0; + let mut cur = Some(folder.to_string()); + while let Some(id) = cur { + depth += 1; + if depth > MAX_DEPTH { + return Err(Error::Database("folder tree is too deep".into())); + } + cur = folder_by_id(conn, &id).await?.and_then(|f| f.parent_id); + } + Ok(depth) +} + /// Inserts a folder with the first free postfix. The partial unique index decides each attempt. async fn insert_folder_postfixed( conn: &Connection, @@ -181,6 +196,10 @@ impl Store { let conn = self.inner.conn.lock().await; if let Some(p) = parent { live_folder(&conn, owner, p).await?; + // The new folder sits one level below its parent, so the parent's chain must leave room. + if chain_depth(&conn, p).await? >= MAX_DEPTH { + return Err(Error::Invalid("folder_too_deep".into())); + } } insert_folder_postfixed(&conn, owner, parent, &base).await } @@ -211,11 +230,12 @@ impl Store { live_folder(&tx, owner, id).await?; if let Some(p) = parent { live_folder(&tx, owner, p).await?; + // The moved folder sits one level below `p`, so `p`'s chain must leave room for it. + if chain_depth(&tx, p).await? >= MAX_DEPTH { + return Err(Error::Invalid("folder_too_deep".into())); + } let mut cur = Some(p.to_string()); - for _ in 0..MAX_DEPTH { - let Some(c) = cur else { - break; - }; + while let Some(c) = cur { if c == id { return Err(Error::Forbidden("cycle".into())); } diff --git a/crates/in-core/src/store/members.rs b/crates/in-core/src/store/members.rs index b02af72..2560a04 100644 --- a/crates/in-core/src/store/members.rs +++ b/crates/in-core/src/store/members.rs @@ -69,7 +69,8 @@ pub struct MemberFields { pub zoneinfo: String, /// Photo version. pub picture_version: i64, - /// Directory timestamp of the change. Sign-in claims carry none, so the sign-in path ignores it. + /// Directory timestamp of the change, in the stamp format of `time.rs`. Sign-in passes the ID token's + /// `iat`; an empty value means "now". pub im_updated_at: String, } @@ -117,14 +118,21 @@ async fn fetch_member(conn: &turso::Connection, sub: &str) -> Result Result { let now = now_stamp(); + // The claims' own time: the caller's stamp, or now when it gave none. + let claims_at = if fields.im_updated_at.is_empty() { + now.clone() + } else { + fields.im_updated_at.clone() + }; let conn = self.inner.conn.lock().await; conn.execute( "INSERT INTO members (sub, email, name, is_admin, locale, zoneinfo, picture_version, \ @@ -132,7 +140,8 @@ impl Store { VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10) \ ON CONFLICT (sub) DO UPDATE SET email = excluded.email, name = excluded.name, \ is_admin = excluded.is_admin, locale = excluded.locale, zoneinfo = excluded.zoneinfo, \ - picture_version = excluded.picture_version, last_sign_in_at = excluded.last_sign_in_at", + picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at \ + WHERE excluded.im_updated_at >= members.im_updated_at", ( fields.sub.clone(), fields.email.clone(), @@ -141,19 +150,20 @@ impl Store { fields.locale.clone(), fields.zoneinfo.clone(), fields.picture_version, - // The insert needs a value; an existing row keeps its own im_updated_at because the - // conflict clause does not touch that column. - if fields.im_updated_at.is_empty() { - now.clone() - } else { - fields.im_updated_at.clone() - }, - now, + claims_at, + now.clone(), default_quota, ), ) .await .map_err(db_err)?; + // Kept apart from the claim update: that one is skipped for a stale sign-in, this one never is. + conn.execute( + "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1", + (fields.sub.clone(), now), + ) + .await + .map_err(db_err)?; fetch_member(&conn, &fields.sub) .await? .ok_or(Error::NotFound) diff --git a/crates/in-core/src/store/uploads.rs b/crates/in-core/src/store/uploads.rs index aa95d02..5c30f18 100644 --- a/crates/in-core/src/store/uploads.rs +++ b/crates/in-core/src/store/uploads.rs @@ -16,6 +16,10 @@ use crate::store::folders::live_folder; use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; use crate::time::now_stamp; +/// Most uploads one person may have open (active and not expired) at once. A create past it is +/// `Conflict("too_many_uploads")`, so an account cannot hold thousands of empty uploads at no cost. +pub const MAX_OPEN_UPLOADS: i64 = 64; + /// Column list for [`map_upload`]. Keep the two in step. pub const UPLOAD_COLS: &str = "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 } impl Store { + /// The bytes the owner's open uploads have declared. A new upload or a direct upload must leave them room. + pub async fn declared_claims_of(&self, owner: &str) -> Result { + let conn = self.read_conn().await; + declared_claims(&conn, owner, &now_stamp(), "").await + } + /// An upload of `owner` by id, or `None` when there is no such upload for that person. pub async fn upload(&self, owner: &str, id: &str) -> Result> { let conn = self.read_conn().await; @@ -121,7 +131,8 @@ impl Store { /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared - /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`. + /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`, + /// and one for too many open uploads ([`MAX_OPEN_UPLOADS`]) is `Conflict("too_many_uploads")`. pub async fn create_upload(&self, new: NewUpload, max_size: i64) -> Result { if new.size < 0 || new.size > max_size { return Err(Error::Invalid("too_large".into())); @@ -141,6 +152,17 @@ impl Store { ) .await? .ok_or(Error::NotFound)?; + let open: i64 = fetch_opt( + &tx, + "SELECT COUNT(*) FROM uploads WHERE owner = ?1 AND state = 'active' AND expires_at > ?2", + (new.owner.clone(), now.clone()), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if open >= MAX_OPEN_UPLOADS { + return Err(Error::Conflict("too_many_uploads".into())); + } let claims = declared_claims(&tx, &new.owner, &now, "").await?; if !quota::fits(new.size, quota::headroom(quota, used, claims)) { return Err(Error::Conflict("quota_exceeded".into())); diff --git a/crates/in-core/src/thumbs.rs b/crates/in-core/src/thumbs.rs index c3b7654..1e46d88 100644 --- a/crates/in-core/src/thumbs.rs +++ b/crates/in-core/src/thumbs.rs @@ -43,6 +43,16 @@ pub fn make_thumbnail(source: &[u8]) -> Result> { if !reader.format().is_some_and(|f| FORMATS.contains(&f)) { return Err(bad()); } + // The header alone gives the size of the decoded picture. A picture that would need more than the + // allocation limit is refused here, before the decoder sizes any buffer, whatever its format. + let (width, height) = ImageReader::new(Cursor::new(source)) + .with_guessed_format() + .map_err(|_| bad())? + .into_dimensions() + .map_err(|_| bad())?; + if u64::from(width) * u64::from(height) * 4 > MAX_ALLOC_BYTES { + return Err(bad()); + } let mut limits = Limits::default(); limits.max_image_width = Some(MAX_DIMENSION); limits.max_image_height = Some(MAX_DIMENSION); diff --git a/crates/in-core/src/time.rs b/crates/in-core/src/time.rs index 38edea1..4d3bc5b 100644 --- a/crates/in-core/src/time.rs +++ b/crates/in-core/src/time.rs @@ -26,6 +26,13 @@ pub fn stamp_after(after: Duration) -> String { format_stamp(OffsetDateTime::now_utc().saturating_add(delta)) } +/// The stamp of a Unix time in whole seconds (an ID token's `iat`), or `None` when it is out of range. +pub fn stamp_from_unix(secs: i64) -> Option { + OffsetDateTime::from_unix_timestamp(secs) + .ok() + .map(format_stamp) +} + /// The stamp for `now - before`. Saturates at the smallest representable time instead of panicking. pub fn stamp_before(before: Duration) -> String { let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX); diff --git a/crates/in-web/src/api/objects.rs b/crates/in-web/src/api/objects.rs index 07e9ac3..730cd1d 100644 --- a/crates/in-web/src/api/objects.rs +++ b/crates/in-web/src/api/objects.rs @@ -11,6 +11,8 @@ //! `If-None-Match: *` refuses an existing id with `409`. //! - `GET` and `HEAD` send the bytes through `serve_bytes`, always as an attachment, with `Range` support. //! The cache policy is `private, no-cache`, because a replace changes what the id names. +//! - A write reserves the bytes it may stage for its service before it reads the body. A write that would +//! take the service past its headroom, together with the writes in flight, is `429 rate_limited`. //! - `DELETE` removes the object. It answers `204` also when the object was already absent. //! - `GET /api/v1/usage` answers the quota, the bytes used and the number of objects. //! @@ -18,8 +20,8 @@ //! write is storing right now, are never removed. A removal that is refused is left to the sweeper. use futures_util::StreamExt; -use http::StatusCode; -use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH}; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH, RETRY_AFTER}; +use http::{HeaderValue, StatusCode}; use in_core::error::Error as CoreError; use in_core::names; use in_core::staging::StagedFile; @@ -236,8 +238,24 @@ async fn put_object(cx: &Cx, body: Body) -> Result { if request.declared.is_some_and(|length| length > headroom) { return Ok(quota_refusal.answer()); } + // The bytes this write may stage: its declared length, or the whole headroom when none was declared. + // They are reserved for the service before a byte is read, so writes in flight together cannot stage + // more than the headroom. The reservation is released when this handler returns, on every path. + let reserve = request.declared.unwrap_or(headroom); + let Some(_staging) = state.staging.reserve(&service, reserve, headroom) else { + let mut response = Refusal { + status: StatusCode::TOO_MANY_REQUESTS, + error: "rate_limited", + message: "other writes to this service are staging; retry shortly", + } + .answer(); + response + .headers_mut() + .insert(RETRY_AFTER, HeaderValue::from_static("1")); + return Ok(response); + }; - let mut staged = StagedFile::create(&state.config.data_dir, headroom).await?; + let mut staged = StagedFile::create(&state.config.data_dir, reserve).await?; let mut frames = body.into_data_stream(); while let Some(frame) = frames.next().await { let written = match frame { diff --git a/crates/in-web/src/api/upload.rs b/crates/in-web/src/api/upload.rs index 4aac494..b973db4 100644 --- a/crates/in-web/src/api/upload.rs +++ b/crates/in-web/src/api/upload.rs @@ -5,7 +5,8 @@ //! The routes: //! - `POST /api/uploads` `{folder_id?, name, size}` starts an upload → `201 {id, chunk_size}`. The size is //! reserved against the quota in the same transaction that creates the row, so two creates cannot -//! together promise more than the headroom. +//! together promise more than the headroom. A person may hold 64 open uploads; the next one is `429` +//! `too_many_uploads`. //! - `GET /api/uploads/{id}` → `{id, state, size, chunk_size, received}`, where `received` lists the chunk //! indexes on disk. A client that lost its connection asks this, then sends only what is missing. //! - `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 { Err(CoreError::Conflict(word)) if word == "quota_exceeded" => { return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer()); } + Err(CoreError::Conflict(word)) if word == "too_many_uploads" => { + return Ok(refuse(StatusCode::TOO_MANY_REQUESTS, "too_many_uploads").answer()); + } Err(error) => return Err(error.into()), }; // The directory is made after the row commits. A crash in between leaves a row with no directory, which diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs index 0ca7c90..809ab6c 100644 --- a/crates/in-web/src/boot.rs +++ b/crates/in-web/src/boot.rs @@ -32,7 +32,7 @@ use crate::oidc::OidcClient; use crate::pages::files; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; -use crate::state::AppState; +use crate::state::{AppState, ObjectStaging}; use crate::sweeper; use crate::throttle::ShareThrottles; use crate::thumbs_worker; @@ -182,6 +182,7 @@ async fn open_state(config: Config) -> Result { oidc, throttles: Arc::new(ShareThrottles::default()), family: Arc::new(FamilyCache::default()), + staging: Arc::new(ObjectStaging::default()), }) } @@ -314,6 +315,7 @@ mod tests { oidc: None, throttles: Arc::new(ShareThrottles::default()), family: Arc::new(FamilyCache::default()), + staging: Arc::new(ObjectStaging::default()), }; (dir, state) } diff --git a/crates/in-web/src/i18n/drive.rs b/crates/in-web/src/i18n/drive.rs index b5cce3c..c2c9610 100644 --- a/crates/in-web/src/i18n/drive.rs +++ b/crates/in-web/src/i18n/drive.rs @@ -126,7 +126,7 @@ pub enum DK { RefuseNameReserved, /// Refusal: the name is too long. RefuseNameTooLong, - /// Refusal: the name holds a slash, backslash or control character. + /// Refusal: the name holds a slash, backslash, control or hidden formatting character. RefuseNameBadChar, /// Refusal: a folder would move into itself. RefuseCycle, @@ -134,6 +134,8 @@ pub enum DK { RefuseNotInTrash, /// Refusal: no free postfix exists. RefuseTooManyNames, + /// Refusal: a folder would nest deeper than the tree allows. + RefuseFolderTooDeep, /// Refusal: nothing else is known. RefuseGeneric, /// Refusal: the upload had no file in it. @@ -272,10 +274,10 @@ pub fn d(lang: Lang, key: DK) -> &'static str { (DK::RefuseNameTooLong, Lang::En) => "The name is too long (255 bytes at most).", (DK::RefuseNameTooLong, Lang::Tr) => "Ad çok uzun (en fazla 255 bayt).", (DK::RefuseNameBadChar, Lang::En) => { - "The name contains a slash, a backslash or a control character." + "The name contains a slash, a backslash, a control character or a hidden formatting character." } (DK::RefuseNameBadChar, Lang::Tr) => { - "Ad eğik çizgi, ters eğik çizgi ya da denetim karakteri içeriyor." + "Ad eğik çizgi, ters eğik çizgi, denetim karakteri ya da gizli biçimlendirme karakteri içeriyor." } (DK::RefuseCycle, Lang::En) => "A folder cannot be moved into itself.", (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 { (DK::RefuseNotInTrash, Lang::Tr) => "Bu öğe çöpte değil.", (DK::RefuseTooManyNames, Lang::En) => "Too many items already use this name.", (DK::RefuseTooManyNames, Lang::Tr) => "Bu adı kullanan çok fazla öğe var.", + (DK::RefuseFolderTooDeep, Lang::En) => "Folders cannot be nested any deeper.", + (DK::RefuseFolderTooDeep, Lang::Tr) => "Klasörler daha fazla iç içe olamaz.", (DK::RefuseGeneric, Lang::En) => "The change could not be made.", (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.", (DK::RefuseNoFile, Lang::En) => "Choose at least one file.", @@ -334,6 +338,7 @@ pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> { "cycle" => d(lang, DK::RefuseCycle), "not_in_trash" => d(lang, DK::RefuseNotInTrash), "too_many_names" => d(lang, DK::RefuseTooManyNames), + "folder_too_deep" => d(lang, DK::RefuseFolderTooDeep), "no_file" => d(lang, DK::RefuseNoFile), "generic" => d(lang, DK::RefuseGeneric), _ => return super::share::refusal_text(lang, word), diff --git a/crates/in-web/src/oidc.rs b/crates/in-web/src/oidc.rs index e9c497f..6a5073d 100644 --- a/crates/in-web/src/oidc.rs +++ b/crates/in-web/src/oidc.rs @@ -127,6 +127,8 @@ pub struct IdClaims { pub zoneinfo: String, /// Photo version; bumps when the photo changes. pub picture_version: i64, + /// When the token was issued, in Unix seconds. `check_iat` has already made sure it is present. + pub iat: i64, } /// The claims of a back-channel logout token that `in` uses. @@ -358,6 +360,10 @@ pub fn verify_id_token( zoneinfo: optional_text_claim(&claims, "zoneinfo") .unwrap_or("UTC") .to_owned(), + iat: claims + .get("iat") + .and_then(Value::as_i64) + .unwrap_or_default(), picture_version: claims .get("picture_version") .and_then(Value::as_i64) diff --git a/crates/in-web/src/pages/drive.rs b/crates/in-web/src/pages/drive.rs index 2ab3720..79cb8ac 100644 --- a/crates/in-web/src/pages/drive.rs +++ b/crates/in-web/src/pages/drive.rs @@ -599,13 +599,14 @@ async fn drive_live(cx: &Cx, query: Option>) -> Result if store.session_by_token_hash(&token_hash).await?.is_none() { return Err(not_found().into()); } - // A grant that was taken away ends the stream too, even though the folder still exists. + // A grant that was taken away ends the stream too, even though the folder still exists. The + // owner has no grant on their own folders, so only a shared folder is checked for one. if let Some(id) = folder.as_deref() { let access = store .access_of(&me, ItemKind::Folder, id) .await? .ok_or_else(not_found)?; - if access.trashed || access.grant == Grant::None { + if access.trashed || (access.grant == Grant::None && owner != me) { return Err(not_found().into()); } } diff --git a/crates/in-web/src/pages/files.rs b/crates/in-web/src/pages/files.rs index ffb29e0..aa21561 100644 --- a/crates/in-web/src/pages/files.rs +++ b/crates/in-web/src/pages/files.rs @@ -84,8 +84,10 @@ async fn read_text(field: &mut Field<'_>, cap: usize) -> Result { String::from_utf8(bytes).map_err(|_| bad_request("field is not UTF-8").into()) } -/// Streams one file part into the store. `Ok(Err(word))` is a refusal the person can read (the quota, the -/// size limit); `Err` is a server failure. Nothing is left behind on either path. +/// Streams one file part into the store. `claims` is the declared size of the owner's other open uploads, +/// which the quota must leave room for. The headroom is worked out before a byte is staged, so the disk +/// never takes more than the quota allows. `Ok(Err(word))` is a refusal the person can read (the quota, +/// the size limit); `Err` is a server failure. Nothing is left behind on either path. async fn store_one( state: &AppState, owner: &str, @@ -93,8 +95,14 @@ async fn store_one( client_name: &str, field: &mut Field<'_>, limit: u64, + claims: i64, ) -> Result> { - let mut staged = StagedFile::create(&state.config.data_dir, limit).await?; + let member = state.store.member(owner).await?.ok_or_else(not_found)?; + let room = quota::headroom(member.quota_bytes, member.used_bytes, claims); + let room_bytes = u64::try_from(room).unwrap_or(0); + // When the quota, not the per-file limit, is what stops the file, the refusal says so. + let quota_binds = room_bytes < limit; + let mut staged = StagedFile::create(&state.config.data_dir, limit.min(room_bytes)).await?; let mut prefix: Vec = Vec::with_capacity(SNIFF_BYTES); loop { let chunk = match field.chunk().await { @@ -112,6 +120,9 @@ async fn store_one( if let Err(error) = staged.write(&chunk).await { staged.abort().await; return match refusal_word(&error) { + Some(word) if quota_binds && word == "too_large" => { + Ok(Err("quota_exceeded".to_owned())) + } Some(word) => Ok(Err(word)), None => Err(error.into()), }; @@ -119,9 +130,7 @@ async fn store_one( } let Staged { path, size, sha256 } = staged.finish().await?; let size = i64::try_from(size).unwrap_or(i64::MAX); - // The quota is checked before the bytes move, so a refused file never reaches the blob store. - let member = state.store.member(owner).await?.ok_or_else(not_found)?; - let room = quota::headroom(member.quota_bytes, member.used_bytes, 0); + // The quota is checked again before the bytes move, so a refused file never reaches the blob store. if !quota::fits(size, room) { let _ = tokio::fs::remove_file(&path).await; return Ok(Err("quota_exceeded".to_owned())); @@ -140,7 +149,7 @@ async fn store_one( mime: sniff(&prefix), size, sha256, - staged_claims: 0, + staged_claims: claims, }; match state.store.insert_file(new).await { Ok(file) => Ok(Ok(file)), @@ -189,6 +198,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { folder = Some(optional_folder(state, owner, &folder_raw).await?); } let target = folder.clone().flatten(); + let claims = state.store.declared_claims_of(&owner.member.sub).await?; match store_one( state, &owner.member.sub, @@ -196,6 +206,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { &client_name, &mut field, limit, + claims, ) .await? { diff --git a/crates/in-web/src/pages/public_share.rs b/crates/in-web/src/pages/public_share.rs index dd70a62..7ab284e 100644 --- a/crates/in-web/src/pages/public_share.rs +++ b/crates/in-web/src/pages/public_share.rs @@ -50,6 +50,10 @@ const GATE_CSRF_COOKIE: &str = "__Host-in_precsrf"; /// How long a successful password keeps a visitor unlocked: twelve hours. const UNLOCK_HOURS: i64 = 12; +/// Longest password that is verified, in characters. A longer one is a wrong password without hashing, +/// so a huge submission costs nothing. The reason: no real share password comes near it. +const MAX_PASSWORD_CHARS: usize = 256; + /// The unlock cookie name of a link. It is scoped to the link's own path, so the name only needs the id. fn unlock_cookie_name(link_id: &str) -> String { format!("in_link_{link_id}") @@ -427,8 +431,9 @@ async fn public_page(cx: &Cx) -> Result { }) } -/// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie; a wrong one is counted -/// against the link and the client address. Both limits are checked before anything else. +/// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie. Every attempt is counted +/// against the link and the client address before it is verified, and a right one takes its count back; +/// so parallel guesses cannot all be verified together. Refused attempts are `429`. #[route(POST "/s/{token}")] async fn unlock(cx: &Cx, Form(form): Form) -> Result { let state = app_context::(cx); @@ -436,13 +441,6 @@ async fn unlock(cx: &Cx, Form(form): Form) -> Result { let token_hash = hash_token(&token); let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default(); let throttles = &state.throttles; - if let Some(wait) = throttles - .per_link - .blocked(&token_hash) - .or_else(|| throttles.per_ip.blocked(&ip)) - { - return Err(too_many_requests(wait).into()); - } let expected_csrf = cookie_value(cx, GATE_CSRF_COOKIE).unwrap_or_default(); if expected_csrf.is_empty() || !constant_time_eq(expected_csrf.as_bytes(), form.csrf.as_bytes()) { @@ -452,7 +450,18 @@ async fn unlock(cx: &Cx, Form(form): Form) -> Result { let Some(hash) = link.password_hash.clone() else { return Ok(see_other(format!("/s/{token}"))); }; - if verify_password_async(form.password, hash.clone()).await? { + if let Err(wait) = throttles.per_link.reserve(&token_hash) { + return Err(too_many_requests(wait).into()); + } + if let Err(wait) = throttles.per_ip.reserve(&ip) { + throttles.per_link.refund(&token_hash); + return Err(too_many_requests(wait).into()); + } + let verified = form.password.chars().count() <= MAX_PASSWORD_CHARS + && verify_password_async(form.password, hash.clone()).await?; + if verified { + throttles.per_link.refund(&token_hash); + throttles.per_ip.refund(&ip); let proof = unlock_proof(&state.key, &link.id, &hash); let cookie = Cookie::build((unlock_cookie_name(&link.id), proof)) .path(format!("/s/{token}")) @@ -464,8 +473,6 @@ async fn unlock(cx: &Cx, Form(form): Form) -> Result { cookies(cx).add(cookie); return Ok(see_other(format!("/s/{token}"))); } - throttles.per_link.failure(&token_hash); - throttles.per_ip.failure(&ip); Ok(see_other(format!("/s/{token}?wrong=1"))) } diff --git a/crates/in-web/src/pages/sign_in.rs b/crates/in-web/src/pages/sign_in.rs index 995d036..a1bddef 100644 --- a/crates/in-web/src/pages/sign_in.rs +++ b/crates/in-web/src/pages/sign_in.rs @@ -14,7 +14,7 @@ use in_core::error::{Error as CoreError, Result as CoreResult}; use in_core::secret; use in_core::store::members::MemberFields; use in_core::store::sessions::NewSession; -use in_core::time::stamp_after; +use in_core::time::{stamp_after, stamp_from_unix}; use in_core::token::{constant_time_eq, generate_token, hash_token}; use serde::{Deserialize, Serialize}; use topcoat::Result; @@ -201,8 +201,9 @@ async fn callback(cx: &Cx, query: Option>) -> Result, /// The switcher list of the family, refreshed by the family worker. pub family: Arc, + /// The bytes object writes may stage right now, per service. + pub staging: Arc, +} + +/// Bytes of object writes that are being staged, per service. A write reserves the bytes it may stage before +/// it reads its body, and the reservation ends when the write does. So parallel writes of one service cannot +/// stage more than the service's headroom together. +#[derive(Default)] +pub struct ObjectStaging { + /// Reserved bytes per service name. An entry is removed when its last reservation ends. + reserved: Mutex>, +} + +impl ObjectStaging { + /// Reserves `bytes` for `service`, when the reservations it already holds plus `bytes` stay within + /// `headroom`. The reservation ends when the guard is dropped. `None` when the budget is used up. + pub fn reserve( + self: &Arc, + service: &str, + bytes: u64, + headroom: u64, + ) -> Option { + let mut map = self.reserved.lock().unwrap_or_else(PoisonError::into_inner); + let held = map.get(service).copied().unwrap_or(0); + if held.saturating_add(bytes) > headroom { + return None; + } + map.insert(service.to_owned(), held.saturating_add(bytes)); + Some(StagingGuard { + staging: Arc::clone(self), + service: service.to_owned(), + bytes, + }) + } +} + +/// A reservation of [`ObjectStaging`]. Dropping it gives the bytes back, on success and on every failure. +pub struct StagingGuard { + staging: Arc, + service: String, + bytes: u64, +} + +impl Drop for StagingGuard { + fn drop(&mut self) { + let mut map = self + .staging + .reserved + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(held) = map.get_mut(&self.service) { + *held = held.saturating_sub(self.bytes); + if *held == 0 { + map.remove(&self.service); + } + } + } } diff --git a/crates/in-web/src/throttle.rs b/crates/in-web/src/throttle.rs index 2114d06..0fd5759 100644 --- a/crates/in-web/src/throttle.rs +++ b/crates/in-web/src/throttle.rs @@ -1,8 +1,9 @@ //! Failure throttling in memory: a sliding window of failures per key, with a bounded number of keys. //! -//! A check asks [`Throttle::blocked`] before any lookup and answers `429` with `Retry-After` when the key -//! has reached its limit. A failure is recorded with [`Throttle::failure`]. Nothing is persisted, so a -//! restart forgets the failures; that is accepted for a family instance and documented in the backlog. +//! An attempt first asks [`Throttle::reserve`], which counts it as a failure and answers `429` with +//! `Retry-After` when the key has reached its limit. A success gives the count back with +//! [`Throttle::refund`]. Check and count are one step, so parallel attempts cannot pass together. +//! Nothing is persisted, so a restart forgets the failures; that is accepted for a family instance and documented in the backlog. //! //! The key count is capped. When a new key would exceed the cap, the windows that have expired are //! dropped first, and then the key whose last failure is oldest. So an attacker who spreads guesses over @@ -48,34 +49,52 @@ impl Throttle { self.failures.lock().unwrap_or_else(PoisonError::into_inner) } - /// The seconds `key` must wait before it may try again, or `None` when it may try now. Only failures - /// inside the window count. - pub fn blocked(&self, key: &str) -> Option { + /// Counts one attempt of `key` now, before the attempt is made. The check and the record are one step, + /// so parallel attempts cannot all pass before any of them is counted. When the key already has `limit` + /// failures in the window, nothing is recorded and the seconds to wait come back (at least one). + /// + /// A reserved attempt counts as a failure until [`Throttle::refund`] takes it back, which a success does. + pub fn reserve(&self, key: &str) -> std::result::Result<(), u64> { let now = Instant::now(); let mut map = self.map(); - let stamps = map.get_mut(key)?; - stamps.retain(|at| now.duration_since(*at) < self.window); - if stamps.len() < self.limit { - return None; + if let Some(stamps) = map.get_mut(key) { + stamps.retain(|at| now.duration_since(*at) < self.window); + if stamps.len() >= self.limit { + return Err(self.wait_seconds(stamps, now)); + } + stamps.push(now); + return Ok(()); + } + if map.len() >= self.max_keys { + self.make_room(&mut map, now); } + map.entry(key.to_owned()).or_default().push(now); + Ok(()) + } + + /// Takes back the newest counted attempt of `key`, for an attempt that succeeded. + pub fn refund(&self, key: &str) { + let emptied = match self.map().get_mut(key) { + Some(stamps) => { + stamps.pop(); + stamps.is_empty() + } + None => false, + }; + if emptied { + self.map().remove(key); + } + } + + /// The seconds until the oldest failure that must leave the window before `key` may try again. Rounded + /// up, and at least one second, so `Retry-After` is never zero for a blocked key. + fn wait_seconds(&self, stamps: &[Instant], now: Instant) -> u64 { // The key may try again once enough failures have left the window: the one at this index is the // last to leave before the count drops below the limit. let index = stamps.len() - self.limit; let free_at = stamps[index] + self.window; let wait = free_at.saturating_duration_since(now); - // Rounded up, and at least one second, so `Retry-After` is never zero for a blocked key. - let seconds = wait.as_secs() + u64::from(wait.subsec_nanos() > 0); - Some(seconds.max(1)) - } - - /// Records one failure of `key` now. - pub fn failure(&self, key: &str) { - let now = Instant::now(); - let mut map = self.map(); - if !map.contains_key(key) && map.len() >= self.max_keys { - self.make_room(&mut map, now); - } - map.entry(key.to_owned()).or_default().push(now); + (wait.as_secs() + u64::from(wait.subsec_nanos() > 0)).max(1) } /// Frees one slot: expired windows go first, then the key with the oldest last failure. @@ -113,3 +132,33 @@ impl Default for ShareThrottles { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + /// Ten parallel wrong guesses against one link: only the limit of them is counted and admitted, and the + /// rest are refused with a wait. The check and the record are one step, so none can slip past. + #[test] + fn parallel_attempts_admit_no_more_than_the_limit() { + let throttle = Arc::new(Throttle::new( + PASSWORD_WINDOW, + LINK_PASSWORD_LIMIT, + MAX_KEYS, + )); + let handles: Vec<_> = (0..10) + .map(|_| { + let throttle = Arc::clone(&throttle); + std::thread::spawn(move || throttle.reserve("link").is_ok()) + }) + .collect(); + let admitted = handles + .into_iter() + .map(|handle| handle.join().expect("attempt thread")) + .filter(|ok| *ok) + .count(); + assert_eq!(admitted, LINK_PASSWORD_LIMIT); + assert!(throttle.reserve("link").is_err_and(|wait| wait >= 1)); + } +}