diff --git a/Cargo.lock b/Cargo.lock index bb4bd51..e1eba03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1883,6 +1883,7 @@ dependencies = [ "tracing", "turso", "ulid", + "unicode-normalization", ] [[package]] @@ -1895,12 +1896,15 @@ dependencies = [ "grass", "hex", "http", + "http-body", + "http-body-util", "in-core", "jsonwebtoken", "rand 0.10.3", "reqwest", "serde", "serde_json", + "serde_urlencoded", "sha2 0.11.1", "tempfile", "thiserror", @@ -4963,6 +4967,15 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-width" version = "0.1.14" diff --git a/Cargo.toml b/Cargo.toml index 5685138..0391c33 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,8 @@ grass = "0.13.4" hex = "0.4.3" hmac = "0.13.0" http = "1.5.0" +http-body = "1.1.0" +http-body-util = "0.1.5" in-core = { path = "crates/in-core" } ipnet = "2.12.2" jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } @@ -59,6 +61,7 @@ rand = "0.10.3" reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] } serde = "1.0.229" serde_json = "1.0.154" +serde_urlencoded = "0.7.1" sha2 = "0.11.1" subtle = "2.6.1" tempfile = "3.27.0" @@ -71,4 +74,5 @@ tracing = "0.1.44" tracing-subscriber = "0.3.23" turso = "0.8.3" ulid = "3.0.0" +unicode-normalization = "0.1.26" diff --git a/crates/in-core/Cargo.toml b/crates/in-core/Cargo.toml index 782d3f6..07ad69b 100644 --- a/crates/in-core/Cargo.toml +++ b/crates/in-core/Cargo.toml @@ -29,6 +29,7 @@ toml.workspace = true tracing.workspace = true turso.workspace = true ulid.workspace = true +unicode-normalization.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/in-core/src/names.rs b/crates/in-core/src/names.rs index 9a995fa..72542f7 100644 --- a/crates/in-core/src/names.rs +++ b/crates/in-core/src/names.rs @@ -1,12 +1,64 @@ //! Display-name rules for files and folders. A name is shown as typed, but it never carries folders, //! control characters or more than 255 characters. Names are compared exactly; the database enforces //! uniqueness among live items in one folder. +//! +//! Two entry points, one per trust level. [`validate_name`] is for names a person types: it refuses +//! what it does not like, so the person sees why. [`upload_name`] is for the file name a browser sends +//! with an upload: that name is untrusted, so it is cleaned instead of refused. Both return the name in +//! Unicode NFC, so `e` plus a combining accent and the precomposed letter compare equal. + +use unicode_normalization::UnicodeNormalization; + +use crate::error::{Error, Result}; /// Longest name in characters (not bytes). pub const MAX_NAME_CHARS: usize = 255; +/// Longest name in bytes, the limit that [`validate_name`] enforces. +pub const MAX_NAME_BYTES: usize = 255; /// Name given to an item whose input has no usable characters left. pub const UNTITLED: &str = "Untitled"; +/// Checks a name typed by a person and returns it trimmed and in NFC. Refusals are +/// `Invalid` with a fixed reason word: `name_empty`, `name_reserved` (`.` or `..`), `name_too_long` +/// (over [`MAX_NAME_BYTES`]) or `name_bad_char` (a `/`, a `\`, a NUL or any other control character). +pub fn validate_name(input: &str) -> Result { + let name: String = input.trim().nfc().collect(); + if name.is_empty() { + return Err(Error::Invalid("name_empty".into())); + } + if name == "." || name == ".." { + return Err(Error::Invalid("name_reserved".into())); + } + if name.len() > MAX_NAME_BYTES { + return Err(Error::Invalid("name_too_long".into())); + } + if name + .chars() + .any(|c| matches!(c, '/' | '\\') || c.is_control()) + { + return Err(Error::Invalid("name_bad_char".into())); + } + Ok(name) +} + +/// Cleans the file name a browser sent with an upload. Path components are dropped, control +/// characters removed, the result put in NFC and cut to [`MAX_NAME_BYTES`] at a character boundary. +/// Input with nothing usable left becomes [`UNTITLED`]. The result always passes [`validate_name`]. +pub fn upload_name(client_name: &str) -> String { + let cleaned: String = display_name(client_name).nfc().collect(); + let mut out = String::new(); + for c in cleaned.chars() { + if out.len() + c.len_utf8() > MAX_NAME_BYTES { + break; + } + out.push(c); + } + if out.is_empty() || out == "." || out == ".." { + return UNTITLED.to_string(); + } + out +} + /// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt` /// becomes `c.txt`. Control characters are dropped, surrounding spaces are trimmed, and input with /// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`]. @@ -83,6 +135,32 @@ mod tests { } } + #[test] + fn validate_name_refuses_what_a_person_should_not_type() { + assert_eq!(validate_name(" Trip ").unwrap(), "Trip"); + assert!(matches!(validate_name(" "), Err(Error::Invalid(m)) if m == "name_empty")); + assert!(matches!(validate_name(".."), Err(Error::Invalid(m)) if m == "name_reserved")); + assert!(matches!(validate_name("a/b"), Err(Error::Invalid(m)) if m == "name_bad_char")); + assert!(matches!(validate_name("a\\b"), Err(Error::Invalid(m)) if m == "name_bad_char")); + assert!(matches!(validate_name("a\0b"), Err(Error::Invalid(m)) if m == "name_bad_char")); + assert!( + matches!(validate_name(&"a".repeat(256)), Err(Error::Invalid(m)) if m == "name_too_long") + ); + // Precomposed and decomposed forms of the same letter come out equal. + assert_eq!(validate_name("e\u{301}").unwrap(), "\u{e9}"); + } + + #[test] + fn upload_name_cleans_instead_of_refusing() { + assert_eq!(upload_name("..\\..\\evil\u{0}.exe"), "evil.exe"); + assert_eq!(upload_name("/etc/passwd"), "passwd"); + assert_eq!(upload_name(".."), UNTITLED); + let long = format!("{}.txt", "\u{e9}".repeat(200)); + let cut = upload_name(&long); + assert!(cut.len() <= MAX_NAME_BYTES); + assert!(validate_name(&cut).is_ok()); + } + #[test] fn display_name_cuts_long_names_by_characters() { let long = "é".repeat(300); diff --git a/crates/in-core/src/store/folders.rs b/crates/in-core/src/store/folders.rs index 500c119..d186246 100644 --- a/crates/in-core/src/store/folders.rs +++ b/crates/in-core/src/store/folders.rs @@ -271,6 +271,21 @@ impl Store { Ok(Listing { folders, files }) } + /// Every live folder of `owner`, sorted by name. The move picker builds the tree from it. + pub async fn live_folders(&self, owner: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {FOLDER_COLS} FROM folders WHERE owner = ?1 AND trashed_at IS NULL \ + ORDER BY name, id" + ), + (owner.to_string(),), + map_folder, + ) + .await + } + /// The chain of folders from the top level down to `folder`, inclusive, for breadcrumbs. The folder /// must be owned by `owner`; trashed folders are shown too, so the trash page can use it. pub async fn folder_path(&self, owner: &str, folder: &str) -> Result> { diff --git a/crates/in-web/Cargo.toml b/crates/in-web/Cargo.toml index 1a37ce0..f7ab435 100644 --- a/crates/in-web/Cargo.toml +++ b/crates/in-web/Cargo.toml @@ -14,6 +14,8 @@ path = "src/main.rs" base64.workspace = true futures-util.workspace = true http.workspace = true +http-body.workspace = true +http-body-util.workspace = true in-core.workspace = true jsonwebtoken.workspace = true rand.workspace = true @@ -31,6 +33,7 @@ tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } [dev-dependencies] +serde_urlencoded.workspace = true # jsonwebtoken 11 pins ed25519-dalek 2.x; the tests make Ed25519 keys with the same version. ed25519-dalek = { workspace = true, features = ["pkcs8"] } tempfile.workspace = true diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs index a5b5668..f6200ff 100644 --- a/crates/in-web/src/boot.rs +++ b/crates/in-web/src/boot.rs @@ -21,11 +21,12 @@ use tokio::net::TcpListener; use tokio::signal::unix::{SignalKind, signal}; use tokio::sync::watch; use topcoat::cookie::RouterBuilderCookieExt; -use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; +use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; use crate::directory; use crate::live::LiveHub; use crate::oidc::OidcClient; +use crate::pages::files; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; @@ -166,6 +167,8 @@ pub fn router(state: AppState) -> Router { .discover() .app_context(state) .cookies() + // The upload form streams, but the body limit still caps how much one request may send. + .layer(BodyLimit::max(files::SMALL_UPLOAD_CEILING).at("/files")) .layer(security) .layer(NotFoundLayer) .build() diff --git a/crates/in-web/src/i18n/drive.rs b/crates/in-web/src/i18n/drive.rs new file mode 100644 index 0000000..c054d17 --- /dev/null +++ b/crates/in-web/src/i18n/drive.rs @@ -0,0 +1,317 @@ +//! Strings of the drive: listings, folders, uploads, the trash, the move picker, the file page and the +//! notices and refusals that Post/Redirect/Get carries back. The keys are exhaustive per language, so a +//! missing Turkish text does not compile. +//! +//! Notices and refusals travel in the query string as fixed words (`?notice=uploaded`). The page maps a +//! word to its text here; a word it does not know is shown as nothing, never echoed. + +use super::Lang; + +/// One variant per phrase of the drive. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DK { + /// The title of the drive and the first breadcrumb. + Drive, + /// Title of the trash page. + Trash, + /// Title of the search results. + SearchResults, + /// Placeholder of the search box. + SearchPlaceholder, + /// The search button. + Search, + /// Label of the new-folder form. + NewFolder, + /// Label of the folder name field. + FolderName, + /// The button that creates a folder. + Create, + /// The button that uploads. + Upload, + /// Label of the file input. + ChooseFiles, + /// Column heading: name. + Name, + /// Column heading: size. + Size, + /// Column heading: when it was last changed. + Modified, + /// Column heading: kind of item. + Kind, + /// Column heading: row actions. + Actions, + /// Kind label: a folder. + FolderKind, + /// Kind label: a file. + FileKind, + /// The link that downloads a file. + Download, + /// The rename action. + Rename, + /// The save button of the rename form. + Save, + /// The move action. + Move, + /// Trash one item. + TrashItem, + /// Trash every checked item. + TrashSelected, + /// Empty folder heading. + EmptyFolder, + /// Empty folder hint. + EmptyFolderHint, + /// Search with no hits. + NoResults, + /// Trash with nothing in it. + TrashEmpty, + /// Explains what the trash does. + TrashNote, + /// Restore a trashed item. + Restore, + /// Delete a trashed item now. + PurgeNow, + /// Delete everything in the trash. + EmptyTrash, + /// Heading of the move picker. + MoveTo, + /// The top level of the drive in the move picker. + TopLevel, + /// The picker's hint. + PickHint, + /// Cancel a form and go back. + Back, + /// Field label: the place the file is in. + Location, + /// Field label: the MIME type. + MimeType, + /// Field label: when it was uploaded. + Uploaded, + /// Field label: how many times it was downloaded. + Downloads, + /// Link to view the bytes in the browser. + OpenRaw, + /// Accessible name of the breadcrumb trail. + Location2, + /// Label of the quota bar. + Storage, + /// Notice: a folder was created. + NoticeCreated, + /// Notice: a name was changed. + NoticeRenamed, + /// Notice: an item was moved. + NoticeMoved, + /// Notice: items went to the trash. + NoticeTrashed, + /// Notice: items were restored. + NoticeRestored, + /// Notice: items were deleted for good. + NoticePurged, + /// Notice: the trash was emptied. + NoticeEmptied, + /// Notice: the upload finished. + NoticeUploaded, + /// Refusal: a live name is taken. + RefuseNameTaken, + /// Refusal: the quota has no room. + RefuseQuota, + /// Refusal: the file is over the upload limit. + RefuseTooLarge, + /// Refusal: the name is empty. + RefuseNameEmpty, + /// Refusal: the name is `.` or `..`. + RefuseNameReserved, + /// Refusal: the name is too long. + RefuseNameTooLong, + /// Refusal: the name holds a slash, backslash or control character. + RefuseNameBadChar, + /// Refusal: a folder would move into itself. + RefuseCycle, + /// Refusal: the item is not in the trash. + RefuseNotInTrash, + /// Refusal: no free postfix exists. + RefuseTooManyNames, + /// Refusal: nothing else is known. + RefuseGeneric, + /// Refusal: the upload had no file in it. + RefuseNoFile, +} + +/// The text of `key` in `lang`. +pub fn d(lang: Lang, key: DK) -> &'static str { + match (key, lang) { + (DK::Drive, Lang::En) => "Drive", + (DK::Drive, Lang::Tr) => "Sürücü", + (DK::Trash, Lang::En) => "Trash", + (DK::Trash, Lang::Tr) => "Çöp", + (DK::SearchResults, Lang::En) => "Search results", + (DK::SearchResults, Lang::Tr) => "Arama sonuçları", + (DK::SearchPlaceholder, Lang::En) => "Search your files", + (DK::SearchPlaceholder, Lang::Tr) => "Dosyalarınızda ara", + (DK::Search, Lang::En) => "Search", + (DK::Search, Lang::Tr) => "Ara", + (DK::NewFolder, Lang::En) => "New folder", + (DK::NewFolder, Lang::Tr) => "Yeni klasör", + (DK::FolderName, Lang::En) => "Folder name", + (DK::FolderName, Lang::Tr) => "Klasör adı", + (DK::Create, Lang::En) => "Create", + (DK::Create, Lang::Tr) => "Oluştur", + (DK::Upload, Lang::En) => "Upload", + (DK::Upload, Lang::Tr) => "Yükle", + (DK::ChooseFiles, Lang::En) => "Files", + (DK::ChooseFiles, Lang::Tr) => "Dosyalar", + (DK::Name, Lang::En) => "Name", + (DK::Name, Lang::Tr) => "Ad", + (DK::Size, Lang::En) => "Size", + (DK::Size, Lang::Tr) => "Boyut", + (DK::Modified, Lang::En) => "Modified", + (DK::Modified, Lang::Tr) => "Değişiklik", + (DK::Kind, Lang::En) => "Kind", + (DK::Kind, Lang::Tr) => "Tür", + (DK::Actions, Lang::En) => "Actions", + (DK::Actions, Lang::Tr) => "İşlemler", + (DK::FolderKind, Lang::En) => "Folder", + (DK::FolderKind, Lang::Tr) => "Klasör", + (DK::FileKind, Lang::En) => "File", + (DK::FileKind, Lang::Tr) => "Dosya", + (DK::Download, Lang::En) => "Download", + (DK::Download, Lang::Tr) => "İndir", + (DK::Rename, Lang::En) => "Rename", + (DK::Rename, Lang::Tr) => "Yeniden adlandır", + (DK::Save, Lang::En) => "Save", + (DK::Save, Lang::Tr) => "Kaydet", + (DK::Move, Lang::En) => "Move", + (DK::Move, Lang::Tr) => "Taşı", + (DK::TrashItem, Lang::En) => "Move to trash", + (DK::TrashItem, Lang::Tr) => "Çöpe taşı", + (DK::TrashSelected, Lang::En) => "Move selected to trash", + (DK::TrashSelected, Lang::Tr) => "Seçilenleri çöpe taşı", + (DK::EmptyFolder, Lang::En) => "This folder is empty.", + (DK::EmptyFolder, Lang::Tr) => "Bu klasör boş.", + (DK::EmptyFolderHint, Lang::En) => "Upload files or create a folder to start.", + (DK::EmptyFolderHint, Lang::Tr) => "Başlamak için dosya yükleyin ya da klasör oluşturun.", + (DK::NoResults, Lang::En) => "Nothing matches your search.", + (DK::NoResults, Lang::Tr) => "Aramanızla eşleşen bir şey yok.", + (DK::TrashEmpty, Lang::En) => "The trash is empty.", + (DK::TrashEmpty, Lang::Tr) => "Çöp boş.", + (DK::TrashNote, Lang::En) => { + "Items stay here until you delete them for good or empty the trash." + } + (DK::TrashNote, Lang::Tr) => { + "Öğeler, siz kalıcı olarak silene ya da çöpü boşaltana kadar burada kalır." + } + (DK::Restore, Lang::En) => "Restore", + (DK::Restore, Lang::Tr) => "Geri yükle", + (DK::PurgeNow, Lang::En) => "Delete for good", + (DK::PurgeNow, Lang::Tr) => "Kalıcı olarak sil", + (DK::EmptyTrash, Lang::En) => "Empty trash", + (DK::EmptyTrash, Lang::Tr) => "Çöpü boşalt", + (DK::MoveTo, Lang::En) => "Move to", + (DK::MoveTo, Lang::Tr) => "Şuraya taşı", + (DK::TopLevel, Lang::En) => "Drive (top level)", + (DK::TopLevel, Lang::Tr) => "Sürücü (en üst düzey)", + (DK::PickHint, Lang::En) => "Choose the folder to move into.", + (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.", + (DK::Back, Lang::En) => "Back", + (DK::Back, Lang::Tr) => "Geri", + (DK::Location, Lang::En) => "Location", + (DK::Location, Lang::Tr) => "Konum", + (DK::MimeType, Lang::En) => "Type", + (DK::MimeType, Lang::Tr) => "Tür", + (DK::Uploaded, Lang::En) => "Uploaded", + (DK::Uploaded, Lang::Tr) => "Yüklendi", + (DK::Downloads, Lang::En) => "Downloads", + (DK::Downloads, Lang::Tr) => "İndirme", + (DK::OpenRaw, Lang::En) => "Open in the browser", + (DK::OpenRaw, Lang::Tr) => "Tarayıcıda aç", + (DK::Location2, Lang::En) => "Location", + (DK::Location2, Lang::Tr) => "Konum", + (DK::Storage, Lang::En) => "Storage", + (DK::Storage, Lang::Tr) => "Depolama", + (DK::NoticeCreated, Lang::En) => "The folder was created.", + (DK::NoticeCreated, Lang::Tr) => "Klasör oluşturuldu.", + (DK::NoticeRenamed, Lang::En) => "The name was changed.", + (DK::NoticeRenamed, Lang::Tr) => "Ad değiştirildi.", + (DK::NoticeMoved, Lang::En) => "The item was moved.", + (DK::NoticeMoved, Lang::Tr) => "Öğe taşındı.", + (DK::NoticeTrashed, Lang::En) => "The items were moved to the trash.", + (DK::NoticeTrashed, Lang::Tr) => "Öğeler çöpe taşındı.", + (DK::NoticeRestored, Lang::En) => "The items were restored.", + (DK::NoticeRestored, Lang::Tr) => "Öğeler geri yüklendi.", + (DK::NoticePurged, Lang::En) => "The items were deleted for good.", + (DK::NoticePurged, Lang::Tr) => "Öğeler kalıcı olarak silindi.", + (DK::NoticeEmptied, Lang::En) => "The trash was emptied.", + (DK::NoticeEmptied, Lang::Tr) => "Çöp boşaltıldı.", + (DK::NoticeUploaded, Lang::En) => "The upload finished.", + (DK::NoticeUploaded, Lang::Tr) => "Yükleme tamamlandı.", + (DK::RefuseNameTaken, Lang::En) => "An item with this name already exists here.", + (DK::RefuseNameTaken, Lang::Tr) => "Bu konumda bu adla bir öğe zaten var.", + (DK::RefuseQuota, Lang::En) => "There is not enough storage left for this file.", + (DK::RefuseQuota, Lang::Tr) => "Bu dosya için yeterli depolama alanı kalmadı.", + (DK::RefuseTooLarge, Lang::En) => "The file is larger than the upload limit.", + (DK::RefuseTooLarge, Lang::Tr) => "Dosya yükleme sınırından büyük.", + (DK::RefuseNameEmpty, Lang::En) => "The name is empty.", + (DK::RefuseNameEmpty, Lang::Tr) => "Ad boş.", + (DK::RefuseNameReserved, Lang::En) => "This name is not allowed.", + (DK::RefuseNameReserved, Lang::Tr) => "Bu ad kullanılamaz.", + (DK::RefuseNameTooLong, Lang::En) => "The name is too long (255 bytes at most).", + (DK::RefuseNameTooLong, Lang::Tr) => "Ad çok uzun (en fazla 255 bayt).", + (DK::RefuseNameBadChar, Lang::En) => { + "The name contains a slash, a backslash or a control character." + } + (DK::RefuseNameBadChar, Lang::Tr) => { + "Ad eğik çizgi, ters eğik çizgi ya da denetim karakteri içeriyor." + } + (DK::RefuseCycle, Lang::En) => "A folder cannot be moved into itself.", + (DK::RefuseCycle, Lang::Tr) => "Bir klasör kendi içine taşınamaz.", + (DK::RefuseNotInTrash, Lang::En) => "That item is not in the trash.", + (DK::RefuseNotInTrash, Lang::Tr) => "Bu öğe çöpte değil.", + (DK::RefuseTooManyNames, Lang::En) => "Too many items already use this name.", + (DK::RefuseTooManyNames, Lang::Tr) => "Bu adı kullanan çok fazla öğe var.", + (DK::RefuseGeneric, Lang::En) => "The change could not be made.", + (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.", + (DK::RefuseNoFile, Lang::En) => "Choose at least one file.", + (DK::RefuseNoFile, Lang::Tr) => "En az bir dosya seçin.", + } +} + +/// The quota line: how much is used of the quota, both already formatted. +pub fn quota_text(lang: Lang, used: &str, quota: &str) -> String { + match lang { + Lang::En => format!("{used} of {quota} used"), + Lang::Tr => format!("{quota} içinden {used} kullanıldı"), + } +} + +/// The text of a notice word from a redirect, or `None` for a word this build does not know. +pub fn notice_text(lang: Lang, word: &str) -> Option<&'static str> { + Some(match word { + "created" => d(lang, DK::NoticeCreated), + "renamed" => d(lang, DK::NoticeRenamed), + "moved" => d(lang, DK::NoticeMoved), + "trashed" => d(lang, DK::NoticeTrashed), + "restored" => d(lang, DK::NoticeRestored), + "purged" => d(lang, DK::NoticePurged), + "emptied" => d(lang, DK::NoticeEmptied), + "uploaded" => d(lang, DK::NoticeUploaded), + _ => return None, + }) +} + +/// The text of a refusal word from a redirect, or `None` for a word this build does not know. +pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> { + Some(match word { + "name_taken" => d(lang, DK::RefuseNameTaken), + "quota_exceeded" => d(lang, DK::RefuseQuota), + "too_large" => d(lang, DK::RefuseTooLarge), + "name_empty" => d(lang, DK::RefuseNameEmpty), + "name_reserved" => d(lang, DK::RefuseNameReserved), + "name_too_long" => d(lang, DK::RefuseNameTooLong), + "name_bad_char" => d(lang, DK::RefuseNameBadChar), + "cycle" => d(lang, DK::RefuseCycle), + "not_in_trash" => d(lang, DK::RefuseNotInTrash), + "too_many_names" => d(lang, DK::RefuseTooManyNames), + "no_file" => d(lang, DK::RefuseNoFile), + "generic" => d(lang, DK::RefuseGeneric), + _ => return None, + }) +} diff --git a/crates/in-web/src/i18n/mod.rs b/crates/in-web/src/i18n/mod.rs index 5f336b9..f2476a1 100644 --- a/crates/in-web/src/i18n/mod.rs +++ b/crates/in-web/src/i18n/mod.rs @@ -7,6 +7,7 @@ //! This module decides the language. It does not format sentences with values; those get small //! helper functions next to their keys. +pub mod drive; pub mod shell; use topcoat::context::Cx; diff --git a/crates/in-web/src/i18n/shell.rs b/crates/in-web/src/i18n/shell.rs index 38a57eb..5beb72d 100644 --- a/crates/in-web/src/i18n/shell.rs +++ b/crates/in-web/src/i18n/shell.rs @@ -26,8 +26,6 @@ pub enum K { SignedOutBody, /// The button that starts sign-in. SignIn, - /// The placeholder under the greeting until the drive exists. - DriveComesNext, /// The button in the user menu that ends the session. SignOut, /// Heading of the page that explains a sign-in that did not finish. @@ -44,14 +42,6 @@ pub enum K { ProblemDeniedBody, } -/// The greeting for a signed-in person. The name is inserted as text; the view escapes it. -pub fn greeting(lang: Lang, name: &str) -> String { - match lang { - Lang::En => format!("Hello, {name}."), - Lang::Tr => format!("Merhaba, {name}."), - } -} - /// The text of `key` in `lang`. pub fn t(lang: Lang, key: K) -> &'static str { match (key, lang) { @@ -75,8 +65,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::SignedOutBody, Lang::Tr) => "Dosyalarınızı açmak için aile hesabınızla oturum açın.", (K::SignIn, Lang::En) => "Sign in", (K::SignIn, Lang::Tr) => "Oturum aç", - (K::DriveComesNext, Lang::En) => "The drive comes next. Your files will appear here.", - (K::DriveComesNext, Lang::Tr) => "Sürücü sıradaki adım. Dosyalarınız burada görünecek.", (K::SignOut, Lang::En) => "Sign out", (K::SignOut, Lang::Tr) => "Oturumu kapat", (K::ProblemFailedTitle, Lang::En) => "Sign-in did not finish", diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index 324ab51..b301206 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -14,6 +14,7 @@ mod live; mod oidc; mod pages; mod security; +mod serve_bytes; mod state; mod views; diff --git a/crates/in-web/src/pages/drive.rs b/crates/in-web/src/pages/drive.rs new file mode 100644 index 0000000..efeab45 --- /dev/null +++ b/crates/in-web/src/pages/drive.rs @@ -0,0 +1,702 @@ +//! The drive's listing pages: the root (`/`), a folder (`/f/{id}`), search (`/search`), the live stream +//! that refreshes an open listing, the folder writes (create, rename, move, trash) and the folder move +//! picker. The file pages live in `files.rs`, the trash in `trash.rs`. +//! +//! Authorization: each item is loaded by id and passed to `authz::authorize`. A refusal to see the item +//! is `404`, so a foreign or missing id looks the same as no item at all. A refusal to change an item the +//! viewer can see is `403`. Every write checks its CSRF token before it touches anything, and every write +//! ends in a redirect (Post/Redirect/Get) back to the page named in the form's `back` field, which must +//! pass `safe_next`. Failures come back as a `refusal` word, successes as a `notice` word. + +use std::collections::{HashMap, HashSet}; +use std::fmt::Write as _; + +use in_core::authz::{self, Action, Actor, Denied, Grant, Target}; +use in_core::error::Error as CoreError; +use in_core::names::validate_name; +use in_core::store::files::File; +use in_core::store::folders::{Folder, Listing}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{page, parse_query_params, path_param_segment, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::{Viewer, require_csrf, require_member, safe_next}; +use crate::i18n::Lang; +use crate::i18n::drive::{DK, d, refusal_text}; +use crate::i18n::lang; +use crate::live::{Topic, stream_changes}; +use crate::oidc::percent_encode; +use crate::state::AppState; +use crate::views::drive::{crumbs, flash, listing_table}; +use crate::views::{ViewerInfo, empty_state, shell}; + +/// How many search hits each kind shows. +const SEARCH_LIMIT: usize = 100; + +/// The query of a listing page. Every field is optional; unknown ones are ignored. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct ListQuery { + /// Sort key: `name` (default), `size` or `modified`. + pub sort: String, + /// `asc` (default) or `desc`. + pub dir: String, + /// The search text, on `/search` only. + pub q: String, + /// A notice word from a finished action. + pub notice: String, + /// A refusal word from a refused action. + pub refusal: String, +} + +/// The column a listing is sorted by. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SortKey { + /// By name (the default). + Name, + /// By size. Folders have none, so they keep name order. + Size, + /// By the last change. + Modified, +} + +impl SortKey { + /// The key a query asks for. Anything unknown is the default. + pub fn of(raw: &str) -> Self { + match raw { + "size" => SortKey::Size, + "modified" => SortKey::Modified, + _ => SortKey::Name, + } + } + + /// The word the key has in a URL. + pub fn word(self) -> &'static str { + match self { + SortKey::Name => "name", + SortKey::Size => "size", + SortKey::Modified => "modified", + } + } +} + +/// Everything a listing page shows, built before the page is rendered. +pub struct Board { + /// The page title and the heading of the listing. + pub heading: String, + /// The folders above the current one, top level first. + pub trail: Vec, + /// The current folder, `None` at the drive root and on search. + pub folder: Option, + /// The search text, empty for a listing. + pub query: String, + /// The folders shown, sorted. + pub folders: Vec, + /// The files shown, sorted. + pub files: Vec, + /// The sort column. + pub sort: SortKey, + /// Whether the sort is descending. + pub descending: bool, + /// The session's CSRF token for the forms. + pub csrf: String, + /// The page the forms return to. + pub back: String, + /// A notice word from the query, if any. + pub notice: String, + /// A refusal word from the query, if any. + pub refusal: String, + /// The stream that refreshes the listing, if it is live. + pub live: Option, + /// The start of the sort links: the listing's URL, ending in `?` or `&`. + pub base: String, +} + +/// The language of a viewer: the stored override, else the `im` language, else the request. +pub fn viewer_lang(cx: &Cx, viewer: &Viewer) -> Lang { + lang( + cx, + Some( + viewer + .member + .locale_override + .as_deref() + .unwrap_or(viewer.member.locale.as_str()), + ), + ) +} + +/// Maps a refusal of the drive's authorization to the HTTP answer. A listing or a view that is refused +/// is always `404`; a change that is refused to someone who can see the item is `403`. +pub fn check(viewer: &Viewer, owner: &str, trashed: bool, action: Action) -> Result<()> { + let target = Target { + owner, + trashed, + inside_link: false, + }; + let actor = Actor::Member { + sub: &viewer.member.sub, + is_admin: viewer.member.is_admin, + }; + match authz::authorize(actor, target, Grant::None, action) { + Ok(()) => Ok(()), + Err(Denied::NotFound) => Err(not_found().into()), + Err(Denied::Forbidden) if matches!(action, Action::List | Action::View) => { + Err(not_found().into()) + } + Err(Denied::Forbidden) => Err(forbidden().into()), + } +} + +/// A live folder by id, after the authorization for `action`. A missing id is `404`. +pub async fn folder_for( + state: &AppState, + viewer: &Viewer, + id: &str, + action: Action, +) -> Result { + let folder = state.store.folder(id).await?.ok_or_else(not_found)?; + check(viewer, &folder.owner, folder.trashed_at.is_some(), action)?; + Ok(folder) +} + +/// The folder a form names in its `parent` (or `folder`) field, checked for `Write`. A blank field is +/// the top level and gives `None`. +pub async fn optional_folder( + state: &AppState, + viewer: &Viewer, + raw: &str, +) -> Result> { + let raw = raw.trim(); + if raw.is_empty() { + return Ok(None); + } + let folder = folder_for(state, viewer, raw, Action::Write).await?; + Ok(Some(folder.id)) +} + +/// The refusal word of an error the person can act on: a name taken, a quota, a bad name, a cycle. Other +/// errors have none and are server failures or missing items. +pub fn refusal_word(error: &CoreError) -> Option { + match error { + CoreError::Conflict(word) | CoreError::Invalid(word) | CoreError::Forbidden(word) => { + Some(if refusal_text(Lang::En, word).is_some() { + word.clone() + } else { + "generic".to_owned() + }) + } + _ => None, + } +} + +/// The return target of a form: its `back` field when that is a safe path, else the given default. +pub fn back_or(raw: &str, default: &str) -> String { + safe_next(raw.trim()).unwrap_or(default).to_owned() +} + +/// Adds a `key=value` pair to a path's query. The values used here are fixed words, so no escaping is +/// needed. +pub fn with_param(path: &str, key: &str, value: &str) -> String { + let sep = if path.contains('?') { '&' } else { '?' }; + format!("{path}{sep}{key}={value}") +} + +/// The redirect after a successful change, carrying a notice word. +pub fn done(back: &str, notice: &str) -> SeeOther { + see_other(with_param(back, "notice", notice)) +} + +/// The answer to a failed change. A refusal the person can act on goes back to `back` with a refusal +/// word; a missing item is `404`; anything else is a server error. +pub fn refused(back: &str, error: CoreError) -> Result { + if matches!(error, CoreError::NotFound) { + return Err(not_found().into()); + } + match refusal_word(&error) { + Some(word) => Ok(see_other(with_param(back, "refusal", &word))), + None => Err(error.into()), + } +} + +/// Tells the owner's open pages that their drive changed. +pub fn changed(state: &AppState, owner: &str) { + state.live.bump(&Topic::Drive(owner.to_owned())); +} + +/// Sorts a listing: folders first, then files; each group by the key, ties by id. Descending reverses +/// the whole order inside each group. +pub fn sort_listing(listing: &mut Listing, key: SortKey, descending: bool) { + listing.folders.sort_by(|a, b| { + let by_key = match key { + SortKey::Modified => a.updated_at.cmp(&b.updated_at), + _ => a.name.cmp(&b.name), + }; + by_key.then_with(|| a.id.cmp(&b.id)) + }); + listing.files.sort_by(|a, b| { + let by_key = match key { + SortKey::Name => a.name.cmp(&b.name), + SortKey::Size => a.size.cmp(&b.size), + SortKey::Modified => a.updated_at.cmp(&b.updated_at), + }; + by_key.then_with(|| a.id.cmp(&b.id)) + }); + if descending { + listing.folders.reverse(); + listing.files.reverse(); + } +} + +/// The folders of a tree, depth first, each with its depth, in the order the picker shows them. The +/// folder `skip` and everything beneath it are left out, so a folder cannot be picked into itself. +pub fn tree_rows(folders: &[Folder], skip: Option<&str>) -> Vec<(usize, Folder)> { + let ids: HashSet<&str> = folders.iter().map(|f| f.id.as_str()).collect(); + let mut children: HashMap<&str, Vec<&Folder>> = HashMap::new(); + let mut roots: Vec<&Folder> = Vec::new(); + for folder in folders { + match folder.parent_id.as_deref() { + Some(parent) if ids.contains(parent) => { + children.entry(parent).or_default().push(folder); + } + _ => roots.push(folder), + } + } + let mut out = Vec::new(); + let mut stack: Vec<(usize, &Folder)> = roots.iter().rev().map(|f| (0, *f)).collect(); + while let Some((depth, folder)) = stack.pop() { + if Some(folder.id.as_str()) == skip { + continue; + } + out.push((depth, folder.clone())); + if let Some(kids) = children.get(folder.id.as_str()) { + for kid in kids.iter().rev() { + stack.push((depth + 1, kid)); + } + } + } + out +} + +/// Builds the listing of a folder (or of the drive root) for a viewer. +pub async fn folder_board( + state: &AppState, + viewer: &Viewer, + folder: Option, + query: &ListQuery, + lang: Lang, +) -> Result { + let owner = viewer.member.sub.clone(); + let (heading, trail) = match folder.as_deref() { + None => (d(lang, DK::Drive).to_owned(), Vec::new()), + Some(id) => { + let row = folder_for(state, viewer, id, Action::List).await?; + let trail = state.store.folder_path(&owner, id).await?; + (row.name.clone(), trail) + } + }; + let mut listing = state.store.list_children(&owner, folder.as_deref()).await?; + let sort = SortKey::of(&query.sort); + let descending = query.dir == "desc"; + sort_listing(&mut listing, sort, descending); + let (base, live, back) = match folder.as_deref() { + None => ("/?".to_owned(), "/live/drive".to_owned(), "/".to_owned()), + Some(id) => ( + format!("/f/{id}?"), + format!("/live/drive?folder={id}"), + format!("/f/{id}"), + ), + }; + Ok(Board { + heading, + trail, + folder, + query: String::new(), + folders: listing.folders, + files: listing.files, + sort, + descending, + csrf: viewer.session.csrf_token.clone(), + back, + notice: query.notice.clone(), + refusal: query.refusal.clone(), + live: Some(live), + base, + }) +} + +/// Builds the search results of a viewer's own items. `q` must not be empty. +pub async fn search_board( + state: &AppState, + viewer: &Viewer, + query: &ListQuery, + lang: Lang, +) -> Result { + let q = query.q.trim().to_owned(); + let mut listing = state + .store + .search(&viewer.member.sub, &q, SEARCH_LIMIT) + .await?; + let sort = SortKey::of(&query.sort); + let descending = query.dir == "desc"; + sort_listing(&mut listing, sort, descending); + let enc = percent_encode(&q); + Ok(Board { + heading: d(lang, DK::SearchResults).to_owned(), + trail: Vec::new(), + folder: None, + query: q, + folders: listing.folders, + files: listing.files, + sort, + descending, + csrf: viewer.session.csrf_token.clone(), + back: format!("/search?q={enc}"), + notice: query.notice.clone(), + refusal: query.refusal.clone(), + live: None, + base: format!("/search?q={enc}&"), + }) +} + +/// The drive root's listing for a signed-in viewer. The start page uses it. +pub async fn root_board( + state: &AppState, + viewer: &Viewer, + query: &ListQuery, + lang: Lang, +) -> Result { + folder_board(state, viewer, None, query, lang).await +} + +/// The main content of a listing page: the heading, the trail, the flash line, the forms that create +/// and upload, and the table. Used by the drive pages and by the start page for a signed-in viewer. +#[component] +pub async fn drive_board(lang: Lang, board: &Board) -> Result { + let parent = board.folder.clone().unwrap_or_default(); + let in_search = !board.query.is_empty(); + let empty = board.folders.is_empty() && board.files.is_empty(); + let search_value = board.query.clone(); + Ok(view! { +
+

