forge
Explore
Log in

Don't you dare go Hollow

Local attachments with sniffing and limits, viewers (image, media, PDF, text, sheet, slides) with zip-bomb guards

Browse files at this commit

b08e0c04929c597b6150a4f192914429bb65344fAhmet Kaan GümüşParent: 488d38e
  • feat
    • local attachments with sniffing and limits, viewers (image, media, PDF, text, sheet, slides) with zip-bomb guards
    • security headers no longer duplicate route headers
Show full message
✨ feat: local attachments with sniffing and limits, viewers (image, media, PDF, text, sheet, slides) with zip-bomb guards; security headers no longer duplicate route headers
Cargo.lockmodified+155 -0
@@ -223,6 +223,16 @@ dependencies = [
223223 "syn 3.0.9",
224224 ]
225225
226+[[package]]
227+name = "atoi_simd"
228+version = "0.18.1"
229+source = "registry+https://github.com/rust-lang/crates.io-index"
230+checksum = "f3cdb3708a128e559a30fb830e8a77a5022ee6902806925c216658652b452a44"
231+dependencies = [
232+ "debug_unsafe",
233+ "rustversion",
234+]
235+
226236 [[package]]
227237 name = "atomic-waker"
228238 version = "1.1.2"
@@ -428,6 +438,23 @@ version = "1.12.1"
428438 source = "registry+https://github.com/rust-lang/crates.io-index"
429439 checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
430440
441+[[package]]
442+name = "calamine"
443+version = "0.37.0"
444+source = "registry+https://github.com/rust-lang/crates.io-index"
445+checksum = "c9ca341b94bc4b29e08970b1a03914fad2dfe177e2ecb67fcd6de9046004aafb"
446+dependencies = [
447+ "atoi_simd",
448+ "byteorder",
449+ "codepage",
450+ "encoding_rs",
451+ "fast-float2",
452+ "log",
453+ "quick-xml",
454+ "serde",
455+ "zip",
456+]
457+
431458 [[package]]
432459 name = "cc"
433460 version = "1.10.0"
@@ -590,6 +617,15 @@ version = "0.1.3"
590617 source = "registry+https://github.com/rust-lang/crates.io-index"
591618 checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24"
592619
620+[[package]]
621+name = "codepage"
622+version = "0.1.3"
623+source = "registry+https://github.com/rust-lang/crates.io-index"
624+checksum = "bdff162541cd8b79de82e2edcc7eff3a8c2a6dc3d75152636028f96d93de3b26"
625+dependencies = [
626+ "encoding_rs",
627+]
628+
593629 [[package]]
594630 name = "colorchoice"
595631 version = "1.0.5"
@@ -759,6 +795,27 @@ dependencies = [
759795 "rand_core 0.10.1",
760796 ]
761797
798+[[package]]
799+name = "csv"
800+version = "1.4.0"
801+source = "registry+https://github.com/rust-lang/crates.io-index"
802+checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
803+dependencies = [
804+ "csv-core",
805+ "itoa",
806+ "ryu",
807+ "serde_core",
808+]
809+
810+[[package]]
811+name = "csv-core"
812+version = "0.1.13"
813+source = "registry+https://github.com/rust-lang/crates.io-index"
814+checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
815+dependencies = [
816+ "memchr",
817+]
818+
762819 [[package]]
763820 name = "ctr"
764821 version = "0.9.2"
@@ -823,6 +880,12 @@ version = "0.2.0"
823880 source = "registry+https://github.com/rust-lang/crates.io-index"
824881 checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
825882
883+[[package]]
884+name = "debug_unsafe"
885+version = "0.1.4"
886+source = "registry+https://github.com/rust-lang/crates.io-index"
887+checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2"
888+
826889 [[package]]
827890 name = "defmt"
828891 version = "1.2.0"
@@ -1006,6 +1069,12 @@ version = "0.3.0"
10061069 source = "registry+https://github.com/rust-lang/crates.io-index"
10071070 checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
10081071
1072+[[package]]
1073+name = "fast-float2"
1074+version = "0.2.4"
1075+source = "registry+https://github.com/rust-lang/crates.io-index"
1076+checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f"
1077+
10091078 [[package]]
10101079 name = "fastbloom"
10111080 version = "0.14.1"
@@ -1035,6 +1104,15 @@ version = "0.1.15"
10351104 source = "registry+https://github.com/rust-lang/crates.io-index"
10361105 checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
10371106
1107+[[package]]
1108+name = "flate2"
1109+version = "1.1.10"
1110+source = "registry+https://github.com/rust-lang/crates.io-index"
1111+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
1112+dependencies = [
1113+ "zlib-rs",
1114+]
1115+
10381116 [[package]]
10391117 name = "fnv"
10401118 version = "1.0.7"
@@ -1787,10 +1865,14 @@ name = "iz-core"
17871865 version = "0.1.0"
17881866 dependencies = [
17891867 "base64 0.23.1",
1868+ "bytes",
1869+ "calamine",
17901870 "chacha20poly1305",
1871+ "csv",
17911872 "hex",
17921873 "ipnet",
17931874 "jiff",
1875+ "quick-xml",
17941876 "rand 0.10.3",
17951877 "serde",
17961878 "serde_json",
@@ -1804,6 +1886,7 @@ dependencies = [
18041886 "tracing",
18051887 "turso",
18061888 "ulid",
1889+ "zip",
18071890 ]
18081891
18091892 [[package]]
@@ -1812,10 +1895,13 @@ version = "0.1.0"
18121895 dependencies = [
18131896 "aws-lc-rs",
18141897 "base64 0.23.1",
1898+ "bytes",
18151899 "futures-util",
18161900 "grass",
18171901 "hex",
18181902 "http",
1903+ "http-body",
1904+ "http-body-util",
18191905 "iz-core",
18201906 "jiff",
18211907 "jsonwebtoken",
@@ -2256,6 +2342,18 @@ version = "0.3.1"
22562342 source = "registry+https://github.com/rust-lang/crates.io-index"
22572343 checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b"
22582344
2345+[[package]]
2346+name = "nix"
2347+version = "0.31.3"
2348+source = "registry+https://github.com/rust-lang/crates.io-index"
2349+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
2350+dependencies = [
2351+ "bitflags 2.13.2",
2352+ "cfg-if",
2353+ "cfg_aliases",
2354+ "libc",
2355+]
2356+
22592357 [[package]]
22602358 name = "nom"
22612359 version = "7.1.3"
@@ -2608,6 +2706,16 @@ dependencies = [
26082706 "syn 2.0.119",
26092707 ]
26102708
2709+[[package]]
2710+name = "quick-xml"
2711+version = "0.42.0"
2712+source = "registry+https://github.com/rust-lang/crates.io-index"
2713+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
2714+dependencies = [
2715+ "encoding_rs",
2716+ "memchr",
2717+]
2718+
26112719 [[package]]
26122720 name = "quinn"
26132721 version = "0.11.12"
@@ -3331,6 +3439,12 @@ dependencies = [
33313439 "rand_core 0.6.4",
33323440 ]
33333441
3442+[[package]]
3443+name = "simd-adler32"
3444+version = "0.3.10"
3445+source = "registry+https://github.com/rust-lang/crates.io-index"
3446+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
3447+
33343448 [[package]]
33353449 name = "simd_cesu8"
33363450 version = "1.2.0"
@@ -4527,6 +4641,12 @@ dependencies = [
45274641 "rand 0.10.3",
45284642 ]
45294643
4644+[[package]]
4645+name = "typed-path"
4646+version = "0.13.0"
4647+source = "registry+https://github.com/rust-lang/crates.io-index"
4648+checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
4649+
45304650 [[package]]
45314651 name = "typeid"
45324652 version = "1.0.3"
@@ -5167,12 +5287,47 @@ dependencies = [
51675287 "syn 3.0.9",
51685288 ]
51695289
5290+[[package]]
5291+name = "zip"
5292+version = "9.1.3"
5293+source = "registry+https://github.com/rust-lang/crates.io-index"
5294+checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb"
5295+dependencies = [
5296+ "crc32fast",
5297+ "flate2",
5298+ "getrandom 0.4.3",
5299+ "indexmap",
5300+ "memchr",
5301+ "nix",
5302+ "typed-path",
5303+ "windows-sys 0.61.2",
5304+ "zopfli",
5305+]
5306+
5307+[[package]]
5308+name = "zlib-rs"
5309+version = "0.6.8"
5310+source = "registry+https://github.com/rust-lang/crates.io-index"
5311+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
5312+
51705313 [[package]]
51715314 name = "zmij"
51725315 version = "1.0.23"
51735316 source = "registry+https://github.com/rust-lang/crates.io-index"
51745317 checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
51755318
5319+[[package]]
5320+name = "zopfli"
5321+version = "0.8.4"
5322+source = "registry+https://github.com/rust-lang/crates.io-index"
5323+checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
5324+dependencies = [
5325+ "bumpalo",
5326+ "crc32fast",
5327+ "log",
5328+ "simd-adler32",
5329+]
5330+
51765331 [[package]]
51775332 name = "zstd"
51785333 version = "0.13.3"
Cargo.tomlmodified+7 -0
@@ -14,9 +14,14 @@ license = "AGPL-3.0-or-later"
1414 # external crates (versions are the latest releases when added)
1515 aws-lc-rs = "1.18.2"
1616 base64 = "0.23.1"
17+bytes = "1.12.1"
18+calamine = "0.37.0"
19+csv = "1.4.0"
1720 futures-util = "0.3.34"
1821 grass = "0.13.4"
1922 http = "1.5.0"
23+http-body = "1.1.0"
24+http-body-util = "0.1.5"
2025 chacha20poly1305 = "0.11.0"
2126 hex = "0.4.3"
2227 ipnet = "2.12.2"
@@ -37,6 +42,8 @@ tracing = "0.1.44"
3742 tracing-subscriber = "0.3.23"
3843 turso = "0.8.3"
3944 ulid = "3.0.0"
45+quick-xml = "0.42.0"
46+zip = { version = "9.1.3", default-features = false, features = ["deflate"] }
4047
4148 # web framework
4249 topcoat = { version = "0.11.0", default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "multipart"] }
crates/iz-core/Cargo.tomlmodified+6 -1
@@ -11,10 +11,14 @@ workspace = true
1111
1212 [dependencies]
1313 base64.workspace = true
14+bytes.workspace = true
15+calamine.workspace = true
16+csv.workspace = true
1417 chacha20poly1305.workspace = true
1518 hex.workspace = true
1619 ipnet.workspace = true
1720 jiff.workspace = true
21+quick-xml.workspace = true
1822 rand.workspace = true
1923 serde.workspace = true
2024 serde_json.workspace = true
@@ -22,11 +26,12 @@ sha2.workspace = true
2226 subtle.workspace = true
2327 thiserror.workspace = true
2428 time.workspace = true
25-tokio.workspace = true
29+tokio = { workspace = true, features = ["fs", "io-util"] }
2630 toml.workspace = true
2731 tracing.workspace = true
2832 turso.workspace = true
2933 ulid.workspace = true
34+zip.workspace = true
3035
3136 [dev-dependencies]
3237 tempfile.workspace = true
crates/iz-core/migrations/0003_blob_deletions.sqladded+12 -0
@@ -0,0 +1,12 @@
1+-- 0003: blob deletions still owed. A deleted attachment's row is removed in the same transaction that
2+-- records its id here; the files worker removes the bytes afterwards and retries with backoff until they
3+-- are gone, and only then removes this row. `location` says where the bytes are ('local' for now; 'in'
4+-- once the Files service backend exists). The id is the attachment id, a ULID.
5+CREATE TABLE blob_deletions (
6+ attachment_id TEXT PRIMARY KEY CHECK (length(attachment_id) = 26),
7+ location TEXT NOT NULL DEFAULT 'local' CHECK (location IN ('local', 'in')),
8+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
9+ next_attempt_at TEXT NOT NULL,
10+ created_at TEXT NOT NULL
11+);
12+CREATE INDEX blob_deletions_due ON blob_deletions(next_attempt_at);
crates/iz-core/src/archive.rsadded+172 -0
@@ -0,0 +1,172 @@
1+//! Zip-container guards for the spreadsheet and slide viewers. A `.xlsx`, `.ods` or `.pptx` is a zip file,
2+//! so one of them can expand to far more than it weighs. Every such file is checked here before any parser
3+//! sees it (`docs/architecture.md`, attack plan section 6: zip bombs).
4+//!
5+//! The check runs in two passes. The first reads only the central directory: the declared uncompressed
6+//! sizes are summed and the declared ratio is judged, so a bomb that announces itself is refused without
7+//! inflating anything. The second inflates every entry into a sink with a hard byte budget, because a
8+//! header can lie: the declared sizes are never trusted alone. Memory use is constant; the sink keeps nothing.
9+
10+use std::fs::File;
11+use std::io::{self, Read};
12+use std::path::Path;
13+
14+use zip::ZipArchive;
15+
16+use crate::error::{Error, Result};
17+use crate::limits::{ARCHIVE_RATIO_FLOOR_BYTES, ARCHIVE_RATIO_MAX, ARCHIVE_UNCOMPRESSED_MAX_BYTES};
18+
19+/// Refusal codes. The viewers show one generic message for all of them; the code is for logs and tests.
20+pub const REFUSED_SIZE: &str = "archive_too_large";
21+/// See [`REFUSED_SIZE`].
22+pub const REFUSED_RATIO: &str = "archive_ratio";
23+/// See [`REFUSED_SIZE`].
24+pub const REFUSED_NOT_ZIP: &str = "archive_not_zip";
25+
26+/// Opens `path` as a zip archive after the zip-bomb checks. `input_max` caps the compressed file size.
27+///
28+/// The returned archive is only for reading the entry list; the viewers open their own readers.
29+pub fn open_checked(path: &Path, input_max: u64) -> Result<ZipArchive<File>> {
30+ let len = std::fs::metadata(path)?.len();
31+ if len > input_max {
32+ return Err(Error::Invalid(REFUSED_SIZE.into()));
33+ }
34+ let file = File::open(path)?;
35+ let mut archive = ZipArchive::new(file).map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?;
36+ check_declared(&mut archive)?;
37+ inflate_within_budget(&mut archive, len)?;
38+ Ok(archive)
39+}
40+
41+/// First pass: the declared sizes of the central directory. Reads no entry data.
42+fn check_declared(archive: &mut ZipArchive<File>) -> Result<()> {
43+ let mut total_plain: u64 = 0;
44+ let mut total_packed: u64 = 0;
45+ for index in 0..archive.len() {
46+ let entry = archive
47+ .by_index_raw(index)
48+ .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?;
49+ total_plain = total_plain.saturating_add(entry.size());
50+ total_packed = total_packed.saturating_add(entry.compressed_size());
51+ }
52+ if total_plain > ARCHIVE_UNCOMPRESSED_MAX_BYTES {
53+ return Err(Error::Invalid(REFUSED_SIZE.into()));
54+ }
55+ if ratio_refused(total_plain, total_packed) {
56+ return Err(Error::Invalid(REFUSED_RATIO.into()));
57+ }
58+ Ok(())
59+}
60+
61+/// Second pass: inflates every entry into a sink, stopping as soon as the total passes the budget. A
62+/// lying header cannot make this read more than the budget.
63+fn inflate_within_budget(archive: &mut ZipArchive<File>, file_len: u64) -> Result<()> {
64+ let mut produced: u64 = 0;
65+ for index in 0..archive.len() {
66+ let mut entry = archive
67+ .by_index(index)
68+ .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?;
69+ let budget = ARCHIVE_UNCOMPRESSED_MAX_BYTES - produced;
70+ // One byte past the budget tells "exactly at the limit" from "over it".
71+ let copied = io::copy(&mut (&mut entry).take(budget + 1), &mut io::sink())
72+ .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?;
73+ produced += copied;
74+ if produced > ARCHIVE_UNCOMPRESSED_MAX_BYTES {
75+ return Err(Error::Invalid(REFUSED_SIZE.into()));
76+ }
77+ }
78+ if ratio_refused(produced, file_len) {
79+ return Err(Error::Invalid(REFUSED_RATIO.into()));
80+ }
81+ Ok(())
82+}
83+
84+/// Whether `plain` bytes from `packed` bytes is a ratio the viewers refuse. Sizes under the floor are not
85+/// judged: a small part can compress badly without being hostile.
86+fn ratio_refused(plain: u64, packed: u64) -> bool {
87+ plain > ARCHIVE_RATIO_FLOOR_BYTES && plain / ARCHIVE_RATIO_MAX.max(1) > packed
88+}
89+
90+/// Reads one entry of an open archive, at most `max` bytes. Returns `None` when the entry is
91+/// missing. A longer entry is cut at `max`; the callers only need the start.
92+pub fn read_entry(archive: &mut ZipArchive<File>, name: &str, max: u64) -> Result<Option<Vec<u8>>> {
93+ let mut entry = match archive.by_name(name) {
94+ Ok(entry) => entry,
95+ Err(zip::result::ZipError::FileNotFound) => return Ok(None),
96+ Err(_) => return Err(Error::Invalid(REFUSED_NOT_ZIP.into())),
97+ };
98+ let mut bytes = Vec::new();
99+ (&mut entry)
100+ .take(max)
101+ .read_to_end(&mut bytes)
102+ .map_err(|_| Error::Invalid(REFUSED_NOT_ZIP.into()))?;
103+ Ok(Some(bytes))
104+}
105+
106+#[cfg(test)]
107+mod tests {
108+ use std::io::Write;
109+
110+ use super::*;
111+
112+ /// Writes a zip file with one deflated entry of `plain` bytes and returns its path inside `dir`.
113+ fn zip_with(dir: &Path, name: &str, plain: &[u8]) -> std::path::PathBuf {
114+ let path = dir.join(name);
115+ let file = File::create(&path).expect("create");
116+ let mut writer = zip::ZipWriter::new(file);
117+ let options = zip::write::SimpleFileOptions::default()
118+ .compression_method(zip::CompressionMethod::Deflated);
119+ writer.start_file("data.xml", options).expect("start");
120+ writer.write_all(plain).expect("write");
121+ writer.finish().expect("finish");
122+ path
123+ }
124+
125+ #[test]
126+ fn a_small_archive_passes() {
127+ let dir = tempfile::tempdir().expect("dir");
128+ let path = zip_with(dir.path(), "ok.xlsx", b"<a>hello</a>");
129+ assert!(open_checked(&path, 1 << 20).is_ok());
130+ }
131+
132+ /// 60 MiB of zeros deflates to a few dozen kilobytes. The declared total is over the limit, so the
133+ /// archive is refused on the first pass, and nothing is inflated.
134+ #[test]
135+ fn a_zip_bomb_is_refused_before_parsing() {
136+ let dir = tempfile::tempdir().expect("dir");
137+ let zeros = vec![0u8; 60 * 1024 * 1024];
138+ let path = zip_with(dir.path(), "bomb.xlsx", &zeros);
139+ let error = open_checked(&path, u64::MAX).expect_err("refused");
140+ assert!(
141+ matches!(error, Error::Invalid(ref code) if code == REFUSED_SIZE || code == REFUSED_RATIO),
142+ "{error:?}"
143+ );
144+ }
145+
146+ #[test]
147+ fn a_file_over_the_input_limit_is_refused() {
148+ let dir = tempfile::tempdir().expect("dir");
149+ let path = zip_with(dir.path(), "big.xlsx", b"<a/>");
150+ let error = open_checked(&path, 4).expect_err("refused");
151+ assert!(matches!(error, Error::Invalid(ref code) if code == REFUSED_SIZE));
152+ }
153+
154+ #[test]
155+ fn a_plain_file_is_not_a_zip() {
156+ let dir = tempfile::tempdir().expect("dir");
157+ let path = dir.path().join("plain.xlsx");
158+ std::fs::write(&path, b"not a zip").expect("write");
159+ let error = open_checked(&path, 1 << 20).expect_err("refused");
160+ assert!(matches!(error, Error::Invalid(ref code) if code == REFUSED_NOT_ZIP));
161+ }
162+
163+ #[test]
164+ fn the_ratio_floor_spares_small_parts() {
165+ assert!(!ratio_refused(ARCHIVE_RATIO_FLOOR_BYTES, 1));
166+ assert!(ratio_refused(ARCHIVE_RATIO_FLOOR_BYTES + 1, 1));
167+ assert!(!ratio_refused(
168+ ARCHIVE_RATIO_FLOOR_BYTES * 2,
169+ ARCHIVE_RATIO_FLOOR_BYTES
170+ ));
171+ }
172+}
crates/iz-core/src/lib.rsmodified+6 -0
@@ -3,13 +3,19 @@
33 //! This crate has no HTTP. It keeps the invariants: the schema, the length limits, the board rules
44 //! (overdue, cycles, ordering), time zone math and sealing of secrets. `iz-web` builds on it.
55
6+pub mod archive;
67 pub mod authz;
78 pub mod board;
89 pub mod clock;
910 pub mod config;
1011 pub mod error;
1112 pub mod limits;
13+pub mod preview;
1214 pub mod secret;
15+pub mod sheet;
16+pub mod slides;
17+pub mod sniff;
18+pub mod staging;
1319 pub mod store;
1420 pub mod time;
1521 pub mod token;
crates/iz-core/src/limits.rsmodified+34 -0
@@ -29,3 +29,37 @@ pub const ATTACHMENT_LIMIT_MIB_MAX: u32 = 500;
2929 pub const REMINDER_MINUTES_MAX: u32 = 1440;
3030 /// Largest mail batching window, in minutes. Reason: longer quiet windows delay mail past usefulness.
3131 pub const BATCH_MINUTES_MAX: u32 = 120;
32+/// Default per-file attachment limit, in MiB. Reason: the starting value of the setting; an admin raises it.
33+pub const ATTACHMENT_DEFAULT_MIB: u32 = 100;
34+/// Most file parts one upload request may carry. Reason: bounds the work one form can cause.
35+pub const UPLOAD_FILES_MAX: usize = 10;
36+/// Leading bytes of an upload that the sniffer reads. Reason: enough for every signature it knows.
37+pub const SNIFF_BYTES: usize = 8192;
38+/// Bytes of a text file the text viewer shows. Reason: a preview, not a reader; the rest is one download away.
39+pub const TEXT_PREVIEW_BYTES: u64 = 256 * 1024;
40+/// Largest compressed spreadsheet or CSV the viewer parses, in bytes. Reason: bounds the work of one preview.
41+pub const SHEET_INPUT_MAX_BYTES: u64 = 5 * 1024 * 1024;
42+/// Largest compressed slide deck the viewer parses, in bytes. Reason: decks carry pictures, so the cap is higher.
43+pub const SLIDES_INPUT_MAX_BYTES: u64 = 20 * 1024 * 1024;
44+/// Largest total uncompressed size of a zip container the viewers read, in bytes. Reason: a zip bomb is
45+/// refused before parsing; real workbooks and decks are far below this.
46+pub const ARCHIVE_UNCOMPRESSED_MAX_BYTES: u64 = 50 * 1024 * 1024;
47+/// Largest uncompressed-to-compressed ratio of a zip container. Reason: zip bombs compress to almost nothing.
48+pub const ARCHIVE_RATIO_MAX: u64 = 100;
49+/// Uncompressed size below which the ratio is not judged, in bytes. Reason: small parts compress badly
50+/// without being hostile, and the total size limit still applies to them.
51+pub const ARCHIVE_RATIO_FLOOR_BYTES: u64 = 1024 * 1024;
52+/// Most sheets a workbook preview shows. Reason: a preview of every tab of a large workbook is a document dump.
53+pub const SHEETS_MAX: usize = 20;
54+/// Most rows a sheet preview shows. Reason: keeps one page render bounded.
55+pub const SHEET_ROWS_MAX: usize = 1000;
56+/// Most columns a sheet preview shows. Reason: wider tables do not fit the viewer width anyway.
57+pub const SHEET_COLS_MAX: usize = 100;
58+/// Longest cell text a sheet preview shows, in characters. Reason: one cell must not fill the page.
59+pub const CELL_TEXT_MAX: usize = 1000;
60+/// Most slides a deck preview lists. Reason: bounds the XML parsed from one request.
61+pub const SLIDES_MAX: usize = 200;
62+/// Longest text of one slide shown, in characters. Reason: a slide's text is a summary, not a transcript.
63+pub const SLIDE_TEXT_MAX: usize = 4000;
64+/// Largest XML part of a deck that is read, in bytes. Reason: a single slide is far below this.
65+pub const DECK_PART_MAX_BYTES: u64 = 4 * 1024 * 1024;
crates/iz-core/src/preview.rsadded+39 -0
@@ -0,0 +1,39 @@
1+//! Previews of files that are read as text: the first part of a text file, escaped by the page. Nothing
2+//! here decides whether a file may be shown; the caller has checked the viewer kind and the caller's
3+//! right to read the file.
4+
5+use std::io::Read;
6+use std::path::Path;
7+
8+use crate::error::Result;
9+
10+/// Reads at most `cap` bytes of `path` as text. Returns the text (invalid UTF-8 replaced) and whether the file
11+/// was longer than the cap.
12+pub fn read_text_head(path: &Path, cap: u64) -> Result<(String, bool)> {
13+ let file = std::fs::File::open(path)?;
14+ let mut bytes = Vec::new();
15+ file.take(cap + 1).read_to_end(&mut bytes)?;
16+ let truncated = bytes.len() as u64 > cap;
17+ bytes.truncate(usize::try_from(cap).unwrap_or(usize::MAX));
18+ Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated))
19+}
20+
21+#[cfg(test)]
22+mod tests {
23+ use super::*;
24+
25+ #[test]
26+ fn a_long_text_is_cut_and_says_so() {
27+ let dir = tempfile::tempdir().expect("dir");
28+ let path = dir.path().join("long.txt");
29+ std::fs::write(&path, "abcdef").expect("write");
30+ assert_eq!(
31+ read_text_head(&path, 4).expect("head"),
32+ ("abcd".into(), true)
33+ );
34+ assert_eq!(
35+ read_text_head(&path, 6).expect("head"),
36+ ("abcdef".into(), false)
37+ );
38+ }
39+}
crates/iz-core/src/sheet.rsadded+175 -0
@@ -0,0 +1,175 @@
1+//! Spreadsheet previews: a workbook (`.xlsx`, `.ods`) or a CSV file read as values only, with the caps of
2+//! `limits.rs`: at most 20 sheets, 1000 rows, 100 columns and 1000 characters a cell. Formulas, formats,
3+//! charts and macros are not read; a cell is its displayed value. The caller turns the result into HTML,
4+//! where every cell is escaped, so a cell that holds markup is shown as text.
5+//!
6+//! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. A CSV is
7+//! read record by record and stops at the row cap, so a long file costs no more than the cap.
8+
9+use std::fs::File;
10+use std::path::Path;
11+
12+use calamine::{Data, Reader, open_workbook_auto};
13+
14+use crate::archive;
15+use crate::error::{Error, Result};
16+use crate::limits::{
17+ CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEETS_MAX,
18+};
19+
20+/// One sheet of a book, as text cells. `rows_cut` is set when the sheet had more rows than the cap.
21+#[derive(Debug, Clone, PartialEq, Eq)]
22+pub struct Sheet {
23+ /// The tab name (for a CSV, the file name).
24+ pub name: String,
25+ /// The rows, each a list of cell texts.
26+ pub rows: Vec<Vec<String>>,
27+ /// Whether rows past the cap were left out.
28+ pub rows_cut: bool,
29+}
30+
31+/// A book: the sheets shown, and how many it has in all.
32+#[derive(Debug, Clone, PartialEq, Eq)]
33+pub struct Book {
34+ /// The first sheets, at most [`SHEETS_MAX`].
35+ pub sheets: Vec<Sheet>,
36+ /// The number of sheets in the file.
37+ pub sheet_count: usize,
38+}
39+
40+/// Cuts a cell's text to [`CELL_TEXT_MAX`] characters.
41+fn cell_text(text: &str) -> String {
42+ text.chars().take(CELL_TEXT_MAX).collect()
43+}
44+
45+/// Reads an `.xlsx` or `.ods` workbook. Refused (as `Invalid`) when the zip checks fail.
46+pub fn read_workbook(path: &Path) -> Result<Book> {
47+ archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?;
48+ let mut workbook =
49+ open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?;
50+ let names = workbook.sheet_names();
51+ let sheet_count = names.len();
52+ let mut sheets = Vec::new();
53+ for name in names.into_iter().take(SHEETS_MAX) {
54+ let range = workbook
55+ .worksheet_range(&name)
56+ .map_err(|_| Error::Invalid("bad_workbook".into()))?;
57+ let mut rows = Vec::new();
58+ let mut rows_cut = false;
59+ for (index, row) in range.rows().enumerate() {
60+ if index == SHEET_ROWS_MAX {
61+ rows_cut = true;
62+ break;
63+ }
64+ rows.push(
65+ row.iter()
66+ .take(SHEET_COLS_MAX)
67+ .map(|cell: &Data| cell_text(&cell.to_string()))
68+ .collect(),
69+ );
70+ }
71+ sheets.push(Sheet {
72+ name,
73+ rows,
74+ rows_cut,
75+ });
76+ }
77+ Ok(Book {
78+ sheets,
79+ sheet_count,
80+ })
81+}
82+
83+/// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters.
84+pub fn read_csv(path: &Path, name: &str) -> Result<Book> {
85+ let len = std::fs::metadata(path)?.len();
86+ if len > SHEET_INPUT_MAX_BYTES {
87+ return Err(Error::Invalid(archive::REFUSED_SIZE.into()));
88+ }
89+ let mut reader = csv::ReaderBuilder::new()
90+ .has_headers(false)
91+ .flexible(true)
92+ .from_reader(File::open(path)?);
93+ let mut rows = Vec::new();
94+ let mut rows_cut = false;
95+ let mut record = csv::ByteRecord::new();
96+ loop {
97+ let more = reader
98+ .read_byte_record(&mut record)
99+ .map_err(|_| Error::Invalid("bad_csv".into()))?;
100+ if !more {
101+ break;
102+ }
103+ if rows.len() == SHEET_ROWS_MAX {
104+ rows_cut = true;
105+ break;
106+ }
107+ rows.push(
108+ record
109+ .iter()
110+ .take(SHEET_COLS_MAX)
111+ .map(|field| cell_text(&String::from_utf8_lossy(field)))
112+ .collect(),
113+ );
114+ }
115+ Ok(Book {
116+ sheets: vec![Sheet {
117+ name: name.to_owned(),
118+ rows,
119+ rows_cut,
120+ }],
121+ sheet_count: 1,
122+ })
123+}
124+
125+#[cfg(test)]
126+mod tests {
127+ use super::*;
128+
129+ #[test]
130+ fn a_csv_keeps_cells_as_plain_text() {
131+ let dir = tempfile::tempdir().expect("dir");
132+ let path = dir.path().join("t.csv");
133+ std::fs::write(&path, "name,note\n<script>x</script>,\"a, b\"\n").expect("write");
134+ let book = read_csv(&path, "t.csv").expect("csv");
135+ assert_eq!(book.sheet_count, 1);
136+ assert_eq!(book.sheets[0].rows[1][0], "<script>x</script>");
137+ assert_eq!(book.sheets[0].rows[1][1], "a, b");
138+ assert!(!book.sheets[0].rows_cut);
139+ }
140+
141+ #[test]
142+ fn a_workbook_zip_bomb_is_refused() {
143+ let dir = tempfile::tempdir().expect("dir");
144+ let path = dir.path().join("bomb.xlsx");
145+ let file = std::fs::File::create(&path).expect("create");
146+ let mut writer = zip::ZipWriter::new(file);
147+ let options = zip::write::SimpleFileOptions::default()
148+ .compression_method(zip::CompressionMethod::Deflated);
149+ writer
150+ .start_file("xl/worksheets/sheet1.xml", options)
151+ .expect("start");
152+ std::io::Write::write_all(&mut writer, &vec![0u8; 60 * 1024 * 1024]).expect("write");
153+ writer.finish().expect("finish");
154+ assert!(read_workbook(&path).is_err());
155+ }
156+
157+ #[test]
158+ fn a_csv_stops_at_the_row_cap() {
159+ let dir = tempfile::tempdir().expect("dir");
160+ let path = dir.path().join("long.csv");
161+ let text: String = (0..SHEET_ROWS_MAX + 5).map(|i| format!("{i}\n")).collect();
162+ std::fs::write(&path, text).expect("write");
163+ let book = read_csv(&path, "long.csv").expect("csv");
164+ assert_eq!(book.sheets[0].rows.len(), SHEET_ROWS_MAX);
165+ assert!(book.sheets[0].rows_cut);
166+ }
167+
168+ #[test]
169+ fn a_cell_is_cut_to_its_cap() {
170+ assert_eq!(
171+ cell_text(&"x".repeat(CELL_TEXT_MAX + 9)).len(),
172+ CELL_TEXT_MAX
173+ );
174+ }
175+}
crates/iz-core/src/slides.rsadded+244 -0
@@ -0,0 +1,244 @@
1+//! Slide deck previews: the text of each slide of a `.pptx`, in slide order, as paragraphs. Pictures,
2+//! notes, embedded objects and layouts are not read, and nothing from the deck is rendered as markup; the
3+//! caller escapes every paragraph.
4+//!
5+//! The deck is a zip container, so it passes `archive::open_checked` first. Slide order comes from
6+//! `ppt/presentation.xml` and its relationships; when those are missing or unreadable, the parts
7+//! `ppt/slides/slideN.xml` are read in order until one is absent.
8+
9+use std::path::Path;
10+
11+use quick_xml::events::Event;
12+use quick_xml::reader::Reader;
13+use zip::ZipArchive;
14+
15+use crate::archive;
16+use crate::error::Result;
17+use crate::limits::{DECK_PART_MAX_BYTES, SLIDE_TEXT_MAX, SLIDES_INPUT_MAX_BYTES, SLIDES_MAX};
18+
19+/// One slide: its position (from 1) and its paragraphs of text.
20+#[derive(Debug, Clone, PartialEq, Eq)]
21+pub struct Slide {
22+ /// Position in the deck, from 1.
23+ pub number: usize,
24+ /// The paragraphs of text, in order. Empty paragraphs are left out.
25+ pub paragraphs: Vec<String>,
26+}
27+
28+/// Reads the slides of a `.pptx` in order, at most [`SLIDES_MAX`] of them.
29+pub fn read_deck(path: &Path) -> Result<Vec<Slide>> {
30+ let mut archive = archive::open_checked(path, SLIDES_INPUT_MAX_BYTES)?;
31+ let parts = slide_parts(&mut archive)?;
32+ let mut slides = Vec::new();
33+ for (index, part) in parts.iter().take(SLIDES_MAX).enumerate() {
34+ let Some(bytes) = archive::read_entry(&mut archive, part, DECK_PART_MAX_BYTES)? else {
35+ break;
36+ };
37+ slides.push(Slide {
38+ number: index + 1,
39+ paragraphs: paragraphs_of(&bytes),
40+ });
41+ }
42+ Ok(slides)
43+}
44+
45+/// The part names of the slides in presentation order.
46+fn slide_parts(archive: &mut ZipArchive<std::fs::File>) -> Result<Vec<String>> {
47+ let order = presentation_order(archive)?;
48+ if !order.is_empty() {
49+ return Ok(order);
50+ }
51+ // Fallback: the conventional names, in order, until one is missing.
52+ let mut parts = Vec::new();
53+ for number in 1..=SLIDES_MAX {
54+ let name = format!("ppt/slides/slide{number}.xml");
55+ if archive.by_name(&name).is_err() {
56+ break;
57+ }
58+ parts.push(name);
59+ }
60+ Ok(parts)
61+}
62+
63+/// The slide parts in the order `ppt/presentation.xml` lists them, resolved through its relationships.
64+/// Empty when either part is missing or names nothing usable.
65+fn presentation_order(archive: &mut ZipArchive<std::fs::File>) -> Result<Vec<String>> {
66+ let Some(presentation) =
67+ archive::read_entry(archive, "ppt/presentation.xml", DECK_PART_MAX_BYTES)?
68+ else {
69+ return Ok(Vec::new());
70+ };
71+ let Some(rels) = archive::read_entry(
72+ archive,
73+ "ppt/_rels/presentation.xml.rels",
74+ DECK_PART_MAX_BYTES,
75+ )?
76+ else {
77+ return Ok(Vec::new());
78+ };
79+ let ids = slide_rel_ids(&presentation);
80+ let targets = relationship_targets(&rels);
81+ let mut parts = Vec::new();
82+ for id in ids {
83+ if let Some((_, target)) = targets.iter().find(|(rel, _)| *rel == id) {
84+ let name = match target.strip_prefix('/') {
85+ Some(absolute) => absolute.to_owned(),
86+ None => format!("ppt/{target}"),
87+ };
88+ // Only slide parts are read; any other target is ignored.
89+ if name.starts_with("ppt/slides/") && name.ends_with(".xml") {
90+ parts.push(name);
91+ }
92+ }
93+ }
94+ Ok(parts)
95+}
96+
97+/// The `r:id` of each `<p:sldId>` of the presentation, in order.
98+fn slide_rel_ids(xml: &[u8]) -> Vec<String> {
99+ let mut ids = Vec::new();
100+ let Ok(text) = std::str::from_utf8(xml) else {
101+ return ids;
102+ };
103+ let mut reader = Reader::from_str(text);
104+ loop {
105+ match reader.read_event() {
106+ Ok(Event::Start(e) | Event::Empty(e)) if e.local_name().as_ref() == "sldId" => {
107+ for attribute in e.attributes().flatten() {
108+ if attribute.key.as_ref() == "r:id" {
109+ // Ids and targets are plain names; a reference inside one is never a slide, so the
110+ // raw value is used and entities are not resolved.
111+ ids.push(attribute.value.to_string());
112+ }
113+ }
114+ }
115+ Ok(Event::Eof) | Err(_) => break,
116+ Ok(_) => {}
117+ }
118+ }
119+ ids
120+}
121+
122+/// The `(Id, Target)` pairs of a relationships part.
123+fn relationship_targets(xml: &[u8]) -> Vec<(String, String)> {
124+ let mut pairs = Vec::new();
125+ let Ok(text) = std::str::from_utf8(xml) else {
126+ return pairs;
127+ };
128+ let mut reader = Reader::from_str(text);
129+ loop {
130+ match reader.read_event() {
131+ Ok(Event::Start(e) | Event::Empty(e)) if e.local_name().as_ref() == "Relationship" => {
132+ let mut id = None;
133+ let mut target = None;
134+ for attribute in e.attributes().flatten() {
135+ let value = Some(attribute.value.to_string());
136+ match attribute.key.as_ref() {
137+ "Id" => id = value,
138+ "Target" => target = value,
139+ _ => {}
140+ }
141+ }
142+ if let (Some(id), Some(target)) = (id, target) {
143+ pairs.push((id, target));
144+ }
145+ }
146+ Ok(Event::Eof) | Err(_) => break,
147+ Ok(_) => {}
148+ }
149+ }
150+ pairs
151+}
152+
153+/// The paragraphs of text of one slide part: each `<a:p>` with the text of its `<a:t>` runs, entities resolved.
154+/// Stops once [`SLIDE_TEXT_MAX`] characters are collected.
155+fn paragraphs_of(xml: &[u8]) -> Vec<String> {
156+ let mut paragraphs = Vec::new();
157+ let Ok(text) = std::str::from_utf8(xml) else {
158+ return paragraphs;
159+ };
160+ let mut reader = Reader::from_str(text);
161+ let mut current = String::new();
162+ let mut in_run = false;
163+ let mut used = 0usize;
164+ while let Ok(event) = reader.read_event() {
165+ match event {
166+ Event::Start(e) if e.local_name().as_ref() == "t" => in_run = true,
167+ Event::End(e) if e.local_name().as_ref() == "t" => in_run = false,
168+ Event::End(e) if e.local_name().as_ref() == "p" => {
169+ let paragraph = current.trim().to_owned();
170+ if !paragraph.is_empty() {
171+ paragraphs.push(paragraph);
172+ }
173+ current.clear();
174+ }
175+ Event::Text(t) if in_run => push_limited(&mut current, &t.xml10_content(), &mut used),
176+ Event::GeneralRef(r) if in_run => {
177+ let resolved = match r.resolve_char_ref() {
178+ Ok(Some(ch)) => Some(ch.to_string()),
179+ Ok(None) => predefined_entity(&r),
180+ Err(_) => None,
181+ };
182+ if let Some(resolved) = resolved {
183+ push_limited(&mut current, &resolved, &mut used);
184+ }
185+ }
186+ Event::Eof => break,
187+ _ => {}
188+ }
189+ if used >= SLIDE_TEXT_MAX {
190+ break;
191+ }
192+ }
193+ paragraphs
194+}
195+
196+/// The character of one of the five predefined XML entities (`&lt;` and the rest).
197+fn predefined_entity(reference: &quick_xml::events::BytesRef<'_>) -> Option<String> {
198+ let name: &str = reference.as_ref();
199+ let ch = match name {
200+ "lt" => '<',
201+ "gt" => '>',
202+ "amp" => '&',
203+ "quot" => '"',
204+ "apos" => '\'',
205+ _ => return None,
206+ };
207+ Some(ch.to_string())
208+}
209+
210+/// Appends `text` to `out`, counting characters against [`SLIDE_TEXT_MAX`].
211+fn push_limited(out: &mut String, text: &str, used: &mut usize) {
212+ for ch in text.chars() {
213+ if *used >= SLIDE_TEXT_MAX {
214+ return;
215+ }
216+ out.push(ch);
217+ *used += 1;
218+ }
219+}
220+
221+#[cfg(test)]
222+mod tests {
223+ use super::*;
224+
225+ #[test]
226+ fn paragraphs_are_the_runs_of_each_a_p_with_entities_resolved() {
227+ let xml = br#"<?xml version="1.0"?><p:sld xmlns:a="x"><a:p><a:r><a:t>Hello &amp; </a:t></a:r><a:r><a:t>&lt;b&gt;</a:t></a:r></a:p><a:p><a:t></a:t></a:p><a:p><a:t>Second</a:t></a:p></p:sld>"#;
228+ assert_eq!(
229+ paragraphs_of(xml),
230+ vec!["Hello & <b>".to_owned(), "Second".to_owned()]
231+ );
232+ }
233+
234+ #[test]
235+ fn relationship_targets_and_slide_ids_are_read() {
236+ let rels = br#"<Relationships><Relationship Id="rId2" Target="slides/slide1.xml"/></Relationships>"#;
237+ assert_eq!(
238+ relationship_targets(rels),
239+ vec![("rId2".to_owned(), "slides/slide1.xml".to_owned())]
240+ );
241+ let pres = br#"<p:presentation><p:sldIdLst><p:sldId id="256" r:id="rId2"/></p:sldIdLst></p:presentation>"#;
242+ assert_eq!(slide_rel_ids(pres), vec!["rId2".to_owned()]);
243+ }
244+}
crates/iz-core/src/sniff.rsadded+247 -0
@@ -0,0 +1,247 @@
1+//! Content sniffing: the MIME type of a file is decided from its first bytes, never from the
2+//! uploader's claim. The result drives the viewers and the `Content-Disposition` of every byte response,
3+//! so SVG and HTML are recognised explicitly: they must never be served inline.
4+//!
5+//! This is a pure function over a prefix. Callers pass the first kilobyte or megabyte of the file;
6+//! an empty prefix is `application/octet-stream`.
7+
8+/// How many leading bytes the text heuristics look at when searching for a markup marker.
9+const TEXT_WINDOW: usize = 1024;
10+
11+/// The MIME type for `prefix`, the first bytes of a file.
12+pub fn sniff(prefix: &[u8]) -> String {
13+ if prefix.is_empty() {
14+ return "application/octet-stream".into();
15+ }
16+ let mime = binary_magic(prefix)
17+ .or(is_svg(prefix).then_some("image/svg+xml"))
18+ .or(is_html(prefix).then_some("text/html"))
19+ .or_else(|| iso_bmff(prefix))
20+ .unwrap_or_else(|| {
21+ if is_utf8_text(prefix) {
22+ "text/plain"
23+ } else {
24+ "application/octet-stream"
25+ }
26+ });
27+ mime.into()
28+}
29+
30+/// Magic numbers of the binary formats. `None` when nothing matches.
31+fn binary_magic(b: &[u8]) -> Option<&'static str> {
32+ let starts = |magic: &[u8]| b.starts_with(magic);
33+ if starts(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) {
34+ return Some("image/png");
35+ }
36+ if starts(&[0xFF, 0xD8, 0xFF]) {
37+ return Some("image/jpeg");
38+ }
39+ if starts(b"GIF87a") || starts(b"GIF89a") {
40+ return Some("image/gif");
41+ }
42+ if starts(b"%PDF-") {
43+ return Some("application/pdf");
44+ }
45+ if starts(&[0x1F, 0x8B]) {
46+ return Some("application/gzip");
47+ }
48+ if starts(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) {
49+ return Some(if contains_utf16(b, "Workbook") {
50+ "application/vnd.ms-excel"
51+ } else {
52+ "application/x-ole-storage"
53+ });
54+ }
55+ if starts(b"PK\x03\x04") {
56+ return Some(zip_flavour(b));
57+ }
58+ if starts(&[0x1A, 0x45, 0xDF, 0xA3]) {
59+ // The EBML header names its document type ("webm" or "matroska") in the first bytes.
60+ let head = &b[..b.len().min(TEXT_WINDOW)];
61+ return Some(if contains(head, b"webm") {
62+ "video/webm"
63+ } else {
64+ "video/x-matroska"
65+ });
66+ }
67+ if starts(b"fLaC") {
68+ return Some("audio/flac");
69+ }
70+ if starts(b"OggS") {
71+ return Some("audio/ogg");
72+ }
73+ if b.len() >= 12 && starts(b"RIFF") && &b[8..12] == b"WEBP" {
74+ return Some("image/webp");
75+ }
76+ if b.len() >= 12 && starts(b"RIFF") && &b[8..12] == b"WAVE" {
77+ return Some("audio/wav");
78+ }
79+ if starts(b"ID3") || starts(&[0xFF, 0xFB]) || starts(&[0xFF, 0xF3]) || starts(&[0xFF, 0xF2]) {
80+ return Some("audio/mpeg");
81+ }
82+ None
83+}
84+
85+/// Tells an OOXML or OpenDocument container from a plain zip by the entry names it contains.
86+/// Zip entry names are stored in the clear, so a substring scan finds them.
87+fn zip_flavour(b: &[u8]) -> &'static str {
88+ if contains(b, b"xl/workbook.xml") {
89+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
90+ } else if contains(b, b"ppt/presentation.xml") {
91+ "application/vnd.openxmlformats-officedocument.presentationml.presentation"
92+ } else if contains(b, b"opendocument.spreadsheet") {
93+ "application/vnd.oasis.opendocument.spreadsheet"
94+ } else {
95+ "application/zip"
96+ }
97+}
98+
99+/// ISO base media files (`ftyp` box at offset 4). The major brand decides the type. A brand that is
100+/// not listed here is treated as generic MP4.
101+fn iso_bmff(b: &[u8]) -> Option<&'static str> {
102+ if b.len() < 12 || &b[4..8] != b"ftyp" {
103+ return None;
104+ }
105+ Some(match &b[8..12] {
106+ b"avif" | b"avis" => "image/avif",
107+ b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevx" => "image/heic",
108+ b"heif" | b"mif1" | b"msf1" => "image/heif",
109+ b"qt " => "video/quicktime",
110+ b"M4A " | b"M4B " => "audio/mp4",
111+ _ => "video/mp4",
112+ })
113+}
114+
115+/// Whether the text starts with an `<svg` root element, after an optional byte order mark, XML
116+/// prolog, comments, and a DOCTYPE that does not name HTML.
117+fn is_svg(b: &[u8]) -> bool {
118+ let mut rest = strip_bom(b);
119+ loop {
120+ rest = trim_start_ws(rest);
121+ if rest.starts_with(b"<?") {
122+ rest = match find(rest, b"?>") {
123+ Some(i) => &rest[i + 2..],
124+ None => return false,
125+ };
126+ } else if rest.starts_with(b"<!--") {
127+ rest = match find(rest, b"-->") {
128+ Some(i) => &rest[i + 3..],
129+ None => return false,
130+ };
131+ } else if starts_with_ci(rest, b"<!doctype") {
132+ let end = find(rest, b">").map_or(rest.len(), |i| i + 1);
133+ if contains_ci(&rest[..end], b"html") {
134+ return false;
135+ }
136+ rest = &rest[end..];
137+ } else {
138+ break;
139+ }
140+ }
141+ starts_with_ci(rest, b"<svg")
142+}
143+
144+/// Whether the text carries an HTML marker near its start. Matching is case-insensitive.
145+fn is_html(b: &[u8]) -> bool {
146+ let body = trim_start_ws(strip_bom(b));
147+ let window = &body[..body.len().min(TEXT_WINDOW)];
148+ [
149+ &b"<!doctype html"[..],
150+ b"<html",
151+ b"<script",
152+ b"<head",
153+ b"<body",
154+ ]
155+ .iter()
156+ .any(|marker| contains_ci(window, marker))
157+}
158+
159+/// Whether the prefix is valid UTF-8. A prefix cut in the middle of a character is accepted, because
160+/// the cut is an artefact of reading only the first bytes.
161+fn is_utf8_text(b: &[u8]) -> bool {
162+ match std::str::from_utf8(b) {
163+ Ok(_) => true,
164+ Err(e) => e.error_len().is_none(),
165+ }
166+}
167+
168+fn strip_bom(b: &[u8]) -> &[u8] {
169+ b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(b)
170+}
171+
172+fn trim_start_ws(b: &[u8]) -> &[u8] {
173+ let n = b.iter().take_while(|c| c.is_ascii_whitespace()).count();
174+ &b[n..]
175+}
176+
177+fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
178+ hay.windows(needle.len()).position(|w| w == needle)
179+}
180+
181+fn contains(hay: &[u8], needle: &[u8]) -> bool {
182+ find(hay, needle).is_some()
183+}
184+
185+fn starts_with_ci(hay: &[u8], needle: &[u8]) -> bool {
186+ hay.len() >= needle.len() && hay[..needle.len()].eq_ignore_ascii_case(needle)
187+}
188+
189+fn contains_ci(hay: &[u8], needle: &[u8]) -> bool {
190+ hay.windows(needle.len())
191+ .any(|w| w.eq_ignore_ascii_case(needle))
192+}
193+
194+/// Whether `word` appears as UTF-16LE text in `b`, as it does inside OLE2 directory entries.
195+fn contains_utf16(b: &[u8], word: &str) -> bool {
196+ let wide: Vec<u8> = word.bytes().flat_map(|c| [c, 0]).collect();
197+ contains(b, &wide)
198+}
199+
200+#[cfg(test)]
201+mod tests {
202+ use super::*;
203+
204+ #[test]
205+ fn recognises_binary_formats_by_magic_number() {
206+ assert_eq!(sniff(b"\x89PNG\r\n\x1a\n rest"), "image/png");
207+ assert_eq!(sniff(b"%PDF-1.7\n"), "application/pdf");
208+ assert_eq!(sniff(b"\xFF\xD8\xFF\xE0 jpeg"), "image/jpeg");
209+ }
210+
211+ #[test]
212+ fn svg_is_detected_after_prolog_comments_and_whitespace() {
213+ assert_eq!(sniff(b"<svg xmlns='x'/>"), "image/svg+xml");
214+ let prolog = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>\n<!-- hi -->\n <SVG></SVG>";
215+ assert_eq!(sniff(prolog), "image/svg+xml");
216+ let doctype = b"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"x.dtd\">\n<svg/>";
217+ assert_eq!(sniff(doctype), "image/svg+xml");
218+ }
219+
220+ #[test]
221+ fn html_is_detected_near_the_start_case_insensitively() {
222+ assert_eq!(sniff(b"<!DOCTYPE html>\n<p>x</p>"), "text/html");
223+ assert_eq!(sniff(b" <Script>alert(1)</Script>"), "text/html");
224+ assert_eq!(sniff(b"<!doctype html><svg/>"), "text/html");
225+ assert_eq!(sniff(b"just words"), "text/plain");
226+ }
227+
228+ #[test]
229+ fn audio_and_video_brands_are_told_apart() {
230+ assert_eq!(sniff(b"\x00\x00\x00\x20ftypM4A \x00\x00"), "audio/mp4");
231+ assert_eq!(sniff(b"\x00\x00\x00\x20ftypM4B \x00\x00"), "audio/mp4");
232+ assert_eq!(sniff(b"\x00\x00\x00\x20ftypisom\x00\x00"), "video/mp4");
233+ }
234+
235+ #[test]
236+ fn empty_and_unknown_binary_are_octet_stream() {
237+ assert_eq!(sniff(b""), "application/octet-stream");
238+ assert_eq!(sniff(&[0xFF, 0x00, 0xFE, 0x81]), "application/octet-stream");
239+ }
240+
241+ #[test]
242+ fn a_cut_multibyte_character_at_the_end_still_counts_as_text() {
243+ let mut bytes = "héllo".as_bytes().to_vec();
244+ bytes.push("é".as_bytes()[0]);
245+ assert_eq!(sniff(&bytes), "text/plain");
246+ }
247+}
crates/iz-core/src/staging.rsadded+186 -0
@@ -0,0 +1,186 @@
1+//! Streaming intake of an upload. Incoming bytes go to `data_dir/tmp/<ulid>` while the SHA-256 and the
2+//! size are computed, so nothing is buffered whole and the file is never trusted before it is complete.
3+//! The per-file limit is enforced while the bytes are read: the write that would pass it is refused, and
4+//! nothing past the limit reaches the disk.
5+//!
6+//! A finished file is moved into `data_dir/attachments/<id>` by [`install_blob`]. A file that is never
7+//! finished is removed by [`StagedFile::abort`], or stays in `data_dir/tmp` after a crash until the sweeper
8+//! removes it. Every path under `attachments` is built from a validated ULID by [`blob_path`], so no name from
9+//! a client ever reaches the disk.
10+
11+use std::path::{Path, PathBuf};
12+
13+use sha2::{Digest, Sha256};
14+use tokio::io::AsyncWriteExt;
15+
16+use crate::error::{Error, Result};
17+
18+/// Name of the staging directory inside the data directory.
19+pub const TMP_DIR: &str = "tmp";
20+/// Name of the directory inside the data directory that holds the bytes of attachments, one file per id.
21+pub const ATTACHMENTS_DIR: &str = "attachments";
22+
23+/// The file that holds the bytes of attachment `id`: `data_dir/attachments/<id>`. `id` must be a ULID in its
24+/// canonical text form (upper case, 26 characters); anything else is `Invalid("bad_id")`, so the path can
25+/// never leave the attachments directory.
26+pub fn blob_path(data_dir: &Path, id: &str) -> Result<PathBuf> {
27+ let canonical = ulid::Ulid::from_string(id)
28+ .map(|parsed| parsed.to_string() == id)
29+ .unwrap_or(false);
30+ if !canonical {
31+ return Err(Error::Invalid("bad_id".into()));
32+ }
33+ Ok(data_dir.join(ATTACHMENTS_DIR).join(id))
34+}
35+
36+/// Moves a finished staged file to the place of attachment `id` and makes the move durable. The directory is
37+/// created with mode 0700 if missing; the file keeps its mode 0600 from the staging step.
38+pub async fn install_blob(data_dir: &Path, id: &str, staged: &Path) -> Result<PathBuf> {
39+ let target = blob_path(data_dir, id)?;
40+ let dir = data_dir.join(ATTACHMENTS_DIR);
41+ tokio::fs::DirBuilder::new()
42+ .recursive(true)
43+ .mode(0o700)
44+ .create(&dir)
45+ .await?;
46+ tokio::fs::rename(staged, &target).await?;
47+ // The rename is durable only once the directory entry is.
48+ tokio::fs::File::open(&dir).await?.sync_all().await?;
49+ Ok(target)
50+}
51+
52+/// Removes the bytes of attachment `id`. A file that is already gone is not an error: the goal is that the
53+/// bytes are not there, and they are not.
54+pub async fn remove_blob(data_dir: &Path, id: &str) -> Result<()> {
55+ let path = blob_path(data_dir, id)?;
56+ match tokio::fs::remove_file(&path).await {
57+ Ok(()) => Ok(()),
58+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
59+ Err(error) => Err(error.into()),
60+ }
61+}
62+
63+/// A file being written. Create it with [`StagedFile::create`], feed it with [`StagedFile::write`], then
64+/// call [`StagedFile::finish`]; or call [`StagedFile::abort`] on any error.
65+pub struct StagedFile {
66+ path: PathBuf,
67+ file: tokio::fs::File,
68+ hasher: Sha256,
69+ size: u64,
70+ max_size: u64,
71+}
72+
73+/// A complete staged file, ready to be moved into place.
74+#[derive(Debug, Clone, PartialEq, Eq)]
75+pub struct Staged {
76+ /// Where the bytes are.
77+ pub path: PathBuf,
78+ /// Number of bytes written.
79+ pub size: u64,
80+ /// Lowercase hex SHA-256 of the bytes.
81+ pub sha256: String,
82+}
83+
84+impl StagedFile {
85+ /// Starts a new staged file in `data_dir/tmp`. The directory is created with mode 0700 and the file with
86+ /// mode 0600. A write that would take the file past `max_size` fails with `Invalid("too_large")`.
87+ pub async fn create(data_dir: &Path, max_size: u64) -> Result<Self> {
88+ let dir = data_dir.join(TMP_DIR);
89+ tokio::fs::DirBuilder::new()
90+ .recursive(true)
91+ .mode(0o700)
92+ .create(&dir)
93+ .await?;
94+ let path = dir.join(crate::store::new_id());
95+ let file = tokio::fs::OpenOptions::new()
96+ .write(true)
97+ .create_new(true)
98+ .mode(0o600)
99+ .open(&path)
100+ .await?;
101+ Ok(Self {
102+ path,
103+ file,
104+ hasher: Sha256::new(),
105+ size: 0,
106+ max_size,
107+ })
108+ }
109+
110+ /// Appends `chunk`. Refused, without writing, when it would take the file past the size limit.
111+ pub async fn write(&mut self, chunk: &[u8]) -> Result<()> {
112+ let len = chunk.len() as u64;
113+ if self.size.saturating_add(len) > self.max_size {
114+ return Err(Error::Invalid("too_large".into()));
115+ }
116+ self.file.write_all(chunk).await?;
117+ self.hasher.update(chunk);
118+ self.size += len;
119+ Ok(())
120+ }
121+
122+ /// Flushes the bytes to the disk and returns the finished file. The caller moves it.
123+ pub async fn finish(mut self) -> Result<Staged> {
124+ self.file.flush().await?;
125+ self.file.sync_all().await?;
126+ let sha256 = hex::encode(self.hasher.finalize());
127+ Ok(Staged {
128+ path: self.path,
129+ size: self.size,
130+ sha256,
131+ })
132+ }
133+
134+ /// Removes the partial file. Used on every refusal and failure, so nothing is left behind.
135+ pub async fn abort(self) {
136+ let path = self.path.clone();
137+ drop(self.file);
138+ let _ = tokio::fs::remove_file(path).await;
139+ }
140+}
141+
142+#[cfg(test)]
143+mod tests {
144+ use super::*;
145+
146+ #[tokio::test]
147+ async fn the_limit_is_enforced_while_writing() {
148+ let dir = tempfile::tempdir().expect("dir");
149+ let mut staged = StagedFile::create(dir.path(), 4).await.expect("create");
150+ staged.write(b"abc").await.expect("first write");
151+ let error = staged.write(b"de").await.expect_err("over the limit");
152+ assert!(matches!(error, Error::Invalid(ref code) if code == "too_large"));
153+ staged.abort().await;
154+ let left = std::fs::read_dir(dir.path().join(TMP_DIR))
155+ .expect("tmp")
156+ .count();
157+ assert_eq!(left, 0, "the partial file is removed");
158+ }
159+
160+ #[test]
161+ fn a_blob_path_takes_only_a_canonical_ulid() {
162+ let dir = Path::new("/data");
163+ let id = crate::store::new_id();
164+ assert_eq!(
165+ blob_path(dir, &id).expect("path"),
166+ dir.join(ATTACHMENTS_DIR).join(&id)
167+ );
168+ assert!(blob_path(dir, "../../etc/passwd").is_err());
169+ assert!(blob_path(dir, &id.to_ascii_lowercase()).is_err());
170+ assert!(blob_path(dir, "").is_err());
171+ }
172+
173+ #[tokio::test]
174+ async fn the_digest_is_of_the_written_bytes() {
175+ let dir = tempfile::tempdir().expect("dir");
176+ let mut staged = StagedFile::create(dir.path(), 1024).await.expect("create");
177+ staged.write(b"ab").await.expect("write");
178+ staged.write(b"c").await.expect("write");
179+ let done = staged.finish().await.expect("finish");
180+ assert_eq!(done.size, 3);
181+ assert_eq!(
182+ done.sha256,
183+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
184+ );
185+ }
186+}
crates/iz-core/src/store/attachments.rsadded+455 -0
@@ -0,0 +1,455 @@
1+//! Attachments of tasks: the rows, the upload policy, and the queue of bytes still to delete.
2+//!
3+//! The bytes themselves are on the disk (`data_dir/attachments/<id>`, written by iz-web); this module owns the
4+//! rows and says which bytes are owed. A row is always reached through its task: a task of another board, a
5+//! deleted task, or a key that does not match is `NotFound`, so an attachment id from one task cannot be used
6+//! on another (attack plan section 6: cross-task IDOR). Adding and deleting are one transaction with their
7+//! activity row; deleting also records the bytes in `blob_deletions` in that same transaction, so a crash
8+//! never loses the record of bytes that must go.
9+
10+use serde_json::json;
11+use turso::Connection;
12+
13+use super::activity::{self, NewActivity};
14+use super::{col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
15+use crate::authz::{Action, Actor, authorize};
16+use crate::error::{Error, Result};
17+use crate::limits::{
18+ ATTACHMENT_DEFAULT_MIB, ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN, FILE_NAME_MAX,
19+};
20+use crate::store::Store;
21+use crate::time::{now_stamp, stamp_after};
22+use std::time::Duration;
23+
24+/// The setting that holds the per-file limit, in MiB.
25+pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib";
26+/// The setting that holds the allowed extensions, separated by spaces or commas.
27+pub const SETTING_EXTENSIONS: &str = "attachment_extensions";
28+/// The extensions allowed when the setting is unset. Reason: office documents, images, audio, video, text.
29+pub const DEFAULT_EXTENSIONS: &[&str] = &[
30+ "pdf", "png", "jpg", "jpeg", "gif", "webp", "heic", "txt", "md", "csv", "xlsx", "ods", "pptx",
31+ "docx", "mp3", "m4a", "wav", "ogg", "mp4", "mov", "webm",
32+];
33+/// Longest extension accepted in the setting, in characters. Reason: an extension is a few letters.
34+const EXTENSION_MAX: usize = 12;
35+
36+/// The upload policy in force: the per-file limit and the allowed extensions.
37+#[derive(Debug, Clone, PartialEq, Eq)]
38+pub struct Policy {
39+ /// The largest file accepted, in bytes.
40+ pub limit_bytes: u64,
41+ /// Lowercase extensions without the dot.
42+ pub extensions: Vec<String>,
43+}
44+
45+/// One attachment as stored.
46+#[derive(Debug, Clone, PartialEq, Eq)]
47+pub struct Attachment {
48+ /// Attachment id (ULID). It names the bytes on the disk.
49+ pub id: String,
50+ /// The task it belongs to.
51+ pub task_id: String,
52+ /// The file name as the uploader gave it, without path components.
53+ pub name: String,
54+ /// The sniffed MIME type. Never the uploader's claim.
55+ pub mime: String,
56+ /// Length in bytes.
57+ pub size: u64,
58+ /// Lowercase hex SHA-256 of the bytes.
59+ pub sha256: String,
60+ /// The uploader's member id.
61+ pub uploaded_by: String,
62+ /// UTC stamp of the upload.
63+ pub created_at: String,
64+}
65+
66+/// What an upload stores. The task and the board are given separately, by the caller's checks.
67+#[derive(Debug, Clone, PartialEq, Eq)]
68+pub struct NewAttachment {
69+ /// The id, chosen before the bytes are moved, so the file name and the row agree.
70+ pub id: String,
71+ /// The cleaned file name (see [`clean_name`]).
72+ pub name: String,
73+ /// The sniffed MIME type.
74+ pub mime: String,
75+ /// Length in bytes.
76+ pub size: u64,
77+ /// Lowercase hex SHA-256 of the bytes.
78+ pub sha256: String,
79+ /// The uploader's member id.
80+ pub uploaded_by: String,
81+}
82+
83+/// Columns of an attachment, prefixed for the joins that filter by task.
84+const ATTACHMENT_COLS: &str =
85+ "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at";
86+
87+fn map_attachment(row: &turso::Row) -> Result<Attachment> {
88+ Ok(Attachment {
89+ id: col_text(row, 0)?,
90+ task_id: col_text(row, 1)?,
91+ name: col_text(row, 2)?,
92+ mime: col_text(row, 3)?,
93+ size: u64::try_from(col_int(row, 4)?).unwrap_or(0),
94+ sha256: col_text(row, 5)?,
95+ uploaded_by: col_text(row, 6)?,
96+ created_at: col_text(row, 7)?,
97+ })
98+}
99+
100+/// Checks a file name from a client and returns it cleaned. Only the last path component is kept, so
101+/// `../../etc/x` and `C:\\a\\b.png` both become a plain name. An empty name, a control character, or a name
102+/// longer than [`FILE_NAME_MAX`] bytes is refused.
103+pub fn clean_name(raw: &str) -> Result<String> {
104+ let last = raw.rsplit(['/', '\\']).next().unwrap_or("");
105+ let name = last.trim();
106+ if name.is_empty() || name == "." || name == ".." {
107+ return Err(Error::Invalid("name_empty".into()));
108+ }
109+ if name.chars().any(char::is_control) {
110+ return Err(Error::Invalid("name_invalid".into()));
111+ }
112+ if name.len() > FILE_NAME_MAX {
113+ return Err(Error::Invalid("name_long".into()));
114+ }
115+ Ok(name.to_owned())
116+}
117+
118+/// The extension of a clean name, lowercase, without the dot. `None` when there is none or it is not a
119+/// plain alphanumeric word.
120+pub fn extension_of(name: &str) -> Option<String> {
121+ let (_, ext) = name.rsplit_once('.')?;
122+ let ok = !ext.is_empty()
123+ && ext.len() <= EXTENSION_MAX
124+ && ext.bytes().all(|b| b.is_ascii_alphanumeric());
125+ ok.then(|| ext.to_ascii_lowercase())
126+}
127+
128+/// Whether `name` has an extension the policy allows.
129+pub fn extension_allowed(name: &str, policy: &Policy) -> bool {
130+ extension_of(name).is_some_and(|ext| policy.extensions.contains(&ext))
131+}
132+
133+/// Reads the extension list of the setting: words separated by spaces, commas or newlines. Each word is
134+/// lowercased, loses leading dots, and must be alphanumeric and short. Duplicates are dropped.
135+pub fn parse_extensions(text: &str) -> Vec<String> {
136+ let mut out: Vec<String> = Vec::new();
137+ for word in text.split(|c: char| c.is_whitespace() || c == ',') {
138+ let word = word.trim_start_matches('.').to_ascii_lowercase();
139+ let ok = !word.is_empty()
140+ && word.len() <= EXTENSION_MAX
141+ && word.bytes().all(|b| b.is_ascii_alphanumeric());
142+ if ok && !out.contains(&word) {
143+ out.push(word);
144+ }
145+ }
146+ out
147+}
148+
149+impl Store {
150+ /// The upload policy in force. A stored value outside its range, or a missing one, is the default.
151+ pub async fn policy(&self) -> Result<Policy> {
152+ let mib = self
153+ .get_setting(SETTING_LIMIT_MIB)
154+ .await?
155+ .and_then(|text| text.trim().parse::<u32>().ok())
156+ .filter(|mib| (ATTACHMENT_LIMIT_MIB_MIN..=ATTACHMENT_LIMIT_MIB_MAX).contains(mib))
157+ .unwrap_or(ATTACHMENT_DEFAULT_MIB);
158+ let extensions = match self.get_setting(SETTING_EXTENSIONS).await? {
159+ Some(text) => parse_extensions(&text),
160+ None => DEFAULT_EXTENSIONS
161+ .iter()
162+ .map(|ext| (*ext).to_owned())
163+ .collect(),
164+ };
165+ Ok(Policy {
166+ limit_bytes: u64::from(mib) * 1024 * 1024,
167+ extensions,
168+ })
169+ }
170+
171+ /// Stores an attachment on a live task of `board_id`, with its `file_added` activity row. The bytes must
172+ /// already be in place under `new.id`; if this fails, the caller removes them.
173+ pub async fn add_attachment(
174+ &self,
175+ board_id: &str,
176+ task_id: &str,
177+ new: NewAttachment,
178+ ) -> Result<Attachment> {
179+ let size = i64::try_from(new.size).map_err(|_| Error::Invalid("too_large".into()))?;
180+ let created_at = now_stamp();
181+ let attachment = Attachment {
182+ id: new.id.clone(),
183+ task_id: task_id.to_owned(),
184+ name: new.name.clone(),
185+ mime: new.mime.clone(),
186+ size: new.size,
187+ sha256: new.sha256.clone(),
188+ uploaded_by: new.uploaded_by.clone(),
189+ created_at: created_at.clone(),
190+ };
191+ let conn = self.inner.conn.lock().await;
192+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
193+ let outcome: Result<()> = async {
194+ let live = fetch_opt(
195+ &tx,
196+ "SELECT id FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL",
197+ (task_id.to_owned(), board_id.to_owned()),
198+ |row| col_text(row, 0),
199+ )
200+ .await?;
201+ if live.is_none() {
202+ return Err(Error::NotFound);
203+ }
204+ tx.execute(
205+ "INSERT INTO attachments (id, task_id, comment_id, name, mime, size, sha256, uploaded_by, created_at, location) \
206+ VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7, ?8, 'local')",
207+ (
208+ new.id.clone(),
209+ task_id.to_owned(),
210+ new.name,
211+ new.mime,
212+ size,
213+ new.sha256,
214+ new.uploaded_by.clone(),
215+ created_at,
216+ ),
217+ )
218+ .await
219+ .map_err(db_err)?;
220+ activity::record(
221+ &tx,
222+ NewActivity {
223+ task_id: Some(task_id),
224+ actor: Some(&new.uploaded_by),
225+ subject: None,
226+ kind: "file_added",
227+ detail: json!({ "attachment": new.id }),
228+ },
229+ )
230+ .await
231+ }
232+ .await;
233+ finish(tx, outcome.map(|()| attachment)).await
234+ }
235+
236+ /// The live attachments of a task of `board_id`, oldest first.
237+ pub async fn list_attachments(&self, board_id: &str, task_id: &str) -> Result<Vec<Attachment>> {
238+ let conn = self.read_conn().await;
239+ fetch_all(
240+ &conn,
241+ &format!(
242+ "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \
243+ WHERE a.task_id = ?1 AND t.board_id = ?2 AND t.deleted_at IS NULL ORDER BY a.created_at, a.id"
244+ ),
245+ (task_id.to_owned(), board_id.to_owned()),
246+ map_attachment,
247+ )
248+ .await
249+ }
250+
251+ /// An attachment by id, on a live task of `board_id`. Used by the byte route, which has no task key.
252+ pub async fn attachment_on_board(
253+ &self,
254+ board_id: &str,
255+ attachment_id: &str,
256+ ) -> Result<Attachment> {
257+ let conn = self.read_conn().await;
258+ fetch_opt(
259+ &conn,
260+ &format!(
261+ "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \
262+ WHERE a.id = ?1 AND t.board_id = ?2 AND t.deleted_at IS NULL"
263+ ),
264+ (attachment_id.to_owned(), board_id.to_owned()),
265+ map_attachment,
266+ )
267+ .await?
268+ .ok_or(Error::NotFound)
269+ }
270+
271+ /// An attachment by id, only when it belongs to the task with `task_key` on `board_id`. Any other
272+ /// combination is `NotFound`: the id of another task never resolves under this key.
273+ pub async fn attachment_of_task(
274+ &self,
275+ board_id: &str,
276+ task_key: &str,
277+ attachment_id: &str,
278+ ) -> Result<Attachment> {
279+ let conn = self.read_conn().await;
280+ fetch_opt(
281+ &conn,
282+ &format!(
283+ "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \
284+ WHERE a.id = ?1 AND t.key = ?2 AND t.board_id = ?3 AND t.deleted_at IS NULL"
285+ ),
286+ (
287+ attachment_id.to_owned(),
288+ task_key.to_owned(),
289+ board_id.to_owned(),
290+ ),
291+ map_attachment,
292+ )
293+ .await?
294+ .ok_or(Error::NotFound)
295+ }
296+
297+ /// Deletes an attachment's row, records its bytes for deletion, and writes its `file_deleted` activity
298+ /// row, all in one transaction. The uploader (while a member) or an admin may do it (`authz`). Returns the
299+ /// deleted attachment, so the caller can tell the task's viewers.
300+ pub async fn delete_attachment(
301+ &self,
302+ board_id: &str,
303+ attachment_id: &str,
304+ actor: &Actor,
305+ ) -> Result<Attachment> {
306+ let conn = self.inner.conn.lock().await;
307+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
308+ let outcome: Result<Attachment> = async {
309+ let current = live_attachment(&tx, board_id, attachment_id).await?;
310+ authorize(
311+ actor,
312+ &Action::DeleteFile {
313+ uploader: current.uploaded_by.clone(),
314+ },
315+ )?;
316+ let sub = match actor {
317+ Actor::Member { sub, .. } => sub.as_str(),
318+ Actor::Anonymous => return Err(Error::Forbidden("sign in to continue".into())),
319+ };
320+ let now = now_stamp();
321+ tx.execute(
322+ "DELETE FROM attachments WHERE id = ?1",
323+ (attachment_id.to_owned(),),
324+ )
325+ .await
326+ .map_err(db_err)?;
327+ tx.execute(
328+ "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \
329+ VALUES (?1, 'local', 0, ?2, ?3)",
330+ (attachment_id.to_owned(), now.clone(), now),
331+ )
332+ .await
333+ .map_err(db_err)?;
334+ activity::record(
335+ &tx,
336+ NewActivity {
337+ task_id: Some(&current.task_id),
338+ actor: Some(sub),
339+ subject: Some(&current.uploaded_by),
340+ kind: "file_deleted",
341+ detail: json!({ "attachment": attachment_id }),
342+ },
343+ )
344+ .await?;
345+ Ok(current)
346+ }
347+ .await;
348+ finish(tx, outcome).await
349+ }
350+
351+ /// Bytes owed to deletion whose next attempt is due, oldest first: `(attachment id, attempts so far)`.
352+ pub async fn due_blob_deletions(&self, limit: i64) -> Result<Vec<(String, i64)>> {
353+ let conn = self.read_conn().await;
354+ fetch_all(
355+ &conn,
356+ "SELECT attachment_id, attempts FROM blob_deletions WHERE next_attempt_at <= ?1 \
357+ ORDER BY next_attempt_at, attachment_id LIMIT ?2",
358+ (now_stamp(), limit),
359+ |row| Ok((col_text(row, 0)?, col_int(row, 1)?)),
360+ )
361+ .await
362+ }
363+
364+ /// Clears a deletion once its bytes are confirmed gone.
365+ pub async fn finish_blob_deletion(&self, attachment_id: &str) -> Result<()> {
366+ let conn = self.inner.conn.lock().await;
367+ conn.execute(
368+ "DELETE FROM blob_deletions WHERE attachment_id = ?1",
369+ (attachment_id.to_owned(),),
370+ )
371+ .await
372+ .map_err(db_err)?;
373+ Ok(())
374+ }
375+
376+ /// Records a failed attempt and sets the next one `delay` from now.
377+ pub async fn defer_blob_deletion(
378+ &self,
379+ attachment_id: &str,
380+ attempts: i64,
381+ delay: Duration,
382+ ) -> Result<()> {
383+ let conn = self.inner.conn.lock().await;
384+ conn.execute(
385+ "UPDATE blob_deletions SET attempts = ?2, next_attempt_at = ?3 WHERE attachment_id = ?1",
386+ (attachment_id.to_owned(), attempts + 1, stamp_after(delay)),
387+ )
388+ .await
389+ .map_err(db_err)?;
390+ Ok(())
391+ }
392+}
393+
394+/// A live attachment of a live task of `board_id`, read on the writer so it is part of the transaction.
395+async fn live_attachment(
396+ conn: &Connection,
397+ board_id: &str,
398+ attachment_id: &str,
399+) -> Result<Attachment> {
400+ fetch_opt(
401+ conn,
402+ &format!(
403+ "SELECT {ATTACHMENT_COLS} FROM attachments a JOIN tasks t ON t.id = a.task_id \
404+ WHERE a.id = ?1 AND t.board_id = ?2 AND t.deleted_at IS NULL"
405+ ),
406+ (attachment_id.to_owned(), board_id.to_owned()),
407+ map_attachment,
408+ )
409+ .await?
410+ .ok_or(Error::NotFound)
411+}
412+
413+/// A fresh attachment id: a ULID, as every row id is.
414+pub fn new_attachment_id() -> String {
415+ new_id()
416+}
417+
418+#[cfg(test)]
419+mod tests {
420+ use super::*;
421+
422+ #[test]
423+ fn a_path_is_reduced_to_its_last_component() {
424+ assert_eq!(clean_name("../../etc/a.png").expect("ok"), "a.png");
425+ assert_eq!(clean_name("C:\\users\\b.pdf").expect("ok"), "b.pdf");
426+ assert_eq!(clean_name(" note.txt ").expect("ok"), "note.txt");
427+ assert!(clean_name("dir/").is_err());
428+ assert!(clean_name("..").is_err());
429+ assert!(clean_name("a\r\nb.txt").is_err());
430+ assert!(clean_name(&format!("{}.txt", "x".repeat(FILE_NAME_MAX))).is_err());
431+ }
432+
433+ #[test]
434+ fn extensions_are_lowercase_and_plain() {
435+ assert_eq!(extension_of("Photo.JPG").as_deref(), Some("jpg"));
436+ assert_eq!(extension_of("noext"), None);
437+ assert_eq!(extension_of("bad.p ng"), None);
438+ assert_eq!(
439+ parse_extensions(".PDF, png\nxlsx pdf"),
440+ vec!["pdf", "png", "xlsx"]
441+ );
442+ assert_eq!(parse_extensions("tar.gz"), Vec::<String>::new());
443+ }
444+
445+ #[test]
446+ fn an_extension_must_be_on_the_allowlist() {
447+ let policy = Policy {
448+ limit_bytes: 1,
449+ extensions: vec!["png".into()],
450+ };
451+ assert!(extension_allowed("a.PNG", &policy));
452+ assert!(!extension_allowed("a.html", &policy));
453+ assert!(!extension_allowed("a", &policy));
454+ }
455+}
crates/iz-core/src/store/migrate.rsmodified+1 -0
@@ -14,6 +14,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
1414 2,
1515 include_str!("../../migrations/0002_session_id_token.sql"),
1616 ),
17+ (3, include_str!("../../migrations/0003_blob_deletions.sql")),
1718 ];
1819
1920 fn migration_err(e: turso::Error) -> Error {
crates/iz-core/src/store/mod.rsmodified+2 -1
@@ -8,6 +8,7 @@
88 //! SELECTs run in parallel with each other and with the writer.
99
1010 pub mod activity;
11+pub mod attachments;
1112 pub mod board;
1213 pub mod comments;
1314 pub mod members;
@@ -379,7 +380,7 @@ mod tests {
379380 })
380381 .await
381382 .unwrap();
382- assert_eq!(versions, vec![1, 2]);
383+ assert_eq!(versions, vec![1, 2, 3]);
383384 }
384385
385386 #[tokio::test]
crates/iz-web/Cargo.tomlmodified+4 -1
@@ -12,9 +12,12 @@ path = "src/main.rs"
1212
1313 [dependencies]
1414 base64.workspace = true
15+bytes.workspace = true
1516 futures-util.workspace = true
1617 hex.workspace = true
1718 http.workspace = true
19+http-body.workspace = true
20+http-body-util.workspace = true
1821 iz-core.workspace = true
1922 jiff.workspace = true
2023 jsonwebtoken.workspace = true
@@ -26,7 +29,7 @@ sha2.workspace = true
2629 subtle.workspace = true
2730 # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout
2831 # and the reconnect backoff, `fs` for the photo cache.
29-tokio = { workspace = true, features = ["fs", "net", "signal", "time"] }
32+tokio = { workspace = true, features = ["fs", "io-util", "net", "signal", "time"] }
3033 topcoat.workspace = true
3134 tracing.workspace = true
3235 thiserror.workspace = true
crates/iz-web/src/attachments.rsadded+90 -0
@@ -0,0 +1,90 @@
1+//! The attachments' disk work that runs outside a request: the deleter. A deleted attachment's row is gone at
2+//! once (the transaction in `iz-core` records the bytes in `blob_deletions`); this worker removes the bytes
3+//! afterwards and retries with a backoff until they are gone, then clears the record. It runs until the stop
4+//! flag is set, like every worker (`docs/architecture.md` section 8).
5+//!
6+//! The bytes are only ever removed through `iz_core::staging::remove_blob`, which builds the path from the
7+//! validated attachment id.
8+
9+use std::time::Duration;
10+
11+use iz_core::staging::remove_blob;
12+use tokio::sync::watch;
13+
14+use crate::state::AppState;
15+
16+/// The largest body of one upload request, in bytes. Reason: several files may come in one form, each up to the
17+/// per-file limit (at most 500 MiB), and this bounds the whole request.
18+pub const UPLOAD_REQUEST_MAX_BYTES: usize = 1024 * 1024 * 1024;
19+/// How often the deleter looks for due deletions. Reason: a deleted file should be gone within seconds.
20+const SWEEP_EVERY: Duration = Duration::from_secs(5);
21+/// Most deletions one sweep handles. Reason: bounds one sweep when many files are deleted at once.
22+const SWEEP_BATCH: i64 = 50;
23+/// The first retry delay, in seconds. Doubles with each failed attempt.
24+const RETRY_BASE_SECS: u64 = 5;
25+/// The longest retry delay, in seconds. Reason: a file that cannot be removed is looked at every ten minutes.
26+const RETRY_CAP_SECS: u64 = 600;
27+
28+/// The delay before the next attempt after `attempts` failures.
29+pub fn retry_delay(attempts: i64) -> Duration {
30+ let shift = u32::try_from(attempts.clamp(0, 16)).unwrap_or(0);
31+ Duration::from_secs((RETRY_BASE_SECS << shift).min(RETRY_CAP_SECS))
32+}
33+
34+/// Starts the deleter. It sweeps at once, then every [`SWEEP_EVERY`], until `stop` is set.
35+pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
36+ tokio::spawn(async move {
37+ loop {
38+ sweep(&state).await;
39+ tokio::select! {
40+ () = tokio::time::sleep(SWEEP_EVERY) => {}
41+ _ = stop.wait_for(|stopped| *stopped) => break,
42+ }
43+ }
44+ tracing::info!("attachment deleter stopped");
45+ });
46+}
47+
48+/// One pass over the due deletions. A failure is logged and retried later; it never stops the worker.
49+async fn sweep(state: &AppState) {
50+ let due = match state.store.due_blob_deletions(SWEEP_BATCH).await {
51+ Ok(due) => due,
52+ Err(error) => {
53+ tracing::warn!(error = %error, "reading the due attachment deletions failed");
54+ return;
55+ }
56+ };
57+ for (id, attempts) in due {
58+ match remove_blob(&state.config.data_dir, &id).await {
59+ Ok(()) => {
60+ if let Err(error) = state.store.finish_blob_deletion(&id).await {
61+ tracing::warn!(error = %error, "clearing a finished attachment deletion failed");
62+ }
63+ }
64+ Err(error) => {
65+ tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying");
66+ if let Err(error) = state
67+ .store
68+ .defer_blob_deletion(&id, attempts, retry_delay(attempts))
69+ .await
70+ {
71+ tracing::warn!(error = %error, "scheduling an attachment deletion retry failed");
72+ }
73+ }
74+ }
75+ }
76+}
77+
78+#[cfg(test)]
79+mod tests {
80+ use super::*;
81+
82+ #[test]
83+ fn the_retry_backoff_doubles_and_is_capped() {
84+ assert_eq!(retry_delay(0), Duration::from_secs(5));
85+ assert_eq!(retry_delay(1), Duration::from_secs(10));
86+ assert_eq!(retry_delay(3), Duration::from_secs(40));
87+ assert_eq!(retry_delay(40), Duration::from_secs(600));
88+ assert_eq!(retry_delay(-3), Duration::from_secs(5));
89+ }
90+}
crates/iz-web/src/boot.rsmodified+4 -1
@@ -16,8 +16,9 @@ use tokio::net::TcpListener;
1616 use tokio::signal::unix::{SignalKind, signal};
1717 use tokio::sync::watch;
1818 use topcoat::cookie::RouterBuilderCookieExt;
19-use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService};
19+use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService};
2020
21+use crate::attachments;
2122 use crate::directory;
2223 use crate::live::LiveHub;
2324 use crate::oidc;
@@ -49,6 +50,7 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> {
4950 // One stop flag. The signal task sets it; the mirror worker and the server both watch it.
5051 let (stop_tx, stop_rx) = watch::channel(false);
5152 directory::spawn(state.clone(), stop_rx.clone());
53+ attachments::spawn(state.clone(), stop_rx.clone());
5254 tokio::spawn(async move {
5355 shutdown_signal().await;
5456 tracing::info!("shutdown signal received");
@@ -113,6 +115,7 @@ pub fn router(state: AppState) -> Router {
113115 .cookies()
114116 .layer(security)
115117 .layer(NotFoundLayer)
118+ .layer(BodyLimit::max(attachments::UPLOAD_REQUEST_MAX_BYTES).at("/tasks/{id}/files"))
116119 .build()
117120 }
118121
crates/iz-web/src/i18n/task.rsmodified+84 -0
@@ -185,6 +185,48 @@ pub enum K {
185185 ErrOtherTask,
186186 /// Refused: the picked direction is not one of the two.
187187 ErrDirection,
188+ /// The heading of the files section.
189+ Files,
190+ /// The text when the task has no files.
191+ NoFiles,
192+ /// The button that uploads the chosen files.
193+ UploadFiles,
194+ /// The label of the file input.
195+ ChooseFiles,
196+ /// The link that opens a file in the viewer.
197+ ViewFile,
198+ /// The link that saves a file.
199+ DownloadFile,
200+ /// The button that deletes a file.
201+ DeleteFile,
202+ /// Refused: a file is larger than the attachment limit.
203+ ErrFileTooLarge,
204+ /// Refused: the extension of a file is not allowed.
205+ ErrFileType,
206+ /// Refused: a file name is empty or not valid.
207+ ErrFileName,
208+ /// Refused: the upload had no file.
209+ ErrNoFile,
210+ /// Refused: the upload has more files than one request may carry.
211+ ErrTooManyFiles,
212+ /// Refused: the file could not be stored; nothing was kept.
213+ ErrFileStore,
214+ /// The viewer message for a file that cannot be previewed (refused, or too large to read).
215+ ViewerRefused,
216+ /// The viewer message for a type with no preview.
217+ NoPreview,
218+ /// The viewer message when a text file was cut to its first part.
219+ ViewerTruncated,
220+ /// The viewer message when a sheet was cut to its first rows and columns.
221+ ViewerCut,
222+ /// The heading of the sheet tabs.
223+ Sheets,
224+ /// The label of a slide, before its number.
225+ SlideLabel,
226+ /// The text of a slide with no text.
227+ NoSlideText,
228+ /// The text of a sheet with no rows.
229+ EmptySheet,
188230 }
189231
190232 /// The text of `key` in `lang`.
@@ -390,6 +432,48 @@ pub fn t(lang: Lang, key: K) -> &'static str {
390432 (K::ErrOtherTask, Lang::Tr) => "Listeden bir görev seçin.",
391433 (K::ErrDirection, Lang::En) => "Pick one of the two directions.",
392434 (K::ErrDirection, Lang::Tr) => "İki yönden birini seçin.",
435+ (K::Files, Lang::En) => "Files",
436+ (K::Files, Lang::Tr) => "Dosyalar",
437+ (K::NoFiles, Lang::En) => "No files yet.",
438+ (K::NoFiles, Lang::Tr) => "Henüz dosya yok.",
439+ (K::UploadFiles, Lang::En) => "Upload",
440+ (K::UploadFiles, Lang::Tr) => "Yükle",
441+ (K::ChooseFiles, Lang::En) => "Choose files",
442+ (K::ChooseFiles, Lang::Tr) => "Dosya seç",
443+ (K::ViewFile, Lang::En) => "View",
444+ (K::ViewFile, Lang::Tr) => "Görüntüle",
445+ (K::DownloadFile, Lang::En) => "Download",
446+ (K::DownloadFile, Lang::Tr) => "İndir",
447+ (K::DeleteFile, Lang::En) => "Delete",
448+ (K::DeleteFile, Lang::Tr) => "Sil",
449+ (K::ErrFileTooLarge, Lang::En) => "The file is larger than the attachment limit.",
450+ (K::ErrFileTooLarge, Lang::Tr) => "Dosya ek boyut sınırından büyük.",
451+ (K::ErrFileType, Lang::En) => "This file type is not allowed.",
452+ (K::ErrFileType, Lang::Tr) => "Bu dosya türüne izin verilmiyor.",
453+ (K::ErrFileName, Lang::En) => "The file name is not valid.",
454+ (K::ErrFileName, Lang::Tr) => "Dosya adı geçerli değil.",
455+ (K::ErrNoFile, Lang::En) => "Choose a file first.",
456+ (K::ErrNoFile, Lang::Tr) => "Önce bir dosya seçin.",
457+ (K::ErrTooManyFiles, Lang::En) => "Upload fewer files at once.",
458+ (K::ErrTooManyFiles, Lang::Tr) => "Bir seferde daha az dosya yükleyin.",
459+ (K::ErrFileStore, Lang::En) => "The file could not be saved. Try again.",
460+ (K::ErrFileStore, Lang::Tr) => "Dosya kaydedilemedi. Tekrar deneyin.",
461+ (K::ViewerRefused, Lang::En) => "This file cannot be previewed. Download it to open it.",
462+ (K::ViewerRefused, Lang::Tr) => "Bu dosya önizlenemiyor. Açmak için indirin.",
463+ (K::NoPreview, Lang::En) => "No preview for this type. Download it to open it.",
464+ (K::NoPreview, Lang::Tr) => "Bu tür için önizleme yok. Açmak için indirin.",
465+ (K::ViewerTruncated, Lang::En) => "Showing the first part of the file.",
466+ (K::ViewerTruncated, Lang::Tr) => "Dosyanın ilk kısmı gösteriliyor.",
467+ (K::ViewerCut, Lang::En) => "Showing the first rows and columns only.",
468+ (K::ViewerCut, Lang::Tr) => "Yalnızca ilk satırlar ve sütunlar gösteriliyor.",
469+ (K::Sheets, Lang::En) => "Sheets",
470+ (K::Sheets, Lang::Tr) => "Sayfalar",
471+ (K::SlideLabel, Lang::En) => "Slide",
472+ (K::SlideLabel, Lang::Tr) => "Slayt",
473+ (K::NoSlideText, Lang::En) => "This slide has no text.",
474+ (K::NoSlideText, Lang::Tr) => "Bu slaytta metin yok.",
475+ (K::EmptySheet, Lang::En) => "This sheet is empty.",
476+ (K::EmptySheet, Lang::Tr) => "Bu sayfa boş.",
393477 }
394478 }
395479
crates/iz-web/src/main.rsmodified+5 -0
@@ -4,7 +4,11 @@
44 //! operator command line, which is not built yet. The configuration file is the `--config` path,
55 //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error.
66
7+// The page handlers nest many view and store futures; the default limit is too small for their types.
8+#![recursion_limit = "256"]
9+
710 mod assets;
11+mod attachments;
812 mod auth;
913 mod boot;
1014 mod directory;
@@ -14,6 +18,7 @@ mod live;
1418 mod oidc;
1519 mod pages;
1620 mod security;
21+mod serve;
1722 mod state;
1823 mod views;
1924
crates/iz-web/src/pages/board.rsmodified+17 -0
@@ -314,6 +314,23 @@ async fn board_page(cx: &Cx) -> Result<Response> {
314314 if !found {
315315 page.alert = Some(K::TaskNotFound);
316316 status = Some(StatusCode::NOT_FOUND);
317+ } else if let Some(file) = query_param(cx, "file").filter(|value| !value.is_empty()) {
318+ let sheet = query_param(cx, "sheet")
319+ .and_then(|value| value.parse::<usize>().ok())
320+ .unwrap_or(0);
321+ let shown = crate::pages::files::open_in_modal(
322+ state,
323+ &mut page,
324+ &key,
325+ &file,
326+ sheet,
327+ query.as_deref(),
328+ )
329+ .await?;
330+ if !shown {
331+ page.alert = Some(K::TaskNotFound);
332+ status = Some(StatusCode::NOT_FOUND);
333+ }
317334 }
318335 }
319336 None => {
crates/iz-web/src/pages/files.rsadded+921 -0
@@ -0,0 +1,921 @@
1+//! Attachments on a task (`docs/architecture.md` sections 4 and 7): the upload, the delete, the bytes of a
2+//! file, the viewer page, and the viewer that the task modal shows for `?file=`.
3+//!
4+//! Every route reaches a file through its task. The bytes are read only for an attachment whose task is live
5+//! and on this board; the viewer page also needs the task key in the URL to match, so the id of a file on
6+//! another task is `404` (attack plan section 6: cross-task IDOR). Writes check the CSRF token before any side
7+//! effect: the upload form carries `csrf` as its first field, so the token is read before any file part is
8+//! stored. A viewer gets `403` for every write.
9+//!
10+//! Uploads stream. Each file part is written to `data_dir/tmp` with the per-file limit enforced while the bytes
11+//! arrive, hashed while it streams, and sniffed from its first kilobytes. The name and the extension are checked
12+//! before any byte is read. Only then is the file moved to `data_dir/attachments/<id>` and its row inserted; if
13+//! the insert fails the moved file is removed, so no bytes are left without a row.
14+//!
15+//! Viewers never execute what they show. Images, media and PDF are shown by the browser from the byte route
16+//! (which sends them with the sandbox policy); text is escaped; sheets and slides are parsed into plain values
17+//! after the zip guards of `iz-core` and rendered as escaped cells and paragraphs.
18+
19+use iz_core::authz::{Action, authorize};
20+use iz_core::limits::{SNIFF_BYTES, TEXT_PREVIEW_BYTES, UPLOAD_FILES_MAX};
21+use iz_core::preview::read_text_head;
22+use iz_core::sheet::{Book, read_csv, read_workbook};
23+use iz_core::slides::{Slide, read_deck};
24+use iz_core::sniff::sniff;
25+use iz_core::staging::{StagedFile, blob_path, install_blob, remove_blob};
26+use iz_core::store::attachments::{
27+ Attachment, NewAttachment, Policy, clean_name, extension_allowed, extension_of,
28+ new_attachment_id,
29+};
30+use jiff::tz::TimeZone;
31+use serde::Deserialize;
32+use std::collections::HashMap;
33+use topcoat::Result;
34+use topcoat::context::{Cx, app_context};
35+use topcoat::router::content::Form;
36+use topcoat::router::content::multipart::{Field, Multipart};
37+use topcoat::router::error::{forbidden, see_other};
38+use topcoat::router::response::Response;
39+use topcoat::router::{path_param_segment, route};
40+use topcoat::view::view;
41+
42+use crate::auth::{
43+ CurrentMember, Need, percent_encode, query_param, require_csrf, require_role, safe_next,
44+};
45+use crate::i18n::lang;
46+use crate::i18n::task::{K, t};
47+use crate::pages::board::{BoardPage, the_board};
48+use crate::pages::task::{Draft, FileRow, back, bump, core_err, local_text, modal_url, refuse};
49+use crate::serve::{ByteAnswer, ByteSource, Disposition, inline_safe, serve_file};
50+use crate::state::AppState;
51+use crate::views::files::file_page;
52+use crate::views::{ViewerInfo, respond, shell};
53+
54+/// Longest text field of the upload form (the csrf token, the return path), in bytes.
55+const FIELD_MAX_BYTES: usize = 2048;
56+/// The MIME types of the spreadsheets and the decks the viewers read.
57+const XLSX: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
58+/// See [`XLSX`].
59+const ODS: &str = "application/vnd.oasis.opendocument.spreadsheet";
60+/// See [`XLSX`].
61+const PPTX: &str = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
62+
63+/// What a file is shown as. Decided from the sniffed type, and from the name for CSV and plain text.
64+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65+pub enum Kind {
66+ /// A picture the browser shows (not SVG, not HEIC).
67+ Image,
68+ /// A video the browser plays.
69+ Video,
70+ /// An audio file the browser plays.
71+ Audio,
72+ /// A PDF, shown in a frame by the browser.
73+ Pdf,
74+ /// Plain text, escaped, cut to the preview size.
75+ Text,
76+ /// An `.xlsx` or `.ods` workbook, read as values.
77+ Workbook,
78+ /// A CSV file, read as one sheet.
79+ Csv,
80+ /// A `.pptx` deck, read as the text of each slide.
81+ Deck,
82+ /// No preview: the file can only be downloaded.
83+ Nothing,
84+}
85+
86+/// The kind of an attachment. Sheets and decks are matched by their sniffed container type; a CSV or a text
87+/// file is matched by its name, since the sniffer calls both plain text. The sniffed type may be `text/html`
88+/// for those (a CSV cell that holds markup): such a file is still never served inline, and its preview is escaped.
89+pub fn kind_of(attachment: &Attachment) -> Kind {
90+ let essence = attachment
91+ .mime
92+ .split(';')
93+ .next()
94+ .unwrap_or_default()
95+ .trim()
96+ .to_ascii_lowercase();
97+ match essence.as_str() {
98+ XLSX | ODS => return Kind::Workbook,
99+ PPTX => return Kind::Deck,
100+ _ => {}
101+ }
102+ let ext = extension_of(&attachment.name);
103+ let text_like = essence == "text/plain" || essence == "text/html";
104+ if text_like && ext.as_deref() == Some("csv") {
105+ return Kind::Csv;
106+ }
107+ if essence == "text/html" && matches!(ext.as_deref(), Some("txt" | "md")) {
108+ return Kind::Text;
109+ }
110+ if !inline_safe(&attachment.mime) {
111+ return Kind::Nothing;
112+ }
113+ if essence.starts_with("image/") {
114+ Kind::Image
115+ } else if essence.starts_with("video/") {
116+ Kind::Video
117+ } else if essence.starts_with("audio/") {
118+ Kind::Audio
119+ } else if essence == "application/pdf" {
120+ Kind::Pdf
121+ } else if essence == "text/plain" {
122+ Kind::Text
123+ } else {
124+ Kind::Nothing
125+ }
126+}
127+
128+/// A size as a person reads it: bytes, kilobytes or megabytes.
129+pub fn size_text(bytes: u64) -> String {
130+ if bytes < 1024 {
131+ format!("{bytes} B")
132+ } else if bytes < 1024 * 1024 {
133+ format!("{:.1} KB", bytes as f64 / 1024.0)
134+ } else {
135+ format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
136+ }
137+}
138+
139+/// The URL of tab `index` of a viewer whose own URL is `base`.
140+fn tab_url(base: &str, index: usize) -> String {
141+ let separator = if base.contains('?') { '&' } else { '?' };
142+ format!("{base}{separator}sheet={index}")
143+}
144+
145+/// One sheet tab of a workbook viewer.
146+pub struct SheetTab {
147+ /// The sheet's name.
148+ pub label: String,
149+ /// The URL that shows this sheet.
150+ pub url: String,
151+ /// Whether this is the sheet shown.
152+ pub active: bool,
153+}
154+
155+/// What the viewer shows for one file.
156+pub enum ViewBody {
157+ /// The browser shows the picture from the byte route.
158+ Image,
159+ /// The browser plays the video from the byte route.
160+ Video,
161+ /// The browser plays the audio from the byte route.
162+ Audio,
163+ /// The browser shows the PDF in a frame from the byte route.
164+ Pdf,
165+ /// The first part of a text file.
166+ Text {
167+ /// The text, shown escaped.
168+ text: String,
169+ /// Whether the file was longer than the preview.
170+ cut: bool,
171+ },
172+ /// The rows of one sheet, with the tabs of the book.
173+ Sheets {
174+ /// Every sheet of the book (up to the cap), as tabs.
175+ tabs: Vec<SheetTab>,
176+ /// The cells of the shown sheet, each cell escaped by the page.
177+ rows: Vec<Vec<String>>,
178+ /// Whether the sheet had more rows than the cap.
179+ cut: bool,
180+ },
181+ /// The text of each slide, in order.
182+ Slides(Vec<Slide>),
183+ /// The file could not be read as its kind (corrupt, refused by the zip guards, or too large).
184+ Refused,
185+ /// There is no preview for this type.
186+ Nothing,
187+}
188+
189+/// A file as the viewer shows it: its details, its links, and what it shows.
190+pub struct FileView {
191+ /// The file name as uploaded (shown escaped).
192+ pub name: String,
193+ /// The size, as text.
194+ pub size_text: String,
195+ /// The URL that saves the file.
196+ pub download_url: String,
197+ /// The URL the browser shows the bytes from.
198+ pub inline_url: String,
199+ /// What the viewer shows.
200+ pub body: ViewBody,
201+}
202+
203+/// Reads the body of a file for the viewer. Blocking parsers run on the blocking pool. A parser refusal is not an
204+/// error for the page: the viewer says it cannot show the file.
205+pub async fn load_view(
206+ state: &AppState,
207+ attachment: &Attachment,
208+ base: &str,
209+ sheet: usize,
210+) -> Result<FileView> {
211+ let path = blob_path(&state.config.data_dir, &attachment.id)?;
212+ let kind = kind_of(attachment);
213+ let body = match kind {
214+ Kind::Image => ViewBody::Image,
215+ Kind::Video => ViewBody::Video,
216+ Kind::Audio => ViewBody::Audio,
217+ Kind::Pdf => ViewBody::Pdf,
218+ Kind::Nothing => ViewBody::Nothing,
219+ Kind::Text => match blocking(move || read_text_head(&path, TEXT_PREVIEW_BYTES)).await {
220+ Some((text, cut)) => ViewBody::Text { text, cut },
221+ None => ViewBody::Refused,
222+ },
223+ Kind::Workbook => match blocking(move || read_workbook(&path)).await {
224+ Some(book) => sheets_body(book, base, sheet),
225+ None => ViewBody::Refused,
226+ },
227+ Kind::Csv => {
228+ let name = attachment.name.clone();
229+ match blocking(move || read_csv(&path, &name)).await {
230+ Some(book) => sheets_body(book, base, sheet),
231+ None => ViewBody::Refused,
232+ }
233+ }
234+ Kind::Deck => match blocking(move || read_deck(&path)).await {
235+ Some(slides) => ViewBody::Slides(slides),
236+ None => ViewBody::Refused,
237+ },
238+ };
239+ Ok(FileView {
240+ name: attachment.name.clone(),
241+ size_text: size_text(attachment.size),
242+ download_url: format!("/files/{}?dl=1", attachment.id),
243+ inline_url: format!("/files/{}", attachment.id),
244+ body,
245+ })
246+}
247+
248+/// Runs a parser on the blocking pool. `None` when it failed or the pool was gone; the parser's error text is not
249+/// shown, because the page says the same thing for every refusal.
250+async fn blocking<T, E, F>(work: F) -> Option<T>
251+where
252+ E: Send + 'static,
253+ F: FnOnce() -> std::result::Result<T, E> + Send + 'static,
254+ T: Send + 'static,
255+{
256+ tokio::task::spawn_blocking(move || work().map_err(drop))
257+ .await
258+ .ok()?
259+ .ok()
260+}
261+
262+/// The sheet viewer body for `book`: the tabs, and the rows of the sheet `sheet` (the first when out of range).
263+fn sheets_body(book: Book, base: &str, sheet: usize) -> ViewBody {
264+ let selected = if sheet < book.sheets.len() { sheet } else { 0 };
265+ let tabs = book
266+ .sheets
267+ .iter()
268+ .enumerate()
269+ .map(|(index, shown)| SheetTab {
270+ label: shown.name.clone(),
271+ url: tab_url(base, index),
272+ active: index == selected,
273+ })
274+ .collect();
275+ match book.sheets.into_iter().nth(selected) {
276+ Some(shown) => ViewBody::Sheets {
277+ tabs,
278+ rows: shown.rows,
279+ cut: shown.rows_cut,
280+ },
281+ None => ViewBody::Sheets {
282+ tabs,
283+ rows: Vec::new(),
284+ cut: false,
285+ },
286+ }
287+}
288+
289+/// The viewer's file rows for the task modal: one per attachment, with the rights of the viewer over it.
290+pub fn file_rows(
291+ files: &[Attachment],
292+ key: &str,
293+ query: Option<&str>,
294+ me: &CurrentMember,
295+ can_write: bool,
296+ names: &HashMap<String, String>,
297+ zone: &TimeZone,
298+) -> Vec<FileRow> {
299+ files
300+ .iter()
301+ .map(|file| {
302+ let uploader = names
303+ .get(&file.uploaded_by)
304+ .cloned()
305+ .unwrap_or_else(|| "-".to_owned());
306+ let can_delete = can_write
307+ && authorize(
308+ &me.actor(),
309+ &Action::DeleteFile {
310+ uploader: file.uploaded_by.clone(),
311+ },
312+ )
313+ .is_ok();
314+ FileRow {
315+ name: file.name.clone(),
316+ size: size_text(file.size),
317+ uploader,
318+ when: local_text(&file.created_at, zone),
319+ viewable: kind_of(file) != Kind::Nothing,
320+ view_url: modal_url(query, key, &[("file", file.id.as_str())]),
321+ download_url: format!("/files/{}?dl=1", file.id),
322+ delete_action: format!("/files/{}/delete", file.id),
323+ can_delete,
324+ }
325+ })
326+ .collect()
327+}
328+
329+/// Shows the viewer of file `id` inside the open task modal. Returns `false` when the file is not on this task.
330+pub async fn open_in_modal(
331+ state: &AppState,
332+ page: &mut BoardPage,
333+ key: &str,
334+ id: &str,
335+ sheet: usize,
336+ query: Option<&str>,
337+) -> Result<bool> {
338+ let board = the_board(&state.store).await?;
339+ let attachment = match state.store.attachment_of_task(&board.id, key, id).await {
340+ Ok(attachment) => attachment,
341+ Err(iz_core::Error::NotFound) => return Ok(false),
342+ Err(error) => return Err(core_err(error)),
343+ };
344+ let base = modal_url(query, key, &[("file", id)]);
345+ let view = load_view(state, &attachment, &base, sheet).await?;
346+ if let Some(modal) = page.modal.as_mut() {
347+ modal.viewer = Some(view);
348+ }
349+ Ok(true)
350+}
351+
352+/// Reads a short text field. Longer than [`FIELD_MAX_BYTES`] is a bad request.
353+async fn read_text(field: &mut Field<'_>) -> Result<String> {
354+ let mut bytes = Vec::new();
355+ while let Some(chunk) = field.chunk().await? {
356+ if bytes.len() + chunk.len() > FIELD_MAX_BYTES {
357+ return Err(topcoat::router::error::bad_request("field too long").into());
358+ }
359+ bytes.extend_from_slice(&chunk);
360+ }
361+ String::from_utf8(bytes)
362+ .map_err(|_| topcoat::router::error::bad_request("field is not UTF-8").into())
363+}
364+
365+/// Why one file of an upload was not kept. Each one has a message in the task's language.
366+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367+enum Refusal {
368+ /// The name is empty, has control characters, or is too long.
369+ Name,
370+ /// The extension is not on the allowlist.
371+ Type,
372+ /// The file is larger than the limit.
373+ TooLarge,
374+ /// Too many file parts in one request.
375+ TooMany,
376+ /// The request had no file.
377+ NoFile,
378+ /// The bytes could not be stored.
379+ Store,
380+}
381+
382+/// The message of a refusal.
383+fn refusal_key(refusal: Refusal) -> K {
384+ match refusal {
385+ Refusal::Name => K::ErrFileName,
386+ Refusal::Type => K::ErrFileType,
387+ Refusal::TooLarge => K::ErrFileTooLarge,
388+ Refusal::TooMany => K::ErrTooManyFiles,
389+ Refusal::NoFile => K::ErrNoFile,
390+ Refusal::Store => K::ErrFileStore,
391+ }
392+}
393+
394+/// Streams one file part into a stored attachment. `Ok(Err(refusal))` is a refusal the person can read; `Err` is a
395+/// server failure. Nothing is left behind on any path.
396+async fn store_one(
397+ state: &AppState,
398+ me: &CurrentMember,
399+ board_id: &str,
400+ task_id: &str,
401+ raw_name: &str,
402+ field: &mut Field<'_>,
403+ policy: &Policy,
404+) -> Result<std::result::Result<(), Refusal>> {
405+ let Ok(name) = clean_name(raw_name) else {
406+ return Ok(Err(Refusal::Name));
407+ };
408+ if !extension_allowed(&name, policy) {
409+ return Ok(Err(Refusal::Type));
410+ }
411+ let data_dir = state.config.data_dir.as_path();
412+ let mut staged = StagedFile::create(data_dir, policy.limit_bytes).await?;
413+ let mut prefix: Vec<u8> = Vec::with_capacity(SNIFF_BYTES);
414+ loop {
415+ let chunk = match field.chunk().await {
416+ Ok(Some(chunk)) => chunk,
417+ Ok(None) => break,
418+ Err(error) => {
419+ staged.abort().await;
420+ return Err(error);
421+ }
422+ };
423+ if prefix.len() < SNIFF_BYTES {
424+ let take = (SNIFF_BYTES - prefix.len()).min(chunk.len());
425+ prefix.extend_from_slice(&chunk[..take]);
426+ }
427+ if let Err(error) = staged.write(&chunk).await {
428+ let too_large = matches!(&error, iz_core::Error::Invalid(code) if code == "too_large");
429+ staged.abort().await;
430+ return if too_large {
431+ Ok(Err(Refusal::TooLarge))
432+ } else {
433+ Err(error.into())
434+ };
435+ }
436+ }
437+ let done = match staged.finish().await {
438+ Ok(done) => done,
439+ Err(error) => return Err(error.into()),
440+ };
441+ let id = new_attachment_id();
442+ if let Err(error) = install_blob(data_dir, &id, &done.path).await {
443+ let _ = tokio::fs::remove_file(&done.path).await;
444+ tracing::error!(error = %error, "moving an upload into place failed");
445+ return Ok(Err(Refusal::Store));
446+ }
447+ let new = NewAttachment {
448+ id: id.clone(),
449+ name,
450+ mime: sniff(&prefix),
451+ size: done.size,
452+ sha256: done.sha256,
453+ uploaded_by: me.member.sub.clone(),
454+ };
455+ match state.store.add_attachment(board_id, task_id, new).await {
456+ Ok(_) => Ok(Ok(())),
457+ Err(error) => {
458+ // No row names these bytes now, so they go.
459+ if let Err(remove) = remove_blob(data_dir, &id).await {
460+ tracing::error!(error = %remove, "removing bytes of a refused upload failed");
461+ }
462+ Err(core_err(error))
463+ }
464+ }
465+}
466+
467+/// `POST /tasks/{id}/files`: the upload. The first field is `csrf` (checked before any file is read), then
468+/// `next` (the modal's own URL), then one or more `files` parts. An empty file input is skipped.
469+#[route(POST "/tasks/{id}/files")]
470+async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> {
471+ let state = app_context::<AppState>(cx);
472+ let task_id = path_param_segment(cx, "id").to_owned();
473+ let mut member: Option<CurrentMember> = None;
474+ let mut board_id = String::new();
475+ let mut key = String::new();
476+ let mut next = String::new();
477+ let mut policy: Option<Policy> = None;
478+ let mut seen = 0usize;
479+ let mut saved = 0usize;
480+ let mut refusal: Option<Refusal> = None;
481+ while let Some(mut field) = multipart.next_field().await? {
482+ match field.name().unwrap_or_default().to_owned().as_str() {
483+ "csrf" => {
484+ let token = read_text(&mut field).await?;
485+ let me = require_csrf(cx, Need::Member, &token).await?;
486+ let board = the_board(&state.store).await?;
487+ let detail = state
488+ .store
489+ .task_detail(&board.id, &task_id)
490+ .await
491+ .map_err(core_err)?;
492+ key = detail.task.key.clone();
493+ board_id = board.id;
494+ policy = Some(state.store.policy().await.map_err(core_err)?);
495+ member = Some(me);
496+ }
497+ "next" => next = read_text(&mut field).await?,
498+ "files" => {
499+ let Some(me) = member.as_ref() else {
500+ return Err(forbidden().into());
501+ };
502+ let raw_name = field.file_name().unwrap_or_default().to_owned();
503+ if raw_name.is_empty() {
504+ continue;
505+ }
506+ seen += 1;
507+ if seen > UPLOAD_FILES_MAX {
508+ refusal = Some(Refusal::TooMany);
509+ break;
510+ }
511+ let Some(policy) = policy.as_ref() else {
512+ return Err(forbidden().into());
513+ };
514+ match store_one(
515+ state, me, &board_id, &task_id, &raw_name, &mut field, policy,
516+ )
517+ .await?
518+ {
519+ Ok(()) => saved += 1,
520+ Err(reason) => {
521+ refusal = Some(reason);
522+ break;
523+ }
524+ }
525+ }
526+ _ => {}
527+ }
528+ }
529+ let Some(me) = member else {
530+ return Err(forbidden().into());
531+ };
532+ if saved > 0 {
533+ bump(state, &board_id, &task_id);
534+ }
535+ let language = lang(cx, me.member.locale_override.as_deref());
536+ let reason = match (refusal, saved) {
537+ (Some(reason), _) => Some(reason),
538+ (None, 0) => Some(Refusal::NoFile),
539+ (None, _) => None,
540+ };
541+ match reason {
542+ Some(reason) => {
543+ let draft = Draft {
544+ error: Some(t(language, refusal_key(reason))),
545+ ..Draft::default()
546+ };
547+ refuse(cx, &me, language, &next, &key, draft).await
548+ }
549+ None => back(&next, Some(key.as_str())),
550+ }
551+}
552+
553+/// The form of `POST /files/{id}/delete`.
554+#[derive(Deserialize, Default)]
555+struct DeleteForm {
556+ #[serde(default)]
557+ csrf: String,
558+ /// The modal URL the form was on.
559+ #[serde(default)]
560+ next: String,
561+}
562+
563+/// `POST /files/{id}/delete`: deletes an attachment. Its uploader (while a member) or an admin may. The row goes
564+/// in one transaction that records the bytes for deletion; the deleter removes the bytes afterwards.
565+#[route(POST "/files/{id}/delete")]
566+async fn delete_file(cx: &Cx, form: Option<Form<DeleteForm>>) -> Result<Response> {
567+ let state = app_context::<AppState>(cx);
568+ let form = form.map(|Form(form)| form).unwrap_or_default();
569+ let id = path_param_segment(cx, "id").to_owned();
570+ let me = require_csrf(cx, Need::Member, &form.csrf).await?;
571+ let board = the_board(&state.store).await?;
572+ let removed = state
573+ .store
574+ .delete_attachment(&board.id, &id, &me.actor())
575+ .await
576+ .map_err(core_err)?;
577+ bump(state, &board.id, &removed.task_id);
578+ Err(see_other(safe_next(Some(&form.next))).into())
579+}
580+
581+/// `GET /files/{id}`: the bytes of a file, through the byte rules: shown when the type allows it, saved as a file
582+/// otherwise and always with `?dl=1`.
583+#[route(GET "/files/{id}")]
584+async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> {
585+ let state = app_context::<AppState>(cx);
586+ require_role(cx, Need::Viewer).await?;
587+ let id = path_param_segment(cx, "id").to_owned();
588+ let board = the_board(&state.store).await?;
589+ let attachment = state
590+ .store
591+ .attachment_on_board(&board.id, &id)
592+ .await
593+ .map_err(core_err)?;
594+ let download = query_param(cx, "dl").is_some_and(|value| value == "1");
595+ let path = blob_path(&state.config.data_dir, &attachment.id)?;
596+ let source = ByteSource {
597+ path: &path,
598+ size: attachment.size,
599+ sha256: &attachment.sha256,
600+ mime: &attachment.mime,
601+ name: &attachment.name,
602+ };
603+ let disposition = if download {
604+ Disposition::Attachment
605+ } else {
606+ Disposition::Inline
607+ };
608+ serve_file(cx, &source, disposition).await
609+}
610+
611+/// The viewer's own page, `GET /tasks/{key}/files/{id}/view`. The file must belong to the task with `key`.
612+#[route(GET "/tasks/{key}/files/{id}/view")]
613+async fn viewer_page(cx: &Cx) -> Result<Response> {
614+ let state = app_context::<AppState>(cx);
615+ let me = require_role(cx, Need::Viewer).await?;
616+ let key = path_param_segment(cx, "key").to_owned();
617+ let id = path_param_segment(cx, "id").to_owned();
618+ let board = the_board(&state.store).await?;
619+ let attachment = state
620+ .store
621+ .attachment_of_task(&board.id, &key, &id)
622+ .await
623+ .map_err(core_err)?;
624+ let language = lang(cx, me.member.locale_override.as_deref());
625+ let sheet = query_param(cx, "sheet")
626+ .and_then(|value| value.parse::<usize>().ok())
627+ .unwrap_or(0);
628+ let base = format!(
629+ "/tasks/{}/files/{}/view",
630+ percent_encode(&key),
631+ attachment.id
632+ );
633+ let view = load_view(state, &attachment, &base, sheet).await?;
634+ let viewer = ViewerInfo {
635+ name: me.member.name.clone(),
636+ is_admin: me.member.im_admin || me.member.role == iz_core::authz::Role::Admin,
637+ csrf: me.session.csrf_token.clone(),
638+ };
639+ let back_to = format!("/?task={}", percent_encode(&key));
640+ let title = attachment.name.clone();
641+ let document = view! {
642+ cx =>
643+ shell(title: title.as_str(), lang: language, viewer: Some(&viewer), page_script: None,
644+ file_page(lang: language, back_to: back_to.as_str(), file: &view)
645+ )
646+ };
647+ respond(cx, document).await
648+}
649+
650+#[cfg(test)]
651+mod tests {
652+ use super::*;
653+
654+ fn attachment(name: &str, mime: &str) -> Attachment {
655+ Attachment {
656+ id: "01HZ0000000000000000000000".into(),
657+ task_id: "t".into(),
658+ name: name.into(),
659+ mime: mime.into(),
660+ size: 1,
661+ sha256: "0".repeat(64),
662+ uploaded_by: "u".into(),
663+ created_at: "x".into(),
664+ }
665+ }
666+
667+ /// The kinds that get a preview, and the types that never do. SVG and HTML are never inline.
668+ #[test]
669+ fn the_viewer_kind_follows_the_sniffed_type() {
670+ assert_eq!(kind_of(&attachment("a.png", "image/png")), Kind::Image);
671+ assert_eq!(
672+ kind_of(&attachment("a.svg", "image/svg+xml")),
673+ Kind::Nothing
674+ );
675+ assert_eq!(kind_of(&attachment("a.pdf", "application/pdf")), Kind::Pdf);
676+ assert_eq!(kind_of(&attachment("a.html", "text/html")), Kind::Nothing);
677+ assert_eq!(kind_of(&attachment("a.png", "text/html")), Kind::Nothing);
678+ assert_eq!(kind_of(&attachment("a.csv", "text/plain")), Kind::Csv);
679+ assert_eq!(kind_of(&attachment("a.csv", "text/html")), Kind::Csv);
680+ assert_eq!(kind_of(&attachment("a.txt", "text/plain")), Kind::Text);
681+ assert_eq!(kind_of(&attachment("a.xlsx", XLSX)), Kind::Workbook);
682+ assert_eq!(kind_of(&attachment("a.pptx", PPTX)), Kind::Deck);
683+ }
684+
685+ #[test]
686+ fn sizes_read_as_people_read_them() {
687+ assert_eq!(size_text(512), "512 B");
688+ assert_eq!(size_text(1536), "1.5 KB");
689+ assert_eq!(size_text(3 * 1024 * 1024), "3.0 MB");
690+ }
691+}
692+
693+/// Route tests: the cross-task `404`, the viewer's `403` on upload, the byte response headers of a page
694+/// disguised as a picture, and the escaped CSV viewer.
695+#[cfg(test)]
696+mod route_tests {
697+ use http::header::{CONTENT_DISPOSITION, CONTENT_SECURITY_POLICY, CONTENT_TYPE, COOKIE};
698+ use iz_core::authz::Role;
699+ use topcoat::router::Body;
700+
701+ use crate::boot::{router, test_state};
702+ use crate::pages::board::{cookie_of, one_card, sign_in_as};
703+ use crate::state::AppState;
704+
705+ const AUTHOR: &str = "01ADAAAAAAAAAAAAAAAAAAAAAA";
706+ const VIEWER: &str = "01VIAAAAAAAAAAAAAAAAAAAAAA";
707+
708+ /// Sends one request and returns the whole response.
709+ async fn send(state: &AppState, request: http::Request<Body>) -> http::Response<Body> {
710+ router(state.clone()).handle(request).await
711+ }
712+
713+ /// A multipart upload of one file named `name`, with the CSRF token as the first field.
714+ fn upload(
715+ path: &str,
716+ token: &str,
717+ csrf: &str,
718+ name: &str,
719+ bytes: &[u8],
720+ ) -> http::Request<Body> {
721+ let boundary = "izboundary";
722+ let mut body = format!(
723+ "--{boundary}\r\nContent-Disposition: form-data; name=\"csrf\"\r\n\r\n{csrf}\r\n\
724+ --{boundary}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"{name}\"\r\n\
725+ Content-Type: application/octet-stream\r\n\r\n"
726+ )
727+ .into_bytes();
728+ body.extend_from_slice(bytes);
729+ body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
730+ http::Request::post(path)
731+ .header(
732+ CONTENT_TYPE,
733+ format!("multipart/form-data; boundary={boundary}"),
734+ )
735+ .header(COOKIE, cookie_of(token))
736+ .body(Body::from(body))
737+ .expect("request")
738+ }
739+
740+ fn get(path: &str, token: &str) -> http::Request<Body> {
741+ http::Request::get(path)
742+ .header(COOKIE, cookie_of(token))
743+ .body(Body::empty())
744+ .expect("request")
745+ }
746+
747+ /// The first attachment on a task, read through the store.
748+ async fn first_attachment(
749+ state: &AppState,
750+ task_id: &str,
751+ ) -> iz_core::store::attachments::Attachment {
752+ let board = state.store.board().await.expect("board").expect("some");
753+ state
754+ .store
755+ .list_attachments(&board.id, task_id)
756+ .await
757+ .expect("list")
758+ .into_iter()
759+ .next()
760+ .expect("an attachment")
761+ }
762+
763+ /// The key of a task, read through the store.
764+ async fn key_of(state: &AppState, task_id: &str) -> String {
765+ let board = state.store.board().await.expect("board").expect("some");
766+ state
767+ .store
768+ .task_detail(&board.id, task_id)
769+ .await
770+ .expect("detail")
771+ .task
772+ .key
773+ }
774+
775+ /// An attachment viewed under another task's key is not found.
776+ #[tokio::test]
777+ async fn an_attachment_under_another_task_key_is_not_found() {
778+ let (_dir, state) = test_state().await;
779+ let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await;
780+ let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
781+ let (other_id, _) = one_card(&state, "Bread", AUTHOR).await;
782+ let response = send(
783+ &state,
784+ upload(
785+ &format!("/tasks/{task_id}/files"),
786+ &token,
787+ &csrf,
788+ "note.txt",
789+ b"hello",
790+ ),
791+ )
792+ .await;
793+ assert!(
794+ response.status().is_redirection(),
795+ "upload: {}",
796+ response.status()
797+ );
798+ let attachment = first_attachment(&state, &task_id).await;
799+ let other_key = key_of(&state, &other_id).await;
800+ let response = send(
801+ &state,
802+ get(
803+ &format!("/tasks/{other_key}/files/{}/view", attachment.id),
804+ &token,
805+ ),
806+ )
807+ .await;
808+ assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
809+ }
810+
811+ /// A viewer cannot upload: the request is refused and nothing is stored.
812+ #[tokio::test]
813+ async fn a_viewer_cannot_upload() {
814+ let (_dir, state) = test_state().await;
815+ sign_in_as(&state, AUTHOR, Role::Member).await;
816+ let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
817+ let (token, csrf) = sign_in_as(&state, VIEWER, Role::Viewer).await;
818+ let response = send(
819+ &state,
820+ upload(
821+ &format!("/tasks/{task_id}/files"),
822+ &token,
823+ &csrf,
824+ "note.txt",
825+ b"hello",
826+ ),
827+ )
828+ .await;
829+ assert_eq!(response.status(), http::StatusCode::FORBIDDEN);
830+ let board = state.store.board().await.expect("board").expect("some");
831+ let stored = state
832+ .store
833+ .list_attachments(&board.id, &task_id)
834+ .await
835+ .expect("list");
836+ assert!(stored.is_empty());
837+ }
838+
839+ /// An HTML page named `.png` is served as an attachment, with one CSP header and nosniff, never inline.
840+ #[tokio::test]
841+ async fn an_html_file_named_as_a_picture_is_served_as_an_attachment() {
842+ let (_dir, state) = test_state().await;
843+ let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await;
844+ let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
845+ let page = b"<!DOCTYPE html><html><body><script>alert(1)</script></body></html>";
846+ let response = send(
847+ &state,
848+ upload(
849+ &format!("/tasks/{task_id}/files"),
850+ &token,
851+ &csrf,
852+ "photo.png",
853+ page,
854+ ),
855+ )
856+ .await;
857+ assert!(
858+ response.status().is_redirection(),
859+ "upload: {}",
860+ response.status()
861+ );
862+ let attachment = first_attachment(&state, &task_id).await;
863+ let response = send(&state, get(&format!("/files/{}", attachment.id), &token)).await;
864+ assert_eq!(response.status(), http::StatusCode::OK);
865+ let headers = response.headers();
866+ let disposition = headers
867+ .get(CONTENT_DISPOSITION)
868+ .and_then(|value| value.to_str().ok())
869+ .unwrap_or_default();
870+ assert!(disposition.starts_with("attachment"), "{disposition}");
871+ assert_eq!(
872+ headers
873+ .get("x-content-type-options")
874+ .and_then(|v| v.to_str().ok()),
875+ Some("nosniff")
876+ );
877+ assert_eq!(headers.get_all(CONTENT_SECURITY_POLICY).iter().count(), 1);
878+ }
879+
880+ /// A CSV cell that holds markup is shown as escaped text in the viewer.
881+ #[tokio::test]
882+ async fn a_csv_cell_with_markup_is_escaped_in_the_viewer() {
883+ let (_dir, state) = test_state().await;
884+ let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await;
885+ let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
886+ let key = key_of(&state, &task_id).await;
887+ let csv = b"name,note\n<script>alert(1)</script>,ok\n";
888+ let response = send(
889+ &state,
890+ upload(
891+ &format!("/tasks/{task_id}/files"),
892+ &token,
893+ &csrf,
894+ "cells.csv",
895+ csv,
896+ ),
897+ )
898+ .await;
899+ assert!(
900+ response.status().is_redirection(),
901+ "upload: {}",
902+ response.status()
903+ );
904+ let attachment = first_attachment(&state, &task_id).await;
905+ let response = send(
906+ &state,
907+ get(
908+ &format!("/tasks/{key}/files/{}/view", attachment.id),
909+ &token,
910+ ),
911+ )
912+ .await;
913+ assert_eq!(response.status(), http::StatusCode::OK);
914+ let bytes = topcoat::router::to_bytes(response.into_body(), 4 * 1024 * 1024)
915+ .await
916+ .expect("body");
917+ let html = String::from_utf8_lossy(&bytes);
918+ assert!(html.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
919+ assert!(!html.contains("<script>alert(1)"));
920+ }
921+}
crates/iz-web/src/pages/mod.rsmodified+1 -0
@@ -2,6 +2,7 @@
22
33 pub mod backchannel;
44 pub mod board;
5+pub mod files;
56 pub mod not_found;
67 pub mod photo;
78 pub mod sign_in;
crates/iz-web/src/pages/task.rsmodified+38 -4
@@ -93,8 +93,34 @@ pub struct ActivityRow {
9393 pub when: String,
9494 }
9595
96+/// One attachment as the modal lists it, with the links and rights of the viewer over it.
97+pub struct FileRow {
98+ /// The file name as uploaded.
99+ pub name: String,
100+ /// The size, as text.
101+ pub size: String,
102+ /// The uploader's name.
103+ pub uploader: String,
104+ /// When it was uploaded, in the viewer's zone.
105+ pub when: String,
106+ /// Whether the viewer can show it (has a preview).
107+ pub viewable: bool,
108+ /// The modal URL that opens its viewer.
109+ pub view_url: String,
110+ /// The URL that saves it.
111+ pub download_url: String,
112+ /// The form action that deletes it.
113+ pub delete_action: String,
114+ /// Whether the viewer may delete it.
115+ pub can_delete: bool,
116+}
117+
96118 /// The task modal, as the board page shows it.
97119 pub struct TaskModal {
120+ /// The attachments of the task, oldest first.
121+ pub files: Vec<FileRow>,
122+ /// The file open in the viewer (`?file=`), when there is one.
123+ pub viewer: Option<crate::pages::files::FileView>,
98124 /// The task with its tag, assignees, subtasks and links.
99125 pub detail: TaskDetail,
100126 /// Whether the viewer may change the task.
@@ -228,7 +254,7 @@ fn zone_of(me: &CurrentMember) -> TimeZone {
228254 }
229255
230256 /// A stored UTC stamp in `zone` as `YYYY-MM-DD HH:MM`. Empty when the stamp does not parse.
231-fn local_text(stamp: &str, zone: &TimeZone) -> String {
257+pub(crate) fn local_text(stamp: &str, zone: &TimeZone) -> String {
232258 match timestamp_of(stamp) {
233259 Ok(at) => {
234260 let local = utc_to_local(zone, at);
@@ -436,7 +462,15 @@ pub async fn open(
436462 .map(|stamp| clock_text(stamp, &zone))
437463 .unwrap_or_default(),
438464 };
465+ let attachments = store
466+ .list_attachments(&board.id, &task_id)
467+ .await
468+ .map_err(core_err)?;
469+ let files =
470+ crate::pages::files::file_rows(&attachments, key, query, me, can_write, &names, &zone);
439471 let modal = TaskModal {
472+ files,
473+ viewer: None,
440474 can_write,
441475 close: board_url(&page.filters, &[]),
442476 base,
@@ -507,7 +541,7 @@ async fn gate_task(cx: &Cx, form: &ModalForm, task_id: &str) -> Result<StdResult
507541
508542 /// Re-renders the board with the modal of `key` open, the refusal above its fields, and `422`. When the
509543 /// task is gone the board answers `404` with its "not found" notice.
510-async fn refuse(
544+pub(crate) async fn refuse(
511545 cx: &Cx,
512546 me: &CurrentMember,
513547 language: Lang,
@@ -537,14 +571,14 @@ fn refusal(message: &'static str) -> Draft {
537571 }
538572
539573 /// Tells every open view of the board and of the task that something changed.
540-fn bump(state: &AppState, board_id: &str, task_id: &str) {
574+pub(crate) fn bump(state: &AppState, board_id: &str, task_id: &str) {
541575 state.live.bump(&Topic::Board(board_id.to_owned()));
542576 state.live.bump(&Topic::Task(task_id.to_owned()));
543577 }
544578
545579 /// Answers a write that went through: the modal of `key` with the saved notice, or the board when there is
546580 /// no task to return to.
547-fn back(next: &str, key: Option<&str>) -> Result<Response> {
581+pub(crate) fn back(next: &str, key: Option<&str>) -> Result<Response> {
548582 let target = match key {
549583 Some(key) => modal_url(query_of(safe_next(Some(next))), key, &[("notice", "saved")]),
550584 None => "/".to_owned(),
crates/iz-web/src/security.rsmodified+21 -4
@@ -43,8 +43,8 @@ pub fn headers_for(base_url: &str) -> HeaderMap {
4343
4444 /// Adds a fixed set of headers to every response of the router.
4545 ///
46-/// It uses the per-request response headers, which the router applies after the layers have run,
47-/// so error responses (404, 500) carry them as well.
46+/// A header that the route already set is kept: a byte response carries its own policy. Errors take the
47+/// per-request response headers, which the router applies after the layers have run.
4848 pub struct SecurityHeaders {
4949 headers: HeaderMap,
5050 }
@@ -63,8 +63,25 @@ impl Layer for SecurityHeaders {
6363
6464 fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
6565 Box::pin(async move {
66- response_headers(cx).extend(self.headers.clone());
67- next.run(cx, body).await
66+ match next.run(cx, body).await {
67+ // A header the route set itself wins: byte responses carry their own sandboxed
68+ // policy, and two policies would apply both (the page one forbids framing).
69+ Ok(mut response) => {
70+ let headers = response.headers_mut();
71+ for (name, value) in &self.headers {
72+ if !headers.contains_key(name) {
73+ headers.insert(name.clone(), value.clone());
74+ }
75+ }
76+ Ok(response)
77+ }
78+ // Errors become responses after the layers have run; the per-request slot gives
79+ // them the headers too.
80+ Err(error) => {
81+ response_headers(cx).extend(self.headers.clone());
82+ Err(error)
83+ }
84+ }
6885 })
6986 }
7087 }
crates/iz-web/src/serve.rsadded+465 -0
@@ -0,0 +1,465 @@
1+//! The one function that sends a stored file to a browser. Every byte route calls [`serve_file`], so the
2+//! headers and the range rules exist in exactly one place (`docs/architecture.md` section 7). A copy of the
3+//! byte rules of the `in` service, adapted to read a local file.
4+//!
5+//! The caller has already decided that the viewer may see the bytes (`authz`). This module decides how
6+//! they are sent: a single byte range, a validator (`ETag`) and its conditional requests, a disposition
7+//! that is `inline` only for types a browser can show without running them, and the response headers
8+//! that stop the bytes from being used as a page. The body is streamed from the file in frames of
9+//! [`FRAME_BYTES`]; nothing is buffered whole.
10+//!
11+//! Range rules: one `bytes=` range is honoured (`a-b`, `a-`, `-n`). A request with several ranges gets the
12+//! whole file with `200`. A malformed, reversed or unsatisfiable range gets `416` with
13+//! `Content-Range: bytes */<len>`. `If-Range` with a validator that is not the current one gets the whole
14+//! file.
15+
16+use std::io::{self, SeekFrom};
17+use std::path::Path;
18+
19+use bytes::Bytes;
20+use http::header::{
21+ ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE,
22+ CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE,
23+ X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
24+};
25+use http_body::Frame;
26+use http_body_util::StreamBody;
27+use tokio::io::{AsyncReadExt, AsyncSeekExt};
28+use topcoat::Result;
29+use topcoat::context::Cx;
30+use topcoat::router::request::headers;
31+use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode};
32+
33+/// What a browser may do with a byte response: show it in the page, or save it.
34+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35+pub enum Disposition {
36+ /// Show the bytes in the page. Granted only to the types in [`inline_safe`].
37+ Inline,
38+ /// Save the bytes as a file.
39+ Attachment,
40+}
41+
42+/// Bytes read per frame of a body. Reason: bounds the memory of one open download.
43+pub const FRAME_BYTES: usize = 64 * 1024;
44+
45+/// Everything about a stored file that a byte response needs. The caller fills it from the row.
46+#[derive(Clone, Copy, Debug)]
47+pub struct ByteSource<'a> {
48+ /// The file on the disk, under `data_dir/attachments`.
49+ pub path: &'a Path,
50+ /// Length of the bytes in bytes.
51+ pub size: u64,
52+ /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes.
53+ pub sha256: &'a str,
54+ /// The sniffed MIME type, as stored. It is never the uploader's claim.
55+ pub mime: &'a str,
56+ /// The display name, used for the `Content-Disposition` file name.
57+ pub name: &'a str,
58+}
59+
60+/// The status, headers and body of a byte response. Handlers return it as they are.
61+pub type ByteAnswer = (StatusCode, HeaderMap, Body);
62+
63+/// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and
64+/// `default-src 'none'` stops it from loading anything but its own image, media or style. Only a page of this
65+/// origin may frame the bytes (the viewer).
66+pub const BYTES_CSP: &str = "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; \
67+ style-src 'unsafe-inline'; frame-ancestors 'self'";
68+
69+/// The same policy without `sandbox`, for PDFs only: browsers refuse to run their PDF viewer in a sandboxed
70+/// document. A PDF is never interpreted as HTML (`nosniff`, fixed type), and no script runs in it.
71+pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; \
72+ style-src 'unsafe-inline'; frame-ancestors 'self'";
73+
74+/// Cache policy of content addressed by id and hash: the bytes behind a URL never change.
75+const BYTES_CACHE: &str = "private, max-age=31536000, immutable";
76+
77+/// The outcome of reading a `Range` header against a length.
78+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79+pub enum Ranged {
80+ /// Send the whole file (no range, or several ranges).
81+ Full,
82+ /// Send the bytes from `start` to `end`, both inclusive, and both inside the file.
83+ Part {
84+ /// First byte, inclusive.
85+ start: u64,
86+ /// Last byte, inclusive.
87+ end: u64,
88+ },
89+ /// The header is malformed, reversed, or asks for nothing the file has. Answer `416`.
90+ Unsatisfiable,
91+}
92+
93+/// Parses the value of a `Range` header for a file of `len` bytes.
94+///
95+/// Accepted: `bytes=a-b` (clamped to the end of the file), `bytes=a-` (to the end), `bytes=-n` (the last
96+/// `n` bytes; a longer `n` means the whole file). Several ranges, separated by commas, give
97+/// [`Ranged::Full`]. Everything else is [`Ranged::Unsatisfiable`]: a missing unit, a non-digit, a value
98+/// that overflows `u64`, `-0`, a last byte before the first, or a first byte at or past the end.
99+pub fn parse_range(value: &str, len: u64) -> Ranged {
100+ let Some(spec) = value.trim().strip_prefix("bytes=") else {
101+ return Ranged::Unsatisfiable;
102+ };
103+ if spec.contains(',') {
104+ return Ranged::Full;
105+ }
106+ let Some((first, last)) = spec.trim().split_once('-') else {
107+ return Ranged::Unsatisfiable;
108+ };
109+ let (first, last) = (first.trim(), last.trim());
110+ if first.is_empty() {
111+ // A suffix range: the last `n` bytes.
112+ let Some(n) = digits(last) else {
113+ return Ranged::Unsatisfiable;
114+ };
115+ if n == 0 || len == 0 {
116+ return Ranged::Unsatisfiable;
117+ }
118+ let n = n.min(len);
119+ return Ranged::Part {
120+ start: len - n,
121+ end: len - 1,
122+ };
123+ }
124+ let Some(start) = digits(first) else {
125+ return Ranged::Unsatisfiable;
126+ };
127+ let end = if last.is_empty() {
128+ None
129+ } else {
130+ match digits(last) {
131+ Some(end) if end >= start => Some(end),
132+ _ => return Ranged::Unsatisfiable,
133+ }
134+ };
135+ if start >= len {
136+ return Ranged::Unsatisfiable;
137+ }
138+ let end = end.map_or(len - 1, |end| end.min(len - 1));
139+ Ranged::Part { start, end }
140+}
141+
142+/// A non-empty run of ASCII digits as a number. Anything else, including an overflow, is `None`.
143+fn digits(text: &str) -> Option<u64> {
144+ if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
145+ return None;
146+ }
147+ text.parse().ok()
148+}
149+
150+/// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong
151+/// form here, which is the rule for `GET` validators (RFC 9110).
152+fn none_match_hits(request: &HeaderMap, etag: &str) -> bool {
153+ request
154+ .get(IF_NONE_MATCH)
155+ .and_then(|value| value.to_str().ok())
156+ .is_some_and(|value| {
157+ value.split(',').map(str::trim).any(|candidate| {
158+ candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
159+ })
160+ })
161+}
162+
163+/// Whether a range may be honoured under `If-Range`. Without the header it always may. With it, only a
164+/// strong validator equal to `etag` allows the range; a date or a weak tag never does.
165+fn if_range_allows(request: &HeaderMap, etag: &str) -> bool {
166+ match request.get(IF_RANGE).and_then(|value| value.to_str().ok()) {
167+ None => true,
168+ Some(value) => value.trim() == etag,
169+ }
170+}
171+
172+/// The range that applies to this request, after `If-Range` has had its say.
173+fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged {
174+ let Some(value) = request.get(RANGE).and_then(|value| value.to_str().ok()) else {
175+ return Ranged::Full;
176+ };
177+ if !if_range_allows(request, etag) {
178+ return Ranged::Full;
179+ }
180+ parse_range(value, len)
181+}
182+
183+/// Whether a type may be shown inline. SVG is never inline: it can carry script. HTML is never inline.
184+/// Images (except SVG and HEIC/HEIF, which browsers do not show everywhere), audio, video, PDF and plain
185+/// text are.
186+pub fn inline_safe(mime: &str) -> bool {
187+ let essence = mime
188+ .split(';')
189+ .next()
190+ .unwrap_or_default()
191+ .trim()
192+ .to_ascii_lowercase();
193+ match essence.as_str() {
194+ "image/svg+xml" | "image/heic" | "image/heif" => false,
195+ "application/pdf" | "text/plain" => true,
196+ other => {
197+ other.starts_with("image/")
198+ || other.starts_with("audio/")
199+ || other.starts_with("video/")
200+ }
201+ }
202+}
203+
204+/// The `Content-Type` value for a stored type. Plain text is always sent as UTF-8.
205+fn content_type_value(mime: &str) -> String {
206+ if mime.trim().eq_ignore_ascii_case("text/plain") {
207+ "text/plain; charset=utf-8".into()
208+ } else {
209+ mime.to_string()
210+ }
211+}
212+
213+/// Characters that may appear unescaped in an RFC 5987 `filename*` value (`attr-char`).
214+fn is_attr_char(b: u8) -> bool {
215+ b.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&b)
216+}
217+
218+/// The `Content-Disposition` header for a file name: `inline` or `attachment`, a quoted ASCII fallback
219+/// and the UTF-8 name percent-encoded per RFC 5987.
220+///
221+/// The fallback keeps printable ASCII except the quote and the backslash, and turns everything else
222+/// (control characters, including CR and LF, non-ASCII letters) into `_`. So no name can close the
223+/// quoted string or start a new header line. The `filename*` value encodes every byte that is not an
224+/// `attr-char`, which covers the same characters.
225+pub fn content_disposition(kind: Disposition, name: &str) -> String {
226+ let fallback: String = name
227+ .chars()
228+ .map(|c| {
229+ if c.is_ascii() && (c.is_ascii_graphic() || c == ' ') && c != '"' && c != '\\' {
230+ c
231+ } else {
232+ '_'
233+ }
234+ })
235+ .collect();
236+ let fallback = if fallback.trim().is_empty() {
237+ "download".to_string()
238+ } else {
239+ fallback
240+ };
241+ let mut encoded = String::with_capacity(name.len());
242+ for b in name.bytes() {
243+ if is_attr_char(b) {
244+ encoded.push(char::from(b));
245+ } else {
246+ encoded.push_str(&format!("%{b:02X}"));
247+ }
248+ }
249+ let kind = match kind {
250+ Disposition::Inline => "inline",
251+ Disposition::Attachment => "attachment",
252+ };
253+ format!("{kind}; filename=\"{fallback}\"; filename*=UTF-8''{encoded}")
254+}
255+
256+/// The headers every byte response carries, whatever its status.
257+fn common_headers(etag: &str, mime: &str) -> HeaderMap {
258+ let mut headers = HeaderMap::new();
259+ insert(&mut headers, ETAG, etag);
260+ headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes"));
261+ headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
262+ let csp = if mime == "application/pdf" {
263+ PDF_CSP
264+ } else {
265+ BYTES_CSP
266+ };
267+ headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(csp));
268+ headers.insert(X_FRAME_OPTIONS, HeaderValue::from_static("SAMEORIGIN"));
269+ headers.insert(
270+ HeaderName::from_static("cross-origin-resource-policy"),
271+ HeaderValue::from_static("same-origin"),
272+ );
273+ headers.insert(CACHE_CONTROL, HeaderValue::from_static(BYTES_CACHE));
274+ headers
275+}
276+
277+/// Inserts a header whose value is text the code controls. A value that is not a valid header value is
278+/// dropped, never sent half-formed; every caller passes ASCII that the code made.
279+fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) {
280+ if let Ok(value) = HeaderValue::from_str(value) {
281+ headers.insert(name, value);
282+ }
283+}
284+
285+/// The `416` answer: no body, and the length the client may ask again within.
286+fn unsatisfiable(etag: &str, len: u64, mime: &str) -> ByteAnswer {
287+ let mut headers = common_headers(etag, mime);
288+ insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}"));
289+ (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty())
290+}
291+
292+/// Sends the bytes of `source` for the request in `cx`.
293+///
294+/// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in
295+/// [`inline_safe`]. The body streams from the file from the first byte the answer needs. A file that cannot be
296+/// opened is an error, which the router answers as a `500`: the row names bytes that are not there.
297+pub async fn serve_file(
298+ cx: &Cx,
299+ source: &ByteSource<'_>,
300+ disposition: Disposition,
301+) -> Result<ByteAnswer> {
302+ let request = headers(cx);
303+ let etag = format!("\"{}\"", source.sha256);
304+ let disposition = match disposition {
305+ Disposition::Inline if inline_safe(source.mime) => Disposition::Inline,
306+ _ => Disposition::Attachment,
307+ };
308+ let mut answer_headers = common_headers(&etag, source.mime);
309+ insert(
310+ &mut answer_headers,
311+ CONTENT_DISPOSITION,
312+ &content_disposition(disposition, source.name),
313+ );
314+ insert(
315+ &mut answer_headers,
316+ CONTENT_TYPE,
317+ &content_type_value(source.mime),
318+ );
319+
320+ if none_match_hits(request, &etag) {
321+ return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty()));
322+ }
323+
324+ match requested_range(request, &etag, source.size) {
325+ Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size, source.mime)),
326+ Ranged::Full => {
327+ insert(
328+ &mut answer_headers,
329+ CONTENT_LENGTH,
330+ &source.size.to_string(),
331+ );
332+ let body = open_streamed(source.path, 0, source.size).await?;
333+ Ok((StatusCode::OK, answer_headers, body))
334+ }
335+ Ranged::Part { start, end } => {
336+ let length = end - start + 1;
337+ insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string());
338+ insert(
339+ &mut answer_headers,
340+ CONTENT_RANGE,
341+ &format!("bytes {start}-{end}/{}", source.size),
342+ );
343+ let body = open_streamed(source.path, start, length).await?;
344+ Ok((StatusCode::PARTIAL_CONTENT, answer_headers, body))
345+ }
346+ }
347+}
348+
349+/// Opens `path`, seeks to `start` and streams `length` bytes from there.
350+async fn open_streamed(path: &Path, start: u64, length: u64) -> Result<Body> {
351+ let mut file = tokio::fs::File::open(path).await?;
352+ if start > 0 {
353+ file.seek(SeekFrom::Start(start)).await?;
354+ }
355+ let frames = futures_util::stream::try_unfold((file, length), |(mut file, left)| async move {
356+ if left == 0 {
357+ return Ok(None);
358+ }
359+ let want = left.min(FRAME_BYTES as u64) as usize;
360+ let mut buf = vec![0u8; want];
361+ let read = file.read(&mut buf).await?;
362+ if read == 0 {
363+ return Err(io::Error::new(
364+ io::ErrorKind::UnexpectedEof,
365+ "the file is shorter than its record",
366+ ));
367+ }
368+ buf.truncate(read);
369+ Ok(Some((
370+ Frame::data(Bytes::from(buf)),
371+ (file, left - read as u64),
372+ )))
373+ });
374+ Ok(Body::new(StreamBody::new(frames)))
375+}
376+
377+#[cfg(test)]
378+mod tests {
379+ use super::*;
380+
381+ /// A table of `Range` values for a 100-byte file, with the answer for each.
382+ #[test]
383+ fn range_table() {
384+ use Ranged::*;
385+ let cases: &[(&str, Ranged)] = &[
386+ ("bytes=0-0", Part { start: 0, end: 0 }),
387+ ("bytes=0-99", Part { start: 0, end: 99 }),
388+ ("bytes=10-19", Part { start: 10, end: 19 }),
389+ // Past the end is clamped, not refused.
390+ ("bytes=50-500", Part { start: 50, end: 99 }),
391+ ("bytes=90-", Part { start: 90, end: 99 }),
392+ ("bytes=-10", Part { start: 90, end: 99 }),
393+ // A suffix longer than the file is the whole file.
394+ ("bytes=-1000", Part { start: 0, end: 99 }),
395+ (" bytes=1 - 2 ", Part { start: 1, end: 2 }),
396+ // Several ranges: the whole file.
397+ ("bytes=0-1,5-6", Full),
398+ // Unsatisfiable or malformed.
399+ ("bytes=-0", Unsatisfiable),
400+ ("bytes=100-", Unsatisfiable),
401+ ("bytes=100-120", Unsatisfiable),
402+ ("bytes=20-10", Unsatisfiable),
403+ ("bytes=5-4", Unsatisfiable),
404+ ("bytes=-", Unsatisfiable),
405+ ("bytes=", Unsatisfiable),
406+ ("bytes=-x", Unsatisfiable),
407+ ("bytes=+1-2", Unsatisfiable),
408+ ("bytes=1e2-", Unsatisfiable),
409+ ("bytes=--1", Unsatisfiable),
410+ ("items=0-1", Unsatisfiable),
411+ ("0-1", Unsatisfiable),
412+ // Overflow of u64 is refused, not wrapped.
413+ ("bytes=18446744073709551616-", Unsatisfiable),
414+ ("bytes=0-18446744073709551616", Unsatisfiable),
415+ ("bytes=-18446744073709551616", Unsatisfiable),
416+ ];
417+ for (header, want) in cases {
418+ assert_eq!(parse_range(header, 100), *want, "header {header:?}");
419+ }
420+ }
421+
422+ #[test]
423+ fn an_empty_file_has_no_satisfiable_range() {
424+ assert_eq!(parse_range("bytes=0-", 0), Ranged::Unsatisfiable);
425+ assert_eq!(parse_range("bytes=-5", 0), Ranged::Unsatisfiable);
426+ }
427+
428+ #[test]
429+ fn disposition_is_inline_only_for_safe_types() {
430+ assert!(inline_safe("image/png"));
431+ assert!(inline_safe("application/pdf"));
432+ assert!(inline_safe("text/plain; charset=utf-8"));
433+ assert!(inline_safe("video/mp4"));
434+ assert!(!inline_safe("image/svg+xml"));
435+ assert!(!inline_safe("image/heic"));
436+ assert!(!inline_safe("text/html"));
437+ assert!(!inline_safe("application/octet-stream"));
438+ assert_eq!(
439+ content_type_value("text/plain"),
440+ "text/plain; charset=utf-8"
441+ );
442+ }
443+
444+ /// Quotes, CR and LF, and a non-ASCII name cannot close the quoted string or add a header line.
445+ #[test]
446+ fn content_disposition_neutralises_quotes_crlf_and_unicode() {
447+ let value = content_disposition(Disposition::Attachment, "a\"b\r\nc é.pdf");
448+ assert!(!value.contains('\r') && !value.contains('\n'));
449+ assert_eq!(
450+ value.matches('"').count(),
451+ 2,
452+ "only the two quotes: {value}"
453+ );
454+ assert_eq!(
455+ value,
456+ "attachment; filename=\"a_b__c _.pdf\"; filename*=UTF-8''a%22b%0D%0Ac%20%C3%A9.pdf"
457+ );
458+ let inline = content_disposition(Disposition::Inline, "plain.txt");
459+ assert_eq!(
460+ inline,
461+ "inline; filename=\"plain.txt\"; filename*=UTF-8''plain.txt"
462+ );
463+ assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\""));
464+ }
465+}
crates/iz-web/src/views/files.rsadded+188 -0
@@ -0,0 +1,188 @@
1+//! The file viewer's markup: the same component in the task modal and on the viewer page. Each kind of file has
2+//! one body. Text and cells are escaped by `view!`, so a file's content is shown as characters; the picture,
3+//! media and PDF bodies are the browser's own, from the byte route, which sends them with the sandbox policy.
4+
5+use topcoat::Result;
6+use topcoat::view::{View, component, view};
7+
8+use crate::i18n::Lang;
9+use crate::i18n::task::{K, t};
10+use crate::pages::files::{FileView, SheetTab, ViewBody};
11+use iz_core::slides::Slide;
12+
13+/// The viewer of one file: its details and download link, then its body.
14+#[component]
15+pub async fn file_view(lang: Lang, file: &FileView) -> Result<impl View> {
16+ Ok(view! {
17+ <section class="viewer" aria-label=(file.name.as_str())>
18+ <p class="viewer-meta">
19+ <span>(file.size_text.as_str())</span>
20+ " "
21+ <a class="button ghost" href=(file.download_url.as_str())>(t(lang, K::DownloadFile))</a>
22+ </p>
23+ if matches!(file.body, ViewBody::Image) {
24+ <img class="viewer-image" src=(file.inline_url.as_str()) alt=(file.name.as_str())>
25+ }
26+ if matches!(file.body, ViewBody::Video) {
27+ <video class="viewer-media" controls="" preload="metadata" src=(file.inline_url.as_str())></video>
28+ }
29+ if matches!(file.body, ViewBody::Audio) {
30+ <audio controls="" preload="metadata" src=(file.inline_url.as_str())></audio>
31+ }
32+ if matches!(file.body, ViewBody::Pdf) {
33+ <iframe class="viewer-frame" src=(file.inline_url.as_str()) title=(file.name.as_str())></iframe>
34+ }
35+ if let ViewBody::Text { text, cut } = &file.body {
36+ <pre class="viewer-text">(text.as_str())</pre>
37+ if *cut {
38+ <p class="muted">(t(lang, K::ViewerTruncated))</p>
39+ }
40+ }
41+ if let ViewBody::Sheets { tabs, rows, cut } = &file.body {
42+ sheet_body(lang: lang, tabs: tabs.as_slice(), rows: rows.as_slice(), cut: *cut)
43+ }
44+ if let ViewBody::Slides(slides) = &file.body {
45+ slide_body(lang: lang, slides: slides.as_slice())
46+ }
47+ if matches!(file.body, ViewBody::Refused) {
48+ <p class="muted">(t(lang, K::ViewerRefused))</p>
49+ }
50+ if matches!(file.body, ViewBody::Nothing) {
51+ <p class="muted">(t(lang, K::NoPreview))</p>
52+ }
53+ </section>
54+ })
55+}
56+
57+/// The sheet viewer: the tabs of the workbook, then the cells of the selected sheet, all escaped.
58+#[component]
59+pub async fn sheet_body(
60+ lang: Lang,
61+ tabs: &[SheetTab],
62+ rows: &[Vec<String>],
63+ cut: bool,
64+) -> Result<impl View> {
65+ Ok(view! {
66+ <nav class="sheet-tabs" aria-label=(t(lang, K::Sheets))>
67+ for tab in tabs.iter() {
68+ if tab.active {
69+ <a class="tab active" href=(tab.url.as_str()) aria-current="page">(tab.label.as_str())</a>
70+ }
71+ if !tab.active {
72+ <a class="tab" href=(tab.url.as_str())>(tab.label.as_str())</a>
73+ }
74+ }
75+ </nav>
76+ if rows.is_empty() {
77+ <p class="muted">(t(lang, K::EmptySheet))</p>
78+ }
79+ <div class="viewer-table">
80+ <table>
81+ <tbody>
82+ for row in rows.iter() {
83+ <tr>
84+ for cell in row.iter() {
85+ <td>(cell.as_str())</td>
86+ }
87+ </tr>
88+ }
89+ </tbody>
90+ </table>
91+ </div>
92+ if cut {
93+ <p class="muted">(t(lang, K::ViewerCut))</p>
94+ }
95+ })
96+}
97+
98+/// The slide viewer: one list item per slide with its text paragraphs, escaped.
99+#[component]
100+pub async fn slide_body(lang: Lang, slides: &[Slide]) -> Result<impl View> {
101+ Ok(view! {
102+ <ol class="slide-list">
103+ for slide in slides.iter() {
104+ <li class="slide">
105+ <h4>(t(lang, K::SlideLabel)) " " (slide.number)</h4>
106+ if slide.paragraphs.is_empty() {
107+ <p class="muted">(t(lang, K::NoSlideText))</p>
108+ }
109+ for paragraph in slide.paragraphs.iter() {
110+ <p>(paragraph.as_str())</p>
111+ }
112+ </li>
113+ }
114+ </ol>
115+ })
116+}
117+
118+/// The viewer page: a link back to the task, the heading, and the viewer.
119+#[component]
120+pub async fn file_page(lang: Lang, back_to: &str, file: &FileView) -> Result<impl View> {
121+ Ok(view! {
122+ <p><a class="button ghost" href=(back_to)>(t(lang, K::Close))</a></p>
123+ <h1 class="viewer-heading">(file.name.as_str())</h1>
124+ file_view(lang: lang, file: file)
125+ })
126+}
127+
128+/// The attachments section of the task modal: the viewer when a file is open, the list of files with their
129+/// links and delete controls, and the upload form for a member.
130+#[component]
131+pub async fn task_files_section(
132+ lang: Lang,
133+ csrf: &str,
134+ next: &str,
135+ task_id: &str,
136+ can_write: bool,
137+ files: &[crate::pages::task::FileRow],
138+ open: Option<&FileView>,
139+) -> Result<impl View> {
140+ let upload_action = format!("/tasks/{task_id}/files");
141+ Ok(view! {
142+ <section class="task-section" aria-labelledby="task-files">
143+ <h3 id="task-files">(t(lang, K::Files))</h3>
144+ if let Some(file) = open {
145+ file_view(lang: lang, file: file)
146+ }
147+ if files.is_empty() {
148+ <p class="muted">(t(lang, K::NoFiles))</p>
149+ }
150+ <ul class="file-list">
151+ for row in files.iter() {
152+ <li class="file-row">
153+ if row.viewable {
154+ <a href=(row.view_url.as_str())>(row.name.as_str())</a>
155+ } else {
156+ <span>(row.name.as_str())</span>
157+ }
158+ " "
159+ <span class="muted">(row.size.as_str()) " · " (row.uploader.as_str()) " · " <time>(row.when.as_str())</time></span>
160+ " "
161+ if row.viewable {
162+ <a class="button ghost" href=(row.view_url.as_str())>(t(lang, K::ViewFile))</a>
163+ }
164+ <a class="button ghost" href=(row.download_url.as_str())>(t(lang, K::DownloadFile))</a>
165+ if row.can_delete {
166+ <form class="task-inline" method="post" action=(row.delete_action.as_str())>
167+ <input type="hidden" name="csrf" value=(csrf)>
168+ <input type="hidden" name="next" value=(next)>
169+ <button class="button ghost danger" type="submit">(t(lang, K::DeleteFile))</button>
170+ </form>
171+ }
172+ </li>
173+ }
174+ </ul>
175+ if can_write {
176+ <form class="task-form" method="post" action=(upload_action.as_str()) enctype="multipart/form-data" data-hard="">
177+ <input type="hidden" name="csrf" value=(csrf)>
178+ <input type="hidden" name="next" value=(next)>
179+ <div class="field field-wide">
180+ <label for="task-file-input">(t(lang, K::ChooseFiles))</label>
181+ <input id="task-file-input" type="file" name="files" multiple="">
182+ </div>
183+ <button class="button primary" type="submit">(t(lang, K::UploadFiles))</button>
184+ </form>
185+ }
186+ </section>
187+ })
188+}
crates/iz-web/src/views/mod.rsmodified+1 -0
@@ -9,6 +9,7 @@ use topcoat::router::response::{IntoResponse, Response};
99 use topcoat::view::{Child, View, ViewExt, component, view};
1010
1111 pub mod board;
12+pub mod files;
1213 pub mod task;
1314
1415 use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF};
crates/iz-web/src/views/task.rsmodified+21 -0
@@ -17,6 +17,7 @@ use crate::pages::board::BoardPage;
1717 use crate::pages::task::{TaskModal, task_link};
1818 use crate::views::alert;
1919 use crate::views::board::flag;
20+use crate::views::files::task_files_section;
2021
2122 /// One piece of a plain-text body: a run of text, a link, or a line break.
2223 pub struct Segment {
@@ -139,6 +140,7 @@ pub async fn task_modal(page: &BoardPage, modal: &TaskModal) -> Result<impl View
139140 }
140141 <h2 id="task-heading" class="task-title">(task.title.as_str())</h2>
141142 task_details(page: page, modal: modal)
143+ task_files(page: page, modal: modal)
142144 task_people(page: page, modal: modal)
143145 task_structure(page: page, modal: modal)
144146 task_links(page: page, modal: modal)
@@ -225,6 +227,25 @@ pub async fn task_details(page: &BoardPage, modal: &TaskModal) -> Result<impl Vi
225227 })
226228 }
227229
230+/// The attachments of the task: the viewer when a file is open, the list and the upload form.
231+#[component]
232+pub async fn task_files(page: &BoardPage, modal: &TaskModal) -> Result<impl View> {
233+ let id = modal.detail.task.id.as_str();
234+ let csrf = page.viewer.csrf.as_str();
235+ let next = modal.base.as_str();
236+ Ok(view! {
237+ task_files_section(
238+ lang: page.lang,
239+ csrf: csrf,
240+ next: next,
241+ task_id: id,
242+ can_write: modal.can_write,
243+ files: modal.files.as_slice(),
244+ open: modal.viewer.as_ref(),
245+ )
246+ })
247+}
248+
228249 /// The assignees, with a remove control each, the picker for a new one, and the watch switch.
229250 #[component]
230251 pub async fn task_people(page: &BoardPage, modal: &TaskModal) -> Result<impl View> {
style/_task.scssmodified+63 -0
@@ -142,3 +142,66 @@
142142 .task-confirm {
143143 border-color: var(--danger);
144144 }
145+
146+// The file viewer: media fills the modal width, the PDF gets a fixed height, text and cells scroll inside
147+// their own boxes so a long line or a wide sheet never stretches the modal.
148+.viewer {
149+ display: grid;
150+ gap: 0.75rem;
151+ margin-block: 0.75rem;
152+}
153+
154+.viewer-image,
155+.viewer-media {
156+ max-width: 100%;
157+ max-height: 70vh;
158+}
159+
160+.viewer-frame {
161+ width: 100%;
162+ height: 70vh;
163+ border: 1px solid var(--border);
164+}
165+
166+.viewer-text {
167+ max-height: 60vh;
168+ overflow: auto;
169+ white-space: pre-wrap;
170+ overflow-wrap: anywhere;
171+}
172+
173+.viewer-table {
174+ max-height: 60vh;
175+ overflow: auto;
176+}
177+
178+.viewer-table td {
179+ border: 1px solid var(--border);
180+ padding: 0.2rem 0.4rem;
181+ white-space: nowrap;
182+}
183+
184+.sheet-tabs {
185+ display: flex;
186+ flex-wrap: wrap;
187+ gap: 0.35rem;
188+}
189+
190+.slide-list {
191+ display: grid;
192+ gap: 0.75rem;
193+ padding-left: 0;
194+ list-style: none;
195+}
196+
197+.slide {
198+ border: 1px solid var(--border);
199+ padding: 0.5rem 0.75rem;
200+}
201+
202+.file-list {
203+ display: grid;
204+ gap: 0.4rem;
205+ padding-left: 0;
206+ list-style: none;
207+}