From 297c9198e685e2453df3474abb0220c41a0bd0a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 18:52:52 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(detail):=20files=20hang=20off?= =?UTF-8?q?=20tasks,=20bytes=20in=20the=20database=20file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Attachments store their bytes in the one database file — no stored_path, no second thing to back up, no way for an uploaded name to become a path. Upload streams with the size limit enforced before buffering past it, the stored mime type is sniffed from the bytes rather than believed from the browser, downloads always answer Content-Disposition: attachment with a header no file name can break out of, and delete is uploader-or-admin. The detail screen gets a FILES section: chips, an upload form, refusals read back off the query string. En route, guard::task_of stopped reading Accounts off leptos context and takes the store as a parameter — the plain axum handlers have no owner tree and panicked the moment a real upload reached the ownership check. --- .../0010_attachments_live_in_the_file.sql | 30 + crates/dizey-core/src/detail.rs | 47 +- crates/dizey-core/src/store/mod.rs | 54 ++ crates/dizey-core/src/store/turso_store.rs | 130 +++- crates/dizey-core/tests/store.rs | 143 ++++- crates/dizey-web/Cargo.toml | 2 +- crates/dizey-web/src/auth.rs | 40 ++ crates/dizey-web/src/detail.rs | 181 +++++- crates/dizey-web/src/files.rs | 318 ++++++++++ crates/dizey-web/src/lib.rs | 2 + crates/dizey-web/src/server.rs | 20 +- crates/dizey-web/tests/http.rs | 572 ++++++++++++++++++ style/main.scss | 77 +++ 13 files changed, 1587 insertions(+), 29 deletions(-) create mode 100644 crates/dizey-core/migrations/0010_attachments_live_in_the_file.sql create mode 100644 crates/dizey-web/src/files.rs diff --git a/crates/dizey-core/migrations/0010_attachments_live_in_the_file.sql b/crates/dizey-core/migrations/0010_attachments_live_in_the_file.sql new file mode 100644 index 0000000..b841562 --- /dev/null +++ b/crates/dizey-core/migrations/0010_attachments_live_in_the_file.sql @@ -0,0 +1,30 @@ +-- Attachments, moved off the filesystem and into the database file. +-- +-- The table 0001 wrote kept a `stored_path`, and nothing ever filled it in. +-- A path is the wrong shape for two reasons. Dizey is one process over one +-- database file, and a second place to keep state is a second thing to back +-- up, to lock, and to get out of step with the rows that name it. And a path +-- is exactly where an uploaded file name must never end up: `../../etc` is a +-- valid file name and a terrible path. Keeping the bytes here means the name +-- is only ever a label printed on a chip, never anything the server resolves. +-- +-- Nothing has ever been written to the old table, so it goes rather than +-- being migrated. +DROP TABLE attachment; + +CREATE TABLE attachment ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + -- The comment this file was posted with, when it was posted with one. + comment_id TEXT REFERENCES comment(id), + -- What the browser called it, kept for display only. + file_name TEXT NOT NULL, + -- What the server decided it is, from the bytes. Never what the upload + -- claimed. + mime_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + bytes BLOB NOT NULL, + uploaded_by TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); +CREATE INDEX attachment_by_task ON attachment(task_id); diff --git a/crates/dizey-core/src/detail.rs b/crates/dizey-core/src/detail.rs index a872142..49d37e1 100644 --- a/crates/dizey-core/src/detail.rs +++ b/crates/dizey-core/src/detail.rs @@ -61,6 +61,38 @@ impl DependencyEdge { } } +/// One file hung off a task, as the detail screen prints it. +/// +/// The bytes are not here and neither is a path: a chip carries the name to +/// show, the size to show beside it, and the id the download handler answers +/// on. The name is display text and nothing resolves it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FileLine { + pub id: String, + pub name: String, + pub size_bytes: u64, + /// The comment this file was posted with, when it was posted with one. + pub comment_id: Option, + pub uploaded_by: String, +} + +impl FileLine { + /// `840 KB`, `1.4 MB` — the size as a chip says it. Whole kilobytes below + /// a megabyte, one decimal above, because a chip is not a disk usage + /// report. + pub fn size_label(&self) -> String { + const KB: u64 = 1024; + const MB: u64 = 1024 * 1024; + if self.size_bytes >= MB { + format!("{:.1} MB", self.size_bytes as f64 / MB as f64) + } else if self.size_bytes >= KB { + format!("{} KB", self.size_bytes / KB) + } else { + format!("{} B", self.size_bytes) + } + } +} + /// What deleting a task would take with it. The confirmation step says this /// out loud before the button fires. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -216,6 +248,8 @@ pub struct TaskDetail { /// Tasks waiting on this one. pub blocks: Vec, pub comments: Vec, + /// Files hung off this task, oldest first. + pub files: Vec, pub activity: Vec, } @@ -276,7 +310,7 @@ pub use reads::{DetailReads, load}; mod reads { use async_trait::async_trait; - use super::{ActivityEntry, Comment, DependencyEdge, TaskDetail, TaskFacts}; + use super::{ActivityEntry, Comment, DependencyEdge, FileLine, TaskDetail, TaskFacts}; use crate::board::{Column, Person}; use crate::store::Result; @@ -304,14 +338,17 @@ mod reads { async fn comments_for_task(&self, task_id: &str) -> Result>; + /// The files hung off a task, without their bytes. + async fn files_for_task(&self, task_id: &str) -> Result>; + async fn activity_for_task(&self, task_id: &str) -> Result>; } - /// Loads one task detail in seven queries — the task, the board's columns, + /// Loads one task detail in eight queries — the task, the board's columns, /// its assignees, the workspace's writers, both directions of its - /// dependencies, its comments and its activity. + /// dependencies, its comments, its files and its activity. /// - /// Seven, not seven-plus-one-per-comment: `a_task_detail_costs_seven_ + /// Eight, not eight-plus-one-per-comment: `a_task_detail_costs_eight_ /// queries_whatever_it_carries` in `tests/store.rs` holds that line. pub async fn load( reads: &dyn DetailReads, @@ -332,6 +369,7 @@ mod reads { let assignable = reads.assignable_people(workspace_id).await?; let edges = reads.dependencies_for_task(task_id).await?; let comments = reads.comments_for_task(task_id).await?; + let files = reads.files_for_task(task_id).await?; let activity = reads.activity_for_task(task_id).await?; let Some(column) = columns @@ -365,6 +403,7 @@ mod reads { blocked_by, blocks, comments, + files, activity, })) } diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index c4bc8f4..7070656 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -64,6 +64,37 @@ pub struct Workspace { pub allowed_file_types: Vec, } +/// One file hung off a task, as a screen lists it: a name, a type, a size and +/// who put it there. The bytes are deliberately not on this type — it is what +/// handlers load and pages serialise, and a file's contents have no business +/// travelling with a list of file names. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attachment { + pub id: String, + pub task_id: String, + /// The comment it was posted with, when it was posted with one. + pub comment_id: Option, + /// What the browser called the file. A label, never a path. + pub file_name: String, + /// What the server decided the bytes are, never what the upload claimed. + pub mime_type: String, + pub size_bytes: u64, + pub uploaded_by: String, + pub uploaded_at: OffsetDateTime, +} + +/// A file on its way into the table, bytes and all. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewAttachment<'a> { + pub task_id: &'a str, + pub comment_id: Option<&'a str>, + pub file_name: &'a str, + pub mime_type: &'a str, + pub bytes: Vec, + pub uploaded_by: &'a str, + pub at: OffsetDateTime, +} + /// A sender as an admin typed it, on its way to the table. /// /// `password` is `None` when the admin left the field untouched, which is what @@ -494,6 +525,29 @@ pub trait Store: BoardReads + DetailReads + 'static { at: OffsetDateTime, ) -> Result; + /// Hangs a file off a task. The bytes go into the database file with the + /// row: there is no second place for a Dizey deployment to keep, and no + /// path for an uploaded name to become. + /// + /// Nothing here decides whether the file was allowed — its size, its type + /// and who may attach it are the handler's questions, answered before the + /// bytes reach this call. + async fn add_attachment(&self, new: NewAttachment<'_>) -> Result; + + /// What is hung off a task, oldest first, without the bytes. This is what + /// a screen reads; a screen never carries a file's contents. + async fn attachments(&self, task_id: &str) -> Result>; + + /// One file's row, still without its bytes. The `task_id` on it is what the + /// handler checks before it hands anything over. + async fn attachment(&self, id: &str) -> Result>; + + /// The bytes themselves, for the one handler that serves them. + async fn attachment_bytes(&self, id: &str) -> Result>>; + + /// Takes a file away for good. `false` when there was no such row. + async fn delete_attachment(&self, id: &str) -> Result; + /// Writes the title, description and deadline the detail screen saved, and /// records one activity line per field that actually changed. async fn save_task( diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index 95b099e..ea8cde2 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -13,14 +13,15 @@ use turso::{Builder, Connection, Row, Value, params}; use uuid::Uuid; use super::{ - Audience, Deletion, Event, Freeing, MailRule, MailSend, NewSender, NewTask, NewUser, Recipient, - Result, + Attachment, Audience, Deletion, Event, Freeing, MailRule, MailSend, NewAttachment, NewSender, + NewTask, NewUser, Recipient, Result, SendState, SenderTest, Session, SigninLink, Store, StoreError, Trigger, User, Workspace, }; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition}; use crate::detail::{ - ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, TaskFacts, + ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine, + TaskFacts, }; use time::Date; use time::format_description::BorrowedFormatItem; @@ -37,6 +38,10 @@ const MIGRATIONS: &[(i64, &str)] = &[ (7, include_str!("../../migrations/0007_who_invited.sql")), (8, include_str!("../../migrations/0008_sender_is_settings.sql")), (9, include_str!("../../migrations/0009_sender_test.sql")), + ( + 10, + include_str!("../../migrations/0010_attachments_live_in_the_file.sql"), + ), ]; /// The board a fresh workspace gets, and its columns. `Done` is the column @@ -319,6 +324,20 @@ fn opt_stamp(row: &Row, idx: usize) -> Result> { } } +/// One attachment row, in the column order every query above selects. +fn attachment_row(row: &Row) -> Result { + Ok(Attachment { + id: text(row, 0)?, + task_id: text(row, 1)?, + comment_id: opt_text(row, 2)?, + file_name: text(row, 3)?, + mime_type: text(row, 4)?, + size_bytes: row.get::(5).map_err(backend)?.max(0) as u64, + uploaded_by: text(row, 6)?, + uploaded_at: parse_stamp(&text(row, 7)?)?, + }) +} + fn text(row: &Row, idx: usize) -> Result { row.get::(idx).map_err(backend) } @@ -1244,6 +1263,86 @@ impl Store for TursoStore { Ok(id) } + async fn add_attachment(&self, new: NewAttachment<'_>) -> Result { + let id = Uuid::new_v4().to_string(); + let size = new.bytes.len() as i64; + self.conn + .execute( + "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \ + size_bytes, bytes, uploaded_by, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + params![ + id.clone(), + new.task_id, + new.comment_id, + new.file_name, + new.mime_type, + size, + new.bytes, + new.uploaded_by, + stamp(new.at)? + ], + ) + .await + .map_err(backend)?; + Ok(id) + } + + async fn attachments(&self, task_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \ + uploaded_by, created_at FROM attachment \ + WHERE task_id = ?1 ORDER BY created_at, rowid", + params![task_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(attachment_row(&row)?); + } + Ok(out) + } + + async fn attachment(&self, id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \ + uploaded_by, created_at FROM attachment WHERE id = ?1", + params![id], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => Ok(Some(attachment_row(&row)?)), + None => Ok(None), + } + } + + async fn attachment_bytes(&self, id: &str) -> Result>> { + let mut rows = self + .conn + .query("SELECT bytes FROM attachment WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => Ok(Some(row.get::>(0).map_err(backend)?)), + None => Ok(None), + } + } + + async fn delete_attachment(&self, id: &str) -> Result { + let gone = self + .conn + .execute("DELETE FROM attachment WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + Ok(gone > 0) + } + async fn save_task( &self, task_id: &str, @@ -2238,6 +2337,31 @@ impl DetailReads for TursoStore { Ok(out) } + async fn files_for_task(&self, task_id: &str) -> Result> { + // `bytes` is not in the SELECT on purpose: a screen listing five files + // must not drag five files through memory to print their names. + let mut rows = self + .conn + .query( + "SELECT id, file_name, size_bytes, comment_id, uploaded_by \ + FROM attachment WHERE task_id = ?1 ORDER BY created_at, rowid", + params![task_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(FileLine { + id: text(&row, 0)?, + name: text(&row, 1)?, + size_bytes: row.get::(2).map_err(backend)?.max(0) as u64, + comment_id: opt_text(&row, 3)?, + uploaded_by: text(&row, 4)?, + }); + } + Ok(out) + } + async fn activity_for_task(&self, task_id: &str) -> Result> { // LEFT JOIN: a line the system wrote has no actor, and dropping it // would hide exactly the events the rules engine causes. diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 580e3e4..69e7e4c 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -9,7 +9,8 @@ use std::path::PathBuf; use dizey_core::Role; use dizey_core::auth::{Token, hash_password}; use dizey_core::store::{ - Audience, MailRule, NewSender, NewUser, SendState, Store, StoreError, Trigger, TursoStore, User, + Audience, MailRule, NewAttachment, NewSender, NewUser, SendState, Store, StoreError, Trigger, + TursoStore, User, }; use time::{Duration, OffsetDateTime}; use uuid::Uuid; @@ -89,14 +90,14 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("dizey.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 9); + assert_eq!(first.schema_version().await.unwrap(), 10); claim(&first).await; drop(first); // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and // must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 9); + assert_eq!(second.schema_version().await.unwrap(), 10); assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); drop(second); let _ = std::fs::remove_dir_all(&dir); @@ -1852,6 +1853,14 @@ impl DetailReads for CountingDetail<'_> { self.inner.comments_for_task(task_id).await } + async fn files_for_task( + &self, + task_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.files_for_task(task_id).await + } + async fn activity_for_task(&self, task_id: &str) -> Result, StoreError> { self.tick(); self.inner.activity_for_task(task_id).await @@ -2152,7 +2161,7 @@ async fn saving_a_task_records_only_what_changed() { } #[tokio::test] -async fn a_task_detail_costs_seven_queries_whatever_it_carries() { +async fn a_task_detail_costs_eight_queries_whatever_it_carries() { let (scratch, workspace, admin) = workspace_with_admin().await; let store = &scratch.store; let now = OffsetDateTime::now_utc(); @@ -2160,7 +2169,7 @@ async fn a_task_detail_costs_seven_queries_whatever_it_carries() { let bare = add_task(store, &workspace, "Backlog", "bare", None, &admin).await; let counted = CountingDetail::new(store); load_detail(&counted, &workspace, &bare).await.unwrap(); - assert_eq!(counted.count(), 7, "a task with nothing hung off it"); + assert_eq!(counted.count(), 8, "a task with nothing hung off it"); // Twenty comments, twenty activity lines, twenty people who could be // assigned and twenty tasks on the other end of a dependency — the four @@ -2209,7 +2218,7 @@ async fn a_task_detail_costs_seven_queries_whatever_it_carries() { assert_eq!(detail.activity.len(), 21); assert_eq!( counted.count(), - 7, + 8, "the round trips a detail costs must not follow what it carries" ); } @@ -3516,3 +3525,125 @@ async fn an_account_records_the_admin_who_made_it() { let reread = scratch.store.user(&member.id).await.unwrap().unwrap(); assert_eq!(reread.invited_by.as_deref(), Some(admin_id.as_str())); } + +#[tokio::test] +async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await; + + // Bytes that are not text and are not valid UTF-8, because an attachment + // is not a string and the column it lives in must not treat it as one. + let bytes: Vec = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe]; + let id = store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "shot.png", + mime_type: "image/png", + bytes: bytes.clone(), + uploaded_by: &admin, + at: now, + }) + .await + .unwrap(); + + let row = store.attachment(&id).await.unwrap().unwrap(); + assert_eq!(row.task_id, task); + assert_eq!(row.file_name, "shot.png"); + assert_eq!(row.mime_type, "image/png"); + assert_eq!(row.size_bytes, bytes.len() as u64); + assert_eq!(row.uploaded_by, admin); + assert_eq!(store.attachment_bytes(&id).await.unwrap().unwrap(), bytes); +} + +#[tokio::test] +async fn a_file_name_that_is_a_path_is_stored_as_the_label_it_is() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await; + + // Nothing in the store resolves a name, so the worst name there is comes + // back exactly as it went in: it is a label on a chip, not a path. + let id = store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "../../etc/passwd", + mime_type: "application/octet-stream", + bytes: b"root:x:0:0".to_vec(), + uploaded_by: &admin, + at: now, + }) + .await + .unwrap(); + let row = store.attachment(&id).await.unwrap().unwrap(); + assert_eq!(row.file_name, "../../etc/passwd"); + // And nothing was written anywhere but the database file and its key + // (see `store::secret`) — never a file named after the attachment. + let written: Vec = std::fs::read_dir(&scratch.dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| !name.starts_with("dizey.db") && name != "dizey.key") + .collect(); + assert!(written.is_empty(), "{written:?}"); +} + +#[tokio::test] +async fn the_detail_lists_a_task_s_files_oldest_first_and_never_their_bytes() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await; + + for (n, name) in ["first.pdf", "second.png"].iter().enumerate() { + store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: name, + mime_type: "application/pdf", + bytes: vec![b'x'; 2048], + uploaded_by: &admin, + at: now + time::Duration::seconds(n as i64), + }) + .await + .unwrap(); + } + + let detail = load_detail(store, &workspace, &task) + .await + .unwrap() + .unwrap(); + let names: Vec<&str> = detail.files.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, vec!["first.pdf", "second.png"]); + assert_eq!(detail.files[0].size_label(), "2 KB"); +} + +#[tokio::test] +async fn a_file_can_be_taken_away_and_saying_so_twice_is_answered_honestly() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await; + let id = store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "note.txt", + mime_type: "text/plain", + bytes: b"hello".to_vec(), + uploaded_by: &admin, + at: now, + }) + .await + .unwrap(); + + assert!(store.delete_attachment(&id).await.unwrap()); + assert!(!store.delete_attachment(&id).await.unwrap()); + assert!(store.attachment(&id).await.unwrap().is_none()); + assert!(store.attachment_bytes(&id).await.unwrap().is_none()); + assert!(store.attachments(&task).await.unwrap().is_empty()); +} diff --git a/crates/dizey-web/Cargo.toml b/crates/dizey-web/Cargo.toml index eded948..45d94a5 100644 --- a/crates/dizey-web/Cargo.toml +++ b/crates/dizey-web/Cargo.toml @@ -19,7 +19,7 @@ time.workspace = true thiserror.workspace = true dizey-core = { workspace = true } -axum = { version = "0.8.9", optional = true } +axum = { version = "0.8.9", features = ["multipart"], optional = true } tokio = { workspace = true, optional = true } tower = { version = "0.5.2", optional = true } tower-http = { version = "0.7.0", features = ["fs", "compression-gzip"], optional = true } diff --git a/crates/dizey-web/src/auth.rs b/crates/dizey-web/src/auth.rs index f3190d1..83e28e9 100644 --- a/crates/dizey-web/src/auth.rs +++ b/crates/dizey-web/src/auth.rs @@ -46,6 +46,12 @@ pub enum Refusal { BadSender(String), /// A comment with nothing in it. EmptyComment, + /// The upload arrived without a file in it. + NoFile, + /// The bytes kept coming past what this workspace allows per file. + FileTooBig, + /// The name does not end in one of the extensions the admin allows. + FileTypeNotAllowed, /// A rule with no subject line: the mail it sends would arrive blank. EmptySubject, /// The date field did not hold a date. @@ -87,6 +93,14 @@ impl Refusal { } Refusal::BadSender(problem) => problem.clone(), Refusal::EmptyComment => "Write something first.".to_string(), + Refusal::NoFile => "Choose a file first.".to_string(), + Refusal::FileTooBig => { + "That file is bigger than this workspace allows. The limit is in Settings." + .to_string() + } + Refusal::FileTypeNotAllowed => { + "That kind of file is not on this workspace's allowed list.".to_string() + } Refusal::EmptySubject => "Give the rule a subject line.".to_string(), Refusal::BadDeadline => "That is not a date.".to_string(), Refusal::Cycle => "That link would put this task behind itself.".to_string(), @@ -130,6 +144,9 @@ impl Refusal { Refusal::BadFileType => "bad-file-type", Refusal::BadSender(_) => "bad-sender", Refusal::EmptyComment => "empty-comment", + Refusal::NoFile => "no-file", + Refusal::FileTooBig => "file-too-big", + Refusal::FileTypeNotAllowed => "file-type", Refusal::EmptySubject => "empty-subject", Refusal::BadDeadline => "bad-deadline", Refusal::Cycle => "cycle", @@ -155,6 +172,9 @@ impl Refusal { "link-not-usable" => Refusal::LinkNotUsable, "empty-title" => Refusal::EmptyTitle, "empty-comment" => Refusal::EmptyComment, + "no-file" => Refusal::NoFile, + "file-too-big" => Refusal::FileTooBig, + "file-type" => Refusal::FileTypeNotAllowed, "empty-subject" => Refusal::EmptySubject, "bad-deadline" => Refusal::BadDeadline, "cycle" => Refusal::Cycle, @@ -209,6 +229,23 @@ where } } +/// What a plain form post refused with, read from the address alone. +/// +/// [`refusal_of`] needs a server action to read the answer off. The upload is +/// not one — it is a multipart form posted to an axum handler, which can only +/// ever answer a browser with a redirect — so its refusal always comes back +/// the way a script-less browser's does, and this reads it from there. +pub fn refusal_from_query(call: &'static str) -> impl Fn() -> Option + Copy { + let query = leptos_router::hooks::use_query_map(); + move || { + let query = query.read(); + if query.get("on")? != call { + return None; + } + Refusal::from_code(&query.get("refusal")?) + } +} + #[cfg(test)] mod refusal_tests { use super::*; @@ -227,6 +264,9 @@ mod refusal_tests { Refusal::LinkNotUsable, Refusal::EmptyTitle, Refusal::EmptyComment, + Refusal::NoFile, + Refusal::FileTooBig, + Refusal::FileTypeNotAllowed, Refusal::BadDeadline, Refusal::Cycle, Refusal::MovedAlready, diff --git a/crates/dizey-web/src/detail.rs b/crates/dizey-web/src/detail.rs index f5ed849..ee8ce3f 100644 --- a/crates/dizey-web/src/detail.rs +++ b/crates/dizey-web/src/detail.rs @@ -38,6 +38,10 @@ pub struct DetailSnapshot { pub may_comment: bool, /// Whether this person may delete the task. A writer may. pub may_delete: bool, + /// Extensions the upload form's `accept` attribute may offer. Empty means + /// every type — the same "empty means everything" the store's limits use. + pub allowed_file_types: Vec, + pub attachment_limit_mb: u64, } /// Which way round a dependency runs, as it travels in a form. @@ -54,13 +58,20 @@ pub enum Direction { pub(crate) mod guard { use crate::auth::Refusal; use dizey_core::detail::TaskFacts; - use dizey_core::store::User; + use dizey_core::store::{Store, User}; /// The task, if this person's workspace is the one holding it. A task in /// another workspace is not found rather than forbidden: the answer says /// nothing about whether the id is real. - pub async fn task_of(user: &User, task_id: &str) -> Result { - let store = crate::server::accounts().store().clone(); + /// + /// Takes the store rather than reading it off leptos context, so a plain + /// axum handler with no leptos owner tree — `crate::files`'s upload and + /// download routes — can call this the same way a server function does. + pub async fn task_of( + store: &dyn Store, + user: &User, + task_id: &str, + ) -> Result { match store.task(task_id).await { Ok(Some(facts)) if facts.workspace_id == user.workspace_id => Ok(facts), Ok(_) => Err(Refusal::NotFound), @@ -74,7 +85,8 @@ pub(crate) mod guard { /// The writer behind this request and the task they named. pub async fn writer_and_task(task_id: &str) -> Result<(User, TaskFacts), Refusal> { let user = crate::server::require_writer().await?; - let facts = task_of(&user, task_id).await?; + let store = crate::server::accounts().store().clone(); + let facts = task_of(store.as_ref(), &user, task_id).await?; Ok((user, facts)) } } @@ -131,12 +143,26 @@ pub async fn fetch_task(task_id: String) -> Result pair, Err(refusal) => return Ok(Some(refusal)), }; - let other = match guard::task_of(&actor, &other_id).await { + let store = accounts().store().clone(); + let other = match guard::task_of(store.as_ref(), &actor, &other_id).await { Ok(facts) => facts, Err(refusal) => return Ok(Some(refusal)), }; @@ -318,7 +345,6 @@ pub async fn link_tasks( Direction::BlockedBy => (task_id.clone(), other_id.clone()), Direction::Blocks => (other_id.clone(), task_id.clone()), }; - let store = accounts().store().clone(); let now = OffsetDateTime::now_utc(); match store.add_dependency(&blocked, &blocking, now).await { Ok(()) => {} @@ -354,7 +380,8 @@ pub async fn unlink_tasks( Ok(pair) => pair, Err(refusal) => return Ok(Some(refusal)), }; - let other = match guard::task_of(&actor, &other_id).await { + let store = accounts().store().clone(); + let other = match guard::task_of(store.as_ref(), &actor, &other_id).await { Ok(facts) => facts, Err(refusal) => return Ok(Some(refusal)), }; @@ -363,7 +390,6 @@ pub async fn unlink_tasks( Direction::BlockedBy => (task_id.clone(), other_id.clone()), Direction::Blocks => (other_id.clone(), task_id.clone()), }; - let store = accounts().store().clone(); let now = OffsetDateTime::now_utc(); let fail = |e: dizey_core::store::StoreError| ServerFnError::new(e.to_string()); store @@ -397,7 +423,8 @@ pub async fn post_comment(task_id: String, body: String) -> Result Result Result, ServerFnErr Ok(None) } +/// Deletes an attachment's row and its bytes. This is a hard delete, unlike +/// [`delete_task`]'s soft one: a file is a blob on disk, not a fact worth +/// keeping around for the audit trail, so there is nothing to undo by hand. +/// That is also why the gate is narrower than a writer's — only the person who +/// put the file there, or an admin cleaning up after them, may take it away. +#[server] +pub async fn delete_file(file_id: String) -> Result, ServerFnError> { + use crate::server::{accounts, require_user}; + + let user = match require_user().await { + Ok(user) => user, + Err(refusal) => return Ok(Some(refusal)), + }; + let store = accounts().store().clone(); + let Some(attachment) = store + .attachment(&file_id) + .await + .map_err(|e| ServerFnError::new(e.to_string()))? + else { + return Ok(Some(Refusal::NotFound)); + }; + if let Err(refusal) = guard::task_of(store.as_ref(), &user, &attachment.task_id).await { + return Ok(Some(refusal)); + } + if user.id != attachment.uploaded_by && !user.role.can_administer() { + return Ok(Some(Refusal::Forbidden)); + } + + store + .delete_attachment(&file_id) + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + Ok(None) +} + // -- the screen ------------------------------------------------------------- /// The artboard's STATUS control: the column the card sits in, and the way to @@ -1144,12 +1205,14 @@ fn DetailScreen( ) -> impl IntoView { let DetailSnapshot { detail, - me: _, + me, today, linkable, may_write, may_comment, may_delete, + allowed_file_types, + attachment_limit_mb, } = snapshot; let id = StoredValue::new(detail.id.clone()); @@ -1164,22 +1227,33 @@ fn DetailScreen( let deadline_label = detail.deadline_label(today); let assignee_count = detail.assignees.len(); let comment_count = detail.comments.len(); + let file_count = detail.files.len(); let unassigned: Vec = detail.unassigned().cloned().collect(); let has_deps = !detail.blocked_by.is_empty() || !detail.blocks.is_empty(); + let accept = (!allowed_file_types.is_empty()).then(|| { + allowed_file_types + .iter() + .map(|kind| format!(".{kind}")) + .collect::>() + .join(",") + }); + let upload_refusal = crate::auth::refusal_from_query("upload_file"); let comment = ServerAction::::new(); let remove = ServerAction::::new(); let move_to = ServerAction::::new(); + let drop_file = ServerAction::::new(); let comment_refusal = crate::auth::refusal_of(comment); let remove_refusal = crate::auth::refusal_of(remove); let move_refusal = crate::auth::refusal_of(move_to); + let drop_file_refusal = crate::auth::refusal_of(drop_file); // Deleting is two steps: ask what it would cost, then say it out loud and // let the person decide. The artboard's red button had no confirmation and // this action reaches other people's tasks. let ask = ServerAction::::new(); // Every action that lands re-reads the task and the board behind it. The // per-region editors own their own actions and do the same. - for value in [comment.value(), move_to.value()] { + for value in [comment.value(), move_to.value(), drop_file.value()] { Effect::new(move |_| { if matches!(value.get(), Some(Ok(None))) { on_change(); @@ -1340,6 +1414,50 @@ fn DetailScreen( {(!has_deps).then(|| view! {