(board.heading.as_str())

+ if board.folder.is_some() { + crumbs(lang: lang, trail: &board.trail) + } + flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str()) +
+ + if !in_search { +
+ + + + + + +
+
+ + + + + + +
+ } +
+ if empty { + if in_search { + empty_state(title: d(lang, DK::NoResults)) + } else { + empty_state(title: d(lang, DK::EmptyFolder),

(d(lang, DK::EmptyFolderHint))

) + } + } else { + listing_table(lang: lang, folders: &board.folders, files: &board.files, csrf: board.csrf.as_str(), back: board.back.as_str(), sort: board.sort.word(), dir: if board.descending { "desc" } else { "asc" }, base: board.base.as_str()) + } +
+ }) +} + +/// The query of the live stream: the folder to follow, empty for the root. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct LiveQuery { + folder: String, +} + +/// A fingerprint of what a listing shows: every row's id, name, size and last change. Equal text means +/// the page would look the same, so the stream stays quiet. +fn fingerprint(listing: &Listing) -> String { + let mut text = String::new(); + for folder in &listing.folders { + let _ = writeln!( + text, + "d|{}|{}|{}", + folder.id, folder.name, folder.updated_at + ); + } + for file in &listing.files { + let _ = writeln!( + text, + "f|{}|{}|{}|{}", + file.id, file.name, file.size, file.updated_at + ); + } + text +} + +/// `GET /f/{folder_id}`: one folder's listing. +#[page("/f/{folder_id}")] +async fn folder_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let folder_id = path_param_segment(cx, "folder_id").to_owned(); + let query: ListQuery = parse_query_params(cx).unwrap_or_default(); + let board = folder_board(state, &viewer, Some(folder_id), &query, lang).await?; + let info = ViewerInfo::of(&viewer); + Ok(view! { + shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), + drive_board(lang: lang, board: &board) + ) + }) +} + +/// `GET /search?q=`: the viewer's own items whose names contain the text. Blank text goes to the root. +#[page("/search")] +async fn search_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let query: ListQuery = parse_query_params(cx).unwrap_or_default(); + if query.q.trim().is_empty() { + return Err(see_other("/").into()); + } + let board = search_board(state, &viewer, &query, lang).await?; + let info = ViewerInfo::of(&viewer); + Ok(view! { + shell(title: board.heading.as_str(), lang: lang, viewer: Some(&info), + drive_board(lang: lang, board: &board) + ) + }) +} + +/// `GET /live/drive?folder=`: the stream that tells an open listing to refresh. It sends a data-less +/// `changed` event when the rows change, and ends when the session is gone or the folder is. +#[route(GET "/live/drive")] +async fn drive_live(cx: &Cx, query: Option>) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let folder = query + .map(|Form(query)| query.folder) + .filter(|folder| !folder.trim().is_empty()); + if let Some(id) = folder.as_deref() { + folder_for(state, &viewer, id, Action::List).await?; + } + let owner = viewer.member.sub.clone(); + let token_hash = viewer.session.token_hash.clone(); + let store = state.store.clone(); + let topics = vec![Topic::Drive(owner.clone())]; + stream_changes(cx, &state.live, &topics, move || { + let store = store.clone(); + let owner = owner.clone(); + let folder = folder.clone(); + let token_hash = token_hash.clone(); + async move { + // A signed-out session ends the stream, so it stops showing the drive. + if store.session_by_token_hash(&token_hash).await?.is_none() { + return Err(not_found().into()); + } + let listing = store.list_children(&owner, folder.as_deref()).await?; + Ok(fingerprint(&listing)) + } + }) + .await +} + +/// The form of `POST /folders`: the CSRF token, the return page, the parent (blank for the top level) +/// and the name. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct CreateFolderForm { + csrf: String, + back: String, + parent: String, + name: String, +} + +/// `POST /folders`: creates a folder. A taken name gets the next postfix from the store. +#[route(POST "/folders")] +async fn create_folder(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let back = back_or(&form.back, "/"); + let parent = optional_folder(state, &viewer, &form.parent).await?; + let name = match validate_name(&form.name) { + Ok(name) => name, + Err(error) => return refused(&back, error), + }; + match state + .store + .create_folder(&viewer.member.sub, parent.as_deref(), &name) + .await + { + Ok(_) => { + changed(state, &viewer.member.sub); + Ok(done(&back, "created")) + } + Err(error) => refused(&back, error), + } +} + +/// The form of the folder and file rename, trash and move actions. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct ItemForm { + /// The CSRF token of the session. + pub csrf: String, + /// The page to return to. + pub back: String, + /// A new name, for a rename. + pub name: String, + /// The destination folder, for a move. Blank is the top level. + pub parent: String, +} + +/// `POST /folders/{id}/rename`. +#[route(POST "/folders/{id}/rename")] +async fn rename_folder(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/"); + folder_for(state, &viewer, &id, Action::Write).await?; + let name = match validate_name(&form.name) { + Ok(name) => name, + Err(error) => return refused(&back, error), + }; + match state + .store + .rename_folder(&viewer.member.sub, &id, &name) + .await + { + Ok(_) => { + changed(state, &viewer.member.sub); + Ok(done(&back, "renamed")) + } + Err(error) => refused(&back, error), + } +} + +/// `POST /folders/{id}/move`: the parent in the form is the new place (blank for the top level). A move +/// into the folder itself or its subtree is refused as a cycle. +#[route(POST "/folders/{id}/move")] +async fn move_folder(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/"); + folder_for(state, &viewer, &id, Action::Write).await?; + let parent = optional_folder(state, &viewer, &form.parent).await?; + match state + .store + .move_folder(&viewer.member.sub, &id, parent.as_deref()) + .await + { + Ok(_) => { + changed(state, &viewer.member.sub); + Ok(done(&back, "moved")) + } + Err(error) => refused(&back, error), + } +} + +/// `POST /folders/{id}/trash`: moves the folder and everything in it to the trash. +#[route(POST "/folders/{id}/trash")] +async fn trash_folder(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/"); + folder_for(state, &viewer, &id, Action::Write).await?; + match state.store.trash_folder(&viewer.member.sub, &id).await { + Ok(()) => { + changed(state, &viewer.member.sub); + Ok(done(&back, "trashed")) + } + Err(error) => refused(&back, error), + } +} + +/// `GET /folders/{id}/pick`: the move picker of a folder. Every live folder of the viewer is a button; the +/// folder itself and its subtree are left out. +#[page("/folders/{id}/pick")] +async fn pick_folder(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let id = path_param_segment(cx, "id").to_owned(); + let folder = folder_for(state, &viewer, &id, Action::Write).await?; + let all = state.store.live_folders(&viewer.member.sub).await?; + let rows = tree_rows(&all, Some(&id)); + let action = format!("/folders/{id}/move"); + let back = format!("/f/{id}"); + let csrf = viewer.session.csrf_token.clone(); + let info = ViewerInfo::of(&viewer); + let title = d(lang, DK::MoveTo); + Ok(view! { + shell(title: title, lang: lang, viewer: Some(&info), + pick_body(lang: lang, subject: folder.name.as_str(), action: action.as_str(), csrf: csrf.as_str(), back: back.as_str(), rows: &rows) + ) + }) +} + +/// The move picker's content: a button per destination, each a form that posts the move. Shared with the +/// file picker. +#[component] +pub async fn pick_body( + lang: Lang, + subject: &str, + action: &str, + csrf: &str, + back: &str, + rows: &[(usize, Folder)], +) -> Result { + Ok(view! { +
+

