Disabled owners' links and grants stop serving, thumbnail timeout and one decoder, no-store share pages, batched purge, truncated bodies abort, measured upload size, finish race answers 409, stale staging swept, per-link and per-visitor password throttle, idle live re-check
Browse files at this commit72a986d33adc7d6dd1c44ee1bc2beef819465504Parent: f94f61e- fix
- disabled owners' links and grants stop serving, thumbnail timeout and one decoder, no-store share pages, batched purge, truncated bodies abort, measured upload size, finish race answers 409, stale staging swept, per-link and per-visitor password throttle, idle live re-check
13 changed files +331 -81
- crates/in-core/src/blob/local.rs +7 -3
- crates/in-core/src/store/links.rs +7 -3
- crates/in-core/src/store/shares.rs +28 -3
- crates/in-core/src/store/trash.rs +98 -26
- crates/in-core/src/store/uploads.rs +14 -0
- crates/in-core/src/thumbs.rs +2 -1
- crates/in-web/src/api/upload.rs +17 -2
- crates/in-web/src/live.rs +14 -2
- crates/in-web/src/pages/public_share.rs +29 -12
- crates/in-web/src/sweeper.rs +58 -1
- crates/in-web/src/throttle.rs +18 -17
- crates/in-web/src/thumbs_worker.rs +29 -6
- docs/architecture.md +10 -5
crates/in-core/src/blob/local.rsmodified+7 -3
| @@ -197,8 +197,9 @@ fn not_found_or_io(e: io::Error) -> Error { | |||
| 197 | } | 197 | } |
| 198 | } | 198 | } |
| 199 | 199 | ||
| 200 | -/// Streams `remaining` bytes from `file`, one frame per read. Ends early when the file ends. A read | 200 | +/// Streams `remaining` bytes from `file`, one frame per read. A file that ends before `remaining` bytes are |
| 201 | -/// error is yielded once and then the stream ends. | 201 | +/// read is an error (`UnexpectedEof`), so the body is aborted and the client sees a truncated transfer rather |
| 202 | +/// than a short one that looks complete. A read error is yielded once and then the stream ends. | ||
| 202 | fn read_frames( | 203 | fn read_frames( |
| 203 | file: File, | 204 | file: File, |
| 204 | remaining: u64, | 205 | remaining: u64, |
| @@ -217,7 +218,10 @@ fn read_frames( | |||
| 217 | }) | 218 | }) |
| 218 | .await; | 219 | .await; |
| 219 | match read { | 220 | match read { |
| 220 | - Ok((_, _, Ok(0))) => None, | 221 | + Ok((_, _, Ok(0))) => Some(( |
| 222 | + Err(Error::Io(io::Error::from(io::ErrorKind::UnexpectedEof))), | ||
| 223 | + None, | ||
| 224 | + )), | ||
| 221 | Ok((file, mut buf, Ok(n))) => { | 225 | Ok((file, mut buf, Ok(n))) => { |
| 222 | buf.truncate(n); | 226 | buf.truncate(n); |
| 223 | let left = remaining - n as u64; | 227 | let left = remaining - n as u64; |
crates/in-core/src/store/links.rsmodified+7 -3
| @@ -248,13 +248,17 @@ impl Store { | |||
| 248 | finish(tx, outcome).await | 248 | finish(tx, outcome).await |
| 249 | } | 249 | } |
| 250 | 250 | ||
| 251 | - /// The link whose token hashes to `token_hash`, whatever its state. The caller decides whether it | 251 | + /// The link whose token hashes to `token_hash`, whatever its state, unless its owner is disabled: such a |
| 252 | - /// still works. | 252 | + /// link does not resolve at all, and it resolves again once the owner is enabled. The caller decides |
| 253 | + /// whether the link still works. | ||
| 253 | pub async fn link_by_token_hash(&self, token_hash: &str) -> Result<Option<Link>> { | 254 | pub async fn link_by_token_hash(&self, token_hash: &str) -> Result<Option<Link>> { |
| 254 | let conn = self.read_conn().await; | 255 | let conn = self.read_conn().await; |
| 255 | fetch_opt( | 256 | fetch_opt( |
| 256 | &conn, | 257 | &conn, |
| 257 | - &format!("SELECT {LINK_COLS} FROM links WHERE token_hash = ?1"), | 258 | + &format!( |
| 259 | + "SELECT {LINK_COLS} FROM links WHERE token_hash = ?1 \ | ||
| 260 | + AND owner IN (SELECT sub FROM members WHERE disabled = 0)" | ||
| 261 | + ), | ||
| 258 | (token_hash.to_string(),), | 262 | (token_hash.to_string(),), |
| 259 | map_link, | 263 | map_link, |
| 260 | ) | 264 | ) |
crates/in-core/src/store/shares.rsmodified+28 -3
| @@ -6,7 +6,8 @@ | |||
| 6 | //! | 6 | //! |
| 7 | //! This module decides what the grants are and what reach they have ([`Access`]). Deciding what a viewer | 7 | //! This module decides what the grants are and what reach they have ([`Access`]). Deciding what a viewer |
| 8 | //! may do with the item stays in `authz`. A grantee must be a current member (not disabled) and not the | 8 | //! may do with the item stays in `authz`. A grantee must be a current member (not disabled) and not the |
| 9 | -//! owner; both are checked when a grant is written. | 9 | +//! owner; both are checked when a grant is written. A grant does not work while its owner is disabled: the |
| 10 | +//! access check and the shared list both skip it, and the grant comes back when the owner is enabled again. | ||
| 10 | 11 | ||
| 11 | use turso::{Connection, Row}; | 12 | use turso::{Connection, Row}; |
| 12 | 13 | ||
| @@ -143,6 +144,24 @@ async fn trashed_state( | |||
| 143 | Ok(Some((trashed, parent))) | 144 | Ok(Some((trashed, parent))) |
| 144 | } | 145 | } |
| 145 | 146 | ||
| 147 | +/// Whether the owner of the item is a current member (not disabled). A disabled owner's grants and links stop | ||
| 148 | +/// working until the owner is enabled again, so nothing is deleted. `false` also when the item does not exist. | ||
| 149 | +async fn owner_enabled(conn: &Connection, kind: ItemKind, id: &str) -> Result<bool> { | ||
| 150 | + let sql = match kind { | ||
| 151 | + ItemKind::File => { | ||
| 152 | + "SELECT 1 FROM files WHERE id = ?1 AND owner IN (SELECT sub FROM members WHERE disabled = 0)" | ||
| 153 | + } | ||
| 154 | + ItemKind::Folder => { | ||
| 155 | + "SELECT 1 FROM folders WHERE id = ?1 AND owner IN (SELECT sub FROM members WHERE disabled = 0)" | ||
| 156 | + } | ||
| 157 | + }; | ||
| 158 | + Ok( | ||
| 159 | + fetch_opt(conn, sql, (id.to_string(),), |row| col_int(row, 0)) | ||
| 160 | + .await? | ||
| 161 | + .is_some(), | ||
| 162 | + ) | ||
| 163 | +} | ||
| 164 | + | ||
| 146 | /// The folder ids from `start` up to the top level, `start` first. Empty for `None`. | 165 | /// The folder ids from `start` up to the top level, `start` first. Empty for `None`. |
| 147 | async fn chain_from(conn: &Connection, start: Option<&str>) -> Result<Vec<String>> { | 166 | async fn chain_from(conn: &Connection, start: Option<&str>) -> Result<Vec<String>> { |
| 148 | let mut out = Vec::new(); | 167 | let mut out = Vec::new(); |
| @@ -181,7 +200,7 @@ async fn direct( | |||
| 181 | } | 200 | } |
| 182 | 201 | ||
| 183 | /// The access `grantee` has to an item: its own grant and the grants on every ancestor folder, the most | 202 | /// The access `grantee` has to an item: its own grant and the grants on every ancestor folder, the most |
| 184 | -/// permissive one wins. `None` when the item does not exist. | 203 | +/// permissive one wins. `None` when the item does not exist or its owner is disabled. |
| 185 | pub(crate) async fn access_in( | 204 | pub(crate) async fn access_in( |
| 186 | conn: &Connection, | 205 | conn: &Connection, |
| 187 | grantee: &str, | 206 | grantee: &str, |
| @@ -191,6 +210,9 @@ pub(crate) async fn access_in( | |||
| 191 | let Some((trashed, parent)) = trashed_state(conn, kind, id).await? else { | 210 | let Some((trashed, parent)) = trashed_state(conn, kind, id).await? else { |
| 192 | return Ok(None); | 211 | return Ok(None); |
| 193 | }; | 212 | }; |
| 213 | + if !owner_enabled(conn, kind, id).await? { | ||
| 214 | + return Ok(None); | ||
| 215 | + } | ||
| 194 | let mut grant = Grant::None; | 216 | let mut grant = Grant::None; |
| 195 | if let Some(can_download) = direct(conn, grantee, kind, id).await? { | 217 | if let Some(can_download) = direct(conn, grantee, kind, id).await? { |
| 196 | grant = grant.max(level(can_download)); | 218 | grant = grant.max(level(can_download)); |
| @@ -422,7 +444,10 @@ impl Store { | |||
| 422 | else { | 444 | else { |
| 423 | continue; | 445 | continue; |
| 424 | }; | 446 | }; |
| 425 | - if trashed || granted_above(&conn, grantee, parent.as_deref()).await? { | 447 | + if trashed |
| 448 | + || !owner_enabled(&conn, share.kind, &share.target_id).await? | ||
| 449 | + || granted_above(&conn, grantee, parent.as_deref()).await? | ||
| 450 | + { | ||
| 426 | continue; | 451 | continue; |
| 427 | } | 452 | } |
| 428 | let (name, mime, size) = match share.kind { | 453 | let (name, mime, size) = match share.kind { |
crates/in-core/src/store/trash.rsmodified+98 -26
| @@ -12,10 +12,16 @@ use crate::error::{Error, Result}; | |||
| 12 | use crate::store::files::thumb_blob_key; | 12 | use crate::store::files::thumb_blob_key; |
| 13 | use crate::store::files::{FILE_COLS, File, map_file}; | 13 | use crate::store::files::{FILE_COLS, File, map_file}; |
| 14 | use crate::store::folders::{FOLDER_COLS, Listing, has_trashed_chain, live_folder, map_folder}; | 14 | use crate::store::folders::{FOLDER_COLS, Listing, has_trashed_chain, live_folder, map_folder}; |
| 15 | -use crate::store::{Store, col_text, db_err, fetch_all, fetch_opt, finish, first_free_name}; | 15 | +use crate::store::{ |
| 16 | + Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, first_free_name, | ||
| 17 | +}; | ||
| 16 | use crate::time::now_stamp; | 18 | use crate::time::now_stamp; |
| 17 | use turso::Connection; | 19 | use turso::Connection; |
| 18 | 20 | ||
| 21 | +/// Most file rows one purge transaction removes. A large trash is purged over several transactions, and the | ||
| 22 | +/// writer lock is released between them, so other writes are not blocked for the whole purge. | ||
| 23 | +pub const PURGE_BATCH: usize = 500; | ||
| 24 | + | ||
| 19 | /// Which kind of item a trash operation names. | 25 | /// Which kind of item a trash operation names. |
| 20 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 26 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 21 | pub enum ItemKind { | 27 | pub enum ItemKind { |
| @@ -28,6 +34,23 @@ pub enum ItemKind { | |||
| 28 | /// Removes a file row and everything that names it, and gives back its bytes in the quota. The blob keys | 34 | /// Removes a file row and everything that names it, and gives back its bytes in the quota. The blob keys |
| 29 | /// are added to `keys` for deletion after commit. | 35 | /// are added to `keys` for deletion after commit. |
| 30 | async fn purge_file_row(conn: &Connection, file: &File, keys: &mut Vec<String>) -> Result<()> { | 36 | async fn purge_file_row(conn: &Connection, file: &File, keys: &mut Vec<String>) -> Result<()> { |
| 37 | + // The counter should never hold less than the bytes it counts. If it does, the clamp below hides it, so it | ||
| 38 | + // is logged here; the nightly quota check corrects it. | ||
| 39 | + let used = fetch_opt( | ||
| 40 | + conn, | ||
| 41 | + "SELECT used_bytes FROM members WHERE sub = ?1", | ||
| 42 | + (file.owner.clone(),), | ||
| 43 | + |row| col_int(row, 0), | ||
| 44 | + ) | ||
| 45 | + .await?; | ||
| 46 | + if used.is_some_and(|used| used < file.size) { | ||
| 47 | + tracing::warn!( | ||
| 48 | + member = %file.owner, | ||
| 49 | + used_bytes = used, | ||
| 50 | + file_size = file.size, | ||
| 51 | + "quota: used bytes below a purged file's size; clamped to zero" | ||
| 52 | + ); | ||
| 53 | + } | ||
| 31 | conn.execute("DELETE FROM files WHERE id = ?1", (file.id.clone(),)) | 54 | conn.execute("DELETE FROM files WHERE id = ?1", (file.id.clone(),)) |
| 32 | .await | 55 | .await |
| 33 | .map_err(db_err)?; | 56 | .map_err(db_err)?; |
| @@ -54,14 +77,17 @@ async fn purge_file_row(conn: &Connection, file: &File, keys: &mut Vec<String>) | |||
| 54 | Ok(()) | 77 | Ok(()) |
| 55 | } | 78 | } |
| 56 | 79 | ||
| 57 | -/// Permanently removes a trashed folder, its subtree, and the files in it. Children are removed before | 80 | +/// Permanently removes a trashed folder, its subtree, and the files in it, up to `budget` file rows. Children |
| 58 | -/// their parents (deepest first), because the schema restricts deleting a parent that still has rows. | 81 | +/// are removed before their parents (deepest first), because the schema restricts deleting a parent that |
| 82 | +/// still has rows. Returns `true` when the whole subtree is gone, and `false` when the budget ran out first; | ||
| 83 | +/// the caller then runs it again in a new transaction. | ||
| 59 | async fn purge_folder_rows( | 84 | async fn purge_folder_rows( |
| 60 | conn: &Connection, | 85 | conn: &Connection, |
| 61 | owner: &str, | 86 | owner: &str, |
| 62 | id: &str, | 87 | id: &str, |
| 63 | keys: &mut Vec<String>, | 88 | keys: &mut Vec<String>, |
| 64 | -) -> Result<()> { | 89 | + budget: &mut usize, |
| 90 | +) -> Result<bool> { | ||
| 65 | let root = fetch_opt( | 91 | let root = fetch_opt( |
| 66 | conn, | 92 | conn, |
| 67 | &format!("SELECT {FOLDER_COLS} FROM folders WHERE id = ?1 AND owner = ?2"), | 93 | &format!("SELECT {FOLDER_COLS} FROM folders WHERE id = ?1 AND owner = ?2"), |
| @@ -88,16 +114,25 @@ async fn purge_folder_rows( | |||
| 88 | next += 1; | 114 | next += 1; |
| 89 | } | 115 | } |
| 90 | for folder_id in order.iter().rev() { | 116 | for folder_id in order.iter().rev() { |
| 117 | + if *budget == 0 { | ||
| 118 | + return Ok(false); | ||
| 119 | + } | ||
| 91 | let files = fetch_all( | 120 | let files = fetch_all( |
| 92 | conn, | 121 | conn, |
| 93 | - &format!("SELECT {FILE_COLS} FROM files WHERE folder_id = ?1 AND owner = ?2"), | 122 | + &format!("SELECT {FILE_COLS} FROM files WHERE folder_id = ?1 AND owner = ?2 LIMIT ?3"), |
| 94 | - (folder_id.clone(), owner.to_string()), | 123 | + (folder_id.clone(), owner.to_string(), *budget as i64), |
| 95 | map_file, | 124 | map_file, |
| 96 | ) | 125 | ) |
| 97 | .await?; | 126 | .await?; |
| 98 | for file in &files { | 127 | for file in &files { |
| 99 | purge_file_row(conn, file, keys).await?; | 128 | purge_file_row(conn, file, keys).await?; |
| 100 | } | 129 | } |
| 130 | + // A full batch may leave rows in this folder, so the folder waits for a later batch. | ||
| 131 | + if files.len() == *budget { | ||
| 132 | + *budget = 0; | ||
| 133 | + return Ok(false); | ||
| 134 | + } | ||
| 135 | + *budget -= files.len(); | ||
| 101 | // Uploads still in progress into this folder fall back to the top level. Finished ones are | 136 | // Uploads still in progress into this folder fall back to the top level. Finished ones are |
| 102 | // history and go with the folder. | 137 | // history and go with the folder. |
| 103 | conn.execute( | 138 | conn.execute( |
| @@ -128,7 +163,7 @@ async fn purge_folder_rows( | |||
| 128 | .await | 163 | .await |
| 129 | .map_err(db_err)?; | 164 | .map_err(db_err)?; |
| 130 | } | 165 | } |
| 131 | - Ok(()) | 166 | + Ok(true) |
| 132 | } | 167 | } |
| 133 | 168 | ||
| 134 | impl Store { | 169 | impl Store { |
| @@ -341,48 +376,85 @@ impl Store { | |||
| 341 | } | 376 | } |
| 342 | 377 | ||
| 343 | /// Permanently deletes a trashed folder of `owner` with everything beneath it. Returns the blob keys | 378 | /// Permanently deletes a trashed folder of `owner` with everything beneath it. Returns the blob keys |
| 344 | - /// to delete after commit. | 379 | + /// to delete. The purge runs in batches of at most [`PURGE_BATCH`] file rows, each committed on its own. |
| 345 | pub async fn purge_folder(&self, owner: &str, id: &str) -> Result<Vec<String>> { | 380 | pub async fn purge_folder(&self, owner: &str, id: &str) -> Result<Vec<String>> { |
| 381 | + let mut keys = Vec::new(); | ||
| 382 | + loop { | ||
| 383 | + let (batch, done) = self.purge_folder_batch(owner, id).await?; | ||
| 384 | + keys.extend(batch); | ||
| 385 | + if done { | ||
| 386 | + return Ok(keys); | ||
| 387 | + } | ||
| 388 | + } | ||
| 389 | + } | ||
| 390 | + | ||
| 391 | + /// One transaction of a folder purge. Returns the blob keys it released and whether the folder is gone. | ||
| 392 | + async fn purge_folder_batch(&self, owner: &str, id: &str) -> Result<(Vec<String>, bool)> { | ||
| 346 | let conn = self.inner.conn.lock().await; | 393 | let conn = self.inner.conn.lock().await; |
| 347 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 394 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 348 | let mut keys = Vec::new(); | 395 | let mut keys = Vec::new(); |
| 349 | - let outcome: Result<()> = purge_folder_rows(&tx, owner, id, &mut keys).await; | 396 | + let mut budget = PURGE_BATCH; |
| 350 | - finish(tx, outcome).await?; | 397 | + let outcome: Result<bool> = purge_folder_rows(&tx, owner, id, &mut keys, &mut budget).await; |
| 351 | - Ok(keys) | 398 | + let done = finish(tx, outcome).await?; |
| 399 | + Ok((keys, done)) | ||
| 352 | } | 400 | } |
| 353 | 401 | ||
| 354 | /// Permanently deletes everything `owner` has in the trash. Folder roots go first, which takes their | 402 | /// Permanently deletes everything `owner` has in the trash. Folder roots go first, which takes their |
| 355 | - /// subtrees with them; the files left over are then purged. One transaction. | 403 | + /// subtrees with them; the files left over are then purged. Each batch of at most [`PURGE_BATCH`] file |
| 404 | + /// rows is its own transaction, so the writer lock is released between them. | ||
| 356 | pub async fn empty_trash(&self, owner: &str) -> Result<Vec<String>> { | 405 | pub async fn empty_trash(&self, owner: &str) -> Result<Vec<String>> { |
| 357 | - let conn = self.inner.conn.lock().await; | 406 | + let roots = { |
| 358 | - let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 407 | + let conn = self.read_conn().await; |
| 359 | - let mut keys = Vec::new(); | 408 | + fetch_all( |
| 360 | - let outcome: Result<()> = async { | 409 | + &conn, |
| 361 | - let roots = fetch_all( | ||
| 362 | - &tx, | ||
| 363 | "SELECT id FROM folders WHERE owner = ?1 AND trashed_at IS NOT NULL AND trash_root IS NULL", | 410 | "SELECT id FROM folders WHERE owner = ?1 AND trashed_at IS NOT NULL AND trash_root IS NULL", |
| 364 | (owner.to_string(),), | 411 | (owner.to_string(),), |
| 365 | |row| col_text(row, 0), | 412 | |row| col_text(row, 0), |
| 366 | ) | 413 | ) |
| 367 | - .await?; | 414 | + .await? |
| 368 | - for root in &roots { | 415 | + }; |
| 369 | - purge_folder_rows(&tx, owner, root, &mut keys).await?; | 416 | + let mut keys = Vec::new(); |
| 417 | + for root in &roots { | ||
| 418 | + match self.purge_folder(owner, root).await { | ||
| 419 | + Ok(released) => keys.extend(released), | ||
| 420 | + // Removed by someone else since the list was read: nothing is left to purge. | ||
| 421 | + Err(Error::NotFound) => {} | ||
| 422 | + Err(error) => return Err(error), | ||
| 370 | } | 423 | } |
| 424 | + } | ||
| 425 | + loop { | ||
| 426 | + let (batch, done) = self.purge_loose_files_batch(owner).await?; | ||
| 427 | + keys.extend(batch); | ||
| 428 | + if done { | ||
| 429 | + return Ok(keys); | ||
| 430 | + } | ||
| 431 | + } | ||
| 432 | + } | ||
| 433 | + | ||
| 434 | + /// One transaction of [`Store::empty_trash`]: up to [`PURGE_BATCH`] trashed file rows of `owner`. Returns | ||
| 435 | + /// the blob keys released and whether no trashed file is left. | ||
| 436 | + async fn purge_loose_files_batch(&self, owner: &str) -> Result<(Vec<String>, bool)> { | ||
| 437 | + let conn = self.inner.conn.lock().await; | ||
| 438 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 439 | + let mut keys = Vec::new(); | ||
| 440 | + let outcome: Result<bool> = async { | ||
| 371 | let files = fetch_all( | 441 | let files = fetch_all( |
| 372 | &tx, | 442 | &tx, |
| 373 | - &format!("SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND trashed_at IS NOT NULL"), | 443 | + &format!( |
| 374 | - (owner.to_string(),), | 444 | + "SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND trashed_at IS NOT NULL LIMIT ?2" |
| 445 | + ), | ||
| 446 | + (owner.to_string(), PURGE_BATCH as i64), | ||
| 375 | map_file, | 447 | map_file, |
| 376 | ) | 448 | ) |
| 377 | .await?; | 449 | .await?; |
| 378 | for file in &files { | 450 | for file in &files { |
| 379 | purge_file_row(&tx, file, &mut keys).await?; | 451 | purge_file_row(&tx, file, &mut keys).await?; |
| 380 | } | 452 | } |
| 381 | - Ok(()) | 453 | + Ok(files.len() < PURGE_BATCH) |
| 382 | } | 454 | } |
| 383 | .await; | 455 | .await; |
| 384 | - finish(tx, outcome).await?; | 456 | + let done = finish(tx, outcome).await?; |
| 385 | - Ok(keys) | 457 | + Ok((keys, done)) |
| 386 | } | 458 | } |
| 387 | 459 | ||
| 388 | /// Permanently deletes every trash root trashed before `cutoff` (a stamp), for every owner. Each | 460 | /// Permanently deletes every trash root trashed before `cutoff` (a stamp), for every owner. Each |
crates/in-core/src/store/uploads.rsmodified+14 -0
| @@ -129,6 +129,20 @@ impl Store { | |||
| 129 | upload_of(&conn, owner, id).await | 129 | upload_of(&conn, owner, id).await |
| 130 | } | 130 | } |
| 131 | 131 | ||
| 132 | + /// Whether an upload with this id is still active. The sweeper keeps the staging directory of an active | ||
| 133 | + /// upload whatever its age, because the upload may still receive chunks. | ||
| 134 | + pub async fn upload_is_open(&self, id: &str) -> Result<bool> { | ||
| 135 | + let conn = self.read_conn().await; | ||
| 136 | + Ok(fetch_opt( | ||
| 137 | + &conn, | ||
| 138 | + "SELECT 1 FROM uploads WHERE id = ?1 AND state = 'active'", | ||
| 139 | + (id.to_string(),), | ||
| 140 | + |row| col_int(row, 0), | ||
| 141 | + ) | ||
| 142 | + .await? | ||
| 143 | + .is_some()) | ||
| 144 | + } | ||
| 145 | + | ||
| 132 | /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size | 146 | /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size |
| 133 | /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared | 147 | /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared |
| 134 | /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`, | 148 | /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`, |
crates/in-core/src/thumbs.rsmodified+2 -1
| @@ -20,7 +20,8 @@ pub const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; | |||
| 20 | /// Largest width or height the decoder accepts, in pixels: 10000 by 10000 is 100 megapixels. | 20 | /// Largest width or height the decoder accepts, in pixels: 10000 by 10000 is 100 megapixels. |
| 21 | pub const MAX_DIMENSION: u32 = 10_000; | 21 | pub const MAX_DIMENSION: u32 = 10_000; |
| 22 | 22 | ||
| 23 | -/// Most memory the decoder may allocate for one picture: 256 MiB. | 23 | +/// Most memory the decoder may allocate for one picture: 256 MiB. The thumbnail worker decodes one picture at a |
| 24 | +/// time, so this and [`MAX_SOURCE_BYTES`] bound its peak. | ||
| 24 | pub const MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024; | 25 | pub const MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024; |
| 25 | 26 | ||
| 26 | /// The formats that get thumbnails. Anything else is not decoded. | 27 | /// The formats that get thumbnails. Anything else is not decoded. |
crates/in-web/src/api/upload.rsmodified+17 -2
| @@ -400,9 +400,24 @@ async fn finish_upload(cx: &Cx) -> Result<Response> { | |||
| 400 | let mut prefix = Vec::with_capacity(SNIFF_BYTES); | 400 | let mut prefix = Vec::with_capacity(SNIFF_BYTES); |
| 401 | if let Err(error) = join_chunks(&dir, count, &mut staged, &mut prefix).await { | 401 | if let Err(error) = join_chunks(&dir, count, &mut staged, &mut prefix).await { |
| 402 | staged.abort().await; | 402 | staged.abort().await; |
| 403 | + // A concurrent finish of this upload may have removed the chunks already. That is a conflict. | ||
| 404 | + if matches!(&error, CoreError::Io(e) if e.kind() == std::io::ErrorKind::NotFound) { | ||
| 405 | + return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); | ||
| 406 | + } | ||
| 403 | return Err(error.into()); | 407 | return Err(error.into()); |
| 404 | } | 408 | } |
| 405 | - let Staged { path, sha256, .. } = staged.finish().await?; | 409 | + let Staged { |
| 410 | + path, | ||
| 411 | + sha256, | ||
| 412 | + size: measured, | ||
| 413 | + } = staged.finish().await?; | ||
| 414 | + // The row records the bytes that were joined. Chunks of the declared length that hold other bytes are | ||
| 415 | + // refused here, not recorded with the declared size. | ||
| 416 | + if measured != size { | ||
| 417 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 418 | + return Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer()); | ||
| 419 | + } | ||
| 420 | + let recorded = i64::try_from(measured).map_err(|_| CoreError::Invalid("too_large".into()))?; | ||
| 406 | 421 | ||
| 407 | // The bytes are durable at their key before the row that names them commits (architecture 3). | 422 | // The bytes are durable at their key before the row that names them commits (architecture 3). |
| 408 | let file_id = new_id(); | 423 | let file_id = new_id(); |
| @@ -417,7 +432,7 @@ async fn finish_upload(cx: &Cx) -> Result<Response> { | |||
| 417 | folder: upload.folder_id.clone(), | 432 | folder: upload.folder_id.clone(), |
| 418 | name: upload.name.clone(), | 433 | name: upload.name.clone(), |
| 419 | mime: sniff(&prefix), | 434 | mime: sniff(&prefix), |
| 420 | - size: upload.size, | 435 | + size: recorded, |
| 421 | sha256, | 436 | sha256, |
| 422 | staged_claims: 0, | 437 | staged_claims: 0, |
| 423 | }; | 438 | }; |
crates/in-web/src/live.rsmodified+14 -2
| @@ -31,6 +31,11 @@ pub const STREAM_RETRY: Duration = Duration::from_millis(1000); | |||
| 31 | /// Silence after which the server sends a keep-alive comment, so proxies keep the stream open. | 31 | /// Silence after which the server sends a keep-alive comment, so proxies keep the stream open. |
| 32 | pub const KEEP_ALIVE: Duration = Duration::from_secs(30); | 32 | pub const KEEP_ALIVE: Duration = Duration::from_secs(30); |
| 33 | 33 | ||
| 34 | +/// How often an idle `changed` stream checks its viewer anyway, so a viewer who signed out or lost access is | ||
| 35 | +/// noticed even when nothing the stream follows changes. | ||
| 36 | +const RECHECK: Duration = Duration::from_secs(15); | ||
| 37 | +/// The longest a `changed` stream lives. The browser then reconnects and is checked again from the start. | ||
| 38 | +const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60); | ||
| 34 | /// What a live page follows. | 39 | /// What a live page follows. |
| 35 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] | 40 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 36 | pub enum Topic { | 41 | pub enum Topic { |
| @@ -118,9 +123,16 @@ where | |||
| 118 | fingerprint, | 123 | fingerprint, |
| 119 | last, | 124 | last, |
| 120 | }; | 125 | }; |
| 121 | - let events = stream::unfold(follow, |mut follow| async move { | 126 | + let until = tokio::time::Instant::now() + MAX_STREAM_LIFE; |
| 127 | + let events = stream::unfold(follow, move |mut follow| async move { | ||
| 122 | loop { | 128 | loop { |
| 123 | - if !wait_any(&mut follow.wakes).await { | 129 | + // A tick runs the fingerprint too: it is where the viewer is checked again. |
| 130 | + let woke = tokio::select! { | ||
| 131 | + woke = wait_any(&mut follow.wakes) => woke, | ||
| 132 | + () = tokio::time::sleep(RECHECK) => true, | ||
| 133 | + () = tokio::time::sleep_until(until) => false, | ||
| 134 | + }; | ||
| 135 | + if !woke { | ||
| 124 | return None; | 136 | return None; |
| 125 | } | 137 | } |
| 126 | match (follow.fingerprint)().await { | 138 | match (follow.fingerprint)().await { |
crates/in-web/src/pages/public_share.rsmodified+29 -12
| @@ -5,12 +5,17 @@ | |||
| 5 | //! inside it; a `?folder=` or `?file=` outside the linked root is `404`, as is any unknown, revoked, | 5 | //! inside it; a `?folder=` or `?file=` outside the linked root is `404`, as is any unknown, revoked, |
| 6 | //! expired or trashed link, all alike. A link with a password shows a gate until the visitor posts the | 6 | //! expired or trashed link, all alike. A link with a password shows a gate until the visitor posts the |
| 7 | //! right one. The unlock cookie is HMAC-keyed to the link and its password hash, so a changed password | 7 | //! right one. The unlock cookie is HMAC-keyed to the link and its password hash, so a changed password |
| 8 | -//! locks everyone out again. Wrong passwords are throttled per link and per client address (see | 8 | +//! locks everyone out again. Wrong passwords are throttled per link (100 in the window, for everyone) and per |
| 9 | -//! `throttle.rs`); the sixth wrong one within the window is `429`. | 9 | +//! link and client address (10 in the window); see `throttle.rs`. Refused attempts are `429`. |
| 10 | +//! | ||
| 11 | +//! A link does not work while its owner is disabled: the owner's items are not served through it, and it | ||
| 12 | +//! works again when the owner is enabled. | ||
| 10 | //! | 13 | //! |
| 11 | //! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` | 14 | //! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` |
| 12 | -//! and `X-Robots-Tag: noindex` (set in `security.rs`). | 15 | +//! and `X-Robots-Tag: noindex` (set in `security.rs`), and `Cache-Control: no-store`. |
| 13 | 16 | ||
| 17 | +use http::HeaderValue; | ||
| 18 | +use http::header::CACHE_CONTROL; | ||
| 14 | use in_core::authz::{Action, Actor, Grant, Target, authorize}; | 19 | use in_core::authz::{Action, Actor, Grant, Target, authorize}; |
| 15 | use in_core::password::verify_password_async; | 20 | use in_core::password::verify_password_async; |
| 16 | use in_core::secret::unlock_proof; | 21 | use in_core::secret::unlock_proof; |
| @@ -28,6 +33,7 @@ use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; | |||
| 28 | use topcoat::router::content::Form; | 33 | use topcoat::router::content::Form; |
| 29 | use topcoat::router::error::{SeeOther, forbidden, not_found, see_other, too_many_requests}; | 34 | use topcoat::router::error::{SeeOther, forbidden, not_found, see_other, too_many_requests}; |
| 30 | use topcoat::router::request::{client_ip, headers}; | 35 | use topcoat::router::request::{client_ip, headers}; |
| 36 | +use topcoat::router::response::response_headers; | ||
| 31 | use topcoat::router::{page, parse_query_params, path_param_segment, route}; | 37 | use topcoat::router::{page, parse_query_params, path_param_segment, route}; |
| 32 | use topcoat::view::{View, component, view}; | 38 | use topcoat::view::{View, component, view}; |
| 33 | 39 | ||
| @@ -59,8 +65,14 @@ fn unlock_cookie_name(link_id: &str) -> String { | |||
| 59 | format!("in_link_{link_id}") | 65 | format!("in_link_{link_id}") |
| 60 | } | 66 | } |
| 61 | 67 | ||
| 68 | +/// Marks a share page as uncacheable. A shared proxy or the browser's back-forward cache must not keep a page | ||
| 69 | +/// that shows a listing or a password gate. Set before the lookup, so the `404` for a dead link carries it too. | ||
| 70 | +fn no_store(cx: &Cx) { | ||
| 71 | + response_headers(cx).append(CACHE_CONTROL, HeaderValue::from_static("no-store")); | ||
| 72 | +} | ||
| 73 | + | ||
| 62 | /// The link of a token, when it is live and its target is not in the trash. Every other case is `404`, so | 74 | /// The link of a token, when it is live and its target is not in the trash. Every other case is `404`, so |
| 63 | -/// an unknown token and a dead one cannot be told apart. | 75 | +/// an unknown token and a dead one cannot be told apart. A link whose owner is disabled is unknown here. |
| 64 | async fn live_link(state: &AppState, token: &str) -> Result<Link> { | 76 | async fn live_link(state: &AppState, token: &str) -> Result<Link> { |
| 65 | let link = state | 77 | let link = state |
| 66 | .store | 78 | .store |
| @@ -408,6 +420,7 @@ async fn content_panel( | |||
| 408 | /// `GET /s/{token}`: the public page of a link, or its password gate. | 420 | /// `GET /s/{token}`: the public page of a link, or its password gate. |
| 409 | #[page("/s/{token}")] | 421 | #[page("/s/{token}")] |
| 410 | async fn public_page(cx: &Cx) -> Result<impl View> { | 422 | async fn public_page(cx: &Cx) -> Result<impl View> { |
| 423 | + no_store(cx); | ||
| 411 | let state = app_context::<AppState>(cx); | 424 | let state = app_context::<AppState>(cx); |
| 412 | let token = path_param_segment(cx, "token").to_owned(); | 425 | let token = path_param_segment(cx, "token").to_owned(); |
| 413 | let link = live_link(state, &token).await?; | 426 | let link = live_link(state, &token).await?; |
| @@ -432,14 +445,16 @@ async fn public_page(cx: &Cx) -> Result<impl View> { | |||
| 432 | } | 445 | } |
| 433 | 446 | ||
| 434 | /// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie. Every attempt is counted | 447 | /// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie. Every attempt is counted |
| 435 | -/// against the link and the client address before it is verified, and a right one takes its count back; | 448 | +/// against the link and against the link and client address before it is verified, and a right one takes its |
| 436 | -/// so parallel guesses cannot all be verified together. Refused attempts are `429`. | 449 | +/// count back; so parallel guesses cannot all be verified together. Refused attempts are `429`. |
| 437 | #[route(POST "/s/{token}")] | 450 | #[route(POST "/s/{token}")] |
| 438 | async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> { | 451 | async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> { |
| 452 | + no_store(cx); | ||
| 439 | let state = app_context::<AppState>(cx); | 453 | let state = app_context::<AppState>(cx); |
| 440 | let token = path_param_segment(cx, "token").to_owned(); | 454 | let token = path_param_segment(cx, "token").to_owned(); |
| 441 | let token_hash = hash_token(&token); | 455 | let token_hash = hash_token(&token); |
| 442 | let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default(); | 456 | let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default(); |
| 457 | + let visitor = format!("{token_hash}:{ip}"); | ||
| 443 | let throttles = &state.throttles; | 458 | let throttles = &state.throttles; |
| 444 | let expected_csrf = cookie_value(cx, GATE_CSRF_COOKIE).unwrap_or_default(); | 459 | let expected_csrf = cookie_value(cx, GATE_CSRF_COOKIE).unwrap_or_default(); |
| 445 | if expected_csrf.is_empty() || !constant_time_eq(expected_csrf.as_bytes(), form.csrf.as_bytes()) | 460 | 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<GateForm>) -> Result<SeeOther> { | |||
| 453 | if let Err(wait) = throttles.per_link.reserve(&token_hash) { | 468 | if let Err(wait) = throttles.per_link.reserve(&token_hash) { |
| 454 | return Err(too_many_requests(wait).into()); | 469 | return Err(too_many_requests(wait).into()); |
| 455 | } | 470 | } |
| 456 | - if let Err(wait) = throttles.per_ip.reserve(&ip) { | 471 | + if let Err(wait) = throttles.per_visitor.reserve(&visitor) { |
| 457 | throttles.per_link.refund(&token_hash); | 472 | throttles.per_link.refund(&token_hash); |
| 458 | return Err(too_many_requests(wait).into()); | 473 | return Err(too_many_requests(wait).into()); |
| 459 | } | 474 | } |
| @@ -461,7 +476,7 @@ async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> { | |||
| 461 | && verify_password_async(form.password, hash.clone()).await?; | 476 | && verify_password_async(form.password, hash.clone()).await?; |
| 462 | if verified { | 477 | if verified { |
| 463 | throttles.per_link.refund(&token_hash); | 478 | throttles.per_link.refund(&token_hash); |
| 464 | - throttles.per_ip.refund(&ip); | 479 | + throttles.per_visitor.refund(&visitor); |
| 465 | let proof = unlock_proof(&state.key, &link.id, &hash); | 480 | let proof = unlock_proof(&state.key, &link.id, &hash); |
| 466 | let cookie = Cookie::build((unlock_cookie_name(&link.id), proof)) | 481 | let cookie = Cookie::build((unlock_cookie_name(&link.id), proof)) |
| 467 | .path(format!("/s/{token}")) | 482 | .path(format!("/s/{token}")) |
| @@ -674,9 +689,9 @@ mod tests { | |||
| 674 | assert_eq!(get(&state, &format!("/s/{token}")).await, 404); | 689 | assert_eq!(get(&state, &format!("/s/{token}")).await, 404); |
| 675 | } | 690 | } |
| 676 | 691 | ||
| 677 | - /// Five wrong passwords are answered with a redirect; the sixth within the window is `429`. | 692 | + /// Ten wrong passwords from one visitor are answered with a redirect; the eleventh within the window is `429`. |
| 678 | #[tokio::test] | 693 | #[tokio::test] |
| 679 | - async fn the_sixth_wrong_password_is_throttled() { | 694 | + async fn the_eleventh_wrong_password_from_one_visitor_is_throttled() { |
| 680 | let (_dir, state) = test_state().await; | 695 | let (_dir, state) = test_state().await; |
| 681 | let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | 696 | let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; |
| 682 | let trips = state | 697 | let trips = state |
| @@ -687,7 +702,7 @@ mod tests { | |||
| 687 | let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, Some("right")).await; | 702 | let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, Some("right")).await; |
| 688 | let path = format!("/s/{token}"); | 703 | let path = format!("/s/{token}"); |
| 689 | let mut statuses = Vec::new(); | 704 | let mut statuses = Vec::new(); |
| 690 | - for _ in 0..6 { | 705 | + for _ in 0..11 { |
| 691 | let request = Request::post(path.as_str()) | 706 | let request = Request::post(path.as_str()) |
| 692 | .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | 707 | .header(CONTENT_TYPE, "application/x-www-form-urlencoded") |
| 693 | .header(COOKIE, format!("{GATE_CSRF_COOKIE}=tok")) | 708 | .header(COOKIE, format!("{GATE_CSRF_COOKIE}=tok")) |
| @@ -696,7 +711,9 @@ mod tests { | |||
| 696 | let response = router(state.clone()).handle(request).await; | 711 | let response = router(state.clone()).handle(request).await; |
| 697 | statuses.push(response.status().as_u16()); | 712 | statuses.push(response.status().as_u16()); |
| 698 | } | 713 | } |
| 699 | - assert_eq!(statuses, vec![303, 303, 303, 303, 303, 429]); | 714 | + let mut expected = vec![303; 10]; |
| 715 | + expected.push(429); | ||
| 716 | + assert_eq!(statuses, expected); | ||
| 700 | } | 717 | } |
| 701 | 718 | ||
| 702 | /// A file link answers the file's bytes only with the unlock cookie of a password-protected link. | 719 | /// A file link answers the file's bytes only with the unlock cookie of a password-protected link. |
crates/in-web/src/sweeper.rsmodified+58 -1
| @@ -3,6 +3,9 @@ | |||
| 3 | //! | 3 | //! |
| 4 | //! - sessions past their expiry, back-channel logout ids past their expiry, and open uploads not finished in | 4 | //! - sessions past their expiry, back-channel logout ids past their expiry, and open uploads not finished in |
| 5 | //! 24 hours, with their staging directories; | 5 | //! 24 hours, with their staging directories; |
| 6 | +//! - staging directories under `data_dir/uploads` that no open upload names and that are at least 24 hours old. | ||
| 7 | +//! This is what retries a removal that failed earlier: the expiry step has already deleted the row; | ||
| 8 | +//! the directory is the only record left; | ||
| 6 | //! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; | 9 | //! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; |
| 7 | //! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; | 10 | //! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; |
| 8 | //! - leftover files in `data_dir/tmp` at least 24 hours old; | 11 | //! - leftover files in `data_dir/tmp` at least 24 hours old; |
| @@ -18,7 +21,7 @@ use std::path::Path; | |||
| 18 | use std::time::{Duration, SystemTime}; | 21 | use std::time::{Duration, SystemTime}; |
| 19 | 22 | ||
| 20 | use in_core::error::Result; | 23 | use in_core::error::Result; |
| 21 | -use in_core::staging::{TMP_DIR, remove_upload_dir}; | 24 | +use in_core::staging::{TMP_DIR, UPLOADS_DIR, remove_upload_dir, upload_dir}; |
| 22 | use in_core::time::{now_stamp, stamp_before}; | 25 | use in_core::time::{now_stamp, stamp_before}; |
| 23 | use tokio::sync::watch; | 26 | use tokio::sync::watch; |
| 24 | 27 | ||
| @@ -70,6 +73,10 @@ pub async fn sweep(state: &AppState) -> Result<()> { | |||
| 70 | expired_uploads = uploads.len(), | 73 | expired_uploads = uploads.len(), |
| 71 | "sweeper: pass done" | 74 | "sweeper: pass done" |
| 72 | ); | 75 | ); |
| 76 | + log_step( | ||
| 77 | + "upload dirs", | ||
| 78 | + sweep_upload_dirs(state, SystemTime::now()).await, | ||
| 79 | + ); | ||
| 73 | log_step("trash", purge_trash(state).await); | 80 | log_step("trash", purge_trash(state).await); |
| 74 | log_step("blobs", sweep_blobs(state, SystemTime::now()).await); | 81 | log_step("blobs", sweep_blobs(state, SystemTime::now()).await); |
| 75 | log_step( | 82 | log_step( |
| @@ -155,6 +162,56 @@ pub async fn sweep_blobs(state: &AppState, now: SystemTime) -> Result<usize> { | |||
| 155 | Ok(removed) | 162 | Ok(removed) |
| 156 | } | 163 | } |
| 157 | 164 | ||
| 165 | +/// Removes the staging directories under `data_dir/uploads` that no open upload names and that are at least | ||
| 166 | +/// [`ORPHAN_GRACE`] old, as of `now`. Only a direct child of that directory whose name is a well-formed upload | ||
| 167 | +/// id is removed; symbolic links and other entries are left alone. | ||
| 168 | +pub async fn sweep_upload_dirs(state: &AppState, now: SystemTime) -> Result<usize> { | ||
| 169 | + let root = state.config.data_dir.join(UPLOADS_DIR); | ||
| 170 | + let mut entries = match tokio::fs::read_dir(&root).await { | ||
| 171 | + Ok(entries) => entries, | ||
| 172 | + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), | ||
| 173 | + Err(error) => return Err(error.into()), | ||
| 174 | + }; | ||
| 175 | + let mut removed = 0; | ||
| 176 | + while let Some(entry) = entries.next_entry().await? { | ||
| 177 | + let Some(id) = entry.file_name().to_str().map(str::to_owned) else { | ||
| 178 | + continue; | ||
| 179 | + }; | ||
| 180 | + // `upload_dir` accepts only a well-formed upload id, and the path must be a direct child of the root. | ||
| 181 | + let Ok(dir) = upload_dir(&state.config.data_dir, &id) else { | ||
| 182 | + continue; | ||
| 183 | + }; | ||
| 184 | + if dir.parent() != Some(root.as_path()) { | ||
| 185 | + continue; | ||
| 186 | + } | ||
| 187 | + let Ok(meta) = tokio::fs::symlink_metadata(&dir).await else { | ||
| 188 | + continue; | ||
| 189 | + }; | ||
| 190 | + if !meta.is_dir() { | ||
| 191 | + continue; | ||
| 192 | + } | ||
| 193 | + let Ok(modified) = meta.modified() else { | ||
| 194 | + continue; | ||
| 195 | + }; | ||
| 196 | + if !is_old(modified, now) || state.store.upload_is_open(&id).await? { | ||
| 197 | + continue; | ||
| 198 | + } | ||
| 199 | + match remove_upload_dir(&state.config.data_dir, &id).await { | ||
| 200 | + Ok(()) => removed += 1, | ||
| 201 | + Err(error) => { | ||
| 202 | + tracing::warn!(upload = %id, error = %error, "sweeper: staging directory not removed"); | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | + } | ||
| 206 | + if removed > 0 { | ||
| 207 | + tracing::info!( | ||
| 208 | + staging_dirs = removed, | ||
| 209 | + "sweeper: staging directories removed" | ||
| 210 | + ); | ||
| 211 | + } | ||
| 212 | + Ok(removed) | ||
| 213 | +} | ||
| 214 | + | ||
| 158 | /// Removes the plain files in `data_dir/tmp` that are at least [`ORPHAN_GRACE`] old. Links are never followed, | 215 | /// Removes the plain files in `data_dir/tmp` that are at least [`ORPHAN_GRACE`] old. Links are never followed, |
| 159 | /// and only regular files are removed. The directory is the fixed staging directory of the data directory. | 216 | /// and only regular files are removed. The directory is the fixed staging directory of the data directory. |
| 160 | pub async fn sweep_tmp(data_dir: &Path, now: SystemTime) -> Result<usize> { | 217 | pub async fn sweep_tmp(data_dir: &Path, now: SystemTime) -> Result<usize> { |
crates/in-web/src/throttle.rsmodified+18 -17
| @@ -16,11 +16,13 @@ use std::time::{Duration, Instant}; | |||
| 16 | /// Length of the sliding window for share-link passwords: 15 minutes. | 16 | /// Length of the sliding window for share-link passwords: 15 minutes. |
| 17 | pub const PASSWORD_WINDOW: Duration = Duration::from_secs(15 * 60); | 17 | pub const PASSWORD_WINDOW: Duration = Duration::from_secs(15 * 60); |
| 18 | 18 | ||
| 19 | -/// Failed password attempts allowed against one link in a window. The sixth is refused with `429`. | 19 | +/// Failed password attempts allowed against one link in a window, from all visitors together. This is a |
| 20 | -pub const LINK_PASSWORD_LIMIT: usize = 5; | 20 | +/// ceiling: it stops guesses spread over many addresses. The 101st is refused with `429`. |
| 21 | +pub const LINK_PASSWORD_LIMIT: usize = 100; | ||
| 21 | 22 | ||
| 22 | -/// Failed password attempts allowed from one client address in a window, across all links. | 23 | +/// Failed password attempts allowed from one client address against one link in a window. The eleventh is |
| 23 | -pub const IP_PASSWORD_LIMIT: usize = 10; | 24 | +/// refused with `429`. Other visitors of the same link have their own count. |
| 25 | +pub const VISITOR_PASSWORD_LIMIT: usize = 10; | ||
| 24 | 26 | ||
| 25 | /// Most keys held at once. Each key is a short string and a short list of instants. | 27 | /// Most keys held at once. Each key is a short string and a short list of instants. |
| 26 | pub const MAX_KEYS: usize = 10_000; | 28 | pub const MAX_KEYS: usize = 10_000; |
| @@ -116,19 +118,20 @@ impl Throttle { | |||
| 116 | } | 118 | } |
| 117 | } | 119 | } |
| 118 | 120 | ||
| 119 | -/// The two throttles of share-link passwords: one per link (by token hash) and one per client address. | 121 | +/// The two throttles of share-link passwords: one per link (by token hash), and one per link and client |
| 122 | +/// address (the key is the token hash, a colon, and the address). | ||
| 120 | pub struct ShareThrottles { | 123 | pub struct ShareThrottles { |
| 121 | - /// Failures per link. | 124 | + /// Failures per link, from all visitors. |
| 122 | pub per_link: Throttle, | 125 | pub per_link: Throttle, |
| 123 | - /// Failures per client address. | 126 | + /// Failures per link and client address. |
| 124 | - pub per_ip: Throttle, | 127 | + pub per_visitor: Throttle, |
| 125 | } | 128 | } |
| 126 | 129 | ||
| 127 | impl Default for ShareThrottles { | 130 | impl Default for ShareThrottles { |
| 128 | fn default() -> Self { | 131 | fn default() -> Self { |
| 129 | Self { | 132 | Self { |
| 130 | per_link: Throttle::new(PASSWORD_WINDOW, LINK_PASSWORD_LIMIT, MAX_KEYS), | 133 | per_link: Throttle::new(PASSWORD_WINDOW, LINK_PASSWORD_LIMIT, MAX_KEYS), |
| 131 | - per_ip: Throttle::new(PASSWORD_WINDOW, IP_PASSWORD_LIMIT, MAX_KEYS), | 134 | + per_visitor: Throttle::new(PASSWORD_WINDOW, VISITOR_PASSWORD_LIMIT, MAX_KEYS), |
| 132 | } | 135 | } |
| 133 | } | 136 | } |
| 134 | } | 137 | } |
| @@ -138,15 +141,13 @@ mod tests { | |||
| 138 | use super::*; | 141 | use super::*; |
| 139 | use std::sync::Arc; | 142 | use std::sync::Arc; |
| 140 | 143 | ||
| 141 | - /// Ten parallel wrong guesses against one link: only the limit of them is counted and admitted, and the | 144 | + /// Ten parallel wrong guesses against one key with a limit of five: only the limit of them is counted and |
| 142 | - /// rest are refused with a wait. The check and the record are one step, so none can slip past. | 145 | + /// admitted, and the rest are refused with a wait. The check and the record are one step, so none can slip |
| 146 | + /// past. | ||
| 143 | #[test] | 147 | #[test] |
| 144 | fn parallel_attempts_admit_no_more_than_the_limit() { | 148 | fn parallel_attempts_admit_no_more_than_the_limit() { |
| 145 | - let throttle = Arc::new(Throttle::new( | 149 | + const LIMIT: usize = 5; |
| 146 | - PASSWORD_WINDOW, | 150 | + let throttle = Arc::new(Throttle::new(PASSWORD_WINDOW, LIMIT, MAX_KEYS)); |
| 147 | - LINK_PASSWORD_LIMIT, | ||
| 148 | - MAX_KEYS, | ||
| 149 | - )); | ||
| 150 | let handles: Vec<_> = (0..10) | 151 | let handles: Vec<_> = (0..10) |
| 151 | .map(|_| { | 152 | .map(|_| { |
| 152 | let throttle = Arc::clone(&throttle); | 153 | let throttle = Arc::clone(&throttle); |
| @@ -158,7 +159,7 @@ mod tests { | |||
| 158 | .map(|handle| handle.join().expect("attempt thread")) | 159 | .map(|handle| handle.join().expect("attempt thread")) |
| 159 | .filter(|ok| *ok) | 160 | .filter(|ok| *ok) |
| 160 | .count(); | 161 | .count(); |
| 161 | - assert_eq!(admitted, LINK_PASSWORD_LIMIT); | 162 | + assert_eq!(admitted, LIMIT); |
| 162 | assert!(throttle.reserve("link").is_err_and(|wait| wait >= 1)); | 163 | assert!(throttle.reserve("link").is_err_and(|wait| wait >= 1)); |
| 163 | } | 164 | } |
| 164 | } | 165 | } |
crates/in-web/src/thumbs_worker.rsmodified+29 -6
| @@ -7,6 +7,7 @@ | |||
| 7 | //! thumbnail was made, the row update finds nothing and the stored bytes are deleted, so no row is left | 7 | //! thumbnail was made, the row update finds nothing and the stored bytes are deleted, so no row is left |
| 8 | //! without its file. | 8 | //! without its file. |
| 9 | 9 | ||
| 10 | +use std::sync::{Arc, LazyLock}; | ||
| 10 | use std::time::Duration; | 11 | use std::time::Duration; |
| 11 | 12 | ||
| 12 | use futures_util::{StreamExt, stream}; | 13 | use futures_util::{StreamExt, stream}; |
| @@ -14,7 +15,7 @@ use in_core::error::{Error, Result}; | |||
| 14 | use in_core::staging::{Staged, StagedFile}; | 15 | use in_core::staging::{Staged, StagedFile}; |
| 15 | use in_core::store::files::{File, thumb_blob_key}; | 16 | use in_core::store::files::{File, thumb_blob_key}; |
| 16 | use in_core::thumbs::{MAX_SOURCE_BYTES, make_thumbnail}; | 17 | use in_core::thumbs::{MAX_SOURCE_BYTES, make_thumbnail}; |
| 17 | -use tokio::sync::watch; | 18 | +use tokio::sync::{Semaphore, watch}; |
| 18 | 19 | ||
| 19 | use crate::live::Topic; | 20 | use crate::live::Topic; |
| 20 | use crate::state::AppState; | 21 | use crate::state::AppState; |
| @@ -22,8 +23,19 @@ use crate::state::AppState; | |||
| 22 | /// Most files taken from the queue in one round. | 23 | /// Most files taken from the queue in one round. |
| 23 | pub const BATCH: usize = 16; | 24 | pub const BATCH: usize = 16; |
| 24 | 25 | ||
| 25 | -/// Most thumbnails made at the same time. | 26 | +/// Most thumbnails made at the same time. One, because a decode may hold a whole source picture |
| 26 | -pub const CONCURRENCY: usize = 2; | 27 | +/// ([`MAX_SOURCE_BYTES`], 64 MiB) and its decoder buffers ([`in_core::thumbs::MAX_ALLOC_BYTES`], 256 MiB); two |
| 28 | +/// together could reach about 640 MiB. One keeps the peak near 320 MiB. | ||
| 29 | +pub const CONCURRENCY: usize = 1; | ||
| 30 | + | ||
| 31 | +/// Longest a decode may run before its file is marked `failed`: ten seconds. | ||
| 32 | +pub const DECODE_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 33 | + | ||
| 34 | +/// The decode slots. A slot is moved into the blocking decode, so it is released when the decoder returns, | ||
| 35 | +/// not when the caller stops waiting. A timed-out decode that still runs keeps its slot, and no other decode | ||
| 36 | +/// starts beside it, so stragglers cannot pile up. | ||
| 37 | +static DECODE_SLOTS: LazyLock<Arc<Semaphore>> = | ||
| 38 | + LazyLock::new(|| Arc::new(Semaphore::new(CONCURRENCY))); | ||
| 27 | 39 | ||
| 28 | /// How long the worker waits when the queue is empty before it looks again. | 40 | /// How long the worker waits when the queue is empty before it looks again. |
| 29 | pub const IDLE: Duration = Duration::from_secs(30); | 41 | pub const IDLE: Duration = Duration::from_secs(30); |
| @@ -91,10 +103,21 @@ async fn build(state: &AppState, file: &File) -> Result<()> { | |||
| 91 | return Err(Error::Invalid("too_large".into())); | 103 | return Err(Error::Invalid("too_large".into())); |
| 92 | } | 104 | } |
| 93 | let source = read_source(state, file, size).await?; | 105 | let source = read_source(state, file, size).await?; |
| 94 | - // The decoder is CPU work: it runs on a blocking thread, never on the async runtime. | 106 | + let slot = Arc::clone(&DECODE_SLOTS) |
| 95 | - let webp = tokio::task::spawn_blocking(move || make_thumbnail(&source)) | 107 | + .acquire_owned() |
| 96 | .await | 108 | .await |
| 97 | - .map_err(|e| Error::Io(std::io::Error::other(e)))??; | 109 | + .map_err(|e| Error::Io(std::io::Error::other(e)))?; |
| 110 | + // The decoder is CPU work: it runs on a blocking thread, never on the async runtime. | ||
| 111 | + let decode = tokio::task::spawn_blocking(move || { | ||
| 112 | + let _slot = slot; | ||
| 113 | + make_thumbnail(&source) | ||
| 114 | + }); | ||
| 115 | + let webp = match tokio::time::timeout(DECODE_TIMEOUT, decode).await { | ||
| 116 | + Ok(joined) => joined.map_err(|e| Error::Io(std::io::Error::other(e)))??, | ||
| 117 | + // A blocking task cannot be stopped. Its result is dropped with the handle, and its slot is held | ||
| 118 | + // until it returns. | ||
| 119 | + Err(_) => return Err(Error::Invalid("decode_timeout".into())), | ||
| 120 | + }; | ||
| 98 | let mut staged = StagedFile::create(&state.config.data_dir, MAX_THUMB_BYTES).await?; | 121 | let mut staged = StagedFile::create(&state.config.data_dir, MAX_THUMB_BYTES).await?; |
| 99 | if let Err(error) = staged.write(&webp).await { | 122 | if let Err(error) = staged.write(&webp).await { |
| 100 | staged.abort().await; | 123 | staged.abort().await; |
docs/architecture.mdmodified+10 -5
| @@ -45,7 +45,7 @@ in/ | |||
| 45 | - `blob/`: `mod.rs` (`BlobStore` trait: `put_stream`, `adopt_file`, `open_range`, `size`, `delete`, `list`), | 45 | - `blob/`: `mod.rs` (`BlobStore` trait: `put_stream`, `adopt_file`, `open_range`, `size`, `delete`, `list`), |
| 46 | `local.rs` (temp file + fsync + rename + dir fsync), `s3.rs` (`object_store` S3 client for R2, Hetzner Object | 46 | `local.rs` (temp file + fsync + rename + dir fsync), `s3.rs` (`object_store` S3 client for R2, Hetzner Object |
| 47 | Storage or any S3 endpoint; multipart for large objects) | 47 | Storage or any S3 endpoint; multipart for large objects) |
| 48 | -- `thumbs.rs`: images with the `image` crate (decode limits: 64 MiB source, 40 megapixels, 10 s on | 48 | +- `thumbs.rs`: images with the `image` crate (decode limits: 64 MiB source, 10000 px per side and 256 MiB decoded, 10 s on |
| 49 | `spawn_blocking`), video through `ffmpeg` when present (10 s kill, temp file in `data_dir/tmp` mode 0600), | 49 | `spawn_blocking`), video through `ffmpeg` when present (10 s kill, temp file in `data_dir/tmp` mode 0600), |
| 50 | WebP output, max edge 512 | 50 | WebP output, max edge 512 |
| 51 | - `store/`: `users.rs` (local mirror of members), `sessions.rs`, `folders.rs`, `files.rs`, `trash.rs`, | 51 | - `store/`: `users.rs` (local mirror of members), `sessions.rs`, `folders.rs`, `files.rs`, `trash.rs`, |
| @@ -202,10 +202,13 @@ and has no sessions. | |||
| 202 | 202 | ||
| 203 | - Token: 32 random bytes; DB stores the SHA-256 and a sealed copy for the owner to re-display. | 203 | - Token: 32 random bytes; DB stores the SHA-256 and a sealed copy for the owner to re-display. |
| 204 | - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none). | 204 | - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none). |
| 205 | -- Password gate: POST checks the password (throttled per link and per IP: 10 failures / 15 min) and sets a cookie | 205 | +- Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and |
| 206 | + per link and client address: 10 failures / 15 min) and sets a cookie | ||
| 206 | `__Host-in_link_<id>` = HMAC-SHA256(instance key, "link-unlock:" || link id || password_hash), 12 h, so | 207 | `__Host-in_link_<id>` = HMAC-SHA256(instance key, "link-unlock:" || link id || password_hash), 12 h, so |
| 207 | changing the password or remint invalidates old unlocks. | 208 | changing the password or remint invalidates old unlocks. |
| 208 | -- Dead links (revoked, expired, target trashed or purged) answer one identical "link no longer works" page. | 209 | +- Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer |
| 210 | + works" page. A disabled owner's links and grants stop working at once and are not deleted: enabling the owner | ||
| 211 | + again restores them. | ||
| 209 | - Remint creates the new link and revokes the old one in one transaction. | 212 | - Remint creates the new link and revokes the old one in one transaction. |
| 210 | 213 | ||
| 211 | --- | 214 | --- |
| @@ -215,8 +218,10 @@ and has no sessions. | |||
| 215 | - **directory**: full fetch, then stream (contracts.md 3), resync on gap; applies member changes; on | 218 | - **directory**: full fetch, then stream (contracts.md 3), resync on gap; applies member changes; on |
| 216 | `disabled` or `deleted` ends the person's sessions. Backoff 1 s → 30 s. | 219 | `disabled` or `deleted` ends the person's sessions. Backoff 1 s → 30 s. |
| 217 | - **family**: fetches the switcher list every 5 minutes. | 220 | - **family**: fetches the switcher list every 5 minutes. |
| 218 | -- **thumbs**: picks `pending` files, generates thumbnails with bounded concurrency (2), marks ready/failed. | 221 | +- **thumbs**: picks `pending` files, generates thumbnails one at a time (see `thumbs_worker.rs` for why), with a |
| 219 | -- **sweeper** (hourly): expired sessions, expired uploads (staging removed), seen JTIs, trash past | 222 | + 10 s limit per decode, marks ready/failed. A decode that outlives its limit keeps its slot until it returns. |
| 223 | +- **sweeper** (hourly): expired sessions, expired uploads, staging directories that no open upload names (24 h old, | ||
| 224 | + which retries failed removals), seen JTIs, trash past | ||
| 220 | `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly). | 225 | `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly). |
| 221 | - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from | 226 | - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from |
| 222 | `in.key`, checked before a restore parses anything), keep N, dead-man pings. | 227 | `in.key`, checked before a restore parses anything), keep N, dead-man pings. |