"Nothing blocks this task."

})} +
+
+ "FILES" + {file_count} +
+ {(file_count > 0) + .then(|| { + view! { +
+ {detail + .files + .iter() + .map(|file| { + view! { } + }) + .collect_view()} +
+ } + })} + {(file_count == 0).then(|| view! {

"No files yet."

})} + {refused(drop_file_refusal)} + {may_comment + .then(|| { + view! { +
+ + + + + {format!("Up to {attachment_limit_mb} MB.")} + +
+ {refused(upload_refusal)} + } + })} +
+
"COMMENTS" @@ -1616,6 +1734,43 @@ fn DepRow( } } +/// One attachment, chip-shaped like a dependency. A file posted with a +/// comment stays listed here too — a person hunting for what someone +/// attached should not have to remember which comment it rode in on — with a +/// quiet note saying where it came from. +#[component] +fn FileChip( + file: dizey_core::detail::FileLine, + me: Me, + action: ServerAction, +) -> impl IntoView { + let may_drop = me.id == file.uploaded_by || me.role.can_administer(); + let size = file.size_label(); + let on_comment = file.comment_id.is_some(); + let file_id = file.id.clone(); + + view! { + + + {file.name.clone()} + + {size} + {on_comment.then(|| view! { "on a comment" })} + {may_drop + .then(|| { + view! { + + + + + } + })} + + } +} + #[component] fn CommentRow(comment: Comment) -> impl IntoView { use dizey_core::detail::moment_label; diff --git a/crates/dizey-web/src/files.rs b/crates/dizey-web/src/files.rs new file mode 100644 index 0000000..abde088 --- /dev/null +++ b/crates/dizey-web/src/files.rs @@ -0,0 +1,318 @@ +//! Attachment upload and download, as plain axum handlers. +//! +//! These sit outside the leptos server-function machinery: a multipart body +//! and a byte stream are not things a server function's JSON codec is meant +//! to carry, so the router hands `/files` and `/files/{id}` to axum directly +//! and the two share `Accounts` and the session cookie the same way the rest +//! of the app does. + +use axum::extract::{Extension, Multipart, Path}; +use axum::http::{HeaderMap, HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Redirect, Response}; +use dizey_core::accounts::Accounts; +use dizey_core::store::{NewAttachment, User}; +use time::OffsetDateTime; + +use crate::auth::Refusal; +use crate::detail::guard; + +/// The person behind this request, read off the session cookie in `headers` +/// rather than the leptos request context a plain axum handler has none of. +pub async fn user_of(accounts: &Accounts, headers: &HeaderMap) -> Option { + let session = crate::server::session_in(headers)?; + accounts.authenticate(&session).await.ok().flatten() +} + +/// Where the browser lands once the upload is settled, success or refusal +/// alike — the task detail modal it was posted from, reopened. This is a +/// plain redirect rather than the `carry_refusal_on_redirect` middleware's +/// rewrite: that middleware turns a `302` server-function answer into one of +/// these, but a handler outside the server-function machinery can just write +/// the query string itself. +fn back_to(task_id: &str, refusal: Option) -> Response { + let location = match refusal { + Some(refusal) => format!("/?task={task_id}&refusal={}&on=upload_file", refusal.code()), + None => format!("/?task={task_id}"), + }; + Redirect::to(&location).into_response() +} + +/// The same redirect, for the refusals that land before a `task_id` is even +/// known to carry in the query. `Redirect::to` is `303 See Other`, which +/// matters here: `carry_refusal_on_redirect` in `server.rs` only rewrites the +/// `302`s a server function's own redirect answers with, and must leave this +/// handler's redirects alone. +fn home(refusal: Refusal) -> Response { + Redirect::to(&format!("/?refusal={}&on=upload_file", refusal.code())).into_response() +} + +/// A basename, stripped of anything that could make it look like a path or +/// carry a control character. What a browser calls a file is a label on a +/// row, never a place to write bytes. +fn label_of(file_name: &str) -> String { + let base = file_name + .rsplit(['/', '\\']) + .next() + .unwrap_or(file_name); + base.chars().filter(|c| !c.is_control()).collect() +} + +/// What the bytes are, decided from the bytes themselves — never from the +/// part's `content_type()`, which is whatever the browser felt like sending. +fn sniff(bytes: &[u8]) -> &'static str { + if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { + "image/png" + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + "image/jpeg" + } else if bytes.starts_with(b"GIF8") { + "image/gif" + } else if bytes.starts_with(b"%PDF-") { + "application/pdf" + } else if bytes.starts_with(b"PK\x03\x04") { + "application/zip" + } else if bytes.starts_with(&[0x1F, 0x8B]) { + "application/gzip" + } else if std::str::from_utf8(bytes).is_ok() { + "text/plain" + } else { + "application/octet-stream" + } +} + +/// Takes one file onto a task. The route this hangs off already caps the +/// whole request body at the widest limit any workspace could set +/// ([`crate::settings::WIDEST_ATTACHMENT_MB`]); this handler enforces the +/// workspace's own, usually narrower, limit while the bytes are still +/// arriving rather than after they have all landed. +pub async fn upload( + Extension(accounts): Extension, + headers: HeaderMap, + mut multipart: Multipart, +) -> Response { + let Some(user) = user_of(&accounts, &headers).await else { + return home(Refusal::SignInFirst); + }; + if !user.role.can_comment() { + return home(Refusal::Forbidden); + } + + let mut task_id: Option = None; + let mut comment_id: Option = None; + let mut file_name: Option = None; + let mut bytes: Option> = None; + + let store = accounts.store().clone(); + + loop { + let field = match multipart.next_field().await { + Ok(Some(field)) => field, + Ok(None) => break, + Err(_) => return home(Refusal::NoFile), + }; + match field.name() { + Some("task_id") => { + task_id = field.text().await.ok(); + } + Some("comment_id") => { + comment_id = field.text().await.ok(); + } + Some("file") => { + let Some(name) = field.file_name().map(str::to_string) else { + continue; + }; + if name.is_empty() { + continue; + } + + let Some(task_id) = task_id.as_deref() else { + return home(Refusal::NotFound); + }; + if let Err(refusal) = guard::task_of(store.as_ref(), &user, task_id).await { + return back_to(task_id, Some(refusal)); + } + let Ok(Some(workspace)) = store.workspace().await else { + return back_to(task_id, Some(Refusal::NotFound)); + }; + let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_lowercase()); + let allowed = workspace.allowed_file_types.is_empty() + || extension + .as_deref() + .is_some_and(|ext| workspace.allowed_file_types.iter().any(|a| a == ext)); + if !allowed { + return back_to(task_id, Some(Refusal::FileTypeNotAllowed)); + } + + let limit = workspace.attachment_limit_bytes; + let mut field = field; + let mut collected = Vec::new(); + loop { + match field.chunk().await { + Ok(Some(chunk)) => { + if (collected.len() + chunk.len()) as u64 > limit { + return back_to(task_id, Some(Refusal::FileTooBig)); + } + collected.extend_from_slice(&chunk); + } + Ok(None) => break, + Err(_) => return back_to(task_id, Some(Refusal::FileTooBig)), + } + } + + file_name = Some(name); + bytes = Some(collected); + } + _ => {} + } + } + + let Some(task_id) = task_id else { + return home(Refusal::NotFound); + }; + let Some(file_name) = file_name else { + return back_to(&task_id, Some(Refusal::NoFile)); + }; + let bytes = bytes.unwrap_or_default(); + + // A `comment_id` only travels if it names a comment that is actually on + // this task; anything else is dropped rather than refused, since the + // upload itself is still perfectly good without it. + let comment_id = match comment_id { + Some(id) => { + let on_task = store + .comments_for_task(&task_id) + .await + .map(|comments| comments.iter().any(|c| c.id == id)) + .unwrap_or(false); + on_task.then_some(id) + } + None => None, + }; + + let label = label_of(&file_name); + let mime_type = sniff(&bytes); + + let added = store + .add_attachment(NewAttachment { + task_id: &task_id, + comment_id: comment_id.as_deref(), + file_name: &label, + mime_type, + bytes, + uploaded_by: &user.id, + at: OffsetDateTime::now_utc(), + }) + .await; + + match added { + Ok(_) => back_to(&task_id, None), + Err(_) => back_to(&task_id, Some(Refusal::NotFound)), + } +} + +/// The `Content-Disposition` header for one download: always `attachment`, so +/// an uploaded HTML or SVG file is offered to save rather than run on Dizey's +/// origin. The ASCII fallback keeps only characters no quoting scheme could +/// turn into a delimiter or a control character; `filename*` carries the real +/// name, percent-encoded, for browsers that read it. +fn disposition_of(file_name: &str) -> String { + let ascii: String = file_name + .chars() + .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { c } else { '_' }) + .collect(); + let mut encoded = String::new(); + for &byte in file_name.as_bytes() { + let c = byte as char; + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '~' | '-') { + encoded.push(c); + } else { + encoded.push_str(&format!("%{byte:02X}")); + } + } + format!("attachment; filename=\"{ascii}\"; filename*=UTF-8''{encoded}") +} + +/// Serves one attachment's bytes, or the same not-found a stranger to the +/// task would see for a task that does not exist — never a `403`, which would +/// confirm the id belongs to someone else's workspace. +pub async fn download( + Extension(accounts): Extension, + headers: HeaderMap, + Path(id): Path, +) -> Response { + let Some(user) = user_of(&accounts, &headers).await else { + return home(Refusal::SignInFirst); + }; + + let store = accounts.store().clone(); + let Ok(Some(row)) = store.attachment(&id).await else { + return StatusCode::NOT_FOUND.into_response(); + }; + if guard::task_of(store.as_ref(), &user, &row.task_id).await.is_err() { + return StatusCode::NOT_FOUND.into_response(); + } + let Ok(Some(bytes)) = store.attachment_bytes(&id).await else { + return StatusCode::NOT_FOUND.into_response(); + }; + + let mut response = bytes.into_response(); + let headers = response.headers_mut(); + headers.insert( + axum::http::header::CONTENT_TYPE, + HeaderValue::from_str(&row.mime_type).unwrap_or(HeaderValue::from_static("application/octet-stream")), + ); + headers.insert( + axum::http::header::CONTENT_DISPOSITION, + HeaderValue::from_str(&disposition_of(&row.file_name)) + .unwrap_or(HeaderValue::from_static("attachment")), + ); + response +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sniffs_the_magic_numbers() { + assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png"); + assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg"); + assert_eq!(sniff(b"hello, this is plainly text"), "text/plain"); + assert_eq!(sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), "application/octet-stream"); + } + + #[test] + fn labels_strip_the_path_and_the_control_characters() { + assert_eq!(label_of("../../etc/passwd"), "passwd"); + assert_eq!(label_of(r"a\b.txt"), "b.txt"); + assert_eq!(label_of("name\r\nwith\tcontrol.txt"), "namewithcontrol.txt"); + } + + #[test] + fn disposition_carries_no_quote_or_control_character() { + let header = disposition_of("a\"b\r\nX: y.txt"); + assert!(!header.contains('\r')); + assert!(!header.contains('\n')); + assert_eq!( + header, + "attachment; filename=\"a_b__X__y.txt\"; filename*=UTF-8''a%22b%0D%0AX%3A%20y.txt" + ); + } + + #[test] + fn disposition_of_a_traversal_name_keeps_no_path_meaning() { + let header = disposition_of("../../etc/passwd"); + assert_eq!( + header, + "attachment; filename=\".._.._etc_passwd\"; filename*=UTF-8''..%2F..%2Fetc%2Fpasswd" + ); + } + + #[test] + fn disposition_of_a_non_ascii_name_falls_back_and_percent_encodes() { + let header = disposition_of("résumé.pdf"); + assert_eq!( + header, + "attachment; filename=\"r_sum_.pdf\"; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf" + ); + } +} diff --git a/crates/dizey-web/src/lib.rs b/crates/dizey-web/src/lib.rs index 086085a..97b5d24 100644 --- a/crates/dizey-web/src/lib.rs +++ b/crates/dizey-web/src/lib.rs @@ -10,6 +10,8 @@ pub mod pages; pub mod rules; pub mod settings; #[cfg(feature = "ssr")] +pub mod files; +#[cfg(feature = "ssr")] pub mod server; #[cfg(feature = "ssr")] pub mod smtp; diff --git a/crates/dizey-web/src/server.rs b/crates/dizey-web/src/server.rs index 734c3ae..18435cc 100644 --- a/crates/dizey-web/src/server.rs +++ b/crates/dizey-web/src/server.rs @@ -103,8 +103,14 @@ pub fn mail() -> Mail { /// The cookie value this request presented, if it presented one. pub fn presented_session() -> Option { - let parts = use_context::()?; - for header in parts.headers.get_all(COOKIE) { + session_in(&use_context::()?.headers) +} + +/// The same scan as `presented_session`, off a plain `HeaderMap` rather than +/// the leptos request context — for handlers axum calls directly, which have +/// no such context to read. +pub fn session_in(headers: &axum::http::HeaderMap) -> Option { + for header in headers.get_all(COOKIE) { let Ok(raw) = header.to_str() else { continue }; for pair in raw.split(';') { let pair = pair.trim(); @@ -245,6 +251,15 @@ pub fn router( let routes = generate_route_list(crate::app::App); Router::new() .route("/healthz", axum::routing::get(|| async { "ok" })) + .route( + "/files", + axum::routing::post(crate::files::upload).layer( + axum::extract::DefaultBodyLimit::max( + crate::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024, + ), + ), + ) + .route("/files/{id}", axum::routing::get(crate::files::download)) .leptos_routes_with_context( &leptos_options, routes, @@ -265,6 +280,7 @@ pub fn router( ) .fallback(leptos_axum::file_and_error_handler(crate::app::shell)) .layer(axum::middleware::from_fn(carry_refusal_on_redirect)) + .layer(axum::Extension(accounts)) .with_state(leptos_options) } diff --git a/crates/dizey-web/tests/http.rs b/crates/dizey-web/tests/http.rs index c65c899..88cfbc1 100644 --- a/crates/dizey-web/tests/http.rs +++ b/crates/dizey-web/tests/http.rs @@ -143,6 +143,111 @@ impl App { location, } } + + /// Posts a multipart form the way a browser's + /// `
` does, hand-built rather than + /// pulling in a client crate for it: the fields first, in the order given + /// — the upload handler reads `task_id` before it reaches `file` — then + /// one `file` part if given. + async fn post_multipart( + &self, + path: &str, + cookie: Option<&str>, + fields: &[(&str, &str)], + file: Option<(&str, &str, &[u8])>, + ) -> Answer { + const BOUNDARY: &str = "dizey-test-boundary"; + let mut body = Vec::new(); + for (name, value) in fields { + body.extend_from_slice( + format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n" + ) + .as_bytes(), + ); + } + if let Some((filename, content_type, bytes)) = file { + body.extend_from_slice( + format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n" + ) + .as_bytes(), + ); + body.extend_from_slice(bytes); + body.extend_from_slice(b"\r\n"); + } + body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes()); + + let mut request = Request::builder() + .method("POST") + .uri(path) + .header( + header::CONTENT_TYPE, + format!("multipart/form-data; boundary={BOUNDARY}"), + ); + if let Some(cookie) = cookie { + request = request.header( + header::COOKIE, + HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), + ); + } + let response = self + .router + .clone() + .oneshot(request.body(Body::from(body)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let location = response + .headers() + .get(header::LOCATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + Answer { + status, + session: None, + body: String::from_utf8_lossy(&bytes).into_owned(), + location, + } + } + + /// Gets a page or a download the way a browser does: no `Accept` header + /// forcing JSON, an optional cookie, and the raw bytes back untouched — a + /// download's body is not always UTF-8. + async fn get(&self, path: &str, cookie: Option<&str>) -> Raw { + let mut request = Request::builder().method("GET").uri(path); + if let Some(cookie) = cookie { + request = request.header( + header::COOKIE, + HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(), + ); + } + let response = self + .router + .clone() + .oneshot(request.body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = response.status(); + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); + let disposition = response + .headers() + .get(header::CONTENT_DISPOSITION) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + Raw { status, content_type, disposition, bytes } + } } impl Drop for App { @@ -151,6 +256,15 @@ impl Drop for App { } } +/// A GET answer kept as raw bytes: a page's HTML or a download's file, neither +/// of which the JSON-shaped [`Answer`] below is meant for. +struct Raw { + status: StatusCode, + content_type: Option, + disposition: Option, + bytes: Vec, +} + struct Answer { status: StatusCode, session: Option, @@ -1967,3 +2081,461 @@ async fn a_signed_out_browser_may_not_touch_the_rules() { ); } } + +// An id nobody's workspace owns answers `404` for a signed-in person, the +// same not-found a stranger to the task would see, and a `303` for nobody at +// all — never a leptos catch-all page, and never a `403` that would confirm +// the id belongs to someone else's workspace. +#[tokio::test] +async fn a_download_of_an_unknown_attachment_is_not_found_and_signed_out_is_a_redirect() { + let app = App::open().await; + let admin = admin(&app).await; + + let request = Request::builder() + .method("GET") + .uri("/files/anything") + .header( + header::COOKIE, + HeaderValue::from_str(&format!("{SESSION_COOKIE}={admin}")).unwrap(), + ) + .body(Body::empty()) + .unwrap(); + let response = app.router.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + + let request = Request::builder() + .method("GET") + .uri("/files/anything") + .body(Body::empty()) + .unwrap(); + let response = app.router.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::SEE_OTHER); +} + +// A signed-in member's detail page carries the upload form no-script needs: +// a real multipart `` posting to `/files`, not the leptos action form +// the rest of the screen uses — a browser with no script still has a way to +// attach a file. +#[tokio::test] +async fn the_files_section_is_on_the_detail_page() { + let app = App::open().await; + let admin = admin(&app).await; + let column = first_column(&app, &admin).await; + let task = a_task(&app, &admin, &column, "Attach something to me").await; + + let request = Request::builder() + .method("GET") + .uri(format!("/?task={task}")) + .header( + header::COOKIE, + HeaderValue::from_str(&format!("{SESSION_COOKIE}={admin}")).unwrap(), + ) + .body(Body::empty()) + .unwrap(); + let response = app.router.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let body = String::from_utf8(bytes.to_vec()).unwrap(); + assert!( + body.contains("multipart/form-data"), + "no multipart upload form on the detail page" + ); + assert!( + body.contains(r#"action="/files""#), + "the upload form does not post to /files" + ); +} + +/// The id of the file named `name` in a [`dizey_web::detail::FetchTask`] +/// snapshot's body, read the way the page would: found by its name, then the +/// `id` field that comes right before it on the wire. +fn attachment_id_named(body: &str, name: &str) -> String { + let needle = format!("\",\"name\":\"{name}\""); + let before = body + .split_once(&needle) + .map(|(head, _)| head) + .unwrap_or_else(|| panic!("no file named {name} in the detail snapshot: {body}")); + before + .rsplit_once("\"id\":\"") + .and_then(|(_, rest)| rest.split('"').next()) + .expect("no id before the file name") + .to_string() +} + +#[tokio::test] +async fn a_viewer_who_posts_an_upload_anyway_is_refused() { + let app = App::open().await; + let admin = admin(&app).await; + let viewer = invited(&app, &admin, "quiet@dizey.sh", "Quiet Reader", Role::Viewer).await; + let column = first_column(&app, &admin).await; + let task = a_task(&app, &admin, &column, "Viewers cannot attach").await; + + let answer = app + .post_multipart( + "/files", + Some(&viewer), + &[("task_id", &task)], + Some(("note.txt", "text/plain", b"hello")), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + answer.location.as_deref(), + Some("/?refusal=forbidden&on=upload_file") + ); +} + +#[tokio::test] +async fn a_member_uploads_a_file_and_the_chip_comes_back() { + let app = App::open().await; + let admin = admin(&app).await; + let member = invited(&app, &admin, "mo@dizey.sh", "Mo Dubois", Role::Member).await; + let column = first_column(&app, &admin).await; + let task = a_task(&app, &admin, &column, "Attach the spec").await; + + let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4]; + let answer = app + .post_multipart( + "/files", + Some(&member), + &[("task_id", &task)], + Some(("spec.png", "image/png", &png)), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + answer.location.as_deref(), + Some(format!("/?task={task}").as_str()) + ); + + let snapshot = app + .post( + path::(), + Some(&member), + &[("task_id", &task)], + ) + .await; + let file_id = attachment_id_named(&snapshot.body, "spec.png"); + + let page = app.get(&format!("/?task={task}"), Some(&member)).await; + assert_eq!(page.status, StatusCode::OK); + let html = String::from_utf8_lossy(&page.bytes); + assert!( + html.contains(&format!("/files/{file_id}")), + "no href to the new file: {html}" + ); + assert!(html.contains("spec.png")); + + let download = app.get(&format!("/files/{file_id}"), Some(&member)).await; + assert_eq!(download.status, StatusCode::OK); + assert_eq!(download.bytes, png); +} + +#[tokio::test] +async fn a_file_past_the_workspace_limit_is_refused_before_it_is_kept() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app, &admin_cookie).await; + let task = a_task(&app, &admin_cookie, &column, "Too big to keep").await; + + let answer = app + .post( + path::(), + Some(&admin_cookie), + &[ + ("attachment_limit_mb", "1"), + ("photo_limit_mb", "2"), + ("allowed_file_types", ""), + ], + ) + .await; + assert_eq!(answer.body, "null", "{}", answer.body); + + let big = vec![0u8; 2 * 1024 * 1024]; + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("big.bin", "application/octet-stream", &big)), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + answer.location.as_deref(), + Some(format!("/?task={task}&refusal=file-too-big&on=upload_file").as_str()) + ); + + let snapshot = app + .post( + path::(), + Some(&admin_cookie), + &[("task_id", &task)], + ) + .await; + assert!(snapshot.body.contains("\"files\":[]"), "{}", snapshot.body); +} + +#[tokio::test] +async fn a_file_type_off_the_list_is_refused() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app, &admin_cookie).await; + let task = a_task(&app, &admin_cookie, &column, "No executables here").await; + + let answer = app + .post( + path::(), + Some(&admin_cookie), + &[ + ("attachment_limit_mb", "25"), + ("photo_limit_mb", "2"), + ("allowed_file_types", "png"), + ], + ) + .await; + assert_eq!(answer.body, "null", "{}", answer.body); + + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("evil.exe", "application/octet-stream", b"MZ\x90\x00")), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + answer.location.as_deref(), + Some(format!("/?task={task}&refusal=file-type&on=upload_file").as_str()) + ); +} + +#[tokio::test] +async fn an_empty_allowed_list_lets_anything_through() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app, &admin_cookie).await; + let task = a_task(&app, &admin_cookie, &column, "Whatever shows up").await; + + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("anything.bin", "application/octet-stream", &[0x00, 0x01, 0x02])), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + answer.location.as_deref(), + Some(format!("/?task={task}").as_str()) + ); +} + +#[tokio::test] +async fn the_stored_type_is_what_the_bytes_are_not_what_the_upload_claimed() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app, &admin_cookie).await; + let task = a_task(&app, &admin_cookie, &column, "Mislabeled on the way in").await; + + let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("liar.pdf", "application/pdf", &png)), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + + let snapshot = app + .post( + path::(), + Some(&admin_cookie), + &[("task_id", &task)], + ) + .await; + let file_id = attachment_id_named(&snapshot.body, "liar.pdf"); + + let download = app.get(&format!("/files/{file_id}"), Some(&admin_cookie)).await; + assert_eq!(download.content_type.as_deref(), Some("image/png")); +} + +#[tokio::test] +async fn a_file_name_that_is_a_path_is_kept_as_a_label() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app, &admin_cookie).await; + let task = a_task(&app, &admin_cookie, &column, "Filename tries to escape").await; + + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("../../etc/passwd", "text/plain", b"root:x:0:0")), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + + let snapshot = app + .post( + path::(), + Some(&admin_cookie), + &[("task_id", &task)], + ) + .await; + assert!( + snapshot.body.contains("\"name\":\"passwd\""), + "the stored name still has a path in it: {}", + snapshot.body + ); + let file_id = attachment_id_named(&snapshot.body, "passwd"); + + let page = app.get(&format!("/?task={task}"), Some(&admin_cookie)).await; + let html = String::from_utf8_lossy(&page.bytes); + assert!( + !html.contains("../../etc/passwd"), + "the raw path leaked onto the chip: {html}" + ); + + let download = app.get(&format!("/files/{file_id}"), Some(&admin_cookie)).await; + let disposition = download + .disposition + .expect("no content-disposition on the download"); + assert!(!disposition.contains('\r'), "{disposition}"); + assert!(!disposition.contains('\n'), "{disposition}"); + assert!(!disposition.contains('/'), "{disposition}"); +} + +/// A second workspace is a second database in this harness — there is no way +/// to build two workspaces sharing one store to prove sibling-workspace +/// isolation directly. What this proves instead: an attachment id that is +/// real, just not in *this* store, gets the same 404 an id from nowhere gets. +#[tokio::test] +async fn a_file_from_another_workspace_is_not_found() { + let app_a = App::open().await; + let admin_a = admin(&app_a).await; + + let app_b = App::open().await; + let admin_b = admin(&app_b).await; + let column_b = first_column(&app_b, &admin_b).await; + let task_b = a_task(&app_b, &admin_b, &column_b, "Lives in the other workspace").await; + let answer = app_b + .post_multipart( + "/files", + Some(&admin_b), + &[("task_id", &task_b)], + Some(("theirs.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + let snapshot = app_b + .post( + path::(), + Some(&admin_b), + &[("task_id", &task_b)], + ) + .await; + let file_id = attachment_id_named(&snapshot.body, "theirs.png"); + + let answer = app_a.get(&format!("/files/{file_id}"), Some(&admin_a)).await; + assert_eq!(answer.status, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn an_upload_without_a_file_is_refused() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app, &admin_cookie).await; + let task = a_task(&app, &admin_cookie, &column, "Nothing was chosen").await; + + let answer = app + .post_multipart("/files", Some(&admin_cookie), &[("task_id", &task)], None) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + answer.location.as_deref(), + Some(format!("/?task={task}&refusal=no-file&on=upload_file").as_str()) + ); +} + +#[tokio::test] +async fn only_the_uploader_or_an_admin_may_delete_a_file() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let member_a = invited(&app, &admin_cookie, "asha@dizey.sh", "Asha", Role::Member).await; + let member_b = invited(&app, &admin_cookie, "beau@dizey.sh", "Beau", Role::Member).await; + let column = first_column(&app, &admin_cookie).await; + let task = a_task(&app, &admin_cookie, &column, "Two uploaders, one task").await; + + let answer = app + .post_multipart( + "/files", + Some(&member_a), + &[("task_id", &task)], + Some(("mine.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + let answer = app + .post_multipart( + "/files", + Some(&member_b), + &[("task_id", &task)], + Some(("theirs.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + + let snapshot = app + .post( + path::(), + Some(&admin_cookie), + &[("task_id", &task)], + ) + .await; + let file_a = attachment_id_named(&snapshot.body, "mine.png"); + let file_b = attachment_id_named(&snapshot.body, "theirs.png"); + + let answer = app + .post( + path::(), + Some(&member_b), + &[("file_id", &file_a)], + ) + .await; + assert_eq!(answer.body, "\"Forbidden\"", "{}", answer.body); + + let answer = app + .post( + path::(), + Some(&member_a), + &[("file_id", &file_a)], + ) + .await; + assert_eq!(answer.body, "null", "the uploader was refused: {}", answer.body); + + let answer = app + .post( + path::(), + Some(&admin_cookie), + &[("file_id", &file_b)], + ) + .await; + assert_eq!(answer.body, "null", "the admin was refused: {}", answer.body); + + let snapshot = app + .post( + path::(), + Some(&admin_cookie), + &[("task_id", &task)], + ) + .await; + assert!(snapshot.body.contains("\"files\":[]"), "{}", snapshot.body); +} diff --git a/style/main.scss b/style/main.scss index cbfe5b8..cb1d048 100644 --- a/style/main.scss +++ b/style/main.scss @@ -1271,6 +1271,83 @@ a { &:hover { color: #a04a24; } } +// -- files -------------------------------------------------------------- + +.file-list { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.file-chip { + display: inline-flex; + align-items: center; + gap: 5px; + height: 26px; + padding: 0 9px; + border: 1px solid var(--border-strong); + border-radius: 5px; + background: var(--surface); + font-size: 12px; + color: var(--muted); +} + +.file-chip-name { + color: inherit; + text-decoration: none; + + &:hover { color: var(--ink); } +} + +.file-chip-size { + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted-soft); +} + +.file-chip-note { + font-size: 11px; + color: var(--muted-soft); +} + +.file-chip-drop-form { display: inline-flex; } + +.file-chip-drop { + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border: none; + border-radius: 4px; + background: transparent; + color: var(--muted-soft); + cursor: pointer; + + &:hover { color: #a04a24; } +} + +.file-upload { + display: flex; + align-items: center; + gap: 8px; + margin-top: 10px; +} + +.file-upload-submit { + height: 30px; + padding: 0 14px; + border: none; + border-radius: var(--radius); + background: var(--ink); + color: #fffefb; + font-family: inherit; + font-size: 12px; + cursor: pointer; + + &:disabled { opacity: 0.5; cursor: default; } +} + // -- comments --------------------------------------------------------------- .comment-list {