(d(lang, DK::MoveTo)) " \u{201c}" (subject) "\u{201d}"

+

(d(lang, DK::PickHint))

+
    +
  • +
    + + + + +
    +
  • + for (depth, folder) in rows { +
  • +
    + + + + +
    +
  • + } +
+

(d(lang, DK::Back))

+
+ }) +} diff --git a/crates/in-web/src/pages/files.rs b/crates/in-web/src/pages/files.rs new file mode 100644 index 0000000..1e587d8 --- /dev/null +++ b/crates/in-web/src/pages/files.rs @@ -0,0 +1,620 @@ +//! The file pages: the upload (`POST /files`), the file page (`/file/{id}`), its bytes +//! (`/file/{id}/download` and `/file/{id}/raw`, both through `serve_bytes`), the file writes (rename, +//! move, trash) and the file move picker. +//! +//! An upload streams. Each file part goes to a staging file under `data_dir/tmp` while its SHA-256 and +//! its first bytes are taken; the sniffed type decides the MIME type, never the uploader's claim. The quota +//! is checked before the bytes reach the blob store, so a refused file leaves nothing behind. The store +//! checks the quota again inside the insert transaction, which is what makes parallel uploads safe. If the +//! insert fails after the bytes were stored, the bytes are deleted, since no row names them. + +use in_core::authz::Action; +use in_core::names::{upload_name, validate_name}; +use in_core::quota; +use in_core::sniff::sniff; +use in_core::staging::{Staged, StagedFile}; +use in_core::store::files::{File, NewFile, files_blob_key}; +use in_core::store::new_id; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::content::multipart::{Field, Multipart}; +use topcoat::router::error::{SeeOther, bad_request, forbidden, not_found, see_other}; +use topcoat::router::page; +use topcoat::router::request::headers; +use topcoat::router::{parse_query_params, path_param_segment, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::{Viewer, require_csrf, require_member}; +use crate::i18n::Lang; +use crate::i18n::drive::{DK, d}; +use crate::pages::drive::{ + ItemForm, ListQuery, back_or, changed, check, done, optional_folder, pick_body, refusal_word, + refused, tree_rows, viewer_lang, with_param, +}; +use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes}; +use crate::state::AppState; +use crate::views::drive::{flash, size_text, stamp_text}; +use crate::views::{ViewerInfo, shell}; + +/// How many leading bytes of an upload the sniffer reads. Enough for every signature it knows. +const SNIFF_BYTES: usize = 8192; + +/// The upload limit a fresh instance uses: 64 MiB per file, unless the settings say otherwise. +pub const DEFAULT_SMALL_UPLOAD: u64 = 64 * 1024 * 1024; + +/// The most a single upload request may carry in total, in bytes. It is the body limit of `POST /files`; +/// a per-file limit above it has no effect. +pub const SMALL_UPLOAD_CEILING: usize = 1024 * 1024 * 1024; + +/// The settings key of the per-file upload limit, in bytes. +pub const SMALL_UPLOAD_SETTING: &str = "small_upload_bytes"; + +/// Longest text a form field may carry. Ids and names are far shorter; the cap stops a huge field from +/// being buffered. +const MAX_FIELD_BYTES: usize = 2048; + +/// The per-file upload limit in force now: the setting when it holds a sane number, else the default. +/// It is never above [`SMALL_UPLOAD_CEILING`]. +pub async fn upload_limit(state: &AppState) -> Result { + let setting = state.store.get_setting(SMALL_UPLOAD_SETTING).await?; + let limit = setting + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(DEFAULT_SMALL_UPLOAD); + Ok(limit.clamp(1, SMALL_UPLOAD_CEILING as u64)) +} + +/// A live or trashed file by id, after the authorization for `action`. A missing id is `404`. +pub async fn file_for(state: &AppState, viewer: &Viewer, id: &str, action: Action) -> Result { + let file = state.store.file(id).await?.ok_or_else(not_found)?; + check(viewer, &file.owner, file.trashed_at.is_some(), action)?; + Ok(file) +} + +/// Reads a small text field. A field longer than `cap` bytes is a bad request. +async fn read_text(field: &mut Field<'_>, cap: usize) -> Result { + let mut bytes = Vec::new(); + while let Some(chunk) = field.chunk().await? { + if bytes.len() + chunk.len() > cap { + return Err(bad_request("field too long").into()); + } + bytes.extend_from_slice(&chunk); + } + String::from_utf8(bytes).map_err(|_| bad_request("field is not UTF-8").into()) +} + +/// Streams one file part into the store. `Ok(Err(word))` is a refusal the person can read (the quota, the +/// size limit); `Err` is a server failure. Nothing is left behind on either path. +async fn store_one( + state: &AppState, + owner: &str, + folder: Option<&str>, + client_name: &str, + field: &mut Field<'_>, + limit: u64, +) -> Result> { + let mut staged = StagedFile::create(&state.config.data_dir, limit).await?; + let mut prefix: Vec = Vec::with_capacity(SNIFF_BYTES); + loop { + let chunk = match field.chunk().await { + Ok(Some(chunk)) => chunk, + Ok(None) => break, + Err(error) => { + staged.abort().await; + return Err(error); + } + }; + if prefix.len() < SNIFF_BYTES { + let take = (SNIFF_BYTES - prefix.len()).min(chunk.len()); + prefix.extend_from_slice(&chunk[..take]); + } + if let Err(error) = staged.write(&chunk).await { + staged.abort().await; + return match refusal_word(&error) { + Some(word) => Ok(Err(word)), + None => Err(error.into()), + }; + } + } + let Staged { path, size, sha256 } = staged.finish().await?; + let size = i64::try_from(size).unwrap_or(i64::MAX); + // The quota is checked before the bytes move, so a refused file never reaches the blob store. + let member = state.store.member(owner).await?.ok_or_else(not_found)?; + let room = quota::headroom(member.quota_bytes, member.used_bytes, 0); + if !quota::fits(size, room) { + let _ = tokio::fs::remove_file(&path).await; + return Ok(Err("quota_exceeded".to_owned())); + } + let id = new_id(); + let key = files_blob_key(&id); + if let Err(error) = state.blobs.put_file(&key, &path).await { + let _ = tokio::fs::remove_file(&path).await; + return Err(error.into()); + } + let new = NewFile { + id, + owner: owner.to_owned(), + folder: folder.map(str::to_owned), + name: upload_name(client_name), + mime: sniff(&prefix), + size, + sha256, + staged_claims: 0, + }; + match state.store.insert_file(new).await { + Ok(file) => Ok(Ok(file)), + Err(error) => { + // No row names these bytes now, so they go. + let _ = state.blobs.delete(&key).await; + match refusal_word(&error) { + Some(word) => Ok(Err(word)), + None => Err(error.into()), + } + } + } +} + +/// `POST /files`: the upload. The form's fields come in this order: `csrf` (checked before anything +/// else), `back`, `folder`, then one or more `files` parts. A file part with no name (an empty file +/// input) is skipped. +#[route(POST "/files")] +async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { + let state = app_context::(cx); + let limit = upload_limit(state).await?; + let mut viewer: Option = None; + let mut back = String::new(); + let mut folder_raw = String::new(); + let mut folder: Option> = None; + let mut stored = 0usize; + let mut refusal: Option = None; + while let Some(mut field) = multipart.next_field().await? { + let name = field.name().unwrap_or_default().to_owned(); + match name.as_str() { + "csrf" => { + let token = read_text(&mut field, MAX_FIELD_BYTES).await?; + viewer = Some(require_csrf(cx, &token).await?); + } + "back" => back = read_text(&mut field, MAX_FIELD_BYTES).await?, + "folder" => folder_raw = read_text(&mut field, MAX_FIELD_BYTES).await?, + "files" => { + let Some(owner) = viewer.as_ref() else { + return Err(forbidden().into()); + }; + let client_name = field.file_name().unwrap_or_default().to_owned(); + if client_name.is_empty() { + continue; + } + if folder.is_none() { + folder = Some(optional_folder(state, owner, &folder_raw).await?); + } + let target = folder.clone().flatten(); + match store_one( + state, + &owner.member.sub, + target.as_deref(), + &client_name, + &mut field, + limit, + ) + .await? + { + Ok(_) => stored += 1, + Err(word) => { + refusal = Some(word); + break; + } + } + } + _ => {} + } + } + let Some(owner) = viewer else { + return Err(forbidden().into()); + }; + let default_back = if folder_raw.trim().is_empty() { + "/".to_owned() + } else { + format!("/f/{}", folder_raw.trim()) + }; + let back = back_or(&back, &default_back); + if stored > 0 { + changed(state, &owner.member.sub); + } + if let Some(word) = refusal { + return Ok(see_other(with_param(&back, "refusal", &word))); + } + if stored == 0 { + return Ok(see_other(with_param(&back, "refusal", "no_file"))); + } + Ok(done(&back, "uploaded")) +} + +/// The file page's content: its details, the links to its bytes and, for the owner of a live file, the +/// actions. +#[component] +pub async fn file_body( + lang: Lang, + file: &File, + location: &str, + csrf: &str, + writable: bool, + notice: &str, + refusal: &str, +) -> Result { + let back = format!("/file/{}", file.id); + let move_page = format!("/files/{}/pick", file.id); + let rename_action = format!("/files/{}/rename", file.id); + let trash_action = format!("/files/{}/trash", file.id); + let download_url = format!("/file/{}/download", file.id); + let raw_url = format!("/file/{}/raw", file.id); + Ok(view! { +
+

(file.name.as_str())

+ flash(lang: lang, notice: notice, refusal: refusal) +
+
(d(lang, DK::Location))
(location)
+
(d(lang, DK::Size))
(size_text(file.size))
+
(d(lang, DK::MimeType))
(file.mime.as_str())
+
(d(lang, DK::Uploaded))
(stamp_text(&file.created_at))
+
(d(lang, DK::Downloads))
(file.download_count.to_string())
+
+

+ (d(lang, DK::Download)) + (d(lang, DK::OpenRaw)) +

+ if writable { +
+ + + + + +
+

+ (d(lang, DK::Move)) +

+ + + +
+

+ } +
+ }) +} + +/// `GET /file/{id}`: the file page. +#[page("/file/{id}")] +async fn file_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let id = path_param_segment(cx, "id").to_owned(); + let file = file_for(state, &viewer, &id, Action::View).await?; + let location = match file.folder_id.as_deref() { + Some(folder) => match state.store.folder(folder).await? { + Some(row) if row.trashed_at.is_none() => row.name, + _ => d(lang, DK::Drive).to_owned(), + }, + None => d(lang, DK::Drive).to_owned(), + }; + let writable = + file.trashed_at.is_none() && check(&viewer, &file.owner, false, Action::Write).is_ok(); + let query: ListQuery = parse_query_params(cx).unwrap_or_default(); + let info = ViewerInfo::of(&viewer); + let csrf = viewer.session.csrf_token.clone(); + let title = file.name.clone(); + Ok(view! { + shell(title: title.as_str(), lang: lang, viewer: Some(&info), + file_body(lang: lang, file: &file, location: location.as_str(), csrf: csrf.as_str(), writable: writable, notice: query.notice.as_str(), refusal: query.refusal.as_str()) + ) + }) +} + +/// Serves the bytes of a file the viewer may act on with `action`. +async fn serve_file( + cx: &Cx, + action: Action, + disposition: Disposition, + count: bool, +) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let id = path_param_segment(cx, "id").to_owned(); + let file = file_for(state, &viewer, &id, action).await?; + let size = u64::try_from(file.size).unwrap_or(0); + if count && counts_as_download(headers(cx), &file.sha256, size) { + state.store.record_download(&file.id).await?; + } + let source = ByteSource { + blob_key: &file.blob_key, + size, + sha256: &file.sha256, + mime: &file.mime, + name: &file.name, + }; + serve_bytes(cx, state.blobs.as_ref(), &source, disposition).await +} + +/// `GET /file/{id}/download`: the bytes as a download. Counts one download when it starts at byte 0. +#[route(GET "/file/{id}/download")] +async fn download_bytes(cx: &Cx) -> Result { + serve_file(cx, Action::Download, Disposition::Attachment, true).await +} + +/// `GET /file/{id}/raw`: the bytes to show in the browser. The type decides whether they are shown or +/// saved. +#[route(GET "/file/{id}/raw")] +async fn raw_bytes(cx: &Cx) -> Result { + serve_file(cx, Action::View, Disposition::Inline, false).await +} + +/// `POST /files/{id}/rename`. +#[route(POST "/files/{id}/rename")] +async fn rename_file(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/"); + file_for(state, &viewer, &id, Action::Write).await?; + let name = match validate_name(&form.name) { + Ok(name) => name, + Err(error) => return refused(&back, error), + }; + match state + .store + .rename_file(&viewer.member.sub, &id, &name) + .await + { + Ok(_) => { + changed(state, &viewer.member.sub); + Ok(done(&back, "renamed")) + } + Err(error) => refused(&back, error), + } +} + +/// `POST /files/{id}/move`: the folder in the form is the new place (blank for the top level). +#[route(POST "/files/{id}/move")] +async fn move_file(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/"); + file_for(state, &viewer, &id, Action::Write).await?; + let parent = optional_folder(state, &viewer, &form.parent).await?; + match state + .store + .move_file(&viewer.member.sub, &id, parent.as_deref()) + .await + { + Ok(_) => { + changed(state, &viewer.member.sub); + Ok(done(&back, "moved")) + } + Err(error) => refused(&back, error), + } +} + +/// `POST /files/{id}/trash`. +#[route(POST "/files/{id}/trash")] +async fn trash_file(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/"); + file_for(state, &viewer, &id, Action::Write).await?; + match state.store.trash_file(&viewer.member.sub, &id).await { + Ok(()) => { + changed(state, &viewer.member.sub); + Ok(done(&back, "trashed")) + } + Err(error) => refused(&back, error), + } +} + +/// `GET /files/{id}/pick`: the move picker of a file. The folders are listed as in the folder picker. +#[page("/files/{id}/pick")] +async fn pick_file(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let id = path_param_segment(cx, "id").to_owned(); + let file = file_for(state, &viewer, &id, Action::Write).await?; + let all = state.store.live_folders(&viewer.member.sub).await?; + let rows = tree_rows(&all, None); + let action = format!("/files/{id}/move"); + let back = format!("/file/{id}"); + let csrf = viewer.session.csrf_token.clone(); + let info = ViewerInfo::of(&viewer); + let title = d(lang, DK::MoveTo); + Ok(view! { + shell(title: title, lang: lang, viewer: Some(&info), + pick_body(lang: lang, subject: file.name.as_str(), action: action.as_str(), csrf: csrf.as_str(), back: back.as_str(), rows: &rows) + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::{SESSION_COOKIE, SESSION_TTL}; + use crate::boot::{router, test_state}; + use http::Request; + use http::header::{CONTENT_TYPE, COOKIE}; + use in_core::quota::DEFAULT_MEMBER_QUOTA; + use in_core::store::members::MemberFields; + use in_core::store::new_id; + use in_core::store::sessions::NewSession; + use in_core::time::stamp_after; + use in_core::token::{generate_token, hash_token}; + use topcoat::router::Body; + + /// A member with a session: returns the session cookie value. + async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String { + state + .store + .upsert_member_from_claims( + &MemberFields { + sub: sub.into(), + email: format!("{sub}@example.test"), + name: sub.into(), + is_admin: false, + locale: "en".into(), + zoneinfo: "UTC".into(), + picture_version: 0, + im_updated_at: String::new(), + }, + DEFAULT_MEMBER_QUOTA, + ) + .await + .expect("member"); + state.store.set_quota(sub, quota).await.expect("quota"); + let token = generate_token(); + state + .store + .create_session(NewSession { + sub: sub.into(), + token_hash: hash_token(&token), + csrf_token: format!("csrf-{sub}"), + im_sid: format!("im-{sub}"), + expires_at: stamp_after(SESSION_TTL), + ip: None, + user_agent: None, + id_token_sealed: None, + }) + .await + .expect("session"); + token + } + + /// A file stored the way an upload stores it, owned by `owner`. + async fn stored_file(state: &AppState, owner: &str, name: &str, bytes: &[u8]) -> File { + let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) + .await + .expect("staging"); + staged.write(bytes).await.expect("write"); + let Staged { path, sha256, .. } = staged.finish().await.expect("finish"); + let id = new_id(); + state + .blobs + .put_file(&files_blob_key(&id), &path) + .await + .expect("blob"); + state + .store + .insert_file(NewFile { + id, + owner: owner.into(), + folder: None, + name: name.into(), + mime: sniff(bytes), + size: bytes.len() as i64, + sha256, + staged_claims: 0, + }) + .await + .expect("row") + } + + /// A multipart body with one part per entry: `(field, file name, content)`. + fn multipart_body(boundary: &str, parts: &[(&str, Option<&str>, &[u8])]) -> Vec { + let mut body = Vec::new(); + for (field, file, content) in parts { + body.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); + match file { + Some(file) => body.extend_from_slice( + format!( + "Content-Disposition: form-data; name=\"{field}\"; filename=\"{file}\"\r\n\ + Content-Type: application/octet-stream\r\n\r\n" + ) + .as_bytes(), + ), + None => body.extend_from_slice( + format!("Content-Disposition: form-data; name=\"{field}\"\r\n\r\n").as_bytes(), + ), + } + body.extend_from_slice(content); + body.extend_from_slice(b"\r\n"); + } + body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes()); + body + } + + #[tokio::test] + async fn another_members_file_id_is_not_found_on_its_bytes() { + let (_dir, state) = test_state().await; + let owner_token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let other_token = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; + let file = stored_file(&state, "ann", "notes.txt", b"hello").await; + let path = format!("/file/{}/download", file.id); + + let as_other = Request::get(&path) + .header(COOKIE, format!("{SESSION_COOKIE}={other_token}")) + .body(Body::empty()) + .expect("request"); + let response = router(state.clone()).handle(as_other).await; + assert_eq!(response.status(), 404, "a foreign id must look missing"); + + let as_owner = Request::get(&path) + .header(COOKIE, format!("{SESSION_COOKIE}={owner_token}")) + .body(Body::empty()) + .expect("request"); + let response = router(state.clone()).handle(as_owner).await; + assert_eq!(response.status(), 200); + assert!( + response.headers()["content-disposition"] + .to_str() + .expect("ascii") + .starts_with("attachment;"), + "a download is an attachment" + ); + } + + #[tokio::test] + async fn an_upload_over_quota_is_refused_and_leaves_no_blob_behind() { + let (dir, state) = test_state().await; + let token = signed_in(&state, "ann", 10).await; + let boundary = "in-test-boundary"; + let body = multipart_body( + boundary, + &[ + ("csrf", None, b"csrf-ann"), + ("back", None, b"/"), + ("folder", None, b""), + ("files", Some("../../big.bin"), &[7u8; 100]), + ], + ); + let request = Request::post("/files") + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) + .header( + CONTENT_TYPE, + format!("multipart/form-data; boundary={boundary}"), + ) + .body(Body::from(body)) + .expect("request"); + let response = router(state.clone()).handle(request).await; + + assert_eq!(response.status(), 303); + let location = response.headers()["location"].to_str().expect("ascii"); + assert!( + location.ends_with("refusal=quota_exceeded"), + "got {location}" + ); + assert!( + state.blobs.list("files/").await.expect("list").is_empty(), + "a refused file must not reach the blob store" + ); + let staged_left = std::fs::read_dir(dir.path().join("tmp")) + .map(|entries| entries.count()) + .unwrap_or(0); + assert_eq!(staged_left, 0, "the staging file is removed"); + let member = state + .store + .member("ann") + .await + .expect("lookup") + .expect("member"); + assert_eq!(member.used_bytes, 0, "nothing was charged"); + } +} diff --git a/crates/in-web/src/pages/home.rs b/crates/in-web/src/pages/home.rs index fae16c7..876fbcb 100644 --- a/crates/in-web/src/pages/home.rs +++ b/crates/in-web/src/pages/home.rs @@ -1,52 +1,49 @@ -//! The start page. Signed out, it offers sign-in. Signed in, it greets the person; the drive that -//! follows it is not built yet, so it says so. +//! The start page (`/`). Signed out, it offers sign-in. Signed in, it is the drive root: the same listing +//! as `/f/{id}` for the top level, built by `drive.rs`. use topcoat::Result; -use topcoat::context::Cx; -use topcoat::router::page; +use topcoat::context::{Cx, app_context}; +use topcoat::router::{page, parse_query_params}; use topcoat::view::{View, view}; use crate::auth::current_member; use crate::i18n::lang; -use crate::i18n::shell::{K, greeting, t}; +use crate::i18n::shell::{K, t}; +use crate::pages::drive::{ListQuery, drive_board, root_board, viewer_lang}; +use crate::state::AppState; use crate::views::{ViewerInfo, shell}; /// `GET /`. #[page("/")] async fn home(cx: &Cx) -> Result { + let state = app_context::(cx); let viewer = current_member(cx).await?; - // The language follows the stored override, else the one `im` reports, else the request. - let lang = lang( - cx, - viewer.as_ref().map(|viewer| { - viewer - .member - .locale_override - .as_deref() - .unwrap_or(viewer.member.locale.as_str()) - }), - ); - let info = viewer.map(|viewer| ViewerInfo { - name: viewer.member.name, - is_admin: viewer.member.is_admin, - csrf: viewer.session.csrf_token, - }); - let heading = match &info { - Some(info) => greeting(lang, &info.name), + let query: ListQuery = parse_query_params(cx).unwrap_or_default(); + let lang = match &viewer { + Some(viewer) => viewer_lang(cx, viewer), + None => lang(cx, None), + }; + let info = viewer.as_ref().map(ViewerInfo::of); + let board = match &viewer { + Some(viewer) => Some(root_board(state, viewer, &query, lang).await?), + None => None, + }; + let heading = match &board { + Some(board) => board.heading.clone(), None => t(lang, K::SignedOutTitle).to_owned(), }; Ok(view! { shell(title: heading.as_str(), lang: lang, viewer: info.as_ref(), -
-

"in"

-

(heading.as_str())

- if info.is_some() { -

(t(lang, K::DriveComesNext))

+ if let Some(board) = &board { + drive_board(lang: lang, board: board) } else { +
+

"in"

+

(t(lang, K::SignedOutTitle))

(t(lang, K::SignedOutBody))

(t(lang, K::SignIn)) +
} -
) }) } diff --git a/crates/in-web/src/pages/mod.rs b/crates/in-web/src/pages/mod.rs index 700b695..18eb898 100644 --- a/crates/in-web/src/pages/mod.rs +++ b/crates/in-web/src/pages/mod.rs @@ -1,7 +1,10 @@ //! The pages and the page-level layers. One file per page or per closely related group of pages. pub mod backchannel; +pub mod drive; +pub mod files; pub mod home; pub mod not_found; pub mod photo; pub mod sign_in; +pub mod trash; diff --git a/crates/in-web/src/pages/trash.rs b/crates/in-web/src/pages/trash.rs new file mode 100644 index 0000000..346ed52 --- /dev/null +++ b/crates/in-web/src/pages/trash.rs @@ -0,0 +1,321 @@ +//! The trash: `/trash` lists what the viewer trashed, and the forms under it restore, delete for good or +//! empty it. `POST /items/trash` moves a set of live items to the trash in one request. +//! +//! Only the owner acts on trashed items (`authz`: restore and purge). The purge routes return the blob keys +//! the store released; they are deleted after the row is gone, and a failed delete is logged, not shown, +//! because the row no longer names those bytes. A bulk trash checks every item before it changes one, so a +//! request that names a foreign or missing item changes nothing. + +use in_core::authz::Action; +use in_core::error::Error as CoreError; +use in_core::store::folders::Listing; +use in_core::store::trash::ItemKind; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::SeeOther; +use topcoat::router::{page, parse_query_params, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::{require_csrf, require_member}; +use crate::i18n::Lang; +use crate::i18n::drive::{DK, d}; +use crate::pages::drive::{ListQuery, back_or, changed, done, folder_for, refused, viewer_lang}; +use crate::pages::files::file_for; +use crate::state::AppState; +use crate::views::drive::{flash, size_text, stamp_text}; +use crate::views::{ViewerInfo, empty_state, shell}; + +/// The form of the trash actions: a CSRF token, the return page, and the item kind and id for a single +/// item. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct TrashForm { + /// The CSRF token of the session. + pub csrf: String, + /// The page to return to. + pub back: String, + /// `file` or `folder`. + pub kind: String, + /// The item's id. + pub id: String, +} + +/// The kind word of a trash form, or `None` for anything else. +fn kind_of(word: &str) -> Option { + match word { + "file" => Some(ItemKind::File), + "folder" => Some(ItemKind::Folder), + _ => None, + } +} + +/// Deletes the blobs the store released. A failure is logged: the rows that named them are gone. +async fn release(state: &AppState, keys: Vec) { + for key in keys { + if let Err(error) = state.blobs.delete(&key).await { + tracing::error!(error = %error, "trash: a released blob could not be deleted"); + } + } +} + +/// The trash page's content: the trashed roots, with a restore and a delete button for each, and the +/// button that empties the trash. +#[component] +pub async fn trash_body( + lang: Lang, + listing: &Listing, + csrf: &str, + notice: &str, + refusal: &str, +) -> Result { + let empty = listing.folders.is_empty() && listing.files.is_empty(); + Ok(view! { +
+

