diff --git a/crates/in-core/src/blob/local.rs b/crates/in-core/src/blob/local.rs index 922e5f0..d5a5fa4 100644 --- a/crates/in-core/src/blob/local.rs +++ b/crates/in-core/src/blob/local.rs @@ -197,8 +197,9 @@ fn not_found_or_io(e: io::Error) -> Error { } } -/// Streams `remaining` bytes from `file`, one frame per read. Ends early when the file ends. A read -/// error is yielded once and then the stream ends. +/// Streams `remaining` bytes from `file`, one frame per read. A file that ends before `remaining` bytes are +/// read is an error (`UnexpectedEof`), so the body is aborted and the client sees a truncated transfer rather +/// than a short one that looks complete. A read error is yielded once and then the stream ends. fn read_frames( file: File, remaining: u64, @@ -217,7 +218,10 @@ fn read_frames( }) .await; match read { - Ok((_, _, Ok(0))) => None, + Ok((_, _, Ok(0))) => Some(( + Err(Error::Io(io::Error::from(io::ErrorKind::UnexpectedEof))), + None, + )), Ok((file, mut buf, Ok(n))) => { buf.truncate(n); let left = remaining - n as u64; diff --git a/crates/in-core/src/store/links.rs b/crates/in-core/src/store/links.rs index 6366f12..5db77a5 100644 --- a/crates/in-core/src/store/links.rs +++ b/crates/in-core/src/store/links.rs @@ -248,13 +248,17 @@ impl Store { finish(tx, outcome).await } - /// The link whose token hashes to `token_hash`, whatever its state. The caller decides whether it - /// still works. + /// The link whose token hashes to `token_hash`, whatever its state, unless its owner is disabled: such a + /// link does not resolve at all, and it resolves again once the owner is enabled. The caller decides + /// whether the link still works. pub async fn link_by_token_hash(&self, token_hash: &str) -> Result> { let conn = self.read_conn().await; fetch_opt( &conn, - &format!("SELECT {LINK_COLS} FROM links WHERE token_hash = ?1"), + &format!( + "SELECT {LINK_COLS} FROM links WHERE token_hash = ?1 \ + AND owner IN (SELECT sub FROM members WHERE disabled = 0)" + ), (token_hash.to_string(),), map_link, ) diff --git a/crates/in-core/src/store/shares.rs b/crates/in-core/src/store/shares.rs index e8624dd..d7aaa07 100644 --- a/crates/in-core/src/store/shares.rs +++ b/crates/in-core/src/store/shares.rs @@ -6,7 +6,8 @@ //! //! This module decides what the grants are and what reach they have ([`Access`]). Deciding what a viewer //! may do with the item stays in `authz`. A grantee must be a current member (not disabled) and not the -//! owner; both are checked when a grant is written. +//! owner; both are checked when a grant is written. A grant does not work while its owner is disabled: the +//! access check and the shared list both skip it, and the grant comes back when the owner is enabled again. use turso::{Connection, Row}; @@ -143,6 +144,24 @@ async fn trashed_state( Ok(Some((trashed, parent))) } +/// Whether the owner of the item is a current member (not disabled). A disabled owner's grants and links stop +/// working until the owner is enabled again, so nothing is deleted. `false` also when the item does not exist. +async fn owner_enabled(conn: &Connection, kind: ItemKind, id: &str) -> Result { + let sql = match kind { + ItemKind::File => { + "SELECT 1 FROM files WHERE id = ?1 AND owner IN (SELECT sub FROM members WHERE disabled = 0)" + } + ItemKind::Folder => { + "SELECT 1 FROM folders WHERE id = ?1 AND owner IN (SELECT sub FROM members WHERE disabled = 0)" + } + }; + Ok( + fetch_opt(conn, sql, (id.to_string(),), |row| col_int(row, 0)) + .await? + .is_some(), + ) +} + /// The folder ids from `start` up to the top level, `start` first. Empty for `None`. async fn chain_from(conn: &Connection, start: Option<&str>) -> Result> { let mut out = Vec::new(); @@ -181,7 +200,7 @@ async fn direct( } /// The access `grantee` has to an item: its own grant and the grants on every ancestor folder, the most -/// permissive one wins. `None` when the item does not exist. +/// permissive one wins. `None` when the item does not exist or its owner is disabled. pub(crate) async fn access_in( conn: &Connection, grantee: &str, @@ -191,6 +210,9 @@ pub(crate) async fn access_in( let Some((trashed, parent)) = trashed_state(conn, kind, id).await? else { return Ok(None); }; + if !owner_enabled(conn, kind, id).await? { + return Ok(None); + } let mut grant = Grant::None; if let Some(can_download) = direct(conn, grantee, kind, id).await? { grant = grant.max(level(can_download)); @@ -422,7 +444,10 @@ impl Store { else { continue; }; - if trashed || granted_above(&conn, grantee, parent.as_deref()).await? { + if trashed + || !owner_enabled(&conn, share.kind, &share.target_id).await? + || granted_above(&conn, grantee, parent.as_deref()).await? + { continue; } let (name, mime, size) = match share.kind { diff --git a/crates/in-core/src/store/trash.rs b/crates/in-core/src/store/trash.rs index 480ab63..d87428f 100644 --- a/crates/in-core/src/store/trash.rs +++ b/crates/in-core/src/store/trash.rs @@ -12,10 +12,16 @@ use crate::error::{Error, Result}; use crate::store::files::thumb_blob_key; use crate::store::files::{FILE_COLS, File, map_file}; use crate::store::folders::{FOLDER_COLS, Listing, has_trashed_chain, live_folder, map_folder}; -use crate::store::{Store, col_text, db_err, fetch_all, fetch_opt, finish, first_free_name}; +use crate::store::{ + Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, first_free_name, +}; use crate::time::now_stamp; use turso::Connection; +/// Most file rows one purge transaction removes. A large trash is purged over several transactions, and the +/// writer lock is released between them, so other writes are not blocked for the whole purge. +pub const PURGE_BATCH: usize = 500; + /// Which kind of item a trash operation names. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ItemKind { @@ -28,6 +34,23 @@ pub enum ItemKind { /// Removes a file row and everything that names it, and gives back its bytes in the quota. The blob keys /// are added to `keys` for deletion after commit. async fn purge_file_row(conn: &Connection, file: &File, keys: &mut Vec) -> Result<()> { + // The counter should never hold less than the bytes it counts. If it does, the clamp below hides it, so it + // is logged here; the nightly quota check corrects it. + let used = fetch_opt( + conn, + "SELECT used_bytes FROM members WHERE sub = ?1", + (file.owner.clone(),), + |row| col_int(row, 0), + ) + .await?; + if used.is_some_and(|used| used < file.size) { + tracing::warn!( + member = %file.owner, + used_bytes = used, + file_size = file.size, + "quota: used bytes below a purged file's size; clamped to zero" + ); + } conn.execute("DELETE FROM files WHERE id = ?1", (file.id.clone(),)) .await .map_err(db_err)?; @@ -54,14 +77,17 @@ async fn purge_file_row(conn: &Connection, file: &File, keys: &mut Vec) Ok(()) } -/// Permanently removes a trashed folder, its subtree, and the files in it. Children are removed before -/// their parents (deepest first), because the schema restricts deleting a parent that still has rows. +/// Permanently removes a trashed folder, its subtree, and the files in it, up to `budget` file rows. Children +/// are removed before their parents (deepest first), because the schema restricts deleting a parent that +/// still has rows. Returns `true` when the whole subtree is gone, and `false` when the budget ran out first; +/// the caller then runs it again in a new transaction. async fn purge_folder_rows( conn: &Connection, owner: &str, id: &str, keys: &mut Vec, -) -> Result<()> { + budget: &mut usize, +) -> Result { let root = fetch_opt( conn, &format!("SELECT {FOLDER_COLS} FROM folders WHERE id = ?1 AND owner = ?2"), @@ -88,16 +114,25 @@ async fn purge_folder_rows( next += 1; } for folder_id in order.iter().rev() { + if *budget == 0 { + return Ok(false); + } let files = fetch_all( conn, - &format!("SELECT {FILE_COLS} FROM files WHERE folder_id = ?1 AND owner = ?2"), - (folder_id.clone(), owner.to_string()), + &format!("SELECT {FILE_COLS} FROM files WHERE folder_id = ?1 AND owner = ?2 LIMIT ?3"), + (folder_id.clone(), owner.to_string(), *budget as i64), map_file, ) .await?; for file in &files { purge_file_row(conn, file, keys).await?; } + // A full batch may leave rows in this folder, so the folder waits for a later batch. + if files.len() == *budget { + *budget = 0; + return Ok(false); + } + *budget -= files.len(); // Uploads still in progress into this folder fall back to the top level. Finished ones are // history and go with the folder. conn.execute( @@ -128,7 +163,7 @@ async fn purge_folder_rows( .await .map_err(db_err)?; } - Ok(()) + Ok(true) } impl Store { @@ -341,48 +376,85 @@ impl Store { } /// Permanently deletes a trashed folder of `owner` with everything beneath it. Returns the blob keys - /// to delete after commit. + /// to delete. The purge runs in batches of at most [`PURGE_BATCH`] file rows, each committed on its own. pub async fn purge_folder(&self, owner: &str, id: &str) -> Result> { + let mut keys = Vec::new(); + loop { + let (batch, done) = self.purge_folder_batch(owner, id).await?; + keys.extend(batch); + if done { + return Ok(keys); + } + } + } + + /// One transaction of a folder purge. Returns the blob keys it released and whether the folder is gone. + async fn purge_folder_batch(&self, owner: &str, id: &str) -> Result<(Vec, bool)> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let mut keys = Vec::new(); - let outcome: Result<()> = purge_folder_rows(&tx, owner, id, &mut keys).await; - finish(tx, outcome).await?; - Ok(keys) + let mut budget = PURGE_BATCH; + let outcome: Result = purge_folder_rows(&tx, owner, id, &mut keys, &mut budget).await; + let done = finish(tx, outcome).await?; + Ok((keys, done)) } /// Permanently deletes everything `owner` has in the trash. Folder roots go first, which takes their - /// subtrees with them; the files left over are then purged. One transaction. + /// subtrees with them; the files left over are then purged. Each batch of at most [`PURGE_BATCH`] file + /// rows is its own transaction, so the writer lock is released between them. pub async fn empty_trash(&self, owner: &str) -> Result> { - let conn = self.inner.conn.lock().await; - let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let mut keys = Vec::new(); - let outcome: Result<()> = async { - let roots = fetch_all( - &tx, + let roots = { + let conn = self.read_conn().await; + fetch_all( + &conn, "SELECT id FROM folders WHERE owner = ?1 AND trashed_at IS NOT NULL AND trash_root IS NULL", (owner.to_string(),), |row| col_text(row, 0), ) - .await?; - for root in &roots { - purge_folder_rows(&tx, owner, root, &mut keys).await?; + .await? + }; + let mut keys = Vec::new(); + for root in &roots { + match self.purge_folder(owner, root).await { + Ok(released) => keys.extend(released), + // Removed by someone else since the list was read: nothing is left to purge. + Err(Error::NotFound) => {} + Err(error) => return Err(error), } + } + loop { + let (batch, done) = self.purge_loose_files_batch(owner).await?; + keys.extend(batch); + if done { + return Ok(keys); + } + } + } + + /// One transaction of [`Store::empty_trash`]: up to [`PURGE_BATCH`] trashed file rows of `owner`. Returns + /// the blob keys released and whether no trashed file is left. + async fn purge_loose_files_batch(&self, owner: &str) -> Result<(Vec, bool)> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let mut keys = Vec::new(); + let outcome: Result = async { let files = fetch_all( &tx, - &format!("SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND trashed_at IS NOT NULL"), - (owner.to_string(),), + &format!( + "SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND trashed_at IS NOT NULL LIMIT ?2" + ), + (owner.to_string(), PURGE_BATCH as i64), map_file, ) .await?; for file in &files { purge_file_row(&tx, file, &mut keys).await?; } - Ok(()) + Ok(files.len() < PURGE_BATCH) } .await; - finish(tx, outcome).await?; - Ok(keys) + let done = finish(tx, outcome).await?; + Ok((keys, done)) } /// Permanently deletes every trash root trashed before `cutoff` (a stamp), for every owner. Each diff --git a/crates/in-core/src/store/uploads.rs b/crates/in-core/src/store/uploads.rs index 5c30f18..b8d693c 100644 --- a/crates/in-core/src/store/uploads.rs +++ b/crates/in-core/src/store/uploads.rs @@ -129,6 +129,20 @@ impl Store { upload_of(&conn, owner, id).await } + /// Whether an upload with this id is still active. The sweeper keeps the staging directory of an active + /// upload whatever its age, because the upload may still receive chunks. + pub async fn upload_is_open(&self, id: &str) -> Result { + let conn = self.read_conn().await; + Ok(fetch_opt( + &conn, + "SELECT 1 FROM uploads WHERE id = ?1 AND state = 'active'", + (id.to_string(),), + |row| col_int(row, 0), + ) + .await? + .is_some()) + } + /// 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")`, diff --git a/crates/in-core/src/thumbs.rs b/crates/in-core/src/thumbs.rs index 1e46d88..df9607e 100644 --- a/crates/in-core/src/thumbs.rs +++ b/crates/in-core/src/thumbs.rs @@ -20,7 +20,8 @@ pub const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; /// Largest width or height the decoder accepts, in pixels: 10000 by 10000 is 100 megapixels. pub const MAX_DIMENSION: u32 = 10_000; -/// Most memory the decoder may allocate for one picture: 256 MiB. +/// Most memory the decoder may allocate for one picture: 256 MiB. The thumbnail worker decodes one picture at a +/// time, so this and [`MAX_SOURCE_BYTES`] bound its peak. pub const MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024; /// The formats that get thumbnails. Anything else is not decoded. diff --git a/crates/in-web/src/api/upload.rs b/crates/in-web/src/api/upload.rs index b973db4..2c07d26 100644 --- a/crates/in-web/src/api/upload.rs +++ b/crates/in-web/src/api/upload.rs @@ -400,9 +400,24 @@ async fn finish_upload(cx: &Cx) -> Result { let mut prefix = Vec::with_capacity(SNIFF_BYTES); if let Err(error) = join_chunks(&dir, count, &mut staged, &mut prefix).await { staged.abort().await; + // A concurrent finish of this upload may have removed the chunks already. That is a conflict. + if matches!(&error, CoreError::Io(e) if e.kind() == std::io::ErrorKind::NotFound) { + return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); + } return Err(error.into()); } - let Staged { path, sha256, .. } = staged.finish().await?; + let Staged { + path, + sha256, + size: measured, + } = staged.finish().await?; + // The row records the bytes that were joined. Chunks of the declared length that hold other bytes are + // refused here, not recorded with the declared size. + if measured != size { + let _ = tokio::fs::remove_file(&path).await; + return Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer()); + } + let recorded = i64::try_from(measured).map_err(|_| CoreError::Invalid("too_large".into()))?; // The bytes are durable at their key before the row that names them commits (architecture 3). let file_id = new_id(); @@ -417,7 +432,7 @@ async fn finish_upload(cx: &Cx) -> Result { folder: upload.folder_id.clone(), name: upload.name.clone(), mime: sniff(&prefix), - size: upload.size, + size: recorded, sha256, staged_claims: 0, }; diff --git a/crates/in-web/src/live.rs b/crates/in-web/src/live.rs index 9d8fea9..b942900 100644 --- a/crates/in-web/src/live.rs +++ b/crates/in-web/src/live.rs @@ -31,6 +31,11 @@ pub const STREAM_RETRY: Duration = Duration::from_millis(1000); /// Silence after which the server sends a keep-alive comment, so proxies keep the stream open. pub const KEEP_ALIVE: Duration = Duration::from_secs(30); +/// How often an idle `changed` stream checks its viewer anyway, so a viewer who signed out or lost access is +/// noticed even when nothing the stream follows changes. +const RECHECK: Duration = Duration::from_secs(15); +/// The longest a `changed` stream lives. The browser then reconnects and is checked again from the start. +const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60); /// What a live page follows. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Topic { @@ -118,9 +123,16 @@ where fingerprint, last, }; - let events = stream::unfold(follow, |mut follow| async move { + let until = tokio::time::Instant::now() + MAX_STREAM_LIFE; + let events = stream::unfold(follow, move |mut follow| async move { loop { - if !wait_any(&mut follow.wakes).await { + // A tick runs the fingerprint too: it is where the viewer is checked again. + let woke = tokio::select! { + woke = wait_any(&mut follow.wakes) => woke, + () = tokio::time::sleep(RECHECK) => true, + () = tokio::time::sleep_until(until) => false, + }; + if !woke { return None; } match (follow.fingerprint)().await { diff --git a/crates/in-web/src/pages/public_share.rs b/crates/in-web/src/pages/public_share.rs index 7ab284e..bb20ed9 100644 --- a/crates/in-web/src/pages/public_share.rs +++ b/crates/in-web/src/pages/public_share.rs @@ -5,12 +5,17 @@ //! inside it; a `?folder=` or `?file=` outside the linked root is `404`, as is any unknown, revoked, //! expired or trashed link, all alike. A link with a password shows a gate until the visitor posts the //! right one. The unlock cookie is HMAC-keyed to the link and its password hash, so a changed password -//! locks everyone out again. Wrong passwords are throttled per link and per client address (see -//! `throttle.rs`); the sixth wrong one within the window is `429`. +//! locks everyone out again. Wrong passwords are throttled per link (100 in the window, for everyone) and per +//! link and client address (10 in the window); see `throttle.rs`. Refused attempts are `429`. +//! +//! A link does not work while its owner is disabled: the owner's items are not served through it, and it +//! works again when the owner is enabled. //! //! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` -//! and `X-Robots-Tag: noindex` (set in `security.rs`). +//! and `X-Robots-Tag: noindex` (set in `security.rs`), and `Cache-Control: no-store`. +use http::HeaderValue; +use http::header::CACHE_CONTROL; use in_core::authz::{Action, Actor, Grant, Target, authorize}; use in_core::password::verify_password_async; use in_core::secret::unlock_proof; @@ -28,6 +33,7 @@ use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, forbidden, not_found, see_other, too_many_requests}; use topcoat::router::request::{client_ip, headers}; +use topcoat::router::response::response_headers; use topcoat::router::{page, parse_query_params, path_param_segment, route}; use topcoat::view::{View, component, view}; @@ -59,8 +65,14 @@ fn unlock_cookie_name(link_id: &str) -> String { format!("in_link_{link_id}") } +/// Marks a share page as uncacheable. A shared proxy or the browser's back-forward cache must not keep a page +/// that shows a listing or a password gate. Set before the lookup, so the `404` for a dead link carries it too. +fn no_store(cx: &Cx) { + response_headers(cx).append(CACHE_CONTROL, HeaderValue::from_static("no-store")); +} + /// The link of a token, when it is live and its target is not in the trash. Every other case is `404`, so -/// an unknown token and a dead one cannot be told apart. +/// an unknown token and a dead one cannot be told apart. A link whose owner is disabled is unknown here. async fn live_link(state: &AppState, token: &str) -> Result { let link = state .store @@ -408,6 +420,7 @@ async fn content_panel( /// `GET /s/{token}`: the public page of a link, or its password gate. #[page("/s/{token}")] async fn public_page(cx: &Cx) -> Result { + no_store(cx); let state = app_context::(cx); let token = path_param_segment(cx, "token").to_owned(); let link = live_link(state, &token).await?; @@ -432,14 +445,16 @@ async fn public_page(cx: &Cx) -> Result { } /// `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`. +/// against the link and against the link and 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 { + no_store(cx); let state = app_context::(cx); let token = path_param_segment(cx, "token").to_owned(); let token_hash = hash_token(&token); let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default(); + let visitor = format!("{token_hash}:{ip}"); let throttles = &state.throttles; 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()) @@ -453,7 +468,7 @@ async fn unlock(cx: &Cx, Form(form): Form) -> Result { 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) { + if let Err(wait) = throttles.per_visitor.reserve(&visitor) { throttles.per_link.refund(&token_hash); return Err(too_many_requests(wait).into()); } @@ -461,7 +476,7 @@ async fn unlock(cx: &Cx, Form(form): Form) -> Result { && verify_password_async(form.password, hash.clone()).await?; if verified { throttles.per_link.refund(&token_hash); - throttles.per_ip.refund(&ip); + throttles.per_visitor.refund(&visitor); let proof = unlock_proof(&state.key, &link.id, &hash); let cookie = Cookie::build((unlock_cookie_name(&link.id), proof)) .path(format!("/s/{token}")) @@ -674,9 +689,9 @@ mod tests { assert_eq!(get(&state, &format!("/s/{token}")).await, 404); } - /// Five wrong passwords are answered with a redirect; the sixth within the window is `429`. + /// Ten wrong passwords from one visitor are answered with a redirect; the eleventh within the window is `429`. #[tokio::test] - async fn the_sixth_wrong_password_is_throttled() { + async fn the_eleventh_wrong_password_from_one_visitor_is_throttled() { let (_dir, state) = test_state().await; let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; let trips = state @@ -687,7 +702,7 @@ mod tests { let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, Some("right")).await; let path = format!("/s/{token}"); let mut statuses = Vec::new(); - for _ in 0..6 { + for _ in 0..11 { let request = Request::post(path.as_str()) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .header(COOKIE, format!("{GATE_CSRF_COOKIE}=tok")) @@ -696,7 +711,9 @@ mod tests { let response = router(state.clone()).handle(request).await; statuses.push(response.status().as_u16()); } - assert_eq!(statuses, vec![303, 303, 303, 303, 303, 429]); + let mut expected = vec![303; 10]; + expected.push(429); + assert_eq!(statuses, expected); } /// A file link answers the file's bytes only with the unlock cookie of a password-protected link. diff --git a/crates/in-web/src/sweeper.rs b/crates/in-web/src/sweeper.rs index c77252d..2ae9849 100644 --- a/crates/in-web/src/sweeper.rs +++ b/crates/in-web/src/sweeper.rs @@ -3,6 +3,9 @@ //! //! - sessions past their expiry, back-channel logout ids past their expiry, and open uploads not finished in //! 24 hours, with their staging directories; +//! - staging directories under `data_dir/uploads` that no open upload names and that are at least 24 hours old. +//! This is what retries a removal that failed earlier: the expiry step has already deleted the row; +//! the directory is the only record left; //! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; //! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; //! - leftover files in `data_dir/tmp` at least 24 hours old; @@ -18,7 +21,7 @@ use std::path::Path; use std::time::{Duration, SystemTime}; use in_core::error::Result; -use in_core::staging::{TMP_DIR, remove_upload_dir}; +use in_core::staging::{TMP_DIR, UPLOADS_DIR, remove_upload_dir, upload_dir}; use in_core::time::{now_stamp, stamp_before}; use tokio::sync::watch; @@ -70,6 +73,10 @@ pub async fn sweep(state: &AppState) -> Result<()> { expired_uploads = uploads.len(), "sweeper: pass done" ); + log_step( + "upload dirs", + sweep_upload_dirs(state, SystemTime::now()).await, + ); log_step("trash", purge_trash(state).await); log_step("blobs", sweep_blobs(state, SystemTime::now()).await); log_step( @@ -155,6 +162,56 @@ pub async fn sweep_blobs(state: &AppState, now: SystemTime) -> Result { Ok(removed) } +/// Removes the staging directories under `data_dir/uploads` that no open upload names and that are at least +/// [`ORPHAN_GRACE`] old, as of `now`. Only a direct child of that directory whose name is a well-formed upload +/// id is removed; symbolic links and other entries are left alone. +pub async fn sweep_upload_dirs(state: &AppState, now: SystemTime) -> Result { + let root = state.config.data_dir.join(UPLOADS_DIR); + let mut entries = match tokio::fs::read_dir(&root).await { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(error) => return Err(error.into()), + }; + let mut removed = 0; + while let Some(entry) = entries.next_entry().await? { + let Some(id) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + // `upload_dir` accepts only a well-formed upload id, and the path must be a direct child of the root. + let Ok(dir) = upload_dir(&state.config.data_dir, &id) else { + continue; + }; + if dir.parent() != Some(root.as_path()) { + continue; + } + let Ok(meta) = tokio::fs::symlink_metadata(&dir).await else { + continue; + }; + if !meta.is_dir() { + continue; + } + let Ok(modified) = meta.modified() else { + continue; + }; + if !is_old(modified, now) || state.store.upload_is_open(&id).await? { + continue; + } + match remove_upload_dir(&state.config.data_dir, &id).await { + Ok(()) => removed += 1, + Err(error) => { + tracing::warn!(upload = %id, error = %error, "sweeper: staging directory not removed"); + } + } + } + if removed > 0 { + tracing::info!( + staging_dirs = removed, + "sweeper: staging directories removed" + ); + } + Ok(removed) +} + /// Removes the plain files in `data_dir/tmp` that are at least [`ORPHAN_GRACE`] old. Links are never followed, /// and only regular files are removed. The directory is the fixed staging directory of the data directory. pub async fn sweep_tmp(data_dir: &Path, now: SystemTime) -> Result { diff --git a/crates/in-web/src/throttle.rs b/crates/in-web/src/throttle.rs index 0fd5759..281dcbd 100644 --- a/crates/in-web/src/throttle.rs +++ b/crates/in-web/src/throttle.rs @@ -16,11 +16,13 @@ use std::time::{Duration, Instant}; /// Length of the sliding window for share-link passwords: 15 minutes. pub const PASSWORD_WINDOW: Duration = Duration::from_secs(15 * 60); -/// Failed password attempts allowed against one link in a window. The sixth is refused with `429`. -pub const LINK_PASSWORD_LIMIT: usize = 5; +/// Failed password attempts allowed against one link in a window, from all visitors together. This is a +/// ceiling: it stops guesses spread over many addresses. The 101st is refused with `429`. +pub const LINK_PASSWORD_LIMIT: usize = 100; -/// Failed password attempts allowed from one client address in a window, across all links. -pub const IP_PASSWORD_LIMIT: usize = 10; +/// Failed password attempts allowed from one client address against one link in a window. The eleventh is +/// refused with `429`. Other visitors of the same link have their own count. +pub const VISITOR_PASSWORD_LIMIT: usize = 10; /// Most keys held at once. Each key is a short string and a short list of instants. pub const MAX_KEYS: usize = 10_000; @@ -116,19 +118,20 @@ impl Throttle { } } -/// The two throttles of share-link passwords: one per link (by token hash) and one per client address. +/// The two throttles of share-link passwords: one per link (by token hash), and one per link and client +/// address (the key is the token hash, a colon, and the address). pub struct ShareThrottles { - /// Failures per link. + /// Failures per link, from all visitors. pub per_link: Throttle, - /// Failures per client address. - pub per_ip: Throttle, + /// Failures per link and client address. + pub per_visitor: Throttle, } impl Default for ShareThrottles { fn default() -> Self { Self { per_link: Throttle::new(PASSWORD_WINDOW, LINK_PASSWORD_LIMIT, MAX_KEYS), - per_ip: Throttle::new(PASSWORD_WINDOW, IP_PASSWORD_LIMIT, MAX_KEYS), + per_visitor: Throttle::new(PASSWORD_WINDOW, VISITOR_PASSWORD_LIMIT, MAX_KEYS), } } } @@ -138,15 +141,13 @@ 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. + /// Ten parallel wrong guesses against one key with a limit of five: 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, - )); + const LIMIT: usize = 5; + let throttle = Arc::new(Throttle::new(PASSWORD_WINDOW, LIMIT, MAX_KEYS)); let handles: Vec<_> = (0..10) .map(|_| { let throttle = Arc::clone(&throttle); @@ -158,7 +159,7 @@ mod tests { .map(|handle| handle.join().expect("attempt thread")) .filter(|ok| *ok) .count(); - assert_eq!(admitted, LINK_PASSWORD_LIMIT); + assert_eq!(admitted, LIMIT); assert!(throttle.reserve("link").is_err_and(|wait| wait >= 1)); } } diff --git a/crates/in-web/src/thumbs_worker.rs b/crates/in-web/src/thumbs_worker.rs index 79aeb4f..18a979c 100644 --- a/crates/in-web/src/thumbs_worker.rs +++ b/crates/in-web/src/thumbs_worker.rs @@ -7,6 +7,7 @@ //! thumbnail was made, the row update finds nothing and the stored bytes are deleted, so no row is left //! without its file. +use std::sync::{Arc, LazyLock}; use std::time::Duration; use futures_util::{StreamExt, stream}; @@ -14,7 +15,7 @@ use in_core::error::{Error, Result}; use in_core::staging::{Staged, StagedFile}; use in_core::store::files::{File, thumb_blob_key}; use in_core::thumbs::{MAX_SOURCE_BYTES, make_thumbnail}; -use tokio::sync::watch; +use tokio::sync::{Semaphore, watch}; use crate::live::Topic; use crate::state::AppState; @@ -22,8 +23,19 @@ use crate::state::AppState; /// Most files taken from the queue in one round. pub const BATCH: usize = 16; -/// Most thumbnails made at the same time. -pub const CONCURRENCY: usize = 2; +/// Most thumbnails made at the same time. One, because a decode may hold a whole source picture +/// ([`MAX_SOURCE_BYTES`], 64 MiB) and its decoder buffers ([`in_core::thumbs::MAX_ALLOC_BYTES`], 256 MiB); two +/// together could reach about 640 MiB. One keeps the peak near 320 MiB. +pub const CONCURRENCY: usize = 1; + +/// Longest a decode may run before its file is marked `failed`: ten seconds. +pub const DECODE_TIMEOUT: Duration = Duration::from_secs(10); + +/// The decode slots. A slot is moved into the blocking decode, so it is released when the decoder returns, +/// not when the caller stops waiting. A timed-out decode that still runs keeps its slot, and no other decode +/// starts beside it, so stragglers cannot pile up. +static DECODE_SLOTS: LazyLock> = + LazyLock::new(|| Arc::new(Semaphore::new(CONCURRENCY))); /// How long the worker waits when the queue is empty before it looks again. pub const IDLE: Duration = Duration::from_secs(30); @@ -91,10 +103,21 @@ async fn build(state: &AppState, file: &File) -> Result<()> { return Err(Error::Invalid("too_large".into())); } let source = read_source(state, file, size).await?; - // The decoder is CPU work: it runs on a blocking thread, never on the async runtime. - let webp = tokio::task::spawn_blocking(move || make_thumbnail(&source)) + let slot = Arc::clone(&DECODE_SLOTS) + .acquire_owned() .await - .map_err(|e| Error::Io(std::io::Error::other(e)))??; + .map_err(|e| Error::Io(std::io::Error::other(e)))?; + // The decoder is CPU work: it runs on a blocking thread, never on the async runtime. + let decode = tokio::task::spawn_blocking(move || { + let _slot = slot; + make_thumbnail(&source) + }); + let webp = match tokio::time::timeout(DECODE_TIMEOUT, decode).await { + Ok(joined) => joined.map_err(|e| Error::Io(std::io::Error::other(e)))??, + // A blocking task cannot be stopped. Its result is dropped with the handle, and its slot is held + // until it returns. + Err(_) => return Err(Error::Invalid("decode_timeout".into())), + }; let mut staged = StagedFile::create(&state.config.data_dir, MAX_THUMB_BYTES).await?; if let Err(error) = staged.write(&webp).await { staged.abort().await; diff --git a/docs/architecture.md b/docs/architecture.md index 65f1368..dc303cc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,7 +45,7 @@ in/ - `blob/`: `mod.rs` (`BlobStore` trait: `put_stream`, `adopt_file`, `open_range`, `size`, `delete`, `list`), `local.rs` (temp file + fsync + rename + dir fsync), `s3.rs` (`object_store` S3 client for R2, Hetzner Object Storage or any S3 endpoint; multipart for large objects) -- `thumbs.rs`: images with the `image` crate (decode limits: 64 MiB source, 40 megapixels, 10 s on +- `thumbs.rs`: images with the `image` crate (decode limits: 64 MiB source, 10000 px per side and 256 MiB decoded, 10 s on `spawn_blocking`), video through `ffmpeg` when present (10 s kill, temp file in `data_dir/tmp` mode 0600), WebP output, max edge 512 - `store/`: `users.rs` (local mirror of members), `sessions.rs`, `folders.rs`, `files.rs`, `trash.rs`, @@ -202,10 +202,13 @@ and has no sessions. - Token: 32 random bytes; DB stores the SHA-256 and a sealed copy for the owner to re-display. - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none). -- Password gate: POST checks the password (throttled per link and per IP: 10 failures / 15 min) and sets a cookie +- Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and + per link and client address: 10 failures / 15 min) and sets a cookie `__Host-in_link_` = HMAC-SHA256(instance key, "link-unlock:" || link id || password_hash), 12 h, so changing the password or remint invalidates old unlocks. -- Dead links (revoked, expired, target trashed or purged) answer one identical "link no longer works" page. +- Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer + works" page. A disabled owner's links and grants stop working at once and are not deleted: enabling the owner + again restores them. - Remint creates the new link and revokes the old one in one transaction. --- @@ -215,8 +218,10 @@ and has no sessions. - **directory**: full fetch, then stream (contracts.md 3), resync on gap; applies member changes; on `disabled` or `deleted` ends the person's sessions. Backoff 1 s → 30 s. - **family**: fetches the switcher list every 5 minutes. -- **thumbs**: picks `pending` files, generates thumbnails with bounded concurrency (2), marks ready/failed. -- **sweeper** (hourly): expired sessions, expired uploads (staging removed), seen JTIs, trash past +- **thumbs**: picks `pending` files, generates thumbnails one at a time (see `thumbs_worker.rs` for why), with a + 10 s limit per decode, marks ready/failed. A decode that outlives its limit keeps its slot until it returns. +- **sweeper** (hourly): expired sessions, expired uploads, staging directories that no open upload names (24 h old, + which retries failed removals), seen JTIs, trash past `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly). - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from `in.key`, checked before a restore parses anything), keep N, dead-man pings.