diff --git a/Cargo.lock b/Cargo.lock index e6d54cc..a3ad5ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -223,6 +223,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "atoi_simd" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cdb3708a128e559a30fb830e8a77a5022ee6902806925c216658652b452a44" +dependencies = [ + "debug_unsafe", + "rustversion", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -428,6 +438,23 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "calamine" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9ca341b94bc4b29e08970b1a03914fad2dfe177e2ecb67fcd6de9046004aafb" +dependencies = [ + "atoi_simd", + "byteorder", + "codepage", + "encoding_rs", + "fast-float2", + "log", + "quick-xml", + "serde", + "zip", +] + [[package]] name = "cc" version = "1.10.0" @@ -590,6 +617,15 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" +[[package]] +name = "codepage" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdff162541cd8b79de82e2edcc7eff3a8c2a6dc3d75152636028f96d93de3b26" +dependencies = [ + "encoding_rs", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -759,6 +795,27 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + [[package]] name = "ctr" version = "0.9.2" @@ -823,6 +880,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" +[[package]] +name = "debug_unsafe" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2" + [[package]] name = "defmt" version = "1.2.0" @@ -1006,6 +1069,12 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" +[[package]] +name = "fast-float2" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" + [[package]] name = "fastbloom" version = "0.14.1" @@ -1035,6 +1104,15 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1787,10 +1865,14 @@ name = "iz-core" version = "0.1.0" dependencies = [ "base64 0.23.1", + "bytes", + "calamine", "chacha20poly1305", + "csv", "hex", "ipnet", "jiff", + "quick-xml", "rand 0.10.3", "serde", "serde_json", @@ -1804,6 +1886,7 @@ dependencies = [ "tracing", "turso", "ulid", + "zip", ] [[package]] @@ -1812,10 +1895,13 @@ version = "0.1.0" dependencies = [ "aws-lc-rs", "base64 0.23.1", + "bytes", "futures-util", "grass", "hex", "http", + "http-body", + "http-body-util", "iz-core", "jiff", "jsonwebtoken", @@ -2256,6 +2342,18 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -2608,6 +2706,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "encoding_rs", + "memchr", +] + [[package]] name = "quinn" version = "0.11.12" @@ -3331,6 +3439,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -4527,6 +4641,12 @@ dependencies = [ "rand 0.10.3", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typeid" version = "1.0.3" @@ -5167,12 +5287,47 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zip" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" +dependencies = [ + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zstd" version = "0.13.3" diff --git a/Cargo.toml b/Cargo.toml index 7b7ea5e..64b900e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,9 +14,14 @@ license = "AGPL-3.0-or-later" # external crates (versions are the latest releases when added) aws-lc-rs = "1.18.2" base64 = "0.23.1" +bytes = "1.12.1" +calamine = "0.37.0" +csv = "1.4.0" futures-util = "0.3.34" grass = "0.13.4" http = "1.5.0" +http-body = "1.1.0" +http-body-util = "0.1.5" chacha20poly1305 = "0.11.0" hex = "0.4.3" ipnet = "2.12.2" @@ -37,6 +42,8 @@ tracing = "0.1.44" tracing-subscriber = "0.3.23" turso = "0.8.3" ulid = "3.0.0" +quick-xml = "0.42.0" +zip = { version = "9.1.3", default-features = false, features = ["deflate"] } # web framework topcoat = { version = "0.11.0", default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "multipart"] } diff --git a/crates/iz-core/Cargo.toml b/crates/iz-core/Cargo.toml index 9621371..331a3f9 100644 --- a/crates/iz-core/Cargo.toml +++ b/crates/iz-core/Cargo.toml @@ -11,10 +11,14 @@ workspace = true [dependencies] base64.workspace = true +bytes.workspace = true +calamine.workspace = true +csv.workspace = true chacha20poly1305.workspace = true hex.workspace = true ipnet.workspace = true jiff.workspace = true +quick-xml.workspace = true rand.workspace = true serde.workspace = true serde_json.workspace = true @@ -22,11 +26,12 @@ sha2.workspace = true subtle.workspace = true thiserror.workspace = true time.workspace = true -tokio.workspace = true +tokio = { workspace = true, features = ["fs", "io-util"] } toml.workspace = true tracing.workspace = true turso.workspace = true ulid.workspace = true +zip.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/iz-core/migrations/0003_blob_deletions.sql b/crates/iz-core/migrations/0003_blob_deletions.sql new file mode 100644 index 0000000..67fdf53 --- /dev/null +++ b/crates/iz-core/migrations/0003_blob_deletions.sql @@ -0,0 +1,12 @@ +-- 0003: blob deletions still owed. A deleted attachment's row is removed in the same transaction that +-- records its id here; the files worker removes the bytes afterwards and retries with backoff until they +-- are gone, and only then removes this row. `location` says where the bytes are ('local' for now; 'in' +-- once the Files service backend exists). The id is the attachment id, a ULID. +CREATE TABLE blob_deletions ( + attachment_id TEXT PRIMARY KEY CHECK (length(attachment_id) = 26), + location TEXT NOT NULL DEFAULT 'local' CHECK (location IN ('local', 'in')), + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), + next_attempt_at TEXT NOT NULL, + created_at TEXT NOT NULL +); +CREATE INDEX blob_deletions_due ON blob_deletions(next_attempt_at); diff --git a/crates/iz-core/src/archive.rs b/crates/iz-core/src/archive.rs new file mode 100644 index 0000000..8870d42 --- /dev/null +++ b/crates/iz-core/src/archive.rs @@ -0,0 +1,172 @@ +//! Zip-container guards for the spreadsheet and slide viewers. A `.xlsx`, `.ods` or `.pptx` is a zip file, +//! so one of them can expand to far more than it weighs. Every such file is checked here before any parser +//! sees it (`docs/architecture.md`, attack plan section 6: zip bombs). +//! +//! The check runs in two passes. The first reads only the central directory: the declared uncompressed +//! sizes are summed and the declared ratio is judged, so a bomb that announces itself is refused without +//! inflating anything. The second inflates every entry into a sink with a hard byte budget, because a +//! header can lie: the declared sizes are never trusted alone. Memory use is constant; the sink keeps nothing. + +use std::fs::File; +use std::io::{self, Read}; +use std::path::Path; + +use zip::ZipArchive; + +use crate::error::{Error, Result}; +use crate::limits::{ARCHIVE_RATIO_FLOOR_BYTES, ARCHIVE_RATIO_MAX, ARCHIVE_UNCOMPRESSED_MAX_BYTES}; + +/// Refusal codes. The viewers show one generic message for all of them; the code is for logs and tests. +pub const REFUSED_SIZE: &str = "archive_too_large"; +/// See [`REFUSED_SIZE`]. +pub const REFUSED_RATIO: &str = "archive_ratio"; +/// See [`REFUSED_SIZE`]. +pub const REFUSED_NOT_ZIP: &str = "archive_not_zip"; + +/// Opens `path` as a zip archive after the zip-bomb checks. `input_max` caps the compressed file size. +/// +/// The returned archive is only for reading the entry list; the viewers open their own readers. +pub fn open_checked(path: &Path, input_max: u64) -> Result> { + let len = std::fs::metadata(path)?.len(); + if len > input_max { + return Err(Error::Invalid(REFUSED_SIZE.into())); + } + let file = File::open(path)?; + let mut archive = ZipArchive::new(file).map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?; + check_declared(&mut archive)?; + inflate_within_budget(&mut archive, len)?; + Ok(archive) +} + +/// First pass: the declared sizes of the central directory. Reads no entry data. +fn check_declared(archive: &mut ZipArchive) -> Result<()> { + let mut total_plain: u64 = 0; + let mut total_packed: u64 = 0; + for index in 0..archive.len() { + let entry = archive + .by_index_raw(index) + .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?; + total_plain = total_plain.saturating_add(entry.size()); + total_packed = total_packed.saturating_add(entry.compressed_size()); + } + if total_plain > ARCHIVE_UNCOMPRESSED_MAX_BYTES { + return Err(Error::Invalid(REFUSED_SIZE.into())); + } + if ratio_refused(total_plain, total_packed) { + return Err(Error::Invalid(REFUSED_RATIO.into())); + } + Ok(()) +} + +/// Second pass: inflates every entry into a sink, stopping as soon as the total passes the budget. A +/// lying header cannot make this read more than the budget. +fn inflate_within_budget(archive: &mut ZipArchive, file_len: u64) -> Result<()> { + let mut produced: u64 = 0; + for index in 0..archive.len() { + let mut entry = archive + .by_index(index) + .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?; + let budget = ARCHIVE_UNCOMPRESSED_MAX_BYTES - produced; + // One byte past the budget tells "exactly at the limit" from "over it". + let copied = io::copy(&mut (&mut entry).take(budget + 1), &mut io::sink()) + .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?; + produced += copied; + if produced > ARCHIVE_UNCOMPRESSED_MAX_BYTES { + return Err(Error::Invalid(REFUSED_SIZE.into())); + } + } + if ratio_refused(produced, file_len) { + return Err(Error::Invalid(REFUSED_RATIO.into())); + } + Ok(()) +} + +/// Whether `plain` bytes from `packed` bytes is a ratio the viewers refuse. Sizes under the floor are not +/// judged: a small part can compress badly without being hostile. +fn ratio_refused(plain: u64, packed: u64) -> bool { + plain > ARCHIVE_RATIO_FLOOR_BYTES && plain / ARCHIVE_RATIO_MAX.max(1) > packed +} + +/// Reads one entry of an open archive, at most `max` bytes. Returns `None` when the entry is +/// missing. A longer entry is cut at `max`; the callers only need the start. +pub fn read_entry(archive: &mut ZipArchive, name: &str, max: u64) -> Result>> { + let mut entry = match archive.by_name(name) { + Ok(entry) => entry, + Err(zip::result::ZipError::FileNotFound) => return Ok(None), + Err(_) => return Err(Error::Invalid(REFUSED_NOT_ZIP.into())), + }; + let mut bytes = Vec::new(); + (&mut entry) + .take(max) + .read_to_end(&mut bytes) + .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?; + Ok(Some(bytes)) +} + +#[cfg(test)] +mod tests { + use std::io::Write; + + use super::*; + + /// Writes a zip file with one deflated entry of `plain` bytes and returns its path inside `dir`. + fn zip_with(dir: &Path, name: &str, plain: &[u8]) -> std::path::PathBuf { + let path = dir.join(name); + let file = File::create(&path).expect("create"); + let mut writer = zip::ZipWriter::new(file); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + writer.start_file("data.xml", options).expect("start"); + writer.write_all(plain).expect("write"); + writer.finish().expect("finish"); + path + } + + #[test] + fn a_small_archive_passes() { + let dir = tempfile::tempdir().expect("dir"); + let path = zip_with(dir.path(), "ok.xlsx", b"hello"); + assert!(open_checked(&path, 1 << 20).is_ok()); + } + + /// 60 MiB of zeros deflates to a few dozen kilobytes. The declared total is over the limit, so the + /// archive is refused on the first pass, and nothing is inflated. + #[test] + fn a_zip_bomb_is_refused_before_parsing() { + let dir = tempfile::tempdir().expect("dir"); + let zeros = vec![0u8; 60 * 1024 * 1024]; + let path = zip_with(dir.path(), "bomb.xlsx", &zeros); + let error = open_checked(&path, u64::MAX).expect_err("refused"); + assert!( + matches!(error, Error::Invalid(ref code) if code == REFUSED_SIZE || code == REFUSED_RATIO), + "{error:?}" + ); + } + + #[test] + fn a_file_over_the_input_limit_is_refused() { + let dir = tempfile::tempdir().expect("dir"); + let path = zip_with(dir.path(), "big.xlsx", b""); + let error = open_checked(&path, 4).expect_err("refused"); + assert!(matches!(error, Error::Invalid(ref code) if code == REFUSED_SIZE)); + } + + #[test] + fn a_plain_file_is_not_a_zip() { + let dir = tempfile::tempdir().expect("dir"); + let path = dir.path().join("plain.xlsx"); + std::fs::write(&path, b"not a zip").expect("write"); + let error = open_checked(&path, 1 << 20).expect_err("refused"); + assert!(matches!(error, Error::Invalid(ref code) if code == REFUSED_NOT_ZIP)); + } + + #[test] + fn the_ratio_floor_spares_small_parts() { + assert!(!ratio_refused(ARCHIVE_RATIO_FLOOR_BYTES, 1)); + assert!(ratio_refused(ARCHIVE_RATIO_FLOOR_BYTES + 1, 1)); + assert!(!ratio_refused( + ARCHIVE_RATIO_FLOOR_BYTES * 2, + ARCHIVE_RATIO_FLOOR_BYTES + )); + } +} diff --git a/crates/iz-core/src/lib.rs b/crates/iz-core/src/lib.rs index 299c96d..1767b79 100644 --- a/crates/iz-core/src/lib.rs +++ b/crates/iz-core/src/lib.rs @@ -3,13 +3,19 @@ //! This crate has no HTTP. It keeps the invariants: the schema, the length limits, the board rules //! (overdue, cycles, ordering), time zone math and sealing of secrets. `iz-web` builds on it. +pub mod archive; pub mod authz; pub mod board; pub mod clock; pub mod config; pub mod error; pub mod limits; +pub mod preview; pub mod secret; +pub mod sheet; +pub mod slides; +pub mod sniff; +pub mod staging; pub mod store; pub mod time; pub mod token; diff --git a/crates/iz-core/src/limits.rs b/crates/iz-core/src/limits.rs index a21805b..ca292d7 100644 --- a/crates/iz-core/src/limits.rs +++ b/crates/iz-core/src/limits.rs @@ -29,3 +29,37 @@ pub const ATTACHMENT_LIMIT_MIB_MAX: u32 = 500; pub const REMINDER_MINUTES_MAX: u32 = 1440; /// Largest mail batching window, in minutes. Reason: longer quiet windows delay mail past usefulness. pub const BATCH_MINUTES_MAX: u32 = 120; +/// Default per-file attachment limit, in MiB. Reason: the starting value of the setting; an admin raises it. +pub const ATTACHMENT_DEFAULT_MIB: u32 = 100; +/// Most file parts one upload request may carry. Reason: bounds the work one form can cause. +pub const UPLOAD_FILES_MAX: usize = 10; +/// Leading bytes of an upload that the sniffer reads. Reason: enough for every signature it knows. +pub const SNIFF_BYTES: usize = 8192; +/// Bytes of a text file the text viewer shows. Reason: a preview, not a reader; the rest is one download away. +pub const TEXT_PREVIEW_BYTES: u64 = 256 * 1024; +/// Largest compressed spreadsheet or CSV the viewer parses, in bytes. Reason: bounds the work of one preview. +pub const SHEET_INPUT_MAX_BYTES: u64 = 5 * 1024 * 1024; +/// Largest compressed slide deck the viewer parses, in bytes. Reason: decks carry pictures, so the cap is higher. +pub const SLIDES_INPUT_MAX_BYTES: u64 = 20 * 1024 * 1024; +/// Largest total uncompressed size of a zip container the viewers read, in bytes. Reason: a zip bomb is +/// refused before parsing; real workbooks and decks are far below this. +pub const ARCHIVE_UNCOMPRESSED_MAX_BYTES: u64 = 50 * 1024 * 1024; +/// Largest uncompressed-to-compressed ratio of a zip container. Reason: zip bombs compress to almost nothing. +pub const ARCHIVE_RATIO_MAX: u64 = 100; +/// Uncompressed size below which the ratio is not judged, in bytes. Reason: small parts compress badly +/// without being hostile, and the total size limit still applies to them. +pub const ARCHIVE_RATIO_FLOOR_BYTES: u64 = 1024 * 1024; +/// Most sheets a workbook preview shows. Reason: a preview of every tab of a large workbook is a document dump. +pub const SHEETS_MAX: usize = 20; +/// Most rows a sheet preview shows. Reason: keeps one page render bounded. +pub const SHEET_ROWS_MAX: usize = 1000; +/// Most columns a sheet preview shows. Reason: wider tables do not fit the viewer width anyway. +pub const SHEET_COLS_MAX: usize = 100; +/// Longest cell text a sheet preview shows, in characters. Reason: one cell must not fill the page. +pub const CELL_TEXT_MAX: usize = 1000; +/// Most slides a deck preview lists. Reason: bounds the XML parsed from one request. +pub const SLIDES_MAX: usize = 200; +/// Longest text of one slide shown, in characters. Reason: a slide's text is a summary, not a transcript. +pub const SLIDE_TEXT_MAX: usize = 4000; +/// Largest XML part of a deck that is read, in bytes. Reason: a single slide is far below this. +pub const DECK_PART_MAX_BYTES: u64 = 4 * 1024 * 1024; diff --git a/crates/iz-core/src/preview.rs b/crates/iz-core/src/preview.rs new file mode 100644 index 0000000..27b7a2d --- /dev/null +++ b/crates/iz-core/src/preview.rs @@ -0,0 +1,39 @@ +//! Previews of files that are read as text: the first part of a text file, escaped by the page. Nothing +//! here decides whether a file may be shown; the caller has checked the viewer kind and the caller's +//! right to read the file. + +use std::io::Read; +use std::path::Path; + +use crate::error::Result; + +/// Reads at most `cap` bytes of `path` as text. Returns the text (invalid UTF-8 replaced) and whether the file +/// was longer than the cap. +pub fn read_text_head(path: &Path, cap: u64) -> Result<(String, bool)> { + let file = std::fs::File::open(path)?; + let mut bytes = Vec::new(); + file.take(cap + 1).read_to_end(&mut bytes)?; + let truncated = bytes.len() as u64 > cap; + bytes.truncate(usize::try_from(cap).unwrap_or(usize::MAX)); + Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_long_text_is_cut_and_says_so() { + let dir = tempfile::tempdir().expect("dir"); + let path = dir.path().join("long.txt"); + std::fs::write(&path, "abcdef").expect("write"); + assert_eq!( + read_text_head(&path, 4).expect("head"), + ("abcd".into(), true) + ); + assert_eq!( + read_text_head(&path, 6).expect("head"), + ("abcdef".into(), false) + ); + } +} diff --git a/crates/iz-core/src/sheet.rs b/crates/iz-core/src/sheet.rs new file mode 100644 index 0000000..29c5e61 --- /dev/null +++ b/crates/iz-core/src/sheet.rs @@ -0,0 +1,175 @@ +//! Spreadsheet previews: a workbook (`.xlsx`, `.ods`) or a CSV file read as values only, with the caps of +//! `limits.rs`: at most 20 sheets, 1000 rows, 100 columns and 1000 characters a cell. Formulas, formats, +//! charts and macros are not read; a cell is its displayed value. The caller turns the result into HTML, +//! where every cell is escaped, so a cell that holds markup is shown as text. +//! +//! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. A CSV is +//! read record by record and stops at the row cap, so a long file costs no more than the cap. + +use std::fs::File; +use std::path::Path; + +use calamine::{Data, Reader, open_workbook_auto}; + +use crate::archive; +use crate::error::{Error, Result}; +use crate::limits::{ + CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEETS_MAX, +}; + +/// One sheet of a book, as text cells. `rows_cut` is set when the sheet had more rows than the cap. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sheet { + /// The tab name (for a CSV, the file name). + pub name: String, + /// The rows, each a list of cell texts. + pub rows: Vec>, + /// Whether rows past the cap were left out. + pub rows_cut: bool, +} + +/// A book: the sheets shown, and how many it has in all. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Book { + /// The first sheets, at most [`SHEETS_MAX`]. + pub sheets: Vec, + /// The number of sheets in the file. + pub sheet_count: usize, +} + +/// Cuts a cell's text to [`CELL_TEXT_MAX`] characters. +fn cell_text(text: &str) -> String { + text.chars().take(CELL_TEXT_MAX).collect() +} + +/// Reads an `.xlsx` or `.ods` workbook. Refused (as `Invalid`) when the zip checks fail. +pub fn read_workbook(path: &Path) -> Result { + archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?; + let mut workbook = + open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?; + let names = workbook.sheet_names(); + let sheet_count = names.len(); + let mut sheets = Vec::new(); + for name in names.into_iter().take(SHEETS_MAX) { + let range = workbook + .worksheet_range(&name) + .map_err(|_| Error::Invalid("bad_workbook".into()))?; + let mut rows = Vec::new(); + let mut rows_cut = false; + for (index, row) in range.rows().enumerate() { + if index == SHEET_ROWS_MAX { + rows_cut = true; + break; + } + rows.push( + row.iter() + .take(SHEET_COLS_MAX) + .map(|cell: &Data| cell_text(&cell.to_string())) + .collect(), + ); + } + sheets.push(Sheet { + name, + rows, + rows_cut, + }); + } + Ok(Book { + sheets, + sheet_count, + }) +} + +/// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters. +pub fn read_csv(path: &Path, name: &str) -> Result { + let len = std::fs::metadata(path)?.len(); + if len > SHEET_INPUT_MAX_BYTES { + return Err(Error::Invalid(archive::REFUSED_SIZE.into())); + } + let mut reader = csv::ReaderBuilder::new() + .has_headers(false) + .flexible(true) + .from_reader(File::open(path)?); + let mut rows = Vec::new(); + let mut rows_cut = false; + let mut record = csv::ByteRecord::new(); + loop { + let more = reader + .read_byte_record(&mut record) + .map_err(|_| Error::Invalid("bad_csv".into()))?; + if !more { + break; + } + if rows.len() == SHEET_ROWS_MAX { + rows_cut = true; + break; + } + rows.push( + record + .iter() + .take(SHEET_COLS_MAX) + .map(|field| cell_text(&String::from_utf8_lossy(field))) + .collect(), + ); + } + Ok(Book { + sheets: vec![Sheet { + name: name.to_owned(), + rows, + rows_cut, + }], + sheet_count: 1, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_csv_keeps_cells_as_plain_text() { + let dir = tempfile::tempdir().expect("dir"); + let path = dir.path().join("t.csv"); + std::fs::write(&path, "name,note\n,\"a, b\"\n").expect("write"); + let book = read_csv(&path, "t.csv").expect("csv"); + assert_eq!(book.sheet_count, 1); + assert_eq!(book.sheets[0].rows[1][0], ""); + assert_eq!(book.sheets[0].rows[1][1], "a, b"); + assert!(!book.sheets[0].rows_cut); + } + + #[test] + fn a_workbook_zip_bomb_is_refused() { + let dir = tempfile::tempdir().expect("dir"); + let path = dir.path().join("bomb.xlsx"); + let file = std::fs::File::create(&path).expect("create"); + let mut writer = zip::ZipWriter::new(file); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + writer + .start_file("xl/worksheets/sheet1.xml", options) + .expect("start"); + std::io::Write::write_all(&mut writer, &vec![0u8; 60 * 1024 * 1024]).expect("write"); + writer.finish().expect("finish"); + assert!(read_workbook(&path).is_err()); + } + + #[test] + fn a_csv_stops_at_the_row_cap() { + let dir = tempfile::tempdir().expect("dir"); + let path = dir.path().join("long.csv"); + let text: String = (0..SHEET_ROWS_MAX + 5).map(|i| format!("{i}\n")).collect(); + std::fs::write(&path, text).expect("write"); + let book = read_csv(&path, "long.csv").expect("csv"); + assert_eq!(book.sheets[0].rows.len(), SHEET_ROWS_MAX); + assert!(book.sheets[0].rows_cut); + } + + #[test] + fn a_cell_is_cut_to_its_cap() { + assert_eq!( + cell_text(&"x".repeat(CELL_TEXT_MAX + 9)).len(), + CELL_TEXT_MAX + ); + } +} diff --git a/crates/iz-core/src/slides.rs b/crates/iz-core/src/slides.rs new file mode 100644 index 0000000..348cb08 --- /dev/null +++ b/crates/iz-core/src/slides.rs @@ -0,0 +1,244 @@ +//! Slide deck previews: the text of each slide of a `.pptx`, in slide order, as paragraphs. Pictures, +//! notes, embedded objects and layouts are not read, and nothing from the deck is rendered as markup; the +//! caller escapes every paragraph. +//! +//! The deck is a zip container, so it passes `archive::open_checked` first. Slide order comes from +//! `ppt/presentation.xml` and its relationships; when those are missing or unreadable, the parts +//! `ppt/slides/slideN.xml` are read in order until one is absent. + +use std::path::Path; + +use quick_xml::events::Event; +use quick_xml::reader::Reader; +use zip::ZipArchive; + +use crate::archive; +use crate::error::Result; +use crate::limits::{DECK_PART_MAX_BYTES, SLIDE_TEXT_MAX, SLIDES_INPUT_MAX_BYTES, SLIDES_MAX}; + +/// One slide: its position (from 1) and its paragraphs of text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Slide { + /// Position in the deck, from 1. + pub number: usize, + /// The paragraphs of text, in order. Empty paragraphs are left out. + pub paragraphs: Vec, +} + +/// Reads the slides of a `.pptx` in order, at most [`SLIDES_MAX`] of them. +pub fn read_deck(path: &Path) -> Result> { + let mut archive = archive::open_checked(path, SLIDES_INPUT_MAX_BYTES)?; + let parts = slide_parts(&mut archive)?; + let mut slides = Vec::new(); + for (index, part) in parts.iter().take(SLIDES_MAX).enumerate() { + let Some(bytes) = archive::read_entry(&mut archive, part, DECK_PART_MAX_BYTES)? else { + break; + }; + slides.push(Slide { + number: index + 1, + paragraphs: paragraphs_of(&bytes), + }); + } + Ok(slides) +} + +/// The part names of the slides in presentation order. +fn slide_parts(archive: &mut ZipArchive) -> Result> { + let order = presentation_order(archive)?; + if !order.is_empty() { + return Ok(order); + } + // Fallback: the conventional names, in order, until one is missing. + let mut parts = Vec::new(); + for number in 1..=SLIDES_MAX { + let name = format!("ppt/slides/slide{number}.xml"); + if archive.by_name(&name).is_err() { + break; + } + parts.push(name); + } + Ok(parts) +} + +/// The slide parts in the order `ppt/presentation.xml` lists them, resolved through its relationships. +/// Empty when either part is missing or names nothing usable. +fn presentation_order(archive: &mut ZipArchive) -> Result> { + let Some(presentation) = + archive::read_entry(archive, "ppt/presentation.xml", DECK_PART_MAX_BYTES)? + else { + return Ok(Vec::new()); + }; + let Some(rels) = archive::read_entry( + archive, + "ppt/_rels/presentation.xml.rels", + DECK_PART_MAX_BYTES, + )? + else { + return Ok(Vec::new()); + }; + let ids = slide_rel_ids(&presentation); + let targets = relationship_targets(&rels); + let mut parts = Vec::new(); + for id in ids { + if let Some((_, target)) = targets.iter().find(|(rel, _)| *rel == id) { + let name = match target.strip_prefix('/') { + Some(absolute) => absolute.to_owned(), + None => format!("ppt/{target}"), + }; + // Only slide parts are read; any other target is ignored. + if name.starts_with("ppt/slides/") && name.ends_with(".xml") { + parts.push(name); + } + } + } + Ok(parts) +} + +/// The `r:id` of each `` of the presentation, in order. +fn slide_rel_ids(xml: &[u8]) -> Vec { + let mut ids = Vec::new(); + let Ok(text) = std::str::from_utf8(xml) else { + return ids; + }; + let mut reader = Reader::from_str(text); + loop { + match reader.read_event() { + Ok(Event::Start(e) | Event::Empty(e)) if e.local_name().as_ref() == "sldId" => { + for attribute in e.attributes().flatten() { + if attribute.key.as_ref() == "r:id" { + // Ids and targets are plain names; a reference inside one is never a slide, so the + // raw value is used and entities are not resolved. + ids.push(attribute.value.to_string()); + } + } + } + Ok(Event::Eof) | Err(_) => break, + Ok(_) => {} + } + } + ids +} + +/// The `(Id, Target)` pairs of a relationships part. +fn relationship_targets(xml: &[u8]) -> Vec<(String, String)> { + let mut pairs = Vec::new(); + let Ok(text) = std::str::from_utf8(xml) else { + return pairs; + }; + let mut reader = Reader::from_str(text); + loop { + match reader.read_event() { + Ok(Event::Start(e) | Event::Empty(e)) if e.local_name().as_ref() == "Relationship" => { + let mut id = None; + let mut target = None; + for attribute in e.attributes().flatten() { + let value = Some(attribute.value.to_string()); + match attribute.key.as_ref() { + "Id" => id = value, + "Target" => target = value, + _ => {} + } + } + if let (Some(id), Some(target)) = (id, target) { + pairs.push((id, target)); + } + } + Ok(Event::Eof) | Err(_) => break, + Ok(_) => {} + } + } + pairs +} + +/// The paragraphs of text of one slide part: each `` with the text of its `` runs, entities resolved. +/// Stops once [`SLIDE_TEXT_MAX`] characters are collected. +fn paragraphs_of(xml: &[u8]) -> Vec { + let mut paragraphs = Vec::new(); + let Ok(text) = std::str::from_utf8(xml) else { + return paragraphs; + }; + let mut reader = Reader::from_str(text); + let mut current = String::new(); + let mut in_run = false; + let mut used = 0usize; + while let Ok(event) = reader.read_event() { + match event { + Event::Start(e) if e.local_name().as_ref() == "t" => in_run = true, + Event::End(e) if e.local_name().as_ref() == "t" => in_run = false, + Event::End(e) if e.local_name().as_ref() == "p" => { + let paragraph = current.trim().to_owned(); + if !paragraph.is_empty() { + paragraphs.push(paragraph); + } + current.clear(); + } + Event::Text(t) if in_run => push_limited(&mut current, &t.xml10_content(), &mut used), + Event::GeneralRef(r) if in_run => { + let resolved = match r.resolve_char_ref() { + Ok(Some(ch)) => Some(ch.to_string()), + Ok(None) => predefined_entity(&r), + Err(_) => None, + }; + if let Some(resolved) = resolved { + push_limited(&mut current, &resolved, &mut used); + } + } + Event::Eof => break, + _ => {} + } + if used >= SLIDE_TEXT_MAX { + break; + } + } + paragraphs +} + +/// The character of one of the five predefined XML entities (`<` and the rest). +fn predefined_entity(reference: &quick_xml::events::BytesRef<'_>) -> Option { + let name: &str = reference.as_ref(); + let ch = match name { + "lt" => '<', + "gt" => '>', + "amp" => '&', + "quot" => '"', + "apos" => '\'', + _ => return None, + }; + Some(ch.to_string()) +} + +/// Appends `text` to `out`, counting characters against [`SLIDE_TEXT_MAX`]. +fn push_limited(out: &mut String, text: &str, used: &mut usize) { + for ch in text.chars() { + if *used >= SLIDE_TEXT_MAX { + return; + } + out.push(ch); + *used += 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paragraphs_are_the_runs_of_each_a_p_with_entities_resolved() { + let xml = br#"Hello & <b>Second"#; + assert_eq!( + paragraphs_of(xml), + vec!["Hello & ".to_owned(), "Second".to_owned()] + ); + } + + #[test] + fn relationship_targets_and_slide_ids_are_read() { + let rels = br#""#; + assert_eq!( + relationship_targets(rels), + vec![("rId2".to_owned(), "slides/slide1.xml".to_owned())] + ); + let pres = br#""#; + assert_eq!(slide_rel_ids(pres), vec!["rId2".to_owned()]); + } +} diff --git a/crates/iz-core/src/sniff.rs b/crates/iz-core/src/sniff.rs new file mode 100644 index 0000000..844f9e9 --- /dev/null +++ b/crates/iz-core/src/sniff.rs @@ -0,0 +1,247 @@ +//! Content sniffing: the MIME type of a file is decided from its first bytes, never from the +//! uploader's claim. The result drives the viewers and the `Content-Disposition` of every byte response, +//! so SVG and HTML are recognised explicitly: they must never be served inline. +//! +//! This is a pure function over a prefix. Callers pass the first kilobyte or megabyte of the file; +//! an empty prefix is `application/octet-stream`. + +/// How many leading bytes the text heuristics look at when searching for a markup marker. +const TEXT_WINDOW: usize = 1024; + +/// The MIME type for `prefix`, the first bytes of a file. +pub fn sniff(prefix: &[u8]) -> String { + if prefix.is_empty() { + return "application/octet-stream".into(); + } + let mime = binary_magic(prefix) + .or(is_svg(prefix).then_some("image/svg+xml")) + .or(is_html(prefix).then_some("text/html")) + .or_else(|| iso_bmff(prefix)) + .unwrap_or_else(|| { + if is_utf8_text(prefix) { + "text/plain" + } else { + "application/octet-stream" + } + }); + mime.into() +} + +/// Magic numbers of the binary formats. `None` when nothing matches. +fn binary_magic(b: &[u8]) -> Option<&'static str> { + let starts = |magic: &[u8]| b.starts_with(magic); + if starts(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) { + return Some("image/png"); + } + if starts(&[0xFF, 0xD8, 0xFF]) { + return Some("image/jpeg"); + } + if starts(b"GIF87a") || starts(b"GIF89a") { + return Some("image/gif"); + } + if starts(b"%PDF-") { + return Some("application/pdf"); + } + if starts(&[0x1F, 0x8B]) { + return Some("application/gzip"); + } + if starts(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { + return Some(if contains_utf16(b, "Workbook") { + "application/vnd.ms-excel" + } else { + "application/x-ole-storage" + }); + } + if starts(b"PK\x03\x04") { + return Some(zip_flavour(b)); + } + if starts(&[0x1A, 0x45, 0xDF, 0xA3]) { + // The EBML header names its document type ("webm" or "matroska") in the first bytes. + let head = &b[..b.len().min(TEXT_WINDOW)]; + return Some(if contains(head, b"webm") { + "video/webm" + } else { + "video/x-matroska" + }); + } + if starts(b"fLaC") { + return Some("audio/flac"); + } + if starts(b"OggS") { + return Some("audio/ogg"); + } + if b.len() >= 12 && starts(b"RIFF") && &b[8..12] == b"WEBP" { + return Some("image/webp"); + } + if b.len() >= 12 && starts(b"RIFF") && &b[8..12] == b"WAVE" { + return Some("audio/wav"); + } + if starts(b"ID3") || starts(&[0xFF, 0xFB]) || starts(&[0xFF, 0xF3]) || starts(&[0xFF, 0xF2]) { + return Some("audio/mpeg"); + } + None +} + +/// Tells an OOXML or OpenDocument container from a plain zip by the entry names it contains. +/// Zip entry names are stored in the clear, so a substring scan finds them. +fn zip_flavour(b: &[u8]) -> &'static str { + if contains(b, b"xl/workbook.xml") { + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + } else if contains(b, b"ppt/presentation.xml") { + "application/vnd.openxmlformats-officedocument.presentationml.presentation" + } else if contains(b, b"opendocument.spreadsheet") { + "application/vnd.oasis.opendocument.spreadsheet" + } else { + "application/zip" + } +} + +/// ISO base media files (`ftyp` box at offset 4). The major brand decides the type. A brand that is +/// not listed here is treated as generic MP4. +fn iso_bmff(b: &[u8]) -> Option<&'static str> { + if b.len() < 12 || &b[4..8] != b"ftyp" { + return None; + } + Some(match &b[8..12] { + b"avif" | b"avis" => "image/avif", + b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevx" => "image/heic", + b"heif" | b"mif1" | b"msf1" => "image/heif", + b"qt " => "video/quicktime", + b"M4A " | b"M4B " => "audio/mp4", + _ => "video/mp4", + }) +} + +/// Whether the text starts with an ` bool { + let mut rest = strip_bom(b); + loop { + rest = trim_start_ws(rest); + if rest.starts_with(b"") { + Some(i) => &rest[i + 2..], + None => return false, + }; + } else if rest.starts_with(b"") { + Some(i) => &rest[i + 3..], + None => return false, + }; + } else if starts_with_ci(rest, b"").map_or(rest.len(), |i| i + 1); + if contains_ci(&rest[..end], b"html") { + return false; + } + rest = &rest[end..]; + } else { + break; + } + } + starts_with_ci(rest, b" bool { + let body = trim_start_ws(strip_bom(b)); + let window = &body[..body.len().min(TEXT_WINDOW)]; + [ + &b" bool { + match std::str::from_utf8(b) { + Ok(_) => true, + Err(e) => e.error_len().is_none(), + } +} + +fn strip_bom(b: &[u8]) -> &[u8] { + b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(b) +} + +fn trim_start_ws(b: &[u8]) -> &[u8] { + let n = b.iter().take_while(|c| c.is_ascii_whitespace()).count(); + &b[n..] +} + +fn find(hay: &[u8], needle: &[u8]) -> Option { + hay.windows(needle.len()).position(|w| w == needle) +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + find(hay, needle).is_some() +} + +fn starts_with_ci(hay: &[u8], needle: &[u8]) -> bool { + hay.len() >= needle.len() && hay[..needle.len()].eq_ignore_ascii_case(needle) +} + +fn contains_ci(hay: &[u8], needle: &[u8]) -> bool { + hay.windows(needle.len()) + .any(|w| w.eq_ignore_ascii_case(needle)) +} + +/// Whether `word` appears as UTF-16LE text in `b`, as it does inside OLE2 directory entries. +fn contains_utf16(b: &[u8], word: &str) -> bool { + let wide: Vec = word.bytes().flat_map(|c| [c, 0]).collect(); + contains(b, &wide) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognises_binary_formats_by_magic_number() { + assert_eq!(sniff(b"\x89PNG\r\n\x1a\n rest"), "image/png"); + assert_eq!(sniff(b"%PDF-1.7\n"), "application/pdf"); + assert_eq!(sniff(b"\xFF\xD8\xFF\xE0 jpeg"), "image/jpeg"); + } + + #[test] + fn svg_is_detected_after_prolog_comments_and_whitespace() { + assert_eq!(sniff(b""), "image/svg+xml"); + let prolog = b"\xEF\xBB\xBF\n\n "; + assert_eq!(sniff(prolog), "image/svg+xml"); + let doctype = b"\n"; + assert_eq!(sniff(doctype), "image/svg+xml"); + } + + #[test] + fn html_is_detected_near_the_start_case_insensitively() { + assert_eq!(sniff(b"\n

x

"), "text/html"); + assert_eq!(sniff(b" "), "text/html"); + assert_eq!(sniff(b""), "text/html"); + assert_eq!(sniff(b"just words"), "text/plain"); + } + + #[test] + fn audio_and_video_brands_are_told_apart() { + assert_eq!(sniff(b"\x00\x00\x00\x20ftypM4A \x00\x00"), "audio/mp4"); + assert_eq!(sniff(b"\x00\x00\x00\x20ftypM4B \x00\x00"), "audio/mp4"); + assert_eq!(sniff(b"\x00\x00\x00\x20ftypisom\x00\x00"), "video/mp4"); + } + + #[test] + fn empty_and_unknown_binary_are_octet_stream() { + assert_eq!(sniff(b""), "application/octet-stream"); + assert_eq!(sniff(&[0xFF, 0x00, 0xFE, 0x81]), "application/octet-stream"); + } + + #[test] + fn a_cut_multibyte_character_at_the_end_still_counts_as_text() { + let mut bytes = "héllo".as_bytes().to_vec(); + bytes.push("é".as_bytes()[0]); + assert_eq!(sniff(&bytes), "text/plain"); + } +} diff --git a/crates/iz-core/src/staging.rs b/crates/iz-core/src/staging.rs new file mode 100644 index 0000000..81aa2f5 --- /dev/null +++ b/crates/iz-core/src/staging.rs @@ -0,0 +1,186 @@ +//! Streaming intake of an upload. Incoming bytes go to `data_dir/tmp/` while the SHA-256 and the +//! size are computed, so nothing is buffered whole and the file is never trusted before it is complete. +//! The per-file limit is enforced while the bytes are read: the write that would pass it is refused, and +//! nothing past the limit reaches the disk. +//! +//! A finished file is moved into `data_dir/attachments/` by [`install_blob`]. A file that is never +//! finished is removed by [`StagedFile::abort`], or stays in `data_dir/tmp` after a crash until the sweeper +//! removes it. Every path under `attachments` is built from a validated ULID by [`blob_path`], so no name from +//! a client ever reaches the disk. + +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; + +use crate::error::{Error, Result}; + +/// Name of the staging directory inside the data directory. +pub const TMP_DIR: &str = "tmp"; +/// Name of the directory inside the data directory that holds the bytes of attachments, one file per id. +pub const ATTACHMENTS_DIR: &str = "attachments"; + +/// The file that holds the bytes of attachment `id`: `data_dir/attachments/`. `id` must be a ULID in its +/// canonical text form (upper case, 26 characters); anything else is `Invalid("bad_id")`, so the path can +/// never leave the attachments directory. +pub fn blob_path(data_dir: &Path, id: &str) -> Result { + let canonical = ulid::Ulid::from_string(id) + .map(|parsed| parsed.to_string() == id) + .unwrap_or(false); + if !canonical { + return Err(Error::Invalid("bad_id".into())); + } + Ok(data_dir.join(ATTACHMENTS_DIR).join(id)) +} + +/// Moves a finished staged file to the place of attachment `id` and makes the move durable. The directory is +/// created with mode 0700 if missing; the file keeps its mode 0600 from the staging step. +pub async fn install_blob(data_dir: &Path, id: &str, staged: &Path) -> Result { + let target = blob_path(data_dir, id)?; + let dir = data_dir.join(ATTACHMENTS_DIR); + tokio::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&dir) + .await?; + tokio::fs::rename(staged, &target).await?; + // The rename is durable only once the directory entry is. + tokio::fs::File::open(&dir).await?.sync_all().await?; + Ok(target) +} + +/// Removes the bytes of attachment `id`. A file that is already gone is not an error: the goal is that the +/// bytes are not there, and they are not. +pub async fn remove_blob(data_dir: &Path, id: &str) -> Result<()> { + let path = blob_path(data_dir, id)?; + match tokio::fs::remove_file(&path).await { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error.into()), + } +} + +/// A file being written. Create it with [`StagedFile::create`], feed it with [`StagedFile::write`], then +/// call [`StagedFile::finish`]; or call [`StagedFile::abort`] on any error. +pub struct StagedFile { + path: PathBuf, + file: tokio::fs::File, + hasher: Sha256, + size: u64, + max_size: u64, +} + +/// A complete staged file, ready to be moved into place. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Staged { + /// Where the bytes are. + pub path: PathBuf, + /// Number of bytes written. + pub size: u64, + /// Lowercase hex SHA-256 of the bytes. + pub sha256: String, +} + +impl StagedFile { + /// Starts a new staged file in `data_dir/tmp`. The directory is created with mode 0700 and the file with + /// mode 0600. A write that would take the file past `max_size` fails with `Invalid("too_large")`. + pub async fn create(data_dir: &Path, max_size: u64) -> Result { + let dir = data_dir.join(TMP_DIR); + tokio::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&dir) + .await?; + let path = dir.join(crate::store::new_id()); + let file = tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path) + .await?; + Ok(Self { + path, + file, + hasher: Sha256::new(), + size: 0, + max_size, + }) + } + + /// Appends `chunk`. Refused, without writing, when it would take the file past the size limit. + pub async fn write(&mut self, chunk: &[u8]) -> Result<()> { + let len = chunk.len() as u64; + if self.size.saturating_add(len) > self.max_size { + return Err(Error::Invalid("too_large".into())); + } + self.file.write_all(chunk).await?; + self.hasher.update(chunk); + self.size += len; + Ok(()) + } + + /// Flushes the bytes to the disk and returns the finished file. The caller moves it. + pub async fn finish(mut self) -> Result { + self.file.flush().await?; + self.file.sync_all().await?; + let sha256 = hex::encode(self.hasher.finalize()); + Ok(Staged { + path: self.path, + size: self.size, + sha256, + }) + } + + /// Removes the partial file. Used on every refusal and failure, so nothing is left behind. + pub async fn abort(self) { + let path = self.path.clone(); + drop(self.file); + let _ = tokio::fs::remove_file(path).await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn the_limit_is_enforced_while_writing() { + let dir = tempfile::tempdir().expect("dir"); + let mut staged = StagedFile::create(dir.path(), 4).await.expect("create"); + staged.write(b"abc").await.expect("first write"); + let error = staged.write(b"de").await.expect_err("over the limit"); + assert!(matches!(error, Error::Invalid(ref code) if code == "too_large")); + staged.abort().await; + let left = std::fs::read_dir(dir.path().join(TMP_DIR)) + .expect("tmp") + .count(); + assert_eq!(left, 0, "the partial file is removed"); + } + + #[test] + fn a_blob_path_takes_only_a_canonical_ulid() { + let dir = Path::new("/data"); + let id = crate::store::new_id(); + assert_eq!( + blob_path(dir, &id).expect("path"), + dir.join(ATTACHMENTS_DIR).join(&id) + ); + assert!(blob_path(dir, "../../etc/passwd").is_err()); + assert!(blob_path(dir, &id.to_ascii_lowercase()).is_err()); + assert!(blob_path(dir, "").is_err()); + } + + #[tokio::test] + async fn the_digest_is_of_the_written_bytes() { + let dir = tempfile::tempdir().expect("dir"); + let mut staged = StagedFile::create(dir.path(), 1024).await.expect("create"); + staged.write(b"ab").await.expect("write"); + staged.write(b"c").await.expect("write"); + let done = staged.finish().await.expect("finish"); + assert_eq!(done.size, 3); + assert_eq!( + done.sha256, + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } +} diff --git a/crates/iz-core/src/store/attachments.rs b/crates/iz-core/src/store/attachments.rs new file mode 100644 index 0000000..5e0e374 --- /dev/null +++ b/crates/iz-core/src/store/attachments.rs @@ -0,0 +1,455 @@ +//! Attachments of tasks: the rows, the upload policy, and the queue of bytes still to delete. +//! +//! The bytes themselves are on the disk (`data_dir/attachments/`, written by iz-web); this module owns the +//! rows and says which bytes are owed. A row is always reached through its task: a task of another board, a +//! deleted task, or a key that does not match is `NotFound`, so an attachment id from one task cannot be used +//! on another (attack plan section 6: cross-task IDOR). Adding and deleting are one transaction with their +//! activity row; deleting also records the bytes in `blob_deletions` in that same transaction, so a crash +//! never loses the record of bytes that must go. + +use serde_json::json; +use turso::Connection; + +use super::activity::{self, NewActivity}; +use super::{col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::authz::{Action, Actor, authorize}; +use crate::error::{Error, Result}; +use crate::limits::{ + ATTACHMENT_DEFAULT_MIB, ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN, FILE_NAME_MAX, +}; +use crate::store::Store; +use crate::time::{now_stamp, stamp_after}; +use std::time::Duration; + +/// The setting that holds the per-file limit, in MiB. +pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib"; +/// The setting that holds the allowed extensions, separated by spaces or commas. +pub const SETTING_EXTENSIONS: &str = "attachment_extensions"; +/// The extensions allowed when the setting is unset. Reason: office documents, images, audio, video, text. +pub const DEFAULT_EXTENSIONS: &[&str] = &[ + "pdf", "png", "jpg", "jpeg", "gif", "webp", "heic", "txt", "md", "csv", "xlsx", "ods", "pptx", + "docx", "mp3", "m4a", "wav", "ogg", "mp4", "mov", "webm", +]; +/// Longest extension accepted in the setting, in characters. Reason: an extension is a few letters. +const EXTENSION_MAX: usize = 12; + +/// The upload policy in force: the per-file limit and the allowed extensions. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Policy { + /// The largest file accepted, in bytes. + pub limit_bytes: u64, + /// Lowercase extensions without the dot. + pub extensions: Vec, +} + +/// One attachment as stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Attachment { + /// Attachment id (ULID). It names the bytes on the disk. + pub id: String, + /// The task it belongs to. + pub task_id: String, + /// The file name as the uploader gave it, without path components. + pub name: String, + /// The sniffed MIME type. Never the uploader's claim. + pub mime: String, + /// Length in bytes. + pub size: u64, + /// Lowercase hex SHA-256 of the bytes. + pub sha256: String, + /// The uploader's member id. + pub uploaded_by: String, + /// UTC stamp of the upload. + pub created_at: String, +} + +/// What an upload stores. The task and the board are given separately, by the caller's checks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewAttachment { + /// The id, chosen before the bytes are moved, so the file name and the row agree. + pub id: String, + /// The cleaned file name (see [`clean_name`]). + pub name: String, + /// The sniffed MIME type. + pub mime: String, + /// Length in bytes. + pub size: u64, + /// Lowercase hex SHA-256 of the bytes. + pub sha256: String, + /// The uploader's member id. + pub uploaded_by: String, +} + +/// Columns of an attachment, prefixed for the joins that filter by task. +const ATTACHMENT_COLS: &str = + "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at"; + +fn map_attachment(row: &turso::Row) -> Result { + Ok(Attachment { + id: col_text(row, 0)?, + task_id: col_text(row, 1)?, + name: col_text(row, 2)?, + mime: col_text(row, 3)?, + size: u64::try_from(col_int(row, 4)?).unwrap_or(0), + sha256: col_text(row, 5)?, + uploaded_by: col_text(row, 6)?, + created_at: col_text(row, 7)?, + }) +} + +/// Checks a file name from a client and returns it cleaned. Only the last path component is kept, so +/// `../../etc/x` and `C:\\a\\b.png` both become a plain name. An empty name, a control character, or a name +/// longer than [`FILE_NAME_MAX`] bytes is refused. +pub fn clean_name(raw: &str) -> Result { + let last = raw.rsplit(['/', '\\']).next().unwrap_or(""); + let name = last.trim(); + if name.is_empty() || name == "." || name == ".." { + return Err(Error::Invalid("name_empty".into())); + } + if name.chars().any(char::is_control) { + return Err(Error::Invalid("name_invalid".into())); + } + if name.len() > FILE_NAME_MAX { + return Err(Error::Invalid("name_long".into())); + } + Ok(name.to_owned()) +} + +/// The extension of a clean name, lowercase, without the dot. `None` when there is none or it is not a +/// plain alphanumeric word. +pub fn extension_of(name: &str) -> Option { + let (_, ext) = name.rsplit_once('.')?; + let ok = !ext.is_empty() + && ext.len() <= EXTENSION_MAX + && ext.bytes().all(|b| b.is_ascii_alphanumeric()); + ok.then(|| ext.to_ascii_lowercase()) +} + +/// Whether `name` has an extension the policy allows. +pub fn extension_allowed(name: &str, policy: &Policy) -> bool { + extension_of(name).is_some_and(|ext| policy.extensions.contains(&ext)) +} + +/// Reads the extension list of the setting: words separated by spaces, commas or newlines. Each word is +/// lowercased, loses leading dots, and must be alphanumeric and short. Duplicates are dropped. +pub fn parse_extensions(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for word in text.split(|c: char| c.is_whitespace() || c == ',') { + let word = word.trim_start_matches('.').to_ascii_lowercase(); + let ok = !word.is_empty() + && word.len() <= EXTENSION_MAX + && word.bytes().all(|b| b.is_ascii_alphanumeric()); + if ok && !out.contains(&word) { + out.push(word); + } + } + out +} + +impl Store { + /// The upload policy in force. A stored value outside its range, or a missing one, is the default. + pub async fn policy(&self) -> Result { + let mib = self + .get_setting(SETTING_LIMIT_MIB) + .await? + .and_then(|text| text.trim().parse::().ok()) + .filter(|mib| (ATTACHMENT_LIMIT_MIB_MIN..=ATTACHMENT_LIMIT_MIB_MAX).contains(mib)) + .unwrap_or(ATTACHMENT_DEFAULT_MIB); + let extensions = match self.get_setting(SETTING_EXTENSIONS).await? { + Some(text) => parse_extensions(&text), + None => DEFAULT_EXTENSIONS + .iter() + .map(|ext| (*ext).to_owned()) + .collect(), + }; + Ok(Policy { + limit_bytes: u64::from(mib) * 1024 * 1024, + extensions, + }) + } + + /// Stores an attachment on a live task of `board_id`, with its `file_added` activity row. The bytes must + /// already be in place under `new.id`; if this fails, the caller removes them. + pub async fn add_attachment( + &self, + board_id: &str, + task_id: &str, + new: NewAttachment, + ) -> Result { + let size = i64::try_from(new.size).map_err(|_| Error::Invalid("too_large".into()))?; + let created_at = now_stamp(); + let attachment = Attachment { + id: new.id.clone(), + task_id: task_id.to_owned(), + name: new.name.clone(), + mime: new.mime.clone(), + size: new.size, + sha256: new.sha256.clone(), + uploaded_by: new.uploaded_by.clone(), + created_at: created_at.clone(), + }; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let live = fetch_opt( + &tx, + "SELECT id FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + (task_id.to_owned(), board_id.to_owned()), + |row| col_text(row, 0), + ) + .await?; + if live.is_none() { + return Err(Error::NotFound); + } + tx.execute( + "INSERT INTO attachments (id, task_id, comment_id, name, mime, size, sha256, uploaded_by, created_at, location) \ + VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7, ?8, 'local')", + ( + new.id.clone(), + task_id.to_owned(), + new.name, + new.mime, + size, + new.sha256, + new.uploaded_by.clone(), + created_at, + ), + ) + .await + .map_err(db_err)?; + activity::record( + &tx, + NewActivity { + task_id: Some(task_id), + actor: Some(&new.uploaded_by), + subject: None, + kind: "file_added", + detail: json!({ "attachment": new.id }), + }, + ) + .await + } + .await; + finish(tx, outcome.map(|()| attachment)).await + } + + /// The live attachments of a task of `board_id`, oldest first. + pub async fn list_attachments(&self, board_id: &str, task_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \ + WHERE a.task_id = ?1 AND t.board_id = ?2 AND t.deleted_at IS NULL ORDER BY a.created_at, a.id" + ), + (task_id.to_owned(), board_id.to_owned()), + map_attachment, + ) + .await + } + + /// An attachment by id, on a live task of `board_id`. Used by the byte route, which has no task key. + pub async fn attachment_on_board( + &self, + board_id: &str, + attachment_id: &str, + ) -> Result { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \ + WHERE a.id = ?1 AND t.board_id = ?2 AND t.deleted_at IS NULL" + ), + (attachment_id.to_owned(), board_id.to_owned()), + map_attachment, + ) + .await? + .ok_or(Error::NotFound) + } + + /// An attachment by id, only when it belongs to the task with `task_key` on `board_id`. Any other + /// combination is `NotFound`: the id of another task never resolves under this key. + pub async fn attachment_of_task( + &self, + board_id: &str, + task_key: &str, + attachment_id: &str, + ) -> Result { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \ + WHERE a.id = ?1 AND t.key = ?2 AND t.board_id = ?3 AND t.deleted_at IS NULL" + ), + ( + attachment_id.to_owned(), + task_key.to_owned(), + board_id.to_owned(), + ), + map_attachment, + ) + .await? + .ok_or(Error::NotFound) + } + + /// Deletes an attachment's row, records its bytes for deletion, and writes its `file_deleted` activity + /// row, all in one transaction. The uploader (while a member) or an admin may do it (`authz`). Returns the + /// deleted attachment, so the caller can tell the task's viewers. + pub async fn delete_attachment( + &self, + board_id: &str, + attachment_id: &str, + actor: &Actor, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let current = live_attachment(&tx, board_id, attachment_id).await?; + authorize( + actor, + &Action::DeleteFile { + uploader: current.uploaded_by.clone(), + }, + )?; + let sub = match actor { + Actor::Member { sub, .. } => sub.as_str(), + Actor::Anonymous => return Err(Error::Forbidden("sign in to continue".into())), + }; + let now = now_stamp(); + tx.execute( + "DELETE FROM attachments WHERE id = ?1", + (attachment_id.to_owned(),), + ) + .await + .map_err(db_err)?; + tx.execute( + "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ + VALUES (?1, 'local', 0, ?2, ?3)", + (attachment_id.to_owned(), now.clone(), now), + ) + .await + .map_err(db_err)?; + activity::record( + &tx, + NewActivity { + task_id: Some(¤t.task_id), + actor: Some(sub), + subject: Some(¤t.uploaded_by), + kind: "file_deleted", + detail: json!({ "attachment": attachment_id }), + }, + ) + .await?; + Ok(current) + } + .await; + finish(tx, outcome).await + } + + /// Bytes owed to deletion whose next attempt is due, oldest first: `(attachment id, attempts so far)`. + pub async fn due_blob_deletions(&self, limit: i64) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT attachment_id, attempts FROM blob_deletions WHERE next_attempt_at <= ?1 \ + ORDER BY next_attempt_at, attachment_id LIMIT ?2", + (now_stamp(), limit), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await + } + + /// Clears a deletion once its bytes are confirmed gone. + pub async fn finish_blob_deletion(&self, attachment_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM blob_deletions WHERE attachment_id = ?1", + (attachment_id.to_owned(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Records a failed attempt and sets the next one `delay` from now. + pub async fn defer_blob_deletion( + &self, + attachment_id: &str, + attempts: i64, + delay: Duration, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE blob_deletions SET attempts = ?2, next_attempt_at = ?3 WHERE attachment_id = ?1", + (attachment_id.to_owned(), attempts + 1, stamp_after(delay)), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} + +/// A live attachment of a live task of `board_id`, read on the writer so it is part of the transaction. +async fn live_attachment( + conn: &Connection, + board_id: &str, + attachment_id: &str, +) -> Result { + fetch_opt( + conn, + &format!( + "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \ + WHERE a.id = ?1 AND t.board_id = ?2 AND t.deleted_at IS NULL" + ), + (attachment_id.to_owned(), board_id.to_owned()), + map_attachment, + ) + .await? + .ok_or(Error::NotFound) +} + +/// A fresh attachment id: a ULID, as every row id is. +pub fn new_attachment_id() -> String { + new_id() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_path_is_reduced_to_its_last_component() { + assert_eq!(clean_name("../../etc/a.png").expect("ok"), "a.png"); + assert_eq!(clean_name("C:\\users\\b.pdf").expect("ok"), "b.pdf"); + assert_eq!(clean_name(" note.txt ").expect("ok"), "note.txt"); + assert!(clean_name("dir/").is_err()); + assert!(clean_name("..").is_err()); + assert!(clean_name("a\r\nb.txt").is_err()); + assert!(clean_name(&format!("{}.txt", "x".repeat(FILE_NAME_MAX))).is_err()); + } + + #[test] + fn extensions_are_lowercase_and_plain() { + assert_eq!(extension_of("Photo.JPG").as_deref(), Some("jpg")); + assert_eq!(extension_of("noext"), None); + assert_eq!(extension_of("bad.p ng"), None); + assert_eq!( + parse_extensions(".PDF, png\nxlsx pdf"), + vec!["pdf", "png", "xlsx"] + ); + assert_eq!(parse_extensions("tar.gz"), Vec::::new()); + } + + #[test] + fn an_extension_must_be_on_the_allowlist() { + let policy = Policy { + limit_bytes: 1, + extensions: vec!["png".into()], + }; + assert!(extension_allowed("a.PNG", &policy)); + assert!(!extension_allowed("a.html", &policy)); + assert!(!extension_allowed("a", &policy)); + } +} diff --git a/crates/iz-core/src/store/migrate.rs b/crates/iz-core/src/store/migrate.rs index 6490cfe..06603f6 100644 --- a/crates/iz-core/src/store/migrate.rs +++ b/crates/iz-core/src/store/migrate.rs @@ -14,6 +14,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 2, include_str!("../../migrations/0002_session_id_token.sql"), ), + (3, include_str!("../../migrations/0003_blob_deletions.sql")), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 25be9b0..413aff7 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -8,6 +8,7 @@ //! SELECTs run in parallel with each other and with the writer. pub mod activity; +pub mod attachments; pub mod board; pub mod comments; pub mod members; @@ -379,7 +380,7 @@ mod tests { }) .await .unwrap(); - assert_eq!(versions, vec![1, 2]); + assert_eq!(versions, vec![1, 2, 3]); } #[tokio::test] diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index 02619ec..ac30ebe 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -12,9 +12,12 @@ path = "src/main.rs" [dependencies] base64.workspace = true +bytes.workspace = true futures-util.workspace = true hex.workspace = true http.workspace = true +http-body.workspace = true +http-body-util.workspace = true iz-core.workspace = true jiff.workspace = true jsonwebtoken.workspace = true @@ -26,7 +29,7 @@ sha2.workspace = true subtle.workspace = true # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout # and the reconnect backoff, `fs` for the photo cache. -tokio = { workspace = true, features = ["fs", "net", "signal", "time"] } +tokio = { workspace = true, features = ["fs", "io-util", "net", "signal", "time"] } topcoat.workspace = true tracing.workspace = true thiserror.workspace = true diff --git a/crates/iz-web/src/attachments.rs b/crates/iz-web/src/attachments.rs new file mode 100644 index 0000000..6f900c6 --- /dev/null +++ b/crates/iz-web/src/attachments.rs @@ -0,0 +1,90 @@ +//! The attachments' disk work that runs outside a request: the deleter. A deleted attachment's row is gone at +//! once (the transaction in `iz-core` records the bytes in `blob_deletions`); this worker removes the bytes +//! afterwards and retries with a backoff until they are gone, then clears the record. It runs until the stop +//! flag is set, like every worker (`docs/architecture.md` section 8). +//! +//! The bytes are only ever removed through `iz_core::staging::remove_blob`, which builds the path from the +//! validated attachment id. + +use std::time::Duration; + +use iz_core::staging::remove_blob; +use tokio::sync::watch; + +use crate::state::AppState; + +/// The largest body of one upload request, in bytes. Reason: several files may come in one form, each up to the +/// per-file limit (at most 500 MiB), and this bounds the whole request. +pub const UPLOAD_REQUEST_MAX_BYTES: usize = 1024 * 1024 * 1024; +/// How often the deleter looks for due deletions. Reason: a deleted file should be gone within seconds. +const SWEEP_EVERY: Duration = Duration::from_secs(5); +/// Most deletions one sweep handles. Reason: bounds one sweep when many files are deleted at once. +const SWEEP_BATCH: i64 = 50; +/// The first retry delay, in seconds. Doubles with each failed attempt. +const RETRY_BASE_SECS: u64 = 5; +/// The longest retry delay, in seconds. Reason: a file that cannot be removed is looked at every ten minutes. +const RETRY_CAP_SECS: u64 = 600; + +/// The delay before the next attempt after `attempts` failures. +pub fn retry_delay(attempts: i64) -> Duration { + let shift = u32::try_from(attempts.clamp(0, 16)).unwrap_or(0); + Duration::from_secs((RETRY_BASE_SECS << shift).min(RETRY_CAP_SECS)) +} + +/// Starts the deleter. It sweeps at once, then every [`SWEEP_EVERY`], until `stop` is set. +pub fn spawn(state: AppState, mut stop: watch::Receiver) { + tokio::spawn(async move { + loop { + sweep(&state).await; + tokio::select! { + () = tokio::time::sleep(SWEEP_EVERY) => {} + _ = stop.wait_for(|stopped| *stopped) => break, + } + } + tracing::info!("attachment deleter stopped"); + }); +} + +/// One pass over the due deletions. A failure is logged and retried later; it never stops the worker. +async fn sweep(state: &AppState) { + let due = match state.store.due_blob_deletions(SWEEP_BATCH).await { + Ok(due) => due, + Err(error) => { + tracing::warn!(error = %error, "reading the due attachment deletions failed"); + return; + } + }; + for (id, attempts) in due { + match remove_blob(&state.config.data_dir, &id).await { + Ok(()) => { + if let Err(error) = state.store.finish_blob_deletion(&id).await { + tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); + } + } + Err(error) => { + tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying"); + if let Err(error) = state + .store + .defer_blob_deletion(&id, attempts, retry_delay(attempts)) + .await + { + tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_retry_backoff_doubles_and_is_capped() { + assert_eq!(retry_delay(0), Duration::from_secs(5)); + assert_eq!(retry_delay(1), Duration::from_secs(10)); + assert_eq!(retry_delay(3), Duration::from_secs(40)); + assert_eq!(retry_delay(40), Duration::from_secs(600)); + assert_eq!(retry_delay(-3), Duration::from_secs(5)); + } +} diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index 6dc83db..200156a 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -16,8 +16,9 @@ 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::attachments; use crate::directory; use crate::live::LiveHub; use crate::oidc; @@ -49,6 +50,7 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { // One stop flag. The signal task sets it; the mirror worker and the server both watch it. let (stop_tx, stop_rx) = watch::channel(false); directory::spawn(state.clone(), stop_rx.clone()); + attachments::spawn(state.clone(), stop_rx.clone()); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); @@ -113,6 +115,7 @@ pub fn router(state: AppState) -> Router { .cookies() .layer(security) .layer(NotFoundLayer) + .layer(BodyLimit::max(attachments::UPLOAD_REQUEST_MAX_BYTES).at("/tasks/{id}/files")) .build() } diff --git a/crates/iz-web/src/i18n/task.rs b/crates/iz-web/src/i18n/task.rs index 15f7daa..0e4945d 100644 --- a/crates/iz-web/src/i18n/task.rs +++ b/crates/iz-web/src/i18n/task.rs @@ -185,6 +185,48 @@ pub enum K { ErrOtherTask, /// Refused: the picked direction is not one of the two. ErrDirection, + /// The heading of the files section. + Files, + /// The text when the task has no files. + NoFiles, + /// The button that uploads the chosen files. + UploadFiles, + /// The label of the file input. + ChooseFiles, + /// The link that opens a file in the viewer. + ViewFile, + /// The link that saves a file. + DownloadFile, + /// The button that deletes a file. + DeleteFile, + /// Refused: a file is larger than the attachment limit. + ErrFileTooLarge, + /// Refused: the extension of a file is not allowed. + ErrFileType, + /// Refused: a file name is empty or not valid. + ErrFileName, + /// Refused: the upload had no file. + ErrNoFile, + /// Refused: the upload has more files than one request may carry. + ErrTooManyFiles, + /// Refused: the file could not be stored; nothing was kept. + ErrFileStore, + /// The viewer message for a file that cannot be previewed (refused, or too large to read). + ViewerRefused, + /// The viewer message for a type with no preview. + NoPreview, + /// The viewer message when a text file was cut to its first part. + ViewerTruncated, + /// The viewer message when a sheet was cut to its first rows and columns. + ViewerCut, + /// The heading of the sheet tabs. + Sheets, + /// The label of a slide, before its number. + SlideLabel, + /// The text of a slide with no text. + NoSlideText, + /// The text of a sheet with no rows. + EmptySheet, } /// The text of `key` in `lang`. @@ -390,6 +432,48 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::ErrOtherTask, Lang::Tr) => "Listeden bir görev seçin.", (K::ErrDirection, Lang::En) => "Pick one of the two directions.", (K::ErrDirection, Lang::Tr) => "İki yönden birini seçin.", + (K::Files, Lang::En) => "Files", + (K::Files, Lang::Tr) => "Dosyalar", + (K::NoFiles, Lang::En) => "No files yet.", + (K::NoFiles, Lang::Tr) => "Henüz dosya yok.", + (K::UploadFiles, Lang::En) => "Upload", + (K::UploadFiles, Lang::Tr) => "Yükle", + (K::ChooseFiles, Lang::En) => "Choose files", + (K::ChooseFiles, Lang::Tr) => "Dosya seç", + (K::ViewFile, Lang::En) => "View", + (K::ViewFile, Lang::Tr) => "Görüntüle", + (K::DownloadFile, Lang::En) => "Download", + (K::DownloadFile, Lang::Tr) => "İndir", + (K::DeleteFile, Lang::En) => "Delete", + (K::DeleteFile, Lang::Tr) => "Sil", + (K::ErrFileTooLarge, Lang::En) => "The file is larger than the attachment limit.", + (K::ErrFileTooLarge, Lang::Tr) => "Dosya ek boyut sınırından büyük.", + (K::ErrFileType, Lang::En) => "This file type is not allowed.", + (K::ErrFileType, Lang::Tr) => "Bu dosya türüne izin verilmiyor.", + (K::ErrFileName, Lang::En) => "The file name is not valid.", + (K::ErrFileName, Lang::Tr) => "Dosya adı geçerli değil.", + (K::ErrNoFile, Lang::En) => "Choose a file first.", + (K::ErrNoFile, Lang::Tr) => "Önce bir dosya seçin.", + (K::ErrTooManyFiles, Lang::En) => "Upload fewer files at once.", + (K::ErrTooManyFiles, Lang::Tr) => "Bir seferde daha az dosya yükleyin.", + (K::ErrFileStore, Lang::En) => "The file could not be saved. Try again.", + (K::ErrFileStore, Lang::Tr) => "Dosya kaydedilemedi. Tekrar deneyin.", + (K::ViewerRefused, Lang::En) => "This file cannot be previewed. Download it to open it.", + (K::ViewerRefused, Lang::Tr) => "Bu dosya önizlenemiyor. Açmak için indirin.", + (K::NoPreview, Lang::En) => "No preview for this type. Download it to open it.", + (K::NoPreview, Lang::Tr) => "Bu tür için önizleme yok. Açmak için indirin.", + (K::ViewerTruncated, Lang::En) => "Showing the first part of the file.", + (K::ViewerTruncated, Lang::Tr) => "Dosyanın ilk kısmı gösteriliyor.", + (K::ViewerCut, Lang::En) => "Showing the first rows and columns only.", + (K::ViewerCut, Lang::Tr) => "Yalnızca ilk satırlar ve sütunlar gösteriliyor.", + (K::Sheets, Lang::En) => "Sheets", + (K::Sheets, Lang::Tr) => "Sayfalar", + (K::SlideLabel, Lang::En) => "Slide", + (K::SlideLabel, Lang::Tr) => "Slayt", + (K::NoSlideText, Lang::En) => "This slide has no text.", + (K::NoSlideText, Lang::Tr) => "Bu slaytta metin yok.", + (K::EmptySheet, Lang::En) => "This sheet is empty.", + (K::EmptySheet, Lang::Tr) => "Bu sayfa boş.", } } diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 35a42ca..c2e22c8 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -4,7 +4,11 @@ //! operator command line, which is not built yet. The configuration file is the `--config` path, //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. +// The page handlers nest many view and store futures; the default limit is too small for their types. +#![recursion_limit = "256"] + mod assets; +mod attachments; mod auth; mod boot; mod directory; @@ -14,6 +18,7 @@ mod live; mod oidc; mod pages; mod security; +mod serve; mod state; mod views; diff --git a/crates/iz-web/src/pages/board.rs b/crates/iz-web/src/pages/board.rs index ae5104a..e49387d 100644 --- a/crates/iz-web/src/pages/board.rs +++ b/crates/iz-web/src/pages/board.rs @@ -314,6 +314,23 @@ async fn board_page(cx: &Cx) -> Result { if !found { page.alert = Some(K::TaskNotFound); status = Some(StatusCode::NOT_FOUND); + } else if let Some(file) = query_param(cx, "file").filter(|value| !value.is_empty()) { + let sheet = query_param(cx, "sheet") + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let shown = crate::pages::files::open_in_modal( + state, + &mut page, + &key, + &file, + sheet, + query.as_deref(), + ) + .await?; + if !shown { + page.alert = Some(K::TaskNotFound); + status = Some(StatusCode::NOT_FOUND); + } } } None => { diff --git a/crates/iz-web/src/pages/files.rs b/crates/iz-web/src/pages/files.rs new file mode 100644 index 0000000..f7aa93a --- /dev/null +++ b/crates/iz-web/src/pages/files.rs @@ -0,0 +1,921 @@ +//! Attachments on a task (`docs/architecture.md` sections 4 and 7): the upload, the delete, the bytes of a +//! file, the viewer page, and the viewer that the task modal shows for `?file=`. +//! +//! Every route reaches a file through its task. The bytes are read only for an attachment whose task is live +//! and on this board; the viewer page also needs the task key in the URL to match, so the id of a file on +//! another task is `404` (attack plan section 6: cross-task IDOR). Writes check the CSRF token before any side +//! effect: the upload form carries `csrf` as its first field, so the token is read before any file part is +//! stored. A viewer gets `403` for every write. +//! +//! Uploads stream. Each file part is written to `data_dir/tmp` with the per-file limit enforced while the bytes +//! arrive, hashed while it streams, and sniffed from its first kilobytes. The name and the extension are checked +//! before any byte is read. Only then is the file moved to `data_dir/attachments/` and its row inserted; if +//! the insert fails the moved file is removed, so no bytes are left without a row. +//! +//! Viewers never execute what they show. Images, media and PDF are shown by the browser from the byte route +//! (which sends them with the sandbox policy); text is escaped; sheets and slides are parsed into plain values +//! after the zip guards of `iz-core` and rendered as escaped cells and paragraphs. + +use iz_core::authz::{Action, authorize}; +use iz_core::limits::{SNIFF_BYTES, TEXT_PREVIEW_BYTES, UPLOAD_FILES_MAX}; +use iz_core::preview::read_text_head; +use iz_core::sheet::{Book, read_csv, read_workbook}; +use iz_core::slides::{Slide, read_deck}; +use iz_core::sniff::sniff; +use iz_core::staging::{StagedFile, blob_path, install_blob, remove_blob}; +use iz_core::store::attachments::{ + Attachment, NewAttachment, Policy, clean_name, extension_allowed, extension_of, + new_attachment_id, +}; +use jiff::tz::TimeZone; +use serde::Deserialize; +use std::collections::HashMap; +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::{forbidden, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{path_param_segment, route}; +use topcoat::view::view; + +use crate::auth::{ + CurrentMember, Need, percent_encode, query_param, require_csrf, require_role, safe_next, +}; +use crate::i18n::lang; +use crate::i18n::task::{K, t}; +use crate::pages::board::{BoardPage, the_board}; +use crate::pages::task::{Draft, FileRow, back, bump, core_err, local_text, modal_url, refuse}; +use crate::serve::{ByteAnswer, ByteSource, Disposition, inline_safe, serve_file}; +use crate::state::AppState; +use crate::views::files::file_page; +use crate::views::{ViewerInfo, respond, shell}; + +/// Longest text field of the upload form (the csrf token, the return path), in bytes. +const FIELD_MAX_BYTES: usize = 2048; +/// The MIME types of the spreadsheets and the decks the viewers read. +const XLSX: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; +/// See [`XLSX`]. +const ODS: &str = "application/vnd.oasis.opendocument.spreadsheet"; +/// See [`XLSX`]. +const PPTX: &str = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; + +/// What a file is shown as. Decided from the sniffed type, and from the name for CSV and plain text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// A picture the browser shows (not SVG, not HEIC). + Image, + /// A video the browser plays. + Video, + /// An audio file the browser plays. + Audio, + /// A PDF, shown in a frame by the browser. + Pdf, + /// Plain text, escaped, cut to the preview size. + Text, + /// An `.xlsx` or `.ods` workbook, read as values. + Workbook, + /// A CSV file, read as one sheet. + Csv, + /// A `.pptx` deck, read as the text of each slide. + Deck, + /// No preview: the file can only be downloaded. + Nothing, +} + +/// The kind of an attachment. Sheets and decks are matched by their sniffed container type; a CSV or a text +/// file is matched by its name, since the sniffer calls both plain text. The sniffed type may be `text/html` +/// for those (a CSV cell that holds markup): such a file is still never served inline, and its preview is escaped. +pub fn kind_of(attachment: &Attachment) -> Kind { + let essence = attachment + .mime + .split(';') + .next() + .unwrap_or_default() + .trim() + .to_ascii_lowercase(); + match essence.as_str() { + XLSX | ODS => return Kind::Workbook, + PPTX => return Kind::Deck, + _ => {} + } + let ext = extension_of(&attachment.name); + let text_like = essence == "text/plain" || essence == "text/html"; + if text_like && ext.as_deref() == Some("csv") { + return Kind::Csv; + } + if essence == "text/html" && matches!(ext.as_deref(), Some("txt" | "md")) { + return Kind::Text; + } + if !inline_safe(&attachment.mime) { + return Kind::Nothing; + } + if essence.starts_with("image/") { + Kind::Image + } else if essence.starts_with("video/") { + Kind::Video + } else if essence.starts_with("audio/") { + Kind::Audio + } else if essence == "application/pdf" { + Kind::Pdf + } else if essence == "text/plain" { + Kind::Text + } else { + Kind::Nothing + } +} + +/// A size as a person reads it: bytes, kilobytes or megabytes. +pub fn size_text(bytes: u64) -> String { + if bytes < 1024 { + format!("{bytes} B") + } else if bytes < 1024 * 1024 { + format!("{:.1} KB", bytes as f64 / 1024.0) + } else { + format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0)) + } +} + +/// The URL of tab `index` of a viewer whose own URL is `base`. +fn tab_url(base: &str, index: usize) -> String { + let separator = if base.contains('?') { '&' } else { '?' }; + format!("{base}{separator}sheet={index}") +} + +/// One sheet tab of a workbook viewer. +pub struct SheetTab { + /// The sheet's name. + pub label: String, + /// The URL that shows this sheet. + pub url: String, + /// Whether this is the sheet shown. + pub active: bool, +} + +/// What the viewer shows for one file. +pub enum ViewBody { + /// The browser shows the picture from the byte route. + Image, + /// The browser plays the video from the byte route. + Video, + /// The browser plays the audio from the byte route. + Audio, + /// The browser shows the PDF in a frame from the byte route. + Pdf, + /// The first part of a text file. + Text { + /// The text, shown escaped. + text: String, + /// Whether the file was longer than the preview. + cut: bool, + }, + /// The rows of one sheet, with the tabs of the book. + Sheets { + /// Every sheet of the book (up to the cap), as tabs. + tabs: Vec, + /// The cells of the shown sheet, each cell escaped by the page. + rows: Vec>, + /// Whether the sheet had more rows than the cap. + cut: bool, + }, + /// The text of each slide, in order. + Slides(Vec), + /// The file could not be read as its kind (corrupt, refused by the zip guards, or too large). + Refused, + /// There is no preview for this type. + Nothing, +} + +/// A file as the viewer shows it: its details, its links, and what it shows. +pub struct FileView { + /// The file name as uploaded (shown escaped). + pub name: String, + /// The size, as text. + pub size_text: String, + /// The URL that saves the file. + pub download_url: String, + /// The URL the browser shows the bytes from. + pub inline_url: String, + /// What the viewer shows. + pub body: ViewBody, +} + +/// Reads the body of a file for the viewer. Blocking parsers run on the blocking pool. A parser refusal is not an +/// error for the page: the viewer says it cannot show the file. +pub async fn load_view( + state: &AppState, + attachment: &Attachment, + base: &str, + sheet: usize, +) -> Result { + let path = blob_path(&state.config.data_dir, &attachment.id)?; + let kind = kind_of(attachment); + let body = match kind { + Kind::Image => ViewBody::Image, + Kind::Video => ViewBody::Video, + Kind::Audio => ViewBody::Audio, + Kind::Pdf => ViewBody::Pdf, + Kind::Nothing => ViewBody::Nothing, + Kind::Text => match blocking(move || read_text_head(&path, TEXT_PREVIEW_BYTES)).await { + Some((text, cut)) => ViewBody::Text { text, cut }, + None => ViewBody::Refused, + }, + Kind::Workbook => match blocking(move || read_workbook(&path)).await { + Some(book) => sheets_body(book, base, sheet), + None => ViewBody::Refused, + }, + Kind::Csv => { + let name = attachment.name.clone(); + match blocking(move || read_csv(&path, &name)).await { + Some(book) => sheets_body(book, base, sheet), + None => ViewBody::Refused, + } + } + Kind::Deck => match blocking(move || read_deck(&path)).await { + Some(slides) => ViewBody::Slides(slides), + None => ViewBody::Refused, + }, + }; + Ok(FileView { + name: attachment.name.clone(), + size_text: size_text(attachment.size), + download_url: format!("/files/{}?dl=1", attachment.id), + inline_url: format!("/files/{}", attachment.id), + body, + }) +} + +/// Runs a parser on the blocking pool. `None` when it failed or the pool was gone; the parser's error text is not +/// shown, because the page says the same thing for every refusal. +async fn blocking(work: F) -> Option +where + E: Send + 'static, + F: FnOnce() -> std::result::Result + Send + 'static, + T: Send + 'static, +{ + tokio::task::spawn_blocking(move || work().map_err(drop)) + .await + .ok()? + .ok() +} + +/// The sheet viewer body for `book`: the tabs, and the rows of the sheet `sheet` (the first when out of range). +fn sheets_body(book: Book, base: &str, sheet: usize) -> ViewBody { + let selected = if sheet < book.sheets.len() { sheet } else { 0 }; + let tabs = book + .sheets + .iter() + .enumerate() + .map(|(index, shown)| SheetTab { + label: shown.name.clone(), + url: tab_url(base, index), + active: index == selected, + }) + .collect(); + match book.sheets.into_iter().nth(selected) { + Some(shown) => ViewBody::Sheets { + tabs, + rows: shown.rows, + cut: shown.rows_cut, + }, + None => ViewBody::Sheets { + tabs, + rows: Vec::new(), + cut: false, + }, + } +} + +/// The viewer's file rows for the task modal: one per attachment, with the rights of the viewer over it. +pub fn file_rows( + files: &[Attachment], + key: &str, + query: Option<&str>, + me: &CurrentMember, + can_write: bool, + names: &HashMap, + zone: &TimeZone, +) -> Vec { + files + .iter() + .map(|file| { + let uploader = names + .get(&file.uploaded_by) + .cloned() + .unwrap_or_else(|| "-".to_owned()); + let can_delete = can_write + && authorize( + &me.actor(), + &Action::DeleteFile { + uploader: file.uploaded_by.clone(), + }, + ) + .is_ok(); + FileRow { + name: file.name.clone(), + size: size_text(file.size), + uploader, + when: local_text(&file.created_at, zone), + viewable: kind_of(file) != Kind::Nothing, + view_url: modal_url(query, key, &[("file", file.id.as_str())]), + download_url: format!("/files/{}?dl=1", file.id), + delete_action: format!("/files/{}/delete", file.id), + can_delete, + } + }) + .collect() +} + +/// Shows the viewer of file `id` inside the open task modal. Returns `false` when the file is not on this task. +pub async fn open_in_modal( + state: &AppState, + page: &mut BoardPage, + key: &str, + id: &str, + sheet: usize, + query: Option<&str>, +) -> Result { + let board = the_board(&state.store).await?; + let attachment = match state.store.attachment_of_task(&board.id, key, id).await { + Ok(attachment) => attachment, + Err(iz_core::Error::NotFound) => return Ok(false), + Err(error) => return Err(core_err(error)), + }; + let base = modal_url(query, key, &[("file", id)]); + let view = load_view(state, &attachment, &base, sheet).await?; + if let Some(modal) = page.modal.as_mut() { + modal.viewer = Some(view); + } + Ok(true) +} + +/// Reads a short text field. Longer than [`FIELD_MAX_BYTES`] is a bad request. +async fn read_text(field: &mut Field<'_>) -> Result { + let mut bytes = Vec::new(); + while let Some(chunk) = field.chunk().await? { + if bytes.len() + chunk.len() > FIELD_MAX_BYTES { + return Err(topcoat::router::error::bad_request("field too long").into()); + } + bytes.extend_from_slice(&chunk); + } + String::from_utf8(bytes) + .map_err(|_| topcoat::router::error::bad_request("field is not UTF-8").into()) +} + +/// Why one file of an upload was not kept. Each one has a message in the task's language. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Refusal { + /// The name is empty, has control characters, or is too long. + Name, + /// The extension is not on the allowlist. + Type, + /// The file is larger than the limit. + TooLarge, + /// Too many file parts in one request. + TooMany, + /// The request had no file. + NoFile, + /// The bytes could not be stored. + Store, +} + +/// The message of a refusal. +fn refusal_key(refusal: Refusal) -> K { + match refusal { + Refusal::Name => K::ErrFileName, + Refusal::Type => K::ErrFileType, + Refusal::TooLarge => K::ErrFileTooLarge, + Refusal::TooMany => K::ErrTooManyFiles, + Refusal::NoFile => K::ErrNoFile, + Refusal::Store => K::ErrFileStore, + } +} + +/// Streams one file part into a stored attachment. `Ok(Err(refusal))` is a refusal the person can read; `Err` is a +/// server failure. Nothing is left behind on any path. +async fn store_one( + state: &AppState, + me: &CurrentMember, + board_id: &str, + task_id: &str, + raw_name: &str, + field: &mut Field<'_>, + policy: &Policy, +) -> Result> { + let Ok(name) = clean_name(raw_name) else { + return Ok(Err(Refusal::Name)); + }; + if !extension_allowed(&name, policy) { + return Ok(Err(Refusal::Type)); + } + let data_dir = state.config.data_dir.as_path(); + let mut staged = StagedFile::create(data_dir, policy.limit_bytes).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 { + let too_large = matches!(&error, iz_core::Error::Invalid(code) if code == "too_large"); + staged.abort().await; + return if too_large { + Ok(Err(Refusal::TooLarge)) + } else { + Err(error.into()) + }; + } + } + let done = match staged.finish().await { + Ok(done) => done, + Err(error) => return Err(error.into()), + }; + let id = new_attachment_id(); + if let Err(error) = install_blob(data_dir, &id, &done.path).await { + let _ = tokio::fs::remove_file(&done.path).await; + tracing::error!(error = %error, "moving an upload into place failed"); + return Ok(Err(Refusal::Store)); + } + let new = NewAttachment { + id: id.clone(), + name, + mime: sniff(&prefix), + size: done.size, + sha256: done.sha256, + uploaded_by: me.member.sub.clone(), + }; + match state.store.add_attachment(board_id, task_id, new).await { + Ok(_) => Ok(Ok(())), + Err(error) => { + // No row names these bytes now, so they go. + if let Err(remove) = remove_blob(data_dir, &id).await { + tracing::error!(error = %remove, "removing bytes of a refused upload failed"); + } + Err(core_err(error)) + } + } +} + +/// `POST /tasks/{id}/files`: the upload. The first field is `csrf` (checked before any file is read), then +/// `next` (the modal's own URL), then one or more `files` parts. An empty file input is skipped. +#[route(POST "/tasks/{id}/files")] +async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { + let state = app_context::(cx); + let task_id = path_param_segment(cx, "id").to_owned(); + let mut member: Option = None; + let mut board_id = String::new(); + let mut key = String::new(); + let mut next = String::new(); + let mut policy: Option = None; + let mut seen = 0usize; + let mut saved = 0usize; + let mut refusal: Option = None; + while let Some(mut field) = multipart.next_field().await? { + match field.name().unwrap_or_default().to_owned().as_str() { + "csrf" => { + let token = read_text(&mut field).await?; + let me = require_csrf(cx, Need::Member, &token).await?; + let board = the_board(&state.store).await?; + let detail = state + .store + .task_detail(&board.id, &task_id) + .await + .map_err(core_err)?; + key = detail.task.key.clone(); + board_id = board.id; + policy = Some(state.store.policy().await.map_err(core_err)?); + member = Some(me); + } + "next" => next = read_text(&mut field).await?, + "files" => { + let Some(me) = member.as_ref() else { + return Err(forbidden().into()); + }; + let raw_name = field.file_name().unwrap_or_default().to_owned(); + if raw_name.is_empty() { + continue; + } + seen += 1; + if seen > UPLOAD_FILES_MAX { + refusal = Some(Refusal::TooMany); + break; + } + let Some(policy) = policy.as_ref() else { + return Err(forbidden().into()); + }; + match store_one( + state, me, &board_id, &task_id, &raw_name, &mut field, policy, + ) + .await? + { + Ok(()) => saved += 1, + Err(reason) => { + refusal = Some(reason); + break; + } + } + } + _ => {} + } + } + let Some(me) = member else { + return Err(forbidden().into()); + }; + if saved > 0 { + bump(state, &board_id, &task_id); + } + let language = lang(cx, me.member.locale_override.as_deref()); + let reason = match (refusal, saved) { + (Some(reason), _) => Some(reason), + (None, 0) => Some(Refusal::NoFile), + (None, _) => None, + }; + match reason { + Some(reason) => { + let draft = Draft { + error: Some(t(language, refusal_key(reason))), + ..Draft::default() + }; + refuse(cx, &me, language, &next, &key, draft).await + } + None => back(&next, Some(key.as_str())), + } +} + +/// The form of `POST /files/{id}/delete`. +#[derive(Deserialize, Default)] +struct DeleteForm { + #[serde(default)] + csrf: String, + /// The modal URL the form was on. + #[serde(default)] + next: String, +} + +/// `POST /files/{id}/delete`: deletes an attachment. Its uploader (while a member) or an admin may. The row goes +/// in one transaction that records the bytes for deletion; the deleter removes the bytes afterwards. +#[route(POST "/files/{id}/delete")] +async fn delete_file(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Member, &form.csrf).await?; + let board = the_board(&state.store).await?; + let removed = state + .store + .delete_attachment(&board.id, &id, &me.actor()) + .await + .map_err(core_err)?; + bump(state, &board.id, &removed.task_id); + Err(see_other(safe_next(Some(&form.next))).into()) +} + +/// `GET /files/{id}`: the bytes of a file, through the byte rules: shown when the type allows it, saved as a file +/// otherwise and always with `?dl=1`. +#[route(GET "/files/{id}")] +async fn file_bytes(cx: &Cx) -> Result { + let state = app_context::(cx); + require_role(cx, Need::Viewer).await?; + let id = path_param_segment(cx, "id").to_owned(); + let board = the_board(&state.store).await?; + let attachment = state + .store + .attachment_on_board(&board.id, &id) + .await + .map_err(core_err)?; + let download = query_param(cx, "dl").is_some_and(|value| value == "1"); + let path = blob_path(&state.config.data_dir, &attachment.id)?; + let source = ByteSource { + path: &path, + size: attachment.size, + sha256: &attachment.sha256, + mime: &attachment.mime, + name: &attachment.name, + }; + let disposition = if download { + Disposition::Attachment + } else { + Disposition::Inline + }; + serve_file(cx, &source, disposition).await +} + +/// The viewer's own page, `GET /tasks/{key}/files/{id}/view`. The file must belong to the task with `key`. +#[route(GET "/tasks/{key}/files/{id}/view")] +async fn viewer_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let me = require_role(cx, Need::Viewer).await?; + let key = path_param_segment(cx, "key").to_owned(); + let id = path_param_segment(cx, "id").to_owned(); + let board = the_board(&state.store).await?; + let attachment = state + .store + .attachment_of_task(&board.id, &key, &id) + .await + .map_err(core_err)?; + let language = lang(cx, me.member.locale_override.as_deref()); + let sheet = query_param(cx, "sheet") + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let base = format!( + "/tasks/{}/files/{}/view", + percent_encode(&key), + attachment.id + ); + let view = load_view(state, &attachment, &base, sheet).await?; + let viewer = ViewerInfo { + name: me.member.name.clone(), + is_admin: me.member.im_admin || me.member.role == iz_core::authz::Role::Admin, + csrf: me.session.csrf_token.clone(), + }; + let back_to = format!("/?task={}", percent_encode(&key)); + let title = attachment.name.clone(); + let document = view! { + cx => + shell(title: title.as_str(), lang: language, viewer: Some(&viewer), page_script: None, + file_page(lang: language, back_to: back_to.as_str(), file: &view) + ) + }; + respond(cx, document).await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn attachment(name: &str, mime: &str) -> Attachment { + Attachment { + id: "01HZ0000000000000000000000".into(), + task_id: "t".into(), + name: name.into(), + mime: mime.into(), + size: 1, + sha256: "0".repeat(64), + uploaded_by: "u".into(), + created_at: "x".into(), + } + } + + /// The kinds that get a preview, and the types that never do. SVG and HTML are never inline. + #[test] + fn the_viewer_kind_follows_the_sniffed_type() { + assert_eq!(kind_of(&attachment("a.png", "image/png")), Kind::Image); + assert_eq!( + kind_of(&attachment("a.svg", "image/svg+xml")), + Kind::Nothing + ); + assert_eq!(kind_of(&attachment("a.pdf", "application/pdf")), Kind::Pdf); + assert_eq!(kind_of(&attachment("a.html", "text/html")), Kind::Nothing); + assert_eq!(kind_of(&attachment("a.png", "text/html")), Kind::Nothing); + assert_eq!(kind_of(&attachment("a.csv", "text/plain")), Kind::Csv); + assert_eq!(kind_of(&attachment("a.csv", "text/html")), Kind::Csv); + assert_eq!(kind_of(&attachment("a.txt", "text/plain")), Kind::Text); + assert_eq!(kind_of(&attachment("a.xlsx", XLSX)), Kind::Workbook); + assert_eq!(kind_of(&attachment("a.pptx", PPTX)), Kind::Deck); + } + + #[test] + fn sizes_read_as_people_read_them() { + assert_eq!(size_text(512), "512 B"); + assert_eq!(size_text(1536), "1.5 KB"); + assert_eq!(size_text(3 * 1024 * 1024), "3.0 MB"); + } +} + +/// Route tests: the cross-task `404`, the viewer's `403` on upload, the byte response headers of a page +/// disguised as a picture, and the escaped CSV viewer. +#[cfg(test)] +mod route_tests { + use http::header::{CONTENT_DISPOSITION, CONTENT_SECURITY_POLICY, CONTENT_TYPE, COOKIE}; + use iz_core::authz::Role; + use topcoat::router::Body; + + use crate::boot::{router, test_state}; + use crate::pages::board::{cookie_of, one_card, sign_in_as}; + use crate::state::AppState; + + const AUTHOR: &str = "01ADAAAAAAAAAAAAAAAAAAAAAA"; + const VIEWER: &str = "01VIAAAAAAAAAAAAAAAAAAAAAA"; + + /// Sends one request and returns the whole response. + async fn send(state: &AppState, request: http::Request) -> http::Response { + router(state.clone()).handle(request).await + } + + /// A multipart upload of one file named `name`, with the CSRF token as the first field. + fn upload( + path: &str, + token: &str, + csrf: &str, + name: &str, + bytes: &[u8], + ) -> http::Request { + let boundary = "izboundary"; + let mut body = format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"csrf\"\r\n\r\n{csrf}\r\n\ + --{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"{name}\"\r\n\ + Content-Type: application/octet-stream\r\n\r\n" + ) + .into_bytes(); + body.extend_from_slice(bytes); + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + http::Request::post(path) + .header( + CONTENT_TYPE, + format!("multipart/form-data; boundary={boundary}"), + ) + .header(COOKIE, cookie_of(token)) + .body(Body::from(body)) + .expect("request") + } + + fn get(path: &str, token: &str) -> http::Request { + http::Request::get(path) + .header(COOKIE, cookie_of(token)) + .body(Body::empty()) + .expect("request") + } + + /// The first attachment on a task, read through the store. + async fn first_attachment( + state: &AppState, + task_id: &str, + ) -> iz_core::store::attachments::Attachment { + let board = state.store.board().await.expect("board").expect("some"); + state + .store + .list_attachments(&board.id, task_id) + .await + .expect("list") + .into_iter() + .next() + .expect("an attachment") + } + + /// The key of a task, read through the store. + async fn key_of(state: &AppState, task_id: &str) -> String { + let board = state.store.board().await.expect("board").expect("some"); + state + .store + .task_detail(&board.id, task_id) + .await + .expect("detail") + .task + .key + } + + /// An attachment viewed under another task's key is not found. + #[tokio::test] + async fn an_attachment_under_another_task_key_is_not_found() { + let (_dir, state) = test_state().await; + let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let (other_id, _) = one_card(&state, "Bread", AUTHOR).await; + let response = send( + &state, + upload( + &format!("/tasks/{task_id}/files"), + &token, + &csrf, + "note.txt", + b"hello", + ), + ) + .await; + assert!( + response.status().is_redirection(), + "upload: {}", + response.status() + ); + let attachment = first_attachment(&state, &task_id).await; + let other_key = key_of(&state, &other_id).await; + let response = send( + &state, + get( + &format!("/tasks/{other_key}/files/{}/view", attachment.id), + &token, + ), + ) + .await; + assert_eq!(response.status(), http::StatusCode::NOT_FOUND); + } + + /// A viewer cannot upload: the request is refused and nothing is stored. + #[tokio::test] + async fn a_viewer_cannot_upload() { + let (_dir, state) = test_state().await; + sign_in_as(&state, AUTHOR, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let (token, csrf) = sign_in_as(&state, VIEWER, Role::Viewer).await; + let response = send( + &state, + upload( + &format!("/tasks/{task_id}/files"), + &token, + &csrf, + "note.txt", + b"hello", + ), + ) + .await; + assert_eq!(response.status(), http::StatusCode::FORBIDDEN); + let board = state.store.board().await.expect("board").expect("some"); + let stored = state + .store + .list_attachments(&board.id, &task_id) + .await + .expect("list"); + assert!(stored.is_empty()); + } + + /// An HTML page named `.png` is served as an attachment, with one CSP header and nosniff, never inline. + #[tokio::test] + async fn an_html_file_named_as_a_picture_is_served_as_an_attachment() { + let (_dir, state) = test_state().await; + let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let page = b""; + let response = send( + &state, + upload( + &format!("/tasks/{task_id}/files"), + &token, + &csrf, + "photo.png", + page, + ), + ) + .await; + assert!( + response.status().is_redirection(), + "upload: {}", + response.status() + ); + let attachment = first_attachment(&state, &task_id).await; + let response = send(&state, get(&format!("/files/{}", attachment.id), &token)).await; + assert_eq!(response.status(), http::StatusCode::OK); + let headers = response.headers(); + let disposition = headers + .get(CONTENT_DISPOSITION) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default(); + assert!(disposition.starts_with("attachment"), "{disposition}"); + assert_eq!( + headers + .get("x-content-type-options") + .and_then(|v| v.to_str().ok()), + Some("nosniff") + ); + assert_eq!(headers.get_all(CONTENT_SECURITY_POLICY).iter().count(), 1); + } + + /// A CSV cell that holds markup is shown as escaped text in the viewer. + #[tokio::test] + async fn a_csv_cell_with_markup_is_escaped_in_the_viewer() { + let (_dir, state) = test_state().await; + let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await; + let (task_id, _) = one_card(&state, "Milk", AUTHOR).await; + let key = key_of(&state, &task_id).await; + let csv = b"name,note\n,ok\n"; + let response = send( + &state, + upload( + &format!("/tasks/{task_id}/files"), + &token, + &csrf, + "cells.csv", + csv, + ), + ) + .await; + assert!( + response.status().is_redirection(), + "upload: {}", + response.status() + ); + let attachment = first_attachment(&state, &task_id).await; + let response = send( + &state, + get( + &format!("/tasks/{key}/files/{}/view", attachment.id), + &token, + ), + ) + .await; + assert_eq!(response.status(), http::StatusCode::OK); + let bytes = topcoat::router::to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .expect("body"); + let html = String::from_utf8_lossy(&bytes); + assert!(html.contains("<script>alert(1)</script>")); + assert!(!html.contains("