(d(lang, DK::Trash))

+ flash(lang: lang, notice: notice, refusal: refusal) +

(d(lang, DK::TrashNote))

+ if empty { + empty_state(title: d(lang, DK::TrashEmpty)) + } else { +
+ + + + + + + + + for folder in &listing.folders { + + + + + + + } + for file in &listing.files { + + + + + + + } + +
(d(lang, DK::Name))(d(lang, DK::Size))(d(lang, DK::Modified))(d(lang, DK::Actions))
(folder.name.as_str())"\u{2014}"(stamp_text(folder.trashed_at.as_deref().unwrap_or_default())) +
+ + + + + +
+
+ + + + + +
+
(file.name.as_str())(size_text(file.size))(stamp_text(file.trashed_at.as_deref().unwrap_or_default())) +
+ + + + + +
+
+ + + + + +
+
+
+
+ + +
+ } +
+ }) +} + +/// `GET /trash`. +#[page("/trash")] +async fn trash_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let query: ListQuery = parse_query_params(cx).unwrap_or_default(); + let listing = state.store.list_trash(&viewer.member.sub).await?; + let info = ViewerInfo::of(&viewer); + let csrf = viewer.session.csrf_token.clone(); + let title = d(lang, DK::Trash); + Ok(view! { + shell(title: title, lang: lang, viewer: Some(&info), + trash_body(lang: lang, listing: &listing, csrf: csrf.as_str(), notice: query.notice.as_str(), refusal: query.refusal.as_str()) + ) + }) +} + +/// `POST /trash/restore`: puts a trashed item back in its place. +#[route(POST "/trash/restore")] +async fn restore(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let back = back_or(&form.back, "/trash"); + let Some(kind) = kind_of(&form.kind) else { + return Err(CoreError::NotFound.into()); + }; + match kind { + ItemKind::File => { + file_for(state, &viewer, &form.id, Action::Restore).await?; + } + ItemKind::Folder => { + folder_for(state, &viewer, &form.id, Action::Restore).await?; + } + } + finish(state, &viewer.member.sub, &back, kind, &form.id, "restored").await +} + +/// Runs a restore after its authorization. Shared by the file and folder branches. +async fn finish( + state: &AppState, + owner: &str, + back: &str, + kind: ItemKind, + id: &str, + notice: &str, +) -> Result { + match state.store.restore(owner, kind, id).await { + Ok(()) => { + changed(state, owner); + Ok(done(back, notice)) + } + Err(error) => refused(back, error), + } +} + +/// `POST /trash/purge`: deletes a trashed item for good, with its bytes. +#[route(POST "/trash/purge")] +async fn purge(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let back = back_or(&form.back, "/trash"); + let Some(kind) = kind_of(&form.kind) else { + return Err(CoreError::NotFound.into()); + }; + match kind { + ItemKind::File => { + file_for(state, &viewer, &form.id, Action::Purge).await?; + } + ItemKind::Folder => { + folder_for(state, &viewer, &form.id, Action::Purge).await?; + } + } + let owner = viewer.member.sub.clone(); + let released = match kind { + ItemKind::File => state.store.purge_file(&owner, &form.id).await, + ItemKind::Folder => state.store.purge_folder(&owner, &form.id).await, + }; + match released { + Ok(keys) => { + release(state, keys).await; + changed(state, &owner); + Ok(done(&back, "purged")) + } + Err(error) => refused(&back, error), + } +} + +/// `POST /trash/empty`: deletes everything in the trash for good. +#[route(POST "/trash/empty")] +async fn empty_trash(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let back = back_or(&form.back, "/trash"); + let owner = viewer.member.sub.clone(); + match state.store.empty_trash(&owner).await { + Ok(keys) => { + release(state, keys).await; + changed(state, &owner); + Ok(done(&back, "emptied")) + } + Err(error) => refused(&back, error), + } +} + +/// `POST /items/trash`: moves the checked live items to the trash. The form is read as raw key/value pairs, +/// because one `item` key repeats once per checked row. Every item is checked first; if one of them is not +/// the viewer's, nothing is trashed and that item's answer is returned. +#[route(POST "/items/trash")] +async fn trash_items(cx: &Cx, Form(pairs): Form>) -> Result { + let state = app_context::(cx); + let mut csrf = String::new(); + let mut back = String::new(); + let mut items = Vec::new(); + for (key, value) in pairs { + match key.as_str() { + "csrf" => csrf = value, + "back" => back = value, + "item" => items.push(value), + _ => {} + } + } + let viewer = require_csrf(cx, &csrf).await?; + let back = back_or(&back, "/"); + let mut files = Vec::new(); + let mut folders = Vec::new(); + for item in &items { + match item.split_once(':') { + Some(("file", id)) => { + file_for(state, &viewer, id, Action::Write).await?; + files.push(id.to_owned()); + } + Some(("folder", id)) => { + folder_for(state, &viewer, id, Action::Write).await?; + folders.push(id.to_owned()); + } + _ => return Err(CoreError::NotFound.into()), + } + } + let owner = viewer.member.sub.clone(); + for id in &files { + if let Err(error) = state.store.trash_file(&owner, id).await { + return refused(&back, error); + } + } + for id in &folders { + if let Err(error) = state.store.trash_folder(&owner, id).await { + return refused(&back, error); + } + } + if !files.is_empty() || !folders.is_empty() { + changed(state, &owner); + } + Ok(done(&back, "trashed")) +} + +#[cfg(test)] +mod tests { + /// The browser repeats `item` once per checked row; the pairs keep every one, in order. + #[test] + fn repeated_item_fields_are_all_kept() { + let pairs: Vec<(String, String)> = serde_urlencoded::from_str( + "csrf=t&back=%2F&item=file%3Aa&item=folder%3Ab&item=file%3Ac", + ) + .expect("form"); + let items: Vec<&str> = pairs + .iter() + .filter(|(key, _)| key == "item") + .map(|(_, value)| value.as_str()) + .collect(); + assert_eq!(items, vec!["file:a", "folder:b", "file:c"]); + } +} diff --git a/crates/in-web/src/serve_bytes.rs b/crates/in-web/src/serve_bytes.rs new file mode 100644 index 0000000..d0156c0 --- /dev/null +++ b/crates/in-web/src/serve_bytes.rs @@ -0,0 +1,458 @@ +//! The one function that sends a stored blob to a browser. Every byte route (download, raw, and the +//! shared and public ones that come later) calls [`serve_bytes`], so the headers and the range rules +//! exist in exactly one place (architecture section 7). +//! +//! The caller has already decided that the viewer may see the bytes (`authz`). This module decides how +//! they are sent: a single byte range, a validator (`ETag`) and its conditional requests, a disposition +//! that is `inline` only for types a browser can show without running them, and the response headers +//! that stop the bytes from being used as a page. The body is streamed from the blob store in frames of +//! [`in_core::blob::FRAME_BYTES`]; nothing is buffered whole. +//! +//! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the +//! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with +//! `Content-Range: bytes */`. `If-Range` with a validator that is not the current one gets the whole +//! file. + +use futures_util::TryStreamExt; +use http::header::{ + ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, + CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, + X_CONTENT_TYPE_OPTIONS, +}; +use http_body::Frame; +use http_body_util::StreamBody; +use in_core::blob::BlobStore; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::request::headers; +use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; + +/// What a browser may do with a byte response: show it in the page, or save it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Disposition { + /// Show the bytes in the page. Granted only to the types in [`inline_safe`]. + Inline, + /// Save the bytes as a file. + Attachment, +} + +/// Everything about a stored file that a byte response needs. The caller fills it from the row. +#[derive(Clone, Copy, Debug)] +pub struct ByteSource<'a> { + /// Key of the bytes in the blob store. + pub blob_key: &'a str, + /// Length of the bytes in bytes. + pub size: u64, + /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes. + pub sha256: &'a str, + /// The sniffed MIME type, as stored. It is never the uploader's claim. + pub mime: &'a str, + /// The display name, used for the `Content-Disposition` file name. + pub name: &'a str, +} + +/// The status, headers and body of a byte response. Handlers return it as they are. +pub type ByteAnswer = (StatusCode, HeaderMap, Body); + +/// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and +/// `default-src 'none'` stops it from loading anything but its own image, media or style. +pub const BYTES_CSP: &str = + "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'"; + +/// Cache policy of content addressed by id and hash: the bytes behind a URL never change. +const BYTES_CACHE: &str = "private, max-age=31536000, immutable"; + +/// The outcome of reading a `Range` header against a length. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ranged { + /// Send the whole file (no range, or several ranges). + Full, + /// Send the bytes from `start` to `end`, both inclusive, and both inside the file. + Part { + /// First byte, inclusive. + start: u64, + /// Last byte, inclusive. + end: u64, + }, + /// The header is malformed, reversed, or asks for nothing the file has. Answer `416`. + Unsatisfiable, +} + +/// Parses the value of a `Range` header for a file of `len` bytes. +/// +/// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last +/// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give +/// [`Ranged::Full`]. Everything else is [`Ranged::Unsatisfiable`]: a missing unit, a non-digit, a value +/// that overflows `u64`, `-0`, a last byte before the first, or a first byte at or past the end. +pub fn parse_range(value: &str, len: u64) -> Ranged { + let Some(spec) = value.trim().strip_prefix("bytes=") else { + return Ranged::Unsatisfiable; + }; + if spec.contains(',') { + return Ranged::Full; + } + let Some((first, last)) = spec.trim().split_once('-') else { + return Ranged::Unsatisfiable; + }; + let (first, last) = (first.trim(), last.trim()); + if first.is_empty() { + // A suffix range: the last `n` bytes. + let Some(n) = digits(last) else { + return Ranged::Unsatisfiable; + }; + if n == 0 || len == 0 { + return Ranged::Unsatisfiable; + } + let n = n.min(len); + return Ranged::Part { + start: len - n, + end: len - 1, + }; + } + let Some(start) = digits(first) else { + return Ranged::Unsatisfiable; + }; + let end = if last.is_empty() { + None + } else { + match digits(last) { + Some(end) if end >= start => Some(end), + _ => return Ranged::Unsatisfiable, + } + }; + if start >= len { + return Ranged::Unsatisfiable; + } + let end = end.map_or(len - 1, |end| end.min(len - 1)); + Ranged::Part { start, end } +} + +/// A non-empty run of ASCII digits as a number. Anything else, including an overflow, is `None`. +fn digits(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +/// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong +/// form here, which is the rule for `GET` validators (RFC 9110). +fn none_match_hits(request: &HeaderMap, etag: &str) -> bool { + request + .get(IF_NONE_MATCH) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + value.split(',').map(str::trim).any(|candidate| { + candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag + }) + }) +} + +/// Whether a range may be honoured under `If-Range`. Without the header it always may. With it, only a +/// strong validator equal to `etag` allows the range; a date or a weak tag never does. +fn if_range_allows(request: &HeaderMap, etag: &str) -> bool { + match request.get(IF_RANGE).and_then(|value| value.to_str().ok()) { + None => true, + Some(value) => value.trim() == etag, + } +} + +/// The range that applies to this request, after `If-Range` has had its say. +fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged { + let Some(value) = request.get(RANGE).and_then(|value| value.to_str().ok()) else { + return Ranged::Full; + }; + if !if_range_allows(request, etag) { + return Ranged::Full; + } + parse_range(value, len) +} + +/// Whether serving this request counts as a download that started at byte 0. A `304`, a range that +/// starts later, and an unsatisfiable range do not count; a whole file, or a range from byte 0, does. +/// The download counter is bumped by the caller before it serves the body. +pub fn counts_as_download(request: &HeaderMap, sha256: &str, size: u64) -> bool { + let etag = format!("\"{sha256}\""); + if none_match_hits(request, &etag) { + return false; + } + match requested_range(request, &etag, size) { + Ranged::Full => true, + Ranged::Part { start, .. } => start == 0, + Ranged::Unsatisfiable => false, + } +} + +/// Whether a type may be shown inline. SVG is never inline: it can carry script. HTML is never inline. +/// Images (except SVG and HEIC/HEIF, which browsers do not show everywhere), audio, video, PDF and plain +/// text are. +pub fn inline_safe(mime: &str) -> bool { + let essence = mime + .split(';') + .next() + .unwrap_or_default() + .trim() + .to_ascii_lowercase(); + match essence.as_str() { + "image/svg+xml" | "image/heic" | "image/heif" => false, + "application/pdf" | "text/plain" => true, + other => { + other.starts_with("image/") + || other.starts_with("audio/") + || other.starts_with("video/") + } + } +} + +/// The `Content-Type` value for a stored type. Plain text is always sent as UTF-8. +fn content_type_value(mime: &str) -> String { + if mime.trim().eq_ignore_ascii_case("text/plain") { + "text/plain; charset=utf-8".into() + } else { + mime.to_string() + } +} + +/// Characters that may appear unescaped in an RFC 5987 `filename*` value (`attr-char`). +fn is_attr_char(b: u8) -> bool { + b.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&b) +} + +/// The `Content-Disposition` header for a file name: `inline` or `attachment`, a quoted ASCII fallback +/// and the UTF-8 name percent-encoded per RFC 5987. +/// +/// The fallback keeps printable ASCII except the quote and the backslash, and turns everything else +/// (control characters, including CR and LF, non-ASCII letters) into `_`. So no name can close the +/// quoted string or start a new header line. The `filename*` value encodes every byte that is not an +/// `attr-char`, which covers the same characters. +pub fn content_disposition(kind: Disposition, name: &str) -> String { + let fallback: String = name + .chars() + .map(|c| { + if c.is_ascii() && (c.is_ascii_graphic() || c == ' ') && c != '"' && c != '\\' { + c + } else { + '_' + } + }) + .collect(); + let fallback = if fallback.trim().is_empty() { + "download".to_string() + } else { + fallback + }; + let mut encoded = String::with_capacity(name.len()); + for b in name.bytes() { + if is_attr_char(b) { + encoded.push(char::from(b)); + } else { + encoded.push_str(&format!("%{b:02X}")); + } + } + let kind = match kind { + Disposition::Inline => "inline", + Disposition::Attachment => "attachment", + }; + format!("{kind}; filename=\"{fallback}\"; filename*=UTF-8''{encoded}") +} + +/// The headers every byte response carries, whatever its status. +fn common_headers(etag: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + insert(&mut headers, ETAG, etag); + headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(BYTES_CSP)); + headers.insert( + HeaderName::from_static("cross-origin-resource-policy"), + HeaderValue::from_static("same-origin"), + ); + headers.insert(CACHE_CONTROL, HeaderValue::from_static(BYTES_CACHE)); + headers +} + +/// Inserts a header whose value is text the code controls. A value that is not a valid header value is +/// dropped, never sent half-formed; every caller passes ASCII that the code made. +fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) { + if let Ok(value) = HeaderValue::from_str(value) { + headers.insert(name, value); + } +} + +/// The `416` answer: no body, and the length the client may ask again within. +fn unsatisfiable(etag: &str, len: u64) -> ByteAnswer { + let mut headers = common_headers(etag); + insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); + (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) +} + +/// Sends the bytes of `source` for the request in `cx`. +/// +/// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in +/// [`inline_safe`]. The body streams from the blob store from the first byte the answer needs. A +/// missing blob is an error (the row names bytes that are not there), which the router answers as a +/// `500`. +pub async fn serve_bytes( + cx: &Cx, + blobs: &dyn BlobStore, + source: &ByteSource<'_>, + disposition: Disposition, +) -> Result { + let request = headers(cx); + let etag = format!("\"{}\"", source.sha256); + let disposition = match disposition { + Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, + _ => Disposition::Attachment, + }; + let mut answer_headers = common_headers(&etag); + insert( + &mut answer_headers, + CONTENT_DISPOSITION, + &content_disposition(disposition, source.name), + ); + insert( + &mut answer_headers, + CONTENT_TYPE, + &content_type_value(source.mime), + ); + + if none_match_hits(request, &etag) { + return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty())); + } + + match requested_range(request, &etag, source.size) { + Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size)), + Ranged::Full => { + insert( + &mut answer_headers, + CONTENT_LENGTH, + &source.size.to_string(), + ); + let stream = blobs.open_range(source.blob_key, 0, source.size).await?; + Ok((StatusCode::OK, answer_headers, streamed(stream))) + } + Ranged::Part { start, end } => { + let length = end - start + 1; + insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string()); + insert( + &mut answer_headers, + CONTENT_RANGE, + &format!("bytes {start}-{end}/{}", source.size), + ); + let stream = blobs.open_range(source.blob_key, start, length).await?; + Ok(( + StatusCode::PARTIAL_CONTENT, + answer_headers, + streamed(stream), + )) + } + } +} + +/// Turns a blob stream into a response body. Frames are passed through as they come. +fn streamed(stream: in_core::blob::BlobStream) -> Body { + Body::new(StreamBody::new(stream.map_ok(Frame::data))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A table of `Range` values for a 100-byte file, with the answer for each. + #[test] + fn range_table() { + use Ranged::*; + let cases: &[(&str, Ranged)] = &[ + ("bytes=0-0", Part { start: 0, end: 0 }), + ("bytes=0-99", Part { start: 0, end: 99 }), + ("bytes=10-19", Part { start: 10, end: 19 }), + // Past the end is clamped, not refused. + ("bytes=50-500", Part { start: 50, end: 99 }), + ("bytes=90-", Part { start: 90, end: 99 }), + ("bytes=-10", Part { start: 90, end: 99 }), + // A suffix longer than the file is the whole file. + ("bytes=-1000", Part { start: 0, end: 99 }), + (" bytes=1 - 2 ", Part { start: 1, end: 2 }), + // Several ranges: the whole file. + ("bytes=0-1,5-6", Full), + // Unsatisfiable or malformed. + ("bytes=-0", Unsatisfiable), + ("bytes=100-", Unsatisfiable), + ("bytes=100-120", Unsatisfiable), + ("bytes=20-10", Unsatisfiable), + ("bytes=5-4", Unsatisfiable), + ("bytes=-", Unsatisfiable), + ("bytes=", Unsatisfiable), + ("bytes=-x", Unsatisfiable), + ("bytes=+1-2", Unsatisfiable), + ("bytes=1e2-", Unsatisfiable), + ("bytes=--1", Unsatisfiable), + ("items=0-1", Unsatisfiable), + ("0-1", Unsatisfiable), + // Overflow of u64 is refused, not wrapped. + ("bytes=18446744073709551616-", Unsatisfiable), + ("bytes=0-18446744073709551616", Unsatisfiable), + ("bytes=-18446744073709551616", Unsatisfiable), + ]; + for (header, want) in cases { + assert_eq!(parse_range(header, 100), *want, "header {header:?}"); + } + } + + #[test] + fn an_empty_file_has_no_satisfiable_range() { + assert_eq!(parse_range("bytes=0-", 0), Ranged::Unsatisfiable); + assert_eq!(parse_range("bytes=-5", 0), Ranged::Unsatisfiable); + } + + #[test] + fn disposition_is_inline_only_for_safe_types() { + assert!(inline_safe("image/png")); + assert!(inline_safe("application/pdf")); + assert!(inline_safe("text/plain; charset=utf-8")); + assert!(inline_safe("video/mp4")); + assert!(!inline_safe("image/svg+xml")); + assert!(!inline_safe("image/heic")); + assert!(!inline_safe("text/html")); + assert!(!inline_safe("application/octet-stream")); + assert_eq!( + content_type_value("text/plain"), + "text/plain; charset=utf-8" + ); + } + + /// Quotes, CR and LF, and a non-ASCII name cannot close the quoted string or add a header line. + #[test] + fn content_disposition_neutralises_quotes_crlf_and_unicode() { + let value = content_disposition(Disposition::Attachment, "a\"b\r\nc é.pdf"); + assert!(!value.contains('\r') && !value.contains('\n')); + assert_eq!( + value.matches('"').count(), + 2, + "only the two quotes: {value}" + ); + assert_eq!( + value, + "attachment; filename=\"a_b__c _.pdf\"; filename*=UTF-8''a%22b%0D%0Ac%20%C3%A9.pdf" + ); + let inline = content_disposition(Disposition::Inline, "plain.txt"); + assert_eq!( + inline, + "inline; filename=\"plain.txt\"; filename*=UTF-8''plain.txt" + ); + assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\"")); + } + + #[test] + fn a_download_counts_only_when_it_starts_at_byte_zero() { + let mut request = HeaderMap::new(); + assert!(counts_as_download(&request, "ab", 10)); + request.insert(RANGE, HeaderValue::from_static("bytes=0-3")); + assert!(counts_as_download(&request, "ab", 10)); + request.insert(RANGE, HeaderValue::from_static("bytes=4-")); + assert!(!counts_as_download(&request, "ab", 10)); + request.insert(RANGE, HeaderValue::from_static("bytes=0-3")); + request.insert(IF_NONE_MATCH, HeaderValue::from_static("\"ab\"")); + assert!(!counts_as_download(&request, "ab", 10)); + } +} diff --git a/crates/in-web/src/views/drive.rs b/crates/in-web/src/views/drive.rs new file mode 100644 index 0000000..4e52de1 --- /dev/null +++ b/crates/in-web/src/views/drive.rs @@ -0,0 +1,212 @@ +//! The drive's page parts: breadcrumbs, the listing table with its row menus, the flash line that shows a +//! notice or a refusal, the quota bar and the small formatters they use. +//! +//! Every form here posts with a `csrf` field and a `back` field. `back` is the page to return to; the +//! handler checks it with `safe_next` before it redirects there. Nothing here runs script: the row menus +//! are `
` elements and the selection is the `form` attribute of a checkbox. + +use topcoat::Result; +use topcoat::view::{View, component, view}; + +use crate::i18n::Lang; +use crate::i18n::drive::{DK, d, notice_text, quota_text, refusal_text}; +use in_core::store::files::File; +use in_core::store::folders::Folder; + +/// Formats a byte count for people: `B`, `KB`, `MB`, `GB` or `TB`, one decimal above bytes. Base 1024. +pub fn size_text(bytes: i64) -> String { + const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; + let mut value = bytes.max(0) as f64; + let mut unit = 0; + while value >= 1024.0 && unit < UNITS.len() - 1 { + value /= 1024.0; + unit += 1; + } + if unit == 0 { + format!("{} B", bytes.max(0)) + } else { + format!("{value:.1} {}", UNITS[unit]) + } +} + +/// Shortens a stored UTC stamp (`2026-10-28T10:00:00.123456789Z`) to `2026-10-28 10:00`. +pub fn stamp_text(stamp: &str) -> String { + stamp.chars().take(16).collect::().replace('T', " ") +} + +/// The quota bar: a `progress` element and its line of text. Used by the shell. +#[component] +pub async fn quota_bar(lang: Lang, used: i64, quota: i64) -> Result { + let line = quota_text(lang, &size_text(used), &size_text(quota)); + Ok(view! { +
+ + (line) +
+ }) +} + +/// The flash line of a page: a notice from a finished action, or a refusal of one. Unknown words show +/// nothing. +#[component] +pub async fn flash(lang: Lang, notice: &str, refusal: &str) -> Result { + let notice_line = notice_text(lang, notice); + let refusal_line = refusal_text(lang, refusal); + Ok(view! { + if let Some(text) = refusal_line { + + } + if let Some(text) = notice_line { +
(text)
+ } + }) +} + +/// The breadcrumb trail, top level first. Empty for the top level, which needs no trail. +#[component] +pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result { + Ok(view! { + + }) +} + +/// The sort links of the listing header: each column header links to the same listing with the sort +/// key and direction the next click would choose. +#[component] +pub async fn sort_link( + base: &str, + key: &str, + label: &str, + current: bool, + descending: bool, +) -> Result { + // Clicking the active column flips its direction; a new column starts ascending. + let next = if current && !descending { + "desc" + } else { + "asc" + }; + let mark = match (current, descending) { + (true, false) => " \u{25b2}", + (true, true) => " \u{25bc}", + _ => "", + }; + let href = format!("{base}sort={key}&dir={next}"); + Ok(view! { + (label)(mark) + }) +} + +/// The row menu of one item: the actions that an owner may take on it. Each action is a form, so the +/// menu works without script. +#[component] +pub async fn row_menu( + lang: Lang, + csrf: &str, + back: &str, + kind: &str, + id: &str, + name: &str, +) -> Result { + let rename_action = format!("/{kind}s/{id}/rename"); + let move_page = format!("/{kind}s/{id}/pick"); + let trash_action = format!("/{kind}s/{id}/trash"); + Ok(view! { +
+ (d(lang, DK::Actions)) +
+
+ + + + + +
+ (d(lang, DK::Move)) +
+ + + +
+
+
+ }) +} + +/// A table of folders and files: the rows, their selection box for the bulk trash, and the row menus. +/// `base` is the listing's own URL without a query, and `query` the sort part already in it. +#[component] +pub async fn listing_table( + lang: Lang, + folders: &[Folder], + files: &[File], + csrf: &str, + back: &str, + sort: &str, + dir: &str, + base: &str, +) -> Result { + let descending = dir == "desc"; + let name_sort = sort == "name"; + let size_sort = sort == "size"; + let modified_sort = sort == "modified"; + Ok(view! { +
+ + + + + + + + + + + + + for folder in folders { + + + + + + + + + } + for file in files { + + + + + + + + + } + +
"\u{2713}" + sort_link(base: base, key: "name", label: d(lang, DK::Name), current: name_sort, descending: descending) + + sort_link(base: base, key: "size", label: d(lang, DK::Size), current: size_sort, descending: descending) + + sort_link(base: base, key: "modified", label: d(lang, DK::Modified), current: modified_sort, descending: descending) + (d(lang, DK::Kind))(d(lang, DK::Actions))
(folder.name.as_str())"\u{2014}"(stamp_text(&folder.updated_at))(d(lang, DK::FolderKind))row_menu(lang: lang, csrf: csrf, back: back, kind: "folder", id: folder.id.as_str(), name: folder.name.as_str())
(file.name.as_str())(size_text(file.size))(stamp_text(&file.updated_at))(d(lang, DK::FileKind)) + (d(lang, DK::Download)) + row_menu(lang: lang, csrf: csrf, back: back, kind: "file", id: file.id.as_str(), name: file.name.as_str()) +
+
+
+ + + +
+ }) +} diff --git a/crates/in-web/src/views/mod.rs b/crates/in-web/src/views/mod.rs index a8d50df..c8e63b1 100644 --- a/crates/in-web/src/views/mod.rs +++ b/crates/in-web/src/views/mod.rs @@ -7,8 +7,13 @@ use topcoat::Result; use topcoat::view::{Child, View, component, view}; use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; +use crate::auth::Viewer; use crate::i18n::Lang; +use crate::i18n::drive::{DK, d}; use crate::i18n::shell::{K, t}; +use crate::views::drive::quota_bar; + +pub mod drive; /// What the shell shows about the signed-in person: the name, the administrator badge, and the CSRF /// token of the session for the sign-out form. @@ -19,6 +24,23 @@ pub struct ViewerInfo { pub is_admin: bool, /// The session's CSRF token, which the sign-out form sends. pub csrf: String, + /// Bytes the viewer's files use, trashed ones included. + pub used: i64, + /// The viewer's quota in bytes. + pub quota: i64, +} + +impl ViewerInfo { + /// What the shell needs to know about a signed-in viewer. + pub fn of(viewer: &Viewer) -> Self { + Self { + name: viewer.member.name.clone(), + is_admin: viewer.member.is_admin, + csrf: viewer.session.csrf_token.clone(), + used: viewer.member.used_bytes, + quota: viewer.member.quota_bytes, + } + } } /// The HTML document around a page. `title` is the page's own title; the document title adds the @@ -50,9 +72,15 @@ pub async fn shell(
"in" - +
if let Some(viewer) = viewer { + quota_bar(lang: lang, used: viewer.used, quota: viewer.quota)
(viewer.name.as_str())
diff --git a/style/_components.scss b/style/_components.scss index 99cc0c5..2604749 100644 --- a/style/_components.scss +++ b/style/_components.scss @@ -313,3 +313,116 @@ textarea::placeholder { transition: none; } } + +// The drive: listings, forms that sit in a row, row menus, breadcrumbs, the quota bar and the pickers. +.drive { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.crumbs ol { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; + list-style: none; + margin: 0; + padding: 0; + color: var(--muted); +} + +.crumbs li + li::before { + content: "/"; + padding-inline-end: 0.35rem; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + align-items: center; +} + +.inline-form { + display: inline-flex; + flex-wrap: wrap; + gap: 0.4rem; + align-items: center; + margin: 0; +} + +.inline-form input[type="text"], +.inline-form input:not([type]), +.inline-form input[type="search"], +.inline-form input[type="file"] { + min-width: 12rem; +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + align-items: center; +} + +.row-menu summary { + cursor: pointer; + color: var(--accent); +} + +.row-menu-body { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + align-items: center; + margin-block-start: 0.5rem; +} + +.details { + display: grid; + grid-template-columns: max-content 1fr; + gap: 0.35rem 1rem; + margin: 0; +} + +.details dt { + color: var(--muted); +} + +.details dd { + margin: 0; +} + +.quota { + display: flex; + flex-direction: column; + align-items: flex-end; + font-size: 0.85rem; +} + +.quota progress { + width: 9rem; +} + +.pick-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.pick-list .button { + justify-content: flex-start; + width: 100%; + text-align: start; +} + +.bulk { + margin-block-start: 0.5rem; +} + +.trash .table td form { + display: inline-flex; +}