forge
Explore
Log in

Don't you dare go Hollow

Files hang off tasks, bytes in the database file

Browse files at this commit

297c9198e685e2453df3474abb0220c41a0bd0a9Ahmet Kaan GümüşParent: bcc7fa7
  • feat
    • files hang off tasks, bytes in the database file
Show full message
✨ feat(detail): files hang off tasks, bytes in the database file

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.
crates/dizey-core/migrations/0010_attachments_live_in_the_file.sqladded+30 -0
@@ -0,0 +1,30 @@
1+-- Attachments, moved off the filesystem and into the database file.
2+--
3+-- The table 0001 wrote kept a `stored_path`, and nothing ever filled it in.
4+-- A path is the wrong shape for two reasons. Dizey is one process over one
5+-- database file, and a second place to keep state is a second thing to back
6+-- up, to lock, and to get out of step with the rows that name it. And a path
7+-- is exactly where an uploaded file name must never end up: `../../etc` is a
8+-- valid file name and a terrible path. Keeping the bytes here means the name
9+-- is only ever a label printed on a chip, never anything the server resolves.
10+--
11+-- Nothing has ever been written to the old table, so it goes rather than
12+-- being migrated.
13+DROP TABLE attachment;
14+
15+CREATE TABLE attachment (
16+ id TEXT PRIMARY KEY,
17+ task_id TEXT NOT NULL REFERENCES task(id),
18+ -- The comment this file was posted with, when it was posted with one.
19+ comment_id TEXT REFERENCES comment(id),
20+ -- What the browser called it, kept for display only.
21+ file_name TEXT NOT NULL,
22+ -- What the server decided it is, from the bytes. Never what the upload
23+ -- claimed.
24+ mime_type TEXT NOT NULL,
25+ size_bytes INTEGER NOT NULL,
26+ bytes BLOB NOT NULL,
27+ uploaded_by TEXT NOT NULL REFERENCES user(id),
28+ created_at TEXT NOT NULL
29+);
30+CREATE INDEX attachment_by_task ON attachment(task_id);
crates/dizey-core/src/detail.rsmodified+43 -4
@@ -61,6 +61,38 @@ impl DependencyEdge {
61 }61 }
62 }62 }
63 63
64+/// One file hung off a task, as the detail screen prints it.
65+///
66+/// The bytes are not here and neither is a path: a chip carries the name to
67+/// show, the size to show beside it, and the id the download handler answers
68+/// on. The name is display text and nothing resolves it.
69+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70+pub struct FileLine {
71+ pub id: String,
72+ pub name: String,
73+ pub size_bytes: u64,
74+ /// The comment this file was posted with, when it was posted with one.
75+ pub comment_id: Option<String>,
76+ pub uploaded_by: String,
77+}
78+
79+impl FileLine {
80+ /// `840 KB`, `1.4 MB` — the size as a chip says it. Whole kilobytes below
81+ /// a megabyte, one decimal above, because a chip is not a disk usage
82+ /// report.
83+ pub fn size_label(&self) -> String {
84+ const KB: u64 = 1024;
85+ const MB: u64 = 1024 * 1024;
86+ if self.size_bytes >= MB {
87+ format!("{:.1} MB", self.size_bytes as f64 / MB as f64)
88+ } else if self.size_bytes >= KB {
89+ format!("{} KB", self.size_bytes / KB)
90+ } else {
91+ format!("{} B", self.size_bytes)
92+ }
93+ }
94+}
95+
64 /// What deleting a task would take with it. The confirmation step says this96 /// What deleting a task would take with it. The confirmation step says this
65 /// out loud before the button fires.97 /// out loud before the button fires.
66 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]98 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -216,6 +248,8 @@ pub struct TaskDetail {
216 /// Tasks waiting on this one.248 /// Tasks waiting on this one.
217 pub blocks: Vec<DependencyEdge>,249 pub blocks: Vec<DependencyEdge>,
218 pub comments: Vec<Comment>,250 pub comments: Vec<Comment>,
251+ /// Files hung off this task, oldest first.
252+ pub files: Vec<FileLine>,
219 pub activity: Vec<ActivityEntry>,253 pub activity: Vec<ActivityEntry>,
220 }254 }
221 255
@@ -276,7 +310,7 @@ pub use reads::{DetailReads, load};
276 mod reads {310 mod reads {
277 use async_trait::async_trait;311 use async_trait::async_trait;
278 312
279- use super::{ActivityEntry, Comment, DependencyEdge, TaskDetail, TaskFacts};313+ use super::{ActivityEntry, Comment, DependencyEdge, FileLine, TaskDetail, TaskFacts};
280 use crate::board::{Column, Person};314 use crate::board::{Column, Person};
281 use crate::store::Result;315 use crate::store::Result;
282 316
@@ -304,14 +338,17 @@ mod reads {
304 338
305 async fn comments_for_task(&self, task_id: &str) -> Result<Vec<Comment>>;339 async fn comments_for_task(&self, task_id: &str) -> Result<Vec<Comment>>;
306 340
341+ /// The files hung off a task, without their bytes.
342+ async fn files_for_task(&self, task_id: &str) -> Result<Vec<FileLine>>;
343+
307 async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>>;344 async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>>;
308 }345 }
309 346
310- /// Loads one task detail in seven queries — the task, the board's columns,347+ /// Loads one task detail in eight queries — the task, the board's columns,
311 /// its assignees, the workspace's writers, both directions of its348 /// its assignees, the workspace's writers, both directions of its
312- /// dependencies, its comments and its activity.349+ /// dependencies, its comments, its files and its activity.
313 ///350 ///
314- /// Seven, not seven-plus-one-per-comment: `a_task_detail_costs_seven_351+ /// Eight, not eight-plus-one-per-comment: `a_task_detail_costs_eight_
315 /// queries_whatever_it_carries` in `tests/store.rs` holds that line.352 /// queries_whatever_it_carries` in `tests/store.rs` holds that line.
316 pub async fn load(353 pub async fn load(
317 reads: &dyn DetailReads,354 reads: &dyn DetailReads,
@@ -332,6 +369,7 @@ mod reads {
332 let assignable = reads.assignable_people(workspace_id).await?;369 let assignable = reads.assignable_people(workspace_id).await?;
333 let edges = reads.dependencies_for_task(task_id).await?;370 let edges = reads.dependencies_for_task(task_id).await?;
334 let comments = reads.comments_for_task(task_id).await?;371 let comments = reads.comments_for_task(task_id).await?;
372+ let files = reads.files_for_task(task_id).await?;
335 let activity = reads.activity_for_task(task_id).await?;373 let activity = reads.activity_for_task(task_id).await?;
336 374
337 let Some(column) = columns375 let Some(column) = columns
@@ -365,6 +403,7 @@ mod reads {
365 blocked_by,403 blocked_by,
366 blocks,404 blocks,
367 comments,405 comments,
406+ files,
368 activity,407 activity,
369 }))408 }))
370 }409 }
crates/dizey-core/src/store/mod.rsmodified+54 -0
@@ -64,6 +64,37 @@ pub struct Workspace {
64 pub allowed_file_types: Vec<String>,64 pub allowed_file_types: Vec<String>,
65 }65 }
66 66
67+/// One file hung off a task, as a screen lists it: a name, a type, a size and
68+/// who put it there. The bytes are deliberately not on this type — it is what
69+/// handlers load and pages serialise, and a file's contents have no business
70+/// travelling with a list of file names.
71+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72+pub struct Attachment {
73+ pub id: String,
74+ pub task_id: String,
75+ /// The comment it was posted with, when it was posted with one.
76+ pub comment_id: Option<String>,
77+ /// What the browser called the file. A label, never a path.
78+ pub file_name: String,
79+ /// What the server decided the bytes are, never what the upload claimed.
80+ pub mime_type: String,
81+ pub size_bytes: u64,
82+ pub uploaded_by: String,
83+ pub uploaded_at: OffsetDateTime,
84+}
85+
86+/// A file on its way into the table, bytes and all.
87+#[derive(Debug, Clone, PartialEq, Eq)]
88+pub struct NewAttachment<'a> {
89+ pub task_id: &'a str,
90+ pub comment_id: Option<&'a str>,
91+ pub file_name: &'a str,
92+ pub mime_type: &'a str,
93+ pub bytes: Vec<u8>,
94+ pub uploaded_by: &'a str,
95+ pub at: OffsetDateTime,
96+}
97+
67 /// A sender as an admin typed it, on its way to the table.98 /// A sender as an admin typed it, on its way to the table.
68 ///99 ///
69 /// `password` is `None` when the admin left the field untouched, which is what100 /// `password` is `None` when the admin left the field untouched, which is what
@@ -494,6 +525,29 @@ pub trait Store: BoardReads + DetailReads + 'static {
494 at: OffsetDateTime,525 at: OffsetDateTime,
495 ) -> Result<String>;526 ) -> Result<String>;
496 527
528+ /// Hangs a file off a task. The bytes go into the database file with the
529+ /// row: there is no second place for a Dizey deployment to keep, and no
530+ /// path for an uploaded name to become.
531+ ///
532+ /// Nothing here decides whether the file was allowed — its size, its type
533+ /// and who may attach it are the handler's questions, answered before the
534+ /// bytes reach this call.
535+ async fn add_attachment(&self, new: NewAttachment<'_>) -> Result<String>;
536+
537+ /// What is hung off a task, oldest first, without the bytes. This is what
538+ /// a screen reads; a screen never carries a file's contents.
539+ async fn attachments(&self, task_id: &str) -> Result<Vec<Attachment>>;
540+
541+ /// One file's row, still without its bytes. The `task_id` on it is what the
542+ /// handler checks before it hands anything over.
543+ async fn attachment(&self, id: &str) -> Result<Option<Attachment>>;
544+
545+ /// The bytes themselves, for the one handler that serves them.
546+ async fn attachment_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;
547+
548+ /// Takes a file away for good. `false` when there was no such row.
549+ async fn delete_attachment(&self, id: &str) -> Result<bool>;
550+
497 /// Writes the title, description and deadline the detail screen saved, and551 /// Writes the title, description and deadline the detail screen saved, and
498 /// records one activity line per field that actually changed.552 /// records one activity line per field that actually changed.
499 async fn save_task(553 async fn save_task(
crates/dizey-core/src/store/turso_store.rsmodified+127 -3
@@ -13,14 +13,15 @@ use turso::{Builder, Connection, Row, Value, params};
13 use uuid::Uuid;13 use uuid::Uuid;
14 14
15 use super::{15 use super::{
16- Audience, Deletion, Event, Freeing, MailRule, MailSend, NewSender, NewTask, NewUser, Recipient,16+ Attachment, Audience, Deletion, Event, Freeing, MailRule, MailSend, NewAttachment, NewSender,
17- Result,17+ NewTask, NewUser, Recipient, Result,
18 SendState, SenderTest, Session, SigninLink, Store, StoreError, Trigger, User, Workspace,18 SendState, SenderTest, Session, SigninLink, Store, StoreError, Trigger, User, Workspace,
19 };19 };
20 use crate::Role;20 use crate::Role;
21 use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition};21 use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition};
22 use crate::detail::{22 use crate::detail::{
23- ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, TaskFacts,23+ ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine,
24+ TaskFacts,
24 };25 };
25 use time::Date;26 use time::Date;
26 use time::format_description::BorrowedFormatItem;27 use time::format_description::BorrowedFormatItem;
@@ -37,6 +38,10 @@ const MIGRATIONS: &[(i64, &str)] = &[
37 (7, include_str!("../../migrations/0007_who_invited.sql")),38 (7, include_str!("../../migrations/0007_who_invited.sql")),
38 (8, include_str!("../../migrations/0008_sender_is_settings.sql")),39 (8, include_str!("../../migrations/0008_sender_is_settings.sql")),
39 (9, include_str!("../../migrations/0009_sender_test.sql")),40 (9, include_str!("../../migrations/0009_sender_test.sql")),
41+ (
42+ 10,
43+ include_str!("../../migrations/0010_attachments_live_in_the_file.sql"),
44+ ),
40 ];45 ];
41 46
42 /// The board a fresh workspace gets, and its columns. `Done` is the column47 /// 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<Option<OffsetDateTime>> {
319 }324 }
320 }325 }
321 326
327+/// One attachment row, in the column order every query above selects.
328+fn attachment_row(row: &Row) -> Result<Attachment> {
329+ Ok(Attachment {
330+ id: text(row, 0)?,
331+ task_id: text(row, 1)?,
332+ comment_id: opt_text(row, 2)?,
333+ file_name: text(row, 3)?,
334+ mime_type: text(row, 4)?,
335+ size_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
336+ uploaded_by: text(row, 6)?,
337+ uploaded_at: parse_stamp(&text(row, 7)?)?,
338+ })
339+}
340+
322 fn text(row: &Row, idx: usize) -> Result<String> {341 fn text(row: &Row, idx: usize) -> Result<String> {
323 row.get::<String>(idx).map_err(backend)342 row.get::<String>(idx).map_err(backend)
324 }343 }
@@ -1244,6 +1263,86 @@ impl Store for TursoStore {
1244 Ok(id)1263 Ok(id)
1245 }1264 }
1246 1265
1266+ async fn add_attachment(&self, new: NewAttachment<'_>) -> Result<String> {
1267+ let id = Uuid::new_v4().to_string();
1268+ let size = new.bytes.len() as i64;
1269+ self.conn
1270+ .execute(
1271+ "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \
1272+ size_bytes, bytes, uploaded_by, created_at) \
1273+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
1274+ params![
1275+ id.clone(),
1276+ new.task_id,
1277+ new.comment_id,
1278+ new.file_name,
1279+ new.mime_type,
1280+ size,
1281+ new.bytes,
1282+ new.uploaded_by,
1283+ stamp(new.at)?
1284+ ],
1285+ )
1286+ .await
1287+ .map_err(backend)?;
1288+ Ok(id)
1289+ }
1290+
1291+ async fn attachments(&self, task_id: &str) -> Result<Vec<Attachment>> {
1292+ let mut rows = self
1293+ .conn
1294+ .query(
1295+ "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \
1296+ uploaded_by, created_at FROM attachment \
1297+ WHERE task_id = ?1 ORDER BY created_at, rowid",
1298+ params![task_id],
1299+ )
1300+ .await
1301+ .map_err(backend)?;
1302+ let mut out = Vec::new();
1303+ while let Some(row) = rows.next().await.map_err(backend)? {
1304+ out.push(attachment_row(&row)?);
1305+ }
1306+ Ok(out)
1307+ }
1308+
1309+ async fn attachment(&self, id: &str) -> Result<Option<Attachment>> {
1310+ let mut rows = self
1311+ .conn
1312+ .query(
1313+ "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \
1314+ uploaded_by, created_at FROM attachment WHERE id = ?1",
1315+ params![id],
1316+ )
1317+ .await
1318+ .map_err(backend)?;
1319+ match rows.next().await.map_err(backend)? {
1320+ Some(row) => Ok(Some(attachment_row(&row)?)),
1321+ None => Ok(None),
1322+ }
1323+ }
1324+
1325+ async fn attachment_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {
1326+ let mut rows = self
1327+ .conn
1328+ .query("SELECT bytes FROM attachment WHERE id = ?1", params![id])
1329+ .await
1330+ .map_err(backend)?;
1331+ match rows.next().await.map_err(backend)? {
1332+ Some(row) => Ok(Some(row.get::<Vec<u8>>(0).map_err(backend)?)),
1333+ None => Ok(None),
1334+ }
1335+ }
1336+
1337+ async fn delete_attachment(&self, id: &str) -> Result<bool> {
1338+ let gone = self
1339+ .conn
1340+ .execute("DELETE FROM attachment WHERE id = ?1", params![id])
1341+ .await
1342+ .map_err(backend)?;
1343+ Ok(gone > 0)
1344+ }
1345+
1247 async fn save_task(1346 async fn save_task(
1248 &self,1347 &self,
1249 task_id: &str,1348 task_id: &str,
@@ -2238,6 +2337,31 @@ impl DetailReads for TursoStore {
2238 Ok(out)2337 Ok(out)
2239 }2338 }
2240 2339
2340+ async fn files_for_task(&self, task_id: &str) -> Result<Vec<FileLine>> {
2341+ // `bytes` is not in the SELECT on purpose: a screen listing five files
2342+ // must not drag five files through memory to print their names.
2343+ let mut rows = self
2344+ .conn
2345+ .query(
2346+ "SELECT id, file_name, size_bytes, comment_id, uploaded_by \
2347+ FROM attachment WHERE task_id = ?1 ORDER BY created_at, rowid",
2348+ params![task_id],
2349+ )
2350+ .await
2351+ .map_err(backend)?;
2352+ let mut out = Vec::new();
2353+ while let Some(row) = rows.next().await.map_err(backend)? {
2354+ out.push(FileLine {
2355+ id: text(&row, 0)?,
2356+ name: text(&row, 1)?,
2357+ size_bytes: row.get::<i64>(2).map_err(backend)?.max(0) as u64,
2358+ comment_id: opt_text(&row, 3)?,
2359+ uploaded_by: text(&row, 4)?,
2360+ });
2361+ }
2362+ Ok(out)
2363+ }
2364+
2241 async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>> {2365 async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>> {
2242 // LEFT JOIN: a line the system wrote has no actor, and dropping it2366 // LEFT JOIN: a line the system wrote has no actor, and dropping it
2243 // would hide exactly the events the rules engine causes.2367 // would hide exactly the events the rules engine causes.
crates/dizey-core/tests/store.rsmodified+137 -6
@@ -9,7 +9,8 @@ use std::path::PathBuf;
9 use dizey_core::Role;9 use dizey_core::Role;
10 use dizey_core::auth::{Token, hash_password};10 use dizey_core::auth::{Token, hash_password};
11 use dizey_core::store::{11 use dizey_core::store::{
12- Audience, MailRule, NewSender, NewUser, SendState, Store, StoreError, Trigger, TursoStore, User,12+ Audience, MailRule, NewAttachment, NewSender, NewUser, SendState, Store, StoreError, Trigger,
13+ TursoStore, User,
13 };14 };
14 use time::{Duration, OffsetDateTime};15 use time::{Duration, OffsetDateTime};
15 use uuid::Uuid;16 use uuid::Uuid;
@@ -89,14 +90,14 @@ async fn migrations_apply_once_and_survive_reopen() {
89 let path = dir.join("dizey.db").to_string_lossy().into_owned();90 let path = dir.join("dizey.db").to_string_lossy().into_owned();
90 91
91 let first = TursoStore::open(&path).await.unwrap();92 let first = TursoStore::open(&path).await.unwrap();
92- assert_eq!(first.schema_version().await.unwrap(), 9);93+ assert_eq!(first.schema_version().await.unwrap(), 10);
93 claim(&first).await;94 claim(&first).await;
94 drop(first);95 drop(first);
95 96
96 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and97 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
97 // must not lose what the first open wrote.98 // must not lose what the first open wrote.
98 let second = TursoStore::open(&path).await.unwrap();99 let second = TursoStore::open(&path).await.unwrap();
99- assert_eq!(second.schema_version().await.unwrap(), 9);100+ assert_eq!(second.schema_version().await.unwrap(), 10);
100 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey");101 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey");
101 drop(second);102 drop(second);
102 let _ = std::fs::remove_dir_all(&dir);103 let _ = std::fs::remove_dir_all(&dir);
@@ -1852,6 +1853,14 @@ impl DetailReads for CountingDetail<'_> {
1852 self.inner.comments_for_task(task_id).await1853 self.inner.comments_for_task(task_id).await
1853 }1854 }
1854 1855
1856+ async fn files_for_task(
1857+ &self,
1858+ task_id: &str,
1859+ ) -> Result<Vec<dizey_core::detail::FileLine>, StoreError> {
1860+ self.tick();
1861+ self.inner.files_for_task(task_id).await
1862+ }
1863+
1855 async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>, StoreError> {1864 async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>, StoreError> {
1856 self.tick();1865 self.tick();
1857 self.inner.activity_for_task(task_id).await1866 self.inner.activity_for_task(task_id).await
@@ -2152,7 +2161,7 @@ async fn saving_a_task_records_only_what_changed() {
2152 }2161 }
2153 2162
2154 #[tokio::test]2163 #[tokio::test]
2155-async fn a_task_detail_costs_seven_queries_whatever_it_carries() {2164+async fn a_task_detail_costs_eight_queries_whatever_it_carries() {
2156 let (scratch, workspace, admin) = workspace_with_admin().await;2165 let (scratch, workspace, admin) = workspace_with_admin().await;
2157 let store = &scratch.store;2166 let store = &scratch.store;
2158 let now = OffsetDateTime::now_utc();2167 let now = OffsetDateTime::now_utc();
@@ -2160,7 +2169,7 @@ async fn a_task_detail_costs_seven_queries_whatever_it_carries() {
2160 let bare = add_task(store, &workspace, "Backlog", "bare", None, &admin).await;2169 let bare = add_task(store, &workspace, "Backlog", "bare", None, &admin).await;
2161 let counted = CountingDetail::new(store);2170 let counted = CountingDetail::new(store);
2162 load_detail(&counted, &workspace, &bare).await.unwrap();2171 load_detail(&counted, &workspace, &bare).await.unwrap();
2163- assert_eq!(counted.count(), 7, "a task with nothing hung off it");2172+ assert_eq!(counted.count(), 8, "a task with nothing hung off it");
2164 2173
2165 // Twenty comments, twenty activity lines, twenty people who could be2174 // Twenty comments, twenty activity lines, twenty people who could be
2166 // assigned and twenty tasks on the other end of a dependency — the four2175 // 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() {
2209 assert_eq!(detail.activity.len(), 21);2218 assert_eq!(detail.activity.len(), 21);
2210 assert_eq!(2219 assert_eq!(
2211 counted.count(),2220 counted.count(),
2212- 7,2221+ 8,
2213 "the round trips a detail costs must not follow what it carries"2222 "the round trips a detail costs must not follow what it carries"
2214 );2223 );
2215 }2224 }
@@ -3516,3 +3525,125 @@ async fn an_account_records_the_admin_who_made_it() {
3516 let reread = scratch.store.user(&member.id).await.unwrap().unwrap();3525 let reread = scratch.store.user(&member.id).await.unwrap().unwrap();
3517 assert_eq!(reread.invited_by.as_deref(), Some(admin_id.as_str()));3526 assert_eq!(reread.invited_by.as_deref(), Some(admin_id.as_str()));
3518 }3527 }
3528+
3529+#[tokio::test]
3530+async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() {
3531+ let (scratch, workspace, admin) = workspace_with_admin().await;
3532+ let store = &scratch.store;
3533+ let now = OffsetDateTime::now_utc();
3534+ let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await;
3535+
3536+ // Bytes that are not text and are not valid UTF-8, because an attachment
3537+ // is not a string and the column it lives in must not treat it as one.
3538+ let bytes: Vec<u8> = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe];
3539+ let id = store
3540+ .add_attachment(NewAttachment {
3541+ task_id: &task,
3542+ comment_id: None,
3543+ file_name: "shot.png",
3544+ mime_type: "image/png",
3545+ bytes: bytes.clone(),
3546+ uploaded_by: &admin,
3547+ at: now,
3548+ })
3549+ .await
3550+ .unwrap();
3551+
3552+ let row = store.attachment(&id).await.unwrap().unwrap();
3553+ assert_eq!(row.task_id, task);
3554+ assert_eq!(row.file_name, "shot.png");
3555+ assert_eq!(row.mime_type, "image/png");
3556+ assert_eq!(row.size_bytes, bytes.len() as u64);
3557+ assert_eq!(row.uploaded_by, admin);
3558+ assert_eq!(store.attachment_bytes(&id).await.unwrap().unwrap(), bytes);
3559+}
3560+
3561+#[tokio::test]
3562+async fn a_file_name_that_is_a_path_is_stored_as_the_label_it_is() {
3563+ let (scratch, workspace, admin) = workspace_with_admin().await;
3564+ let store = &scratch.store;
3565+ let now = OffsetDateTime::now_utc();
3566+ let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await;
3567+
3568+ // Nothing in the store resolves a name, so the worst name there is comes
3569+ // back exactly as it went in: it is a label on a chip, not a path.
3570+ let id = store
3571+ .add_attachment(NewAttachment {
3572+ task_id: &task,
3573+ comment_id: None,
3574+ file_name: "../../etc/passwd",
3575+ mime_type: "application/octet-stream",
3576+ bytes: b"root:x:0:0".to_vec(),
3577+ uploaded_by: &admin,
3578+ at: now,
3579+ })
3580+ .await
3581+ .unwrap();
3582+ let row = store.attachment(&id).await.unwrap().unwrap();
3583+ assert_eq!(row.file_name, "../../etc/passwd");
3584+ // And nothing was written anywhere but the database file and its key
3585+ // (see `store::secret`) — never a file named after the attachment.
3586+ let written: Vec<String> = std::fs::read_dir(&scratch.dir)
3587+ .unwrap()
3588+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
3589+ .filter(|name| !name.starts_with("dizey.db") && name != "dizey.key")
3590+ .collect();
3591+ assert!(written.is_empty(), "{written:?}");
3592+}
3593+
3594+#[tokio::test]
3595+async fn the_detail_lists_a_task_s_files_oldest_first_and_never_their_bytes() {
3596+ let (scratch, workspace, admin) = workspace_with_admin().await;
3597+ let store = &scratch.store;
3598+ let now = OffsetDateTime::now_utc();
3599+ let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await;
3600+
3601+ for (n, name) in ["first.pdf", "second.png"].iter().enumerate() {
3602+ store
3603+ .add_attachment(NewAttachment {
3604+ task_id: &task,
3605+ comment_id: None,
3606+ file_name: name,
3607+ mime_type: "application/pdf",
3608+ bytes: vec![b'x'; 2048],
3609+ uploaded_by: &admin,
3610+ at: now + time::Duration::seconds(n as i64),
3611+ })
3612+ .await
3613+ .unwrap();
3614+ }
3615+
3616+ let detail = load_detail(store, &workspace, &task)
3617+ .await
3618+ .unwrap()
3619+ .unwrap();
3620+ let names: Vec<&str> = detail.files.iter().map(|f| f.name.as_str()).collect();
3621+ assert_eq!(names, vec!["first.pdf", "second.png"]);
3622+ assert_eq!(detail.files[0].size_label(), "2 KB");
3623+}
3624+
3625+#[tokio::test]
3626+async fn a_file_can_be_taken_away_and_saying_so_twice_is_answered_honestly() {
3627+ let (scratch, workspace, admin) = workspace_with_admin().await;
3628+ let store = &scratch.store;
3629+ let now = OffsetDateTime::now_utc();
3630+ let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await;
3631+ let id = store
3632+ .add_attachment(NewAttachment {
3633+ task_id: &task,
3634+ comment_id: None,
3635+ file_name: "note.txt",
3636+ mime_type: "text/plain",
3637+ bytes: b"hello".to_vec(),
3638+ uploaded_by: &admin,
3639+ at: now,
3640+ })
3641+ .await
3642+ .unwrap();
3643+
3644+ assert!(store.delete_attachment(&id).await.unwrap());
3645+ assert!(!store.delete_attachment(&id).await.unwrap());
3646+ assert!(store.attachment(&id).await.unwrap().is_none());
3647+ assert!(store.attachment_bytes(&id).await.unwrap().is_none());
3648+ assert!(store.attachments(&task).await.unwrap().is_empty());
3649+}
crates/dizey-web/Cargo.tomlmodified+1 -1
@@ -19,7 +19,7 @@ time.workspace = true
19 thiserror.workspace = true19 thiserror.workspace = true
20 20
21 dizey-core = { workspace = true }21 dizey-core = { workspace = true }
22-axum = { version = "0.8.9", optional = true }22+axum = { version = "0.8.9", features = ["multipart"], optional = true }
23 tokio = { workspace = true, optional = true }23 tokio = { workspace = true, optional = true }
24 tower = { version = "0.5.2", optional = true }24 tower = { version = "0.5.2", optional = true }
25 tower-http = { version = "0.7.0", features = ["fs", "compression-gzip"], optional = true }25 tower-http = { version = "0.7.0", features = ["fs", "compression-gzip"], optional = true }
crates/dizey-web/src/auth.rsmodified+40 -0
@@ -46,6 +46,12 @@ pub enum Refusal {
46 BadSender(String),46 BadSender(String),
47 /// A comment with nothing in it.47 /// A comment with nothing in it.
48 EmptyComment,48 EmptyComment,
49+ /// The upload arrived without a file in it.
50+ NoFile,
51+ /// The bytes kept coming past what this workspace allows per file.
52+ FileTooBig,
53+ /// The name does not end in one of the extensions the admin allows.
54+ FileTypeNotAllowed,
49 /// A rule with no subject line: the mail it sends would arrive blank.55 /// A rule with no subject line: the mail it sends would arrive blank.
50 EmptySubject,56 EmptySubject,
51 /// The date field did not hold a date.57 /// The date field did not hold a date.
@@ -87,6 +93,14 @@ impl Refusal {
87 }93 }
88 Refusal::BadSender(problem) => problem.clone(),94 Refusal::BadSender(problem) => problem.clone(),
89 Refusal::EmptyComment => "Write something first.".to_string(),95 Refusal::EmptyComment => "Write something first.".to_string(),
96+ Refusal::NoFile => "Choose a file first.".to_string(),
97+ Refusal::FileTooBig => {
98+ "That file is bigger than this workspace allows. The limit is in Settings."
99+ .to_string()
100+ }
101+ Refusal::FileTypeNotAllowed => {
102+ "That kind of file is not on this workspace's allowed list.".to_string()
103+ }
90 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),104 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
91 Refusal::BadDeadline => "That is not a date.".to_string(),105 Refusal::BadDeadline => "That is not a date.".to_string(),
92 Refusal::Cycle => "That link would put this task behind itself.".to_string(),106 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
@@ -130,6 +144,9 @@ impl Refusal {
130 Refusal::BadFileType => "bad-file-type",144 Refusal::BadFileType => "bad-file-type",
131 Refusal::BadSender(_) => "bad-sender",145 Refusal::BadSender(_) => "bad-sender",
132 Refusal::EmptyComment => "empty-comment",146 Refusal::EmptyComment => "empty-comment",
147+ Refusal::NoFile => "no-file",
148+ Refusal::FileTooBig => "file-too-big",
149+ Refusal::FileTypeNotAllowed => "file-type",
133 Refusal::EmptySubject => "empty-subject",150 Refusal::EmptySubject => "empty-subject",
134 Refusal::BadDeadline => "bad-deadline",151 Refusal::BadDeadline => "bad-deadline",
135 Refusal::Cycle => "cycle",152 Refusal::Cycle => "cycle",
@@ -155,6 +172,9 @@ impl Refusal {
155 "link-not-usable" => Refusal::LinkNotUsable,172 "link-not-usable" => Refusal::LinkNotUsable,
156 "empty-title" => Refusal::EmptyTitle,173 "empty-title" => Refusal::EmptyTitle,
157 "empty-comment" => Refusal::EmptyComment,174 "empty-comment" => Refusal::EmptyComment,
175+ "no-file" => Refusal::NoFile,
176+ "file-too-big" => Refusal::FileTooBig,
177+ "file-type" => Refusal::FileTypeNotAllowed,
158 "empty-subject" => Refusal::EmptySubject,178 "empty-subject" => Refusal::EmptySubject,
159 "bad-deadline" => Refusal::BadDeadline,179 "bad-deadline" => Refusal::BadDeadline,
160 "cycle" => Refusal::Cycle,180 "cycle" => Refusal::Cycle,
@@ -209,6 +229,23 @@ where
209 }229 }
210 }230 }
211 231
232+/// What a plain form post refused with, read from the address alone.
233+///
234+/// [`refusal_of`] needs a server action to read the answer off. The upload is
235+/// not one — it is a multipart form posted to an axum handler, which can only
236+/// ever answer a browser with a redirect — so its refusal always comes back
237+/// the way a script-less browser's does, and this reads it from there.
238+pub fn refusal_from_query(call: &'static str) -> impl Fn() -> Option<Refusal> + Copy {
239+ let query = leptos_router::hooks::use_query_map();
240+ move || {
241+ let query = query.read();
242+ if query.get("on")? != call {
243+ return None;
244+ }
245+ Refusal::from_code(&query.get("refusal")?)
246+ }
247+}
248+
212 #[cfg(test)]249 #[cfg(test)]
213 mod refusal_tests {250 mod refusal_tests {
214 use super::*;251 use super::*;
@@ -227,6 +264,9 @@ mod refusal_tests {
227 Refusal::LinkNotUsable,264 Refusal::LinkNotUsable,
228 Refusal::EmptyTitle,265 Refusal::EmptyTitle,
229 Refusal::EmptyComment,266 Refusal::EmptyComment,
267+ Refusal::NoFile,
268+ Refusal::FileTooBig,
269+ Refusal::FileTypeNotAllowed,
230 Refusal::BadDeadline,270 Refusal::BadDeadline,
231 Refusal::Cycle,271 Refusal::Cycle,
232 Refusal::MovedAlready,272 Refusal::MovedAlready,
crates/dizey-web/src/detail.rsmodified+168 -13
@@ -38,6 +38,10 @@ pub struct DetailSnapshot {
38 pub may_comment: bool,38 pub may_comment: bool,
39 /// Whether this person may delete the task. A writer may.39 /// Whether this person may delete the task. A writer may.
40 pub may_delete: bool,40 pub may_delete: bool,
41+ /// Extensions the upload form's `accept` attribute may offer. Empty means
42+ /// every type — the same "empty means everything" the store's limits use.
43+ pub allowed_file_types: Vec<String>,
44+ pub attachment_limit_mb: u64,
41 }45 }
42 46
43 /// Which way round a dependency runs, as it travels in a form.47 /// Which way round a dependency runs, as it travels in a form.
@@ -54,13 +58,20 @@ pub enum Direction {
54 pub(crate) mod guard {58 pub(crate) mod guard {
55 use crate::auth::Refusal;59 use crate::auth::Refusal;
56 use dizey_core::detail::TaskFacts;60 use dizey_core::detail::TaskFacts;
57- use dizey_core::store::User;61+ use dizey_core::store::{Store, User};
58 62
59 /// The task, if this person's workspace is the one holding it. A task in63 /// The task, if this person's workspace is the one holding it. A task in
60 /// another workspace is not found rather than forbidden: the answer says64 /// another workspace is not found rather than forbidden: the answer says
61 /// nothing about whether the id is real.65 /// nothing about whether the id is real.
62- pub async fn task_of(user: &User, task_id: &str) -> Result<TaskFacts, Refusal> {66+ ///
63- let store = crate::server::accounts().store().clone();67+ /// Takes the store rather than reading it off leptos context, so a plain
68+ /// axum handler with no leptos owner tree — `crate::files`'s upload and
69+ /// download routes — can call this the same way a server function does.
70+ pub async fn task_of(
71+ store: &dyn Store,
72+ user: &User,
73+ task_id: &str,
74+ ) -> Result<TaskFacts, Refusal> {
64 match store.task(task_id).await {75 match store.task(task_id).await {
65 Ok(Some(facts)) if facts.workspace_id == user.workspace_id => Ok(facts),76 Ok(Some(facts)) if facts.workspace_id == user.workspace_id => Ok(facts),
66 Ok(_) => Err(Refusal::NotFound),77 Ok(_) => Err(Refusal::NotFound),
@@ -74,7 +85,8 @@ pub(crate) mod guard {
74 /// The writer behind this request and the task they named.85 /// The writer behind this request and the task they named.
75 pub async fn writer_and_task(task_id: &str) -> Result<(User, TaskFacts), Refusal> {86 pub async fn writer_and_task(task_id: &str) -> Result<(User, TaskFacts), Refusal> {
76 let user = crate::server::require_writer().await?;87 let user = crate::server::require_writer().await?;
77- let facts = task_of(&user, task_id).await?;88+ let store = crate::server::accounts().store().clone();
89+ let facts = task_of(store.as_ref(), &user, task_id).await?;
78 Ok((user, facts))90 Ok((user, facts))
79 }91 }
80 }92 }
@@ -131,12 +143,26 @@ pub async fn fetch_task(task_id: String) -> Result<Result<DetailSnapshot, Refusa
131 // goes with it, which is what makes that safe — not a role.143 // goes with it, which is what makes that safe — not a role.
132 let may_write = user.role.can_write_tasks();144 let may_write = user.role.can_write_tasks();
133 145
146+ // The upload form's own limits, read the same way Settings reads them —
147+ // megabytes on the screen, bytes in the store.
148+ const MB: u64 = 1024 * 1024;
149+ let workspace = store.workspace().await.map_err(fail)?;
150+ let allowed_file_types = workspace
151+ .as_ref()
152+ .map(|workspace| workspace.allowed_file_types.clone())
153+ .unwrap_or_default();
154+ let attachment_limit_mb = workspace
155+ .map(|workspace| workspace.attachment_limit_bytes / MB)
156+ .unwrap_or(0);
157+
134 Ok(Ok(DetailSnapshot {158 Ok(Ok(DetailSnapshot {
135 detail,159 detail,
136 linkable,160 linkable,
137 may_write,161 may_write,
138 may_comment: user.role.can_comment(),162 may_comment: user.role.can_comment(),
139 may_delete: may_write,163 may_delete: may_write,
164+ allowed_file_types,
165+ attachment_limit_mb,
140 me: Me {166 me: Me {
141 id: user.id,167 id: user.id,
142 display_name: user.display_name,168 display_name: user.display_name,
@@ -309,7 +335,8 @@ pub async fn link_tasks(
309 Ok(pair) => pair,335 Ok(pair) => pair,
310 Err(refusal) => return Ok(Some(refusal)),336 Err(refusal) => return Ok(Some(refusal)),
311 };337 };
312- let other = match guard::task_of(&actor, &other_id).await {338+ let store = accounts().store().clone();
339+ let other = match guard::task_of(store.as_ref(), &actor, &other_id).await {
313 Ok(facts) => facts,340 Ok(facts) => facts,
314 Err(refusal) => return Ok(Some(refusal)),341 Err(refusal) => return Ok(Some(refusal)),
315 };342 };
@@ -318,7 +345,6 @@ pub async fn link_tasks(
318 Direction::BlockedBy => (task_id.clone(), other_id.clone()),345 Direction::BlockedBy => (task_id.clone(), other_id.clone()),
319 Direction::Blocks => (other_id.clone(), task_id.clone()),346 Direction::Blocks => (other_id.clone(), task_id.clone()),
320 };347 };
321- let store = accounts().store().clone();
322 let now = OffsetDateTime::now_utc();348 let now = OffsetDateTime::now_utc();
323 match store.add_dependency(&blocked, &blocking, now).await {349 match store.add_dependency(&blocked, &blocking, now).await {
324 Ok(()) => {}350 Ok(()) => {}
@@ -354,7 +380,8 @@ pub async fn unlink_tasks(
354 Ok(pair) => pair,380 Ok(pair) => pair,
355 Err(refusal) => return Ok(Some(refusal)),381 Err(refusal) => return Ok(Some(refusal)),
356 };382 };
357- let other = match guard::task_of(&actor, &other_id).await {383+ let store = accounts().store().clone();
384+ let other = match guard::task_of(store.as_ref(), &actor, &other_id).await {
358 Ok(facts) => facts,385 Ok(facts) => facts,
359 Err(refusal) => return Ok(Some(refusal)),386 Err(refusal) => return Ok(Some(refusal)),
360 };387 };
@@ -363,7 +390,6 @@ pub async fn unlink_tasks(
363 Direction::BlockedBy => (task_id.clone(), other_id.clone()),390 Direction::BlockedBy => (task_id.clone(), other_id.clone()),
364 Direction::Blocks => (other_id.clone(), task_id.clone()),391 Direction::Blocks => (other_id.clone(), task_id.clone()),
365 };392 };
366- let store = accounts().store().clone();
367 let now = OffsetDateTime::now_utc();393 let now = OffsetDateTime::now_utc();
368 let fail = |e: dizey_core::store::StoreError| ServerFnError::new(e.to_string());394 let fail = |e: dizey_core::store::StoreError| ServerFnError::new(e.to_string());
369 store395 store
@@ -397,7 +423,8 @@ pub async fn post_comment(task_id: String, body: String) -> Result<Option<Refusa
397 if !user.role.can_comment() {423 if !user.role.can_comment() {
398 return Ok(Some(Refusal::Forbidden));424 return Ok(Some(Refusal::Forbidden));
399 }425 }
400- if let Err(refusal) = guard::task_of(&user, &task_id).await {426+ let store = accounts().store().clone();
427+ if let Err(refusal) = guard::task_of(store.as_ref(), &user, &task_id).await {
401 return Ok(Some(refusal));428 return Ok(Some(refusal));
402 }429 }
403 let body = body.trim();430 let body = body.trim();
@@ -405,8 +432,7 @@ pub async fn post_comment(task_id: String, body: String) -> Result<Option<Refusa
405 return Ok(Some(Refusal::EmptyComment));432 return Ok(Some(Refusal::EmptyComment));
406 }433 }
407 434
408- accounts()435+ store
409- .store()
410 .add_comment(&task_id, &user.id, body, OffsetDateTime::now_utc())436 .add_comment(&task_id, &user.id, body, OffsetDateTime::now_utc())
411 .await437 .await
412 .map_err(|e| ServerFnError::new(e.to_string()))?;438 .map_err(|e| ServerFnError::new(e.to_string()))?;
@@ -461,6 +487,41 @@ pub async fn delete_task(task_id: String) -> Result<Option<Refusal>, ServerFnErr
461 Ok(None)487 Ok(None)
462 }488 }
463 489
490+/// Deletes an attachment's row and its bytes. This is a hard delete, unlike
491+/// [`delete_task`]'s soft one: a file is a blob on disk, not a fact worth
492+/// keeping around for the audit trail, so there is nothing to undo by hand.
493+/// That is also why the gate is narrower than a writer's — only the person who
494+/// put the file there, or an admin cleaning up after them, may take it away.
495+#[server]
496+pub async fn delete_file(file_id: String) -> Result<Option<Refusal>, ServerFnError> {
497+ use crate::server::{accounts, require_user};
498+
499+ let user = match require_user().await {
500+ Ok(user) => user,
501+ Err(refusal) => return Ok(Some(refusal)),
502+ };
503+ let store = accounts().store().clone();
504+ let Some(attachment) = store
505+ .attachment(&file_id)
506+ .await
507+ .map_err(|e| ServerFnError::new(e.to_string()))?
508+ else {
509+ return Ok(Some(Refusal::NotFound));
510+ };
511+ if let Err(refusal) = guard::task_of(store.as_ref(), &user, &attachment.task_id).await {
512+ return Ok(Some(refusal));
513+ }
514+ if user.id != attachment.uploaded_by && !user.role.can_administer() {
515+ return Ok(Some(Refusal::Forbidden));
516+ }
517+
518+ store
519+ .delete_attachment(&file_id)
520+ .await
521+ .map_err(|e| ServerFnError::new(e.to_string()))?;
522+ Ok(None)
523+}
524+
464 // -- the screen -------------------------------------------------------------525 // -- the screen -------------------------------------------------------------
465 526
466 /// The artboard's STATUS control: the column the card sits in, and the way to527 /// The artboard's STATUS control: the column the card sits in, and the way to
@@ -1144,12 +1205,14 @@ fn DetailScreen(
1144 ) -> impl IntoView {1205 ) -> impl IntoView {
1145 let DetailSnapshot {1206 let DetailSnapshot {
1146 detail,1207 detail,
1147- me: _,1208+ me,
1148 today,1209 today,
1149 linkable,1210 linkable,
1150 may_write,1211 may_write,
1151 may_comment,1212 may_comment,
1152 may_delete,1213 may_delete,
1214+ allowed_file_types,
1215+ attachment_limit_mb,
1153 } = snapshot;1216 } = snapshot;
1154 1217
1155 let id = StoredValue::new(detail.id.clone());1218 let id = StoredValue::new(detail.id.clone());
@@ -1164,22 +1227,33 @@ fn DetailScreen(
1164 let deadline_label = detail.deadline_label(today);1227 let deadline_label = detail.deadline_label(today);
1165 let assignee_count = detail.assignees.len();1228 let assignee_count = detail.assignees.len();
1166 let comment_count = detail.comments.len();1229 let comment_count = detail.comments.len();
1230+ let file_count = detail.files.len();
1167 let unassigned: Vec<Person> = detail.unassigned().cloned().collect();1231 let unassigned: Vec<Person> = detail.unassigned().cloned().collect();
1168 let has_deps = !detail.blocked_by.is_empty() || !detail.blocks.is_empty();1232 let has_deps = !detail.blocked_by.is_empty() || !detail.blocks.is_empty();
1233+ let accept = (!allowed_file_types.is_empty()).then(|| {
1234+ allowed_file_types
1235+ .iter()
1236+ .map(|kind| format!(".{kind}"))
1237+ .collect::<Vec<_>>()
1238+ .join(",")
1239+ });
1240+ let upload_refusal = crate::auth::refusal_from_query("upload_file");
1169 1241
1170 let comment = ServerAction::<PostComment>::new();1242 let comment = ServerAction::<PostComment>::new();
1171 let remove = ServerAction::<DeleteTask>::new();1243 let remove = ServerAction::<DeleteTask>::new();
1172 let move_to = ServerAction::<crate::board::MoveCard>::new();1244 let move_to = ServerAction::<crate::board::MoveCard>::new();
1245+ let drop_file = ServerAction::<DeleteFile>::new();
1173 let comment_refusal = crate::auth::refusal_of(comment);1246 let comment_refusal = crate::auth::refusal_of(comment);
1174 let remove_refusal = crate::auth::refusal_of(remove);1247 let remove_refusal = crate::auth::refusal_of(remove);
1175 let move_refusal = crate::auth::refusal_of(move_to);1248 let move_refusal = crate::auth::refusal_of(move_to);
1249+ let drop_file_refusal = crate::auth::refusal_of(drop_file);
1176 // Deleting is two steps: ask what it would cost, then say it out loud and1250 // Deleting is two steps: ask what it would cost, then say it out loud and
1177 // let the person decide. The artboard's red button had no confirmation and1251 // let the person decide. The artboard's red button had no confirmation and
1178 // this action reaches other people's tasks.1252 // this action reaches other people's tasks.
1179 let ask = ServerAction::<WhatDeleteCosts>::new();1253 let ask = ServerAction::<WhatDeleteCosts>::new();
1180 // Every action that lands re-reads the task and the board behind it. The1254 // Every action that lands re-reads the task and the board behind it. The
1181 // per-region editors own their own actions and do the same.1255 // per-region editors own their own actions and do the same.
1182- for value in [comment.value(), move_to.value()] {1256+ for value in [comment.value(), move_to.value(), drop_file.value()] {
1183 Effect::new(move |_| {1257 Effect::new(move |_| {
1184 if matches!(value.get(), Some(Ok(None))) {1258 if matches!(value.get(), Some(Ok(None))) {
1185 on_change();1259 on_change();
@@ -1340,6 +1414,50 @@ fn DetailScreen(
1340 {(!has_deps).then(|| view! { <p class="detail-quiet">"Nothing blocks this task."</p> })}1414 {(!has_deps).then(|| view! { <p class="detail-quiet">"Nothing blocks this task."</p> })}
1341 </section>1415 </section>
1342 1416
1417+ <section class="detail-block">
1418+ <div class="detail-block-head">
1419+ <span class="detail-label">"FILES"</span>
1420+ <span class="detail-count">{file_count}</span>
1421+ </div>
1422+ {(file_count > 0)
1423+ .then(|| {
1424+ view! {
1425+ <div class="file-list">
1426+ {detail
1427+ .files
1428+ .iter()
1429+ .map(|file| {
1430+ view! { <FileChip file=file.clone() me=me.clone() action=drop_file/> }
1431+ })
1432+ .collect_view()}
1433+ </div>
1434+ }
1435+ })}
1436+ {(file_count == 0).then(|| view! { <p class="detail-quiet">"No files yet."</p> })}
1437+ {refused(drop_file_refusal)}
1438+ {may_comment
1439+ .then(|| {
1440+ view! {
1441+ <form
1442+ class="file-upload"
1443+ method="post"
1444+ action="/files"
1445+ enctype="multipart/form-data"
1446+ >
1447+ <input type="hidden" name="task_id" value=move || id.get_value()/>
1448+ <input type="file" name="file" accept=accept required/>
1449+ <button class="file-upload-submit" type="submit">
1450+ "Upload"
1451+ </button>
1452+ <span class="detail-quiet">
1453+ {format!("Up to {attachment_limit_mb} MB.")}
1454+ </span>
1455+ </form>
1456+ {refused(upload_refusal)}
1457+ }
1458+ })}
1459+ </section>
1460+
1343 <section class="detail-block">1461 <section class="detail-block">
1344 <div class="detail-block-head">1462 <div class="detail-block-head">
1345 <span class="detail-label">"COMMENTS"</span>1463 <span class="detail-label">"COMMENTS"</span>
@@ -1616,6 +1734,43 @@ fn DepRow(
1616 }1734 }
1617 }1735 }
1618 1736
1737+/// One attachment, chip-shaped like a dependency. A file posted with a
1738+/// comment stays listed here too — a person hunting for what someone
1739+/// attached should not have to remember which comment it rode in on — with a
1740+/// quiet note saying where it came from.
1741+#[component]
1742+fn FileChip(
1743+ file: dizey_core::detail::FileLine,
1744+ me: Me,
1745+ action: ServerAction<DeleteFile>,
1746+) -> impl IntoView {
1747+ let may_drop = me.id == file.uploaded_by || me.role.can_administer();
1748+ let size = file.size_label();
1749+ let on_comment = file.comment_id.is_some();
1750+ let file_id = file.id.clone();
1751+
1752+ view! {
1753+ <span class="file-chip">
1754+ <a class="file-chip-name" href=format!("/files/{}", file.id)>
1755+ {file.name.clone()}
1756+ </a>
1757+ <span class="file-chip-size">{size}</span>
1758+ {on_comment.then(|| view! { <span class="file-chip-note">"on a comment"</span> })}
1759+ {may_drop
1760+ .then(|| {
1761+ view! {
1762+ <ActionForm action=action attr:class="file-chip-drop-form">
1763+ <input type="hidden" name="file_id" value=file_id/>
1764+ <button class="file-chip-drop" type="submit" title="Remove this file">
1765+ {glyph::cross()}
1766+ </button>
1767+ </ActionForm>
1768+ }
1769+ })}
1770+ </span>
1771+ }
1772+}
1773+
1619 #[component]1774 #[component]
1620 fn CommentRow(comment: Comment) -> impl IntoView {1775 fn CommentRow(comment: Comment) -> impl IntoView {
1621 use dizey_core::detail::moment_label;1776 use dizey_core::detail::moment_label;
crates/dizey-web/src/files.rsadded+318 -0
@@ -0,0 +1,318 @@
1+//! Attachment upload and download, as plain axum handlers.
2+//!
3+//! These sit outside the leptos server-function machinery: a multipart body
4+//! and a byte stream are not things a server function's JSON codec is meant
5+//! to carry, so the router hands `/files` and `/files/{id}` to axum directly
6+//! and the two share `Accounts` and the session cookie the same way the rest
7+//! of the app does.
8+
9+use axum::extract::{Extension, Multipart, Path};
10+use axum::http::{HeaderMap, HeaderValue, StatusCode};
11+use axum::response::{IntoResponse, Redirect, Response};
12+use dizey_core::accounts::Accounts;
13+use dizey_core::store::{NewAttachment, User};
14+use time::OffsetDateTime;
15+
16+use crate::auth::Refusal;
17+use crate::detail::guard;
18+
19+/// The person behind this request, read off the session cookie in `headers`
20+/// rather than the leptos request context a plain axum handler has none of.
21+pub async fn user_of(accounts: &Accounts, headers: &HeaderMap) -> Option<User> {
22+ let session = crate::server::session_in(headers)?;
23+ accounts.authenticate(&session).await.ok().flatten()
24+}
25+
26+/// Where the browser lands once the upload is settled, success or refusal
27+/// alike — the task detail modal it was posted from, reopened. This is a
28+/// plain redirect rather than the `carry_refusal_on_redirect` middleware's
29+/// rewrite: that middleware turns a `302` server-function answer into one of
30+/// these, but a handler outside the server-function machinery can just write
31+/// the query string itself.
32+fn back_to(task_id: &str, refusal: Option<Refusal>) -> Response {
33+ let location = match refusal {
34+ Some(refusal) => format!("/?task={task_id}&refusal={}&on=upload_file", refusal.code()),
35+ None => format!("/?task={task_id}"),
36+ };
37+ Redirect::to(&location).into_response()
38+}
39+
40+/// The same redirect, for the refusals that land before a `task_id` is even
41+/// known to carry in the query. `Redirect::to` is `303 See Other`, which
42+/// matters here: `carry_refusal_on_redirect` in `server.rs` only rewrites the
43+/// `302`s a server function's own redirect answers with, and must leave this
44+/// handler's redirects alone.
45+fn home(refusal: Refusal) -> Response {
46+ Redirect::to(&format!("/?refusal={}&on=upload_file", refusal.code())).into_response()
47+}
48+
49+/// A basename, stripped of anything that could make it look like a path or
50+/// carry a control character. What a browser calls a file is a label on a
51+/// row, never a place to write bytes.
52+fn label_of(file_name: &str) -> String {
53+ let base = file_name
54+ .rsplit(['/', '\\'])
55+ .next()
56+ .unwrap_or(file_name);
57+ base.chars().filter(|c| !c.is_control()).collect()
58+}
59+
60+/// What the bytes are, decided from the bytes themselves — never from the
61+/// part's `content_type()`, which is whatever the browser felt like sending.
62+fn sniff(bytes: &[u8]) -> &'static str {
63+ if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
64+ "image/png"
65+ } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
66+ "image/jpeg"
67+ } else if bytes.starts_with(b"GIF8") {
68+ "image/gif"
69+ } else if bytes.starts_with(b"%PDF-") {
70+ "application/pdf"
71+ } else if bytes.starts_with(b"PK\x03\x04") {
72+ "application/zip"
73+ } else if bytes.starts_with(&[0x1F, 0x8B]) {
74+ "application/gzip"
75+ } else if std::str::from_utf8(bytes).is_ok() {
76+ "text/plain"
77+ } else {
78+ "application/octet-stream"
79+ }
80+}
81+
82+/// Takes one file onto a task. The route this hangs off already caps the
83+/// whole request body at the widest limit any workspace could set
84+/// ([`crate::settings::WIDEST_ATTACHMENT_MB`]); this handler enforces the
85+/// workspace's own, usually narrower, limit while the bytes are still
86+/// arriving rather than after they have all landed.
87+pub async fn upload(
88+ Extension(accounts): Extension<Accounts>,
89+ headers: HeaderMap,
90+ mut multipart: Multipart,
91+) -> Response {
92+ let Some(user) = user_of(&accounts, &headers).await else {
93+ return home(Refusal::SignInFirst);
94+ };
95+ if !user.role.can_comment() {
96+ return home(Refusal::Forbidden);
97+ }
98+
99+ let mut task_id: Option<String> = None;
100+ let mut comment_id: Option<String> = None;
101+ let mut file_name: Option<String> = None;
102+ let mut bytes: Option<Vec<u8>> = None;
103+
104+ let store = accounts.store().clone();
105+
106+ loop {
107+ let field = match multipart.next_field().await {
108+ Ok(Some(field)) => field,
109+ Ok(None) => break,
110+ Err(_) => return home(Refusal::NoFile),
111+ };
112+ match field.name() {
113+ Some("task_id") => {
114+ task_id = field.text().await.ok();
115+ }
116+ Some("comment_id") => {
117+ comment_id = field.text().await.ok();
118+ }
119+ Some("file") => {
120+ let Some(name) = field.file_name().map(str::to_string) else {
121+ continue;
122+ };
123+ if name.is_empty() {
124+ continue;
125+ }
126+
127+ let Some(task_id) = task_id.as_deref() else {
128+ return home(Refusal::NotFound);
129+ };
130+ if let Err(refusal) = guard::task_of(store.as_ref(), &user, task_id).await {
131+ return back_to(task_id, Some(refusal));
132+ }
133+ let Ok(Some(workspace)) = store.workspace().await else {
134+ return back_to(task_id, Some(Refusal::NotFound));
135+ };
136+ let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_lowercase());
137+ let allowed = workspace.allowed_file_types.is_empty()
138+ || extension
139+ .as_deref()
140+ .is_some_and(|ext| workspace.allowed_file_types.iter().any(|a| a == ext));
141+ if !allowed {
142+ return back_to(task_id, Some(Refusal::FileTypeNotAllowed));
143+ }
144+
145+ let limit = workspace.attachment_limit_bytes;
146+ let mut field = field;
147+ let mut collected = Vec::new();
148+ loop {
149+ match field.chunk().await {
150+ Ok(Some(chunk)) => {
151+ if (collected.len() + chunk.len()) as u64 > limit {
152+ return back_to(task_id, Some(Refusal::FileTooBig));
153+ }
154+ collected.extend_from_slice(&chunk);
155+ }
156+ Ok(None) => break,
157+ Err(_) => return back_to(task_id, Some(Refusal::FileTooBig)),
158+ }
159+ }
160+
161+ file_name = Some(name);
162+ bytes = Some(collected);
163+ }
164+ _ => {}
165+ }
166+ }
167+
168+ let Some(task_id) = task_id else {
169+ return home(Refusal::NotFound);
170+ };
171+ let Some(file_name) = file_name else {
172+ return back_to(&task_id, Some(Refusal::NoFile));
173+ };
174+ let bytes = bytes.unwrap_or_default();
175+
176+ // A `comment_id` only travels if it names a comment that is actually on
177+ // this task; anything else is dropped rather than refused, since the
178+ // upload itself is still perfectly good without it.
179+ let comment_id = match comment_id {
180+ Some(id) => {
181+ let on_task = store
182+ .comments_for_task(&task_id)
183+ .await
184+ .map(|comments| comments.iter().any(|c| c.id == id))
185+ .unwrap_or(false);
186+ on_task.then_some(id)
187+ }
188+ None => None,
189+ };
190+
191+ let label = label_of(&file_name);
192+ let mime_type = sniff(&bytes);
193+
194+ let added = store
195+ .add_attachment(NewAttachment {
196+ task_id: &task_id,
197+ comment_id: comment_id.as_deref(),
198+ file_name: &label,
199+ mime_type,
200+ bytes,
201+ uploaded_by: &user.id,
202+ at: OffsetDateTime::now_utc(),
203+ })
204+ .await;
205+
206+ match added {
207+ Ok(_) => back_to(&task_id, None),
208+ Err(_) => back_to(&task_id, Some(Refusal::NotFound)),
209+ }
210+}
211+
212+/// The `Content-Disposition` header for one download: always `attachment`, so
213+/// an uploaded HTML or SVG file is offered to save rather than run on Dizey's
214+/// origin. The ASCII fallback keeps only characters no quoting scheme could
215+/// turn into a delimiter or a control character; `filename*` carries the real
216+/// name, percent-encoded, for browsers that read it.
217+fn disposition_of(file_name: &str) -> String {
218+ let ascii: String = file_name
219+ .chars()
220+ .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { c } else { '_' })
221+ .collect();
222+ let mut encoded = String::new();
223+ for &byte in file_name.as_bytes() {
224+ let c = byte as char;
225+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '~' | '-') {
226+ encoded.push(c);
227+ } else {
228+ encoded.push_str(&format!("%{byte:02X}"));
229+ }
230+ }
231+ format!("attachment; filename=\"{ascii}\"; filename*=UTF-8''{encoded}")
232+}
233+
234+/// Serves one attachment's bytes, or the same not-found a stranger to the
235+/// task would see for a task that does not exist — never a `403`, which would
236+/// confirm the id belongs to someone else's workspace.
237+pub async fn download(
238+ Extension(accounts): Extension<Accounts>,
239+ headers: HeaderMap,
240+ Path(id): Path<String>,
241+) -> Response {
242+ let Some(user) = user_of(&accounts, &headers).await else {
243+ return home(Refusal::SignInFirst);
244+ };
245+
246+ let store = accounts.store().clone();
247+ let Ok(Some(row)) = store.attachment(&id).await else {
248+ return StatusCode::NOT_FOUND.into_response();
249+ };
250+ if guard::task_of(store.as_ref(), &user, &row.task_id).await.is_err() {
251+ return StatusCode::NOT_FOUND.into_response();
252+ }
253+ let Ok(Some(bytes)) = store.attachment_bytes(&id).await else {
254+ return StatusCode::NOT_FOUND.into_response();
255+ };
256+
257+ let mut response = bytes.into_response();
258+ let headers = response.headers_mut();
259+ headers.insert(
260+ axum::http::header::CONTENT_TYPE,
261+ HeaderValue::from_str(&row.mime_type).unwrap_or(HeaderValue::from_static("application/octet-stream")),
262+ );
263+ headers.insert(
264+ axum::http::header::CONTENT_DISPOSITION,
265+ HeaderValue::from_str(&disposition_of(&row.file_name))
266+ .unwrap_or(HeaderValue::from_static("attachment")),
267+ );
268+ response
269+}
270+
271+#[cfg(test)]
272+mod tests {
273+ use super::*;
274+
275+ #[test]
276+ fn sniffs_the_magic_numbers() {
277+ assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png");
278+ assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg");
279+ assert_eq!(sniff(b"hello, this is plainly text"), "text/plain");
280+ assert_eq!(sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), "application/octet-stream");
281+ }
282+
283+ #[test]
284+ fn labels_strip_the_path_and_the_control_characters() {
285+ assert_eq!(label_of("../../etc/passwd"), "passwd");
286+ assert_eq!(label_of(r"a\b.txt"), "b.txt");
287+ assert_eq!(label_of("name\r\nwith\tcontrol.txt"), "namewithcontrol.txt");
288+ }
289+
290+ #[test]
291+ fn disposition_carries_no_quote_or_control_character() {
292+ let header = disposition_of("a\"b\r\nX: y.txt");
293+ assert!(!header.contains('\r'));
294+ assert!(!header.contains('\n'));
295+ assert_eq!(
296+ header,
297+ "attachment; filename=\"a_b__X__y.txt\"; filename*=UTF-8''a%22b%0D%0AX%3A%20y.txt"
298+ );
299+ }
300+
301+ #[test]
302+ fn disposition_of_a_traversal_name_keeps_no_path_meaning() {
303+ let header = disposition_of("../../etc/passwd");
304+ assert_eq!(
305+ header,
306+ "attachment; filename=\".._.._etc_passwd\"; filename*=UTF-8''..%2F..%2Fetc%2Fpasswd"
307+ );
308+ }
309+
310+ #[test]
311+ fn disposition_of_a_non_ascii_name_falls_back_and_percent_encodes() {
312+ let header = disposition_of("résumé.pdf");
313+ assert_eq!(
314+ header,
315+ "attachment; filename=\"r_sum_.pdf\"; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf"
316+ );
317+ }
318+}
crates/dizey-web/src/lib.rsmodified+2 -0
@@ -10,6 +10,8 @@ pub mod pages;
10 pub mod rules;10 pub mod rules;
11 pub mod settings;11 pub mod settings;
12 #[cfg(feature = "ssr")]12 #[cfg(feature = "ssr")]
13+pub mod files;
14+#[cfg(feature = "ssr")]
13 pub mod server;15 pub mod server;
14 #[cfg(feature = "ssr")]16 #[cfg(feature = "ssr")]
15 pub mod smtp;17 pub mod smtp;
crates/dizey-web/src/server.rsmodified+18 -2
@@ -103,8 +103,14 @@ pub fn mail() -> Mail {
103 103
104 /// The cookie value this request presented, if it presented one.104 /// The cookie value this request presented, if it presented one.
105 pub fn presented_session() -> Option<String> {105 pub fn presented_session() -> Option<String> {
106- let parts = use_context::<Parts>()?;106+ session_in(&use_context::<Parts>()?.headers)
107- for header in parts.headers.get_all(COOKIE) {107+}
108+
109+/// The same scan as `presented_session`, off a plain `HeaderMap` rather than
110+/// the leptos request context — for handlers axum calls directly, which have
111+/// no such context to read.
112+pub fn session_in(headers: &axum::http::HeaderMap) -> Option<String> {
113+ for header in headers.get_all(COOKIE) {
108 let Ok(raw) = header.to_str() else { continue };114 let Ok(raw) = header.to_str() else { continue };
109 for pair in raw.split(';') {115 for pair in raw.split(';') {
110 let pair = pair.trim();116 let pair = pair.trim();
@@ -245,6 +251,15 @@ pub fn router(
245 let routes = generate_route_list(crate::app::App);251 let routes = generate_route_list(crate::app::App);
246 Router::new()252 Router::new()
247 .route("/healthz", axum::routing::get(|| async { "ok" }))253 .route("/healthz", axum::routing::get(|| async { "ok" }))
254+ .route(
255+ "/files",
256+ axum::routing::post(crate::files::upload).layer(
257+ axum::extract::DefaultBodyLimit::max(
258+ crate::settings::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024,
259+ ),
260+ ),
261+ )
262+ .route("/files/{id}", axum::routing::get(crate::files::download))
248 .leptos_routes_with_context(263 .leptos_routes_with_context(
249 &leptos_options,264 &leptos_options,
250 routes,265 routes,
@@ -265,6 +280,7 @@ pub fn router(
265 )280 )
266 .fallback(leptos_axum::file_and_error_handler(crate::app::shell))281 .fallback(leptos_axum::file_and_error_handler(crate::app::shell))
267 .layer(axum::middleware::from_fn(carry_refusal_on_redirect))282 .layer(axum::middleware::from_fn(carry_refusal_on_redirect))
283+ .layer(axum::Extension(accounts))
268 .with_state(leptos_options)284 .with_state(leptos_options)
269 }285 }
270 286
crates/dizey-web/tests/http.rsmodified+572 -0
@@ -143,6 +143,111 @@ impl App {
143 location,143 location,
144 }144 }
145 }145 }
146+
147+ /// Posts a multipart form the way a browser's
148+ /// `<form enctype="multipart/form-data">` does, hand-built rather than
149+ /// pulling in a client crate for it: the fields first, in the order given
150+ /// — the upload handler reads `task_id` before it reaches `file` — then
151+ /// one `file` part if given.
152+ async fn post_multipart(
153+ &self,
154+ path: &str,
155+ cookie: Option<&str>,
156+ fields: &[(&str, &str)],
157+ file: Option<(&str, &str, &[u8])>,
158+ ) -> Answer {
159+ const BOUNDARY: &str = "dizey-test-boundary";
160+ let mut body = Vec::new();
161+ for (name, value) in fields {
162+ body.extend_from_slice(
163+ format!(
164+ "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
165+ )
166+ .as_bytes(),
167+ );
168+ }
169+ if let Some((filename, content_type, bytes)) = file {
170+ body.extend_from_slice(
171+ format!(
172+ "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n"
173+ )
174+ .as_bytes(),
175+ );
176+ body.extend_from_slice(bytes);
177+ body.extend_from_slice(b"\r\n");
178+ }
179+ body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
180+
181+ let mut request = Request::builder()
182+ .method("POST")
183+ .uri(path)
184+ .header(
185+ header::CONTENT_TYPE,
186+ format!("multipart/form-data; boundary={BOUNDARY}"),
187+ );
188+ if let Some(cookie) = cookie {
189+ request = request.header(
190+ header::COOKIE,
191+ HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
192+ );
193+ }
194+ let response = self
195+ .router
196+ .clone()
197+ .oneshot(request.body(Body::from(body)).unwrap())
198+ .await
199+ .unwrap();
200+ let status = response.status();
201+ let location = response
202+ .headers()
203+ .get(header::LOCATION)
204+ .and_then(|value| value.to_str().ok())
205+ .map(str::to_string);
206+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
207+ .await
208+ .unwrap();
209+ Answer {
210+ status,
211+ session: None,
212+ body: String::from_utf8_lossy(&bytes).into_owned(),
213+ location,
214+ }
215+ }
216+
217+ /// Gets a page or a download the way a browser does: no `Accept` header
218+ /// forcing JSON, an optional cookie, and the raw bytes back untouched — a
219+ /// download's body is not always UTF-8.
220+ async fn get(&self, path: &str, cookie: Option<&str>) -> Raw {
221+ let mut request = Request::builder().method("GET").uri(path);
222+ if let Some(cookie) = cookie {
223+ request = request.header(
224+ header::COOKIE,
225+ HeaderValue::from_str(&format!("{SESSION_COOKIE}={cookie}")).unwrap(),
226+ );
227+ }
228+ let response = self
229+ .router
230+ .clone()
231+ .oneshot(request.body(Body::empty()).unwrap())
232+ .await
233+ .unwrap();
234+ let status = response.status();
235+ let content_type = response
236+ .headers()
237+ .get(header::CONTENT_TYPE)
238+ .and_then(|value| value.to_str().ok())
239+ .map(str::to_string);
240+ let disposition = response
241+ .headers()
242+ .get(header::CONTENT_DISPOSITION)
243+ .and_then(|value| value.to_str().ok())
244+ .map(str::to_string);
245+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
246+ .await
247+ .unwrap()
248+ .to_vec();
249+ Raw { status, content_type, disposition, bytes }
250+ }
146 }251 }
147 252
148 impl Drop for App {253 impl Drop for App {
@@ -151,6 +256,15 @@ impl Drop for App {
151 }256 }
152 }257 }
153 258
259+/// A GET answer kept as raw bytes: a page's HTML or a download's file, neither
260+/// of which the JSON-shaped [`Answer`] below is meant for.
261+struct Raw {
262+ status: StatusCode,
263+ content_type: Option<String>,
264+ disposition: Option<String>,
265+ bytes: Vec<u8>,
266+}
267+
154 struct Answer {268 struct Answer {
155 status: StatusCode,269 status: StatusCode,
156 session: Option<String>,270 session: Option<String>,
@@ -1967,3 +2081,461 @@ async fn a_signed_out_browser_may_not_touch_the_rules() {
1967 );2081 );
1968 }2082 }
1969 }2083 }
2084+
2085+// An id nobody's workspace owns answers `404` for a signed-in person, the
2086+// same not-found a stranger to the task would see, and a `303` for nobody at
2087+// all — never a leptos catch-all page, and never a `403` that would confirm
2088+// the id belongs to someone else's workspace.
2089+#[tokio::test]
2090+async fn a_download_of_an_unknown_attachment_is_not_found_and_signed_out_is_a_redirect() {
2091+ let app = App::open().await;
2092+ let admin = admin(&app).await;
2093+
2094+ let request = Request::builder()
2095+ .method("GET")
2096+ .uri("/files/anything")
2097+ .header(
2098+ header::COOKIE,
2099+ HeaderValue::from_str(&format!("{SESSION_COOKIE}={admin}")).unwrap(),
2100+ )
2101+ .body(Body::empty())
2102+ .unwrap();
2103+ let response = app.router.clone().oneshot(request).await.unwrap();
2104+ assert_eq!(response.status(), StatusCode::NOT_FOUND);
2105+
2106+ let request = Request::builder()
2107+ .method("GET")
2108+ .uri("/files/anything")
2109+ .body(Body::empty())
2110+ .unwrap();
2111+ let response = app.router.clone().oneshot(request).await.unwrap();
2112+ assert_eq!(response.status(), StatusCode::SEE_OTHER);
2113+}
2114+
2115+// A signed-in member's detail page carries the upload form no-script needs:
2116+// a real multipart `<form>` posting to `/files`, not the leptos action form
2117+// the rest of the screen uses — a browser with no script still has a way to
2118+// attach a file.
2119+#[tokio::test]
2120+async fn the_files_section_is_on_the_detail_page() {
2121+ let app = App::open().await;
2122+ let admin = admin(&app).await;
2123+ let column = first_column(&app, &admin).await;
2124+ let task = a_task(&app, &admin, &column, "Attach something to me").await;
2125+
2126+ let request = Request::builder()
2127+ .method("GET")
2128+ .uri(format!("/?task={task}"))
2129+ .header(
2130+ header::COOKIE,
2131+ HeaderValue::from_str(&format!("{SESSION_COOKIE}={admin}")).unwrap(),
2132+ )
2133+ .body(Body::empty())
2134+ .unwrap();
2135+ let response = app.router.clone().oneshot(request).await.unwrap();
2136+ assert_eq!(response.status(), StatusCode::OK);
2137+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
2138+ .await
2139+ .unwrap();
2140+ let body = String::from_utf8(bytes.to_vec()).unwrap();
2141+ assert!(
2142+ body.contains("multipart/form-data"),
2143+ "no multipart upload form on the detail page"
2144+ );
2145+ assert!(
2146+ body.contains(r#"action="/files""#),
2147+ "the upload form does not post to /files"
2148+ );
2149+}
2150+
2151+/// The id of the file named `name` in a [`dizey_web::detail::FetchTask`]
2152+/// snapshot's body, read the way the page would: found by its name, then the
2153+/// `id` field that comes right before it on the wire.
2154+fn attachment_id_named(body: &str, name: &str) -> String {
2155+ let needle = format!("\",\"name\":\"{name}\"");
2156+ let before = body
2157+ .split_once(&needle)
2158+ .map(|(head, _)| head)
2159+ .unwrap_or_else(|| panic!("no file named {name} in the detail snapshot: {body}"));
2160+ before
2161+ .rsplit_once("\"id\":\"")
2162+ .and_then(|(_, rest)| rest.split('"').next())
2163+ .expect("no id before the file name")
2164+ .to_string()
2165+}
2166+
2167+#[tokio::test]
2168+async fn a_viewer_who_posts_an_upload_anyway_is_refused() {
2169+ let app = App::open().await;
2170+ let admin = admin(&app).await;
2171+ let viewer = invited(&app, &admin, "quiet@dizey.sh", "Quiet Reader", Role::Viewer).await;
2172+ let column = first_column(&app, &admin).await;
2173+ let task = a_task(&app, &admin, &column, "Viewers cannot attach").await;
2174+
2175+ let answer = app
2176+ .post_multipart(
2177+ "/files",
2178+ Some(&viewer),
2179+ &[("task_id", &task)],
2180+ Some(("note.txt", "text/plain", b"hello")),
2181+ )
2182+ .await;
2183+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2184+ assert_eq!(
2185+ answer.location.as_deref(),
2186+ Some("/?refusal=forbidden&on=upload_file")
2187+ );
2188+}
2189+
2190+#[tokio::test]
2191+async fn a_member_uploads_a_file_and_the_chip_comes_back() {
2192+ let app = App::open().await;
2193+ let admin = admin(&app).await;
2194+ let member = invited(&app, &admin, "mo@dizey.sh", "Mo Dubois", Role::Member).await;
2195+ let column = first_column(&app, &admin).await;
2196+ let task = a_task(&app, &admin, &column, "Attach the spec").await;
2197+
2198+ let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
2199+ let answer = app
2200+ .post_multipart(
2201+ "/files",
2202+ Some(&member),
2203+ &[("task_id", &task)],
2204+ Some(("spec.png", "image/png", &png)),
2205+ )
2206+ .await;
2207+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2208+ assert_eq!(
2209+ answer.location.as_deref(),
2210+ Some(format!("/?task={task}").as_str())
2211+ );
2212+
2213+ let snapshot = app
2214+ .post(
2215+ path::<dizey_web::detail::FetchTask>(),
2216+ Some(&member),
2217+ &[("task_id", &task)],
2218+ )
2219+ .await;
2220+ let file_id = attachment_id_named(&snapshot.body, "spec.png");
2221+
2222+ let page = app.get(&format!("/?task={task}"), Some(&member)).await;
2223+ assert_eq!(page.status, StatusCode::OK);
2224+ let html = String::from_utf8_lossy(&page.bytes);
2225+ assert!(
2226+ html.contains(&format!("/files/{file_id}")),
2227+ "no href to the new file: {html}"
2228+ );
2229+ assert!(html.contains("spec.png"));
2230+
2231+ let download = app.get(&format!("/files/{file_id}"), Some(&member)).await;
2232+ assert_eq!(download.status, StatusCode::OK);
2233+ assert_eq!(download.bytes, png);
2234+}
2235+
2236+#[tokio::test]
2237+async fn a_file_past_the_workspace_limit_is_refused_before_it_is_kept() {
2238+ let app = App::open().await;
2239+ let admin_cookie = admin(&app).await;
2240+ let column = first_column(&app, &admin_cookie).await;
2241+ let task = a_task(&app, &admin_cookie, &column, "Too big to keep").await;
2242+
2243+ let answer = app
2244+ .post(
2245+ path::<dizey_web::settings::SaveLimits>(),
2246+ Some(&admin_cookie),
2247+ &[
2248+ ("attachment_limit_mb", "1"),
2249+ ("photo_limit_mb", "2"),
2250+ ("allowed_file_types", ""),
2251+ ],
2252+ )
2253+ .await;
2254+ assert_eq!(answer.body, "null", "{}", answer.body);
2255+
2256+ let big = vec![0u8; 2 * 1024 * 1024];
2257+ let answer = app
2258+ .post_multipart(
2259+ "/files",
2260+ Some(&admin_cookie),
2261+ &[("task_id", &task)],
2262+ Some(("big.bin", "application/octet-stream", &big)),
2263+ )
2264+ .await;
2265+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2266+ assert_eq!(
2267+ answer.location.as_deref(),
2268+ Some(format!("/?task={task}&refusal=file-too-big&on=upload_file").as_str())
2269+ );
2270+
2271+ let snapshot = app
2272+ .post(
2273+ path::<dizey_web::detail::FetchTask>(),
2274+ Some(&admin_cookie),
2275+ &[("task_id", &task)],
2276+ )
2277+ .await;
2278+ assert!(snapshot.body.contains("\"files\":[]"), "{}", snapshot.body);
2279+}
2280+
2281+#[tokio::test]
2282+async fn a_file_type_off_the_list_is_refused() {
2283+ let app = App::open().await;
2284+ let admin_cookie = admin(&app).await;
2285+ let column = first_column(&app, &admin_cookie).await;
2286+ let task = a_task(&app, &admin_cookie, &column, "No executables here").await;
2287+
2288+ let answer = app
2289+ .post(
2290+ path::<dizey_web::settings::SaveLimits>(),
2291+ Some(&admin_cookie),
2292+ &[
2293+ ("attachment_limit_mb", "25"),
2294+ ("photo_limit_mb", "2"),
2295+ ("allowed_file_types", "png"),
2296+ ],
2297+ )
2298+ .await;
2299+ assert_eq!(answer.body, "null", "{}", answer.body);
2300+
2301+ let answer = app
2302+ .post_multipart(
2303+ "/files",
2304+ Some(&admin_cookie),
2305+ &[("task_id", &task)],
2306+ Some(("evil.exe", "application/octet-stream", b"MZ\x90\x00")),
2307+ )
2308+ .await;
2309+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2310+ assert_eq!(
2311+ answer.location.as_deref(),
2312+ Some(format!("/?task={task}&refusal=file-type&on=upload_file").as_str())
2313+ );
2314+}
2315+
2316+#[tokio::test]
2317+async fn an_empty_allowed_list_lets_anything_through() {
2318+ let app = App::open().await;
2319+ let admin_cookie = admin(&app).await;
2320+ let column = first_column(&app, &admin_cookie).await;
2321+ let task = a_task(&app, &admin_cookie, &column, "Whatever shows up").await;
2322+
2323+ let answer = app
2324+ .post_multipart(
2325+ "/files",
2326+ Some(&admin_cookie),
2327+ &[("task_id", &task)],
2328+ Some(("anything.bin", "application/octet-stream", &[0x00, 0x01, 0x02])),
2329+ )
2330+ .await;
2331+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2332+ assert_eq!(
2333+ answer.location.as_deref(),
2334+ Some(format!("/?task={task}").as_str())
2335+ );
2336+}
2337+
2338+#[tokio::test]
2339+async fn the_stored_type_is_what_the_bytes_are_not_what_the_upload_claimed() {
2340+ let app = App::open().await;
2341+ let admin_cookie = admin(&app).await;
2342+ let column = first_column(&app, &admin_cookie).await;
2343+ let task = a_task(&app, &admin_cookie, &column, "Mislabeled on the way in").await;
2344+
2345+ let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
2346+ let answer = app
2347+ .post_multipart(
2348+ "/files",
2349+ Some(&admin_cookie),
2350+ &[("task_id", &task)],
2351+ Some(("liar.pdf", "application/pdf", &png)),
2352+ )
2353+ .await;
2354+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2355+
2356+ let snapshot = app
2357+ .post(
2358+ path::<dizey_web::detail::FetchTask>(),
2359+ Some(&admin_cookie),
2360+ &[("task_id", &task)],
2361+ )
2362+ .await;
2363+ let file_id = attachment_id_named(&snapshot.body, "liar.pdf");
2364+
2365+ let download = app.get(&format!("/files/{file_id}"), Some(&admin_cookie)).await;
2366+ assert_eq!(download.content_type.as_deref(), Some("image/png"));
2367+}
2368+
2369+#[tokio::test]
2370+async fn a_file_name_that_is_a_path_is_kept_as_a_label() {
2371+ let app = App::open().await;
2372+ let admin_cookie = admin(&app).await;
2373+ let column = first_column(&app, &admin_cookie).await;
2374+ let task = a_task(&app, &admin_cookie, &column, "Filename tries to escape").await;
2375+
2376+ let answer = app
2377+ .post_multipart(
2378+ "/files",
2379+ Some(&admin_cookie),
2380+ &[("task_id", &task)],
2381+ Some(("../../etc/passwd", "text/plain", b"root:x:0:0")),
2382+ )
2383+ .await;
2384+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2385+
2386+ let snapshot = app
2387+ .post(
2388+ path::<dizey_web::detail::FetchTask>(),
2389+ Some(&admin_cookie),
2390+ &[("task_id", &task)],
2391+ )
2392+ .await;
2393+ assert!(
2394+ snapshot.body.contains("\"name\":\"passwd\""),
2395+ "the stored name still has a path in it: {}",
2396+ snapshot.body
2397+ );
2398+ let file_id = attachment_id_named(&snapshot.body, "passwd");
2399+
2400+ let page = app.get(&format!("/?task={task}"), Some(&admin_cookie)).await;
2401+ let html = String::from_utf8_lossy(&page.bytes);
2402+ assert!(
2403+ !html.contains("../../etc/passwd"),
2404+ "the raw path leaked onto the chip: {html}"
2405+ );
2406+
2407+ let download = app.get(&format!("/files/{file_id}"), Some(&admin_cookie)).await;
2408+ let disposition = download
2409+ .disposition
2410+ .expect("no content-disposition on the download");
2411+ assert!(!disposition.contains('\r'), "{disposition}");
2412+ assert!(!disposition.contains('\n'), "{disposition}");
2413+ assert!(!disposition.contains('/'), "{disposition}");
2414+}
2415+
2416+/// A second workspace is a second database in this harness — there is no way
2417+/// to build two workspaces sharing one store to prove sibling-workspace
2418+/// isolation directly. What this proves instead: an attachment id that is
2419+/// real, just not in *this* store, gets the same 404 an id from nowhere gets.
2420+#[tokio::test]
2421+async fn a_file_from_another_workspace_is_not_found() {
2422+ let app_a = App::open().await;
2423+ let admin_a = admin(&app_a).await;
2424+
2425+ let app_b = App::open().await;
2426+ let admin_b = admin(&app_b).await;
2427+ let column_b = first_column(&app_b, &admin_b).await;
2428+ let task_b = a_task(&app_b, &admin_b, &column_b, "Lives in the other workspace").await;
2429+ let answer = app_b
2430+ .post_multipart(
2431+ "/files",
2432+ Some(&admin_b),
2433+ &[("task_id", &task_b)],
2434+ Some(("theirs.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])),
2435+ )
2436+ .await;
2437+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2438+ let snapshot = app_b
2439+ .post(
2440+ path::<dizey_web::detail::FetchTask>(),
2441+ Some(&admin_b),
2442+ &[("task_id", &task_b)],
2443+ )
2444+ .await;
2445+ let file_id = attachment_id_named(&snapshot.body, "theirs.png");
2446+
2447+ let answer = app_a.get(&format!("/files/{file_id}"), Some(&admin_a)).await;
2448+ assert_eq!(answer.status, StatusCode::NOT_FOUND);
2449+}
2450+
2451+#[tokio::test]
2452+async fn an_upload_without_a_file_is_refused() {
2453+ let app = App::open().await;
2454+ let admin_cookie = admin(&app).await;
2455+ let column = first_column(&app, &admin_cookie).await;
2456+ let task = a_task(&app, &admin_cookie, &column, "Nothing was chosen").await;
2457+
2458+ let answer = app
2459+ .post_multipart("/files", Some(&admin_cookie), &[("task_id", &task)], None)
2460+ .await;
2461+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2462+ assert_eq!(
2463+ answer.location.as_deref(),
2464+ Some(format!("/?task={task}&refusal=no-file&on=upload_file").as_str())
2465+ );
2466+}
2467+
2468+#[tokio::test]
2469+async fn only_the_uploader_or_an_admin_may_delete_a_file() {
2470+ let app = App::open().await;
2471+ let admin_cookie = admin(&app).await;
2472+ let member_a = invited(&app, &admin_cookie, "asha@dizey.sh", "Asha", Role::Member).await;
2473+ let member_b = invited(&app, &admin_cookie, "beau@dizey.sh", "Beau", Role::Member).await;
2474+ let column = first_column(&app, &admin_cookie).await;
2475+ let task = a_task(&app, &admin_cookie, &column, "Two uploaders, one task").await;
2476+
2477+ let answer = app
2478+ .post_multipart(
2479+ "/files",
2480+ Some(&member_a),
2481+ &[("task_id", &task)],
2482+ Some(("mine.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])),
2483+ )
2484+ .await;
2485+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2486+ let answer = app
2487+ .post_multipart(
2488+ "/files",
2489+ Some(&member_b),
2490+ &[("task_id", &task)],
2491+ Some(("theirs.png", "image/png", &[0x89, 0x50, 0x4E, 0x47])),
2492+ )
2493+ .await;
2494+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
2495+
2496+ let snapshot = app
2497+ .post(
2498+ path::<dizey_web::detail::FetchTask>(),
2499+ Some(&admin_cookie),
2500+ &[("task_id", &task)],
2501+ )
2502+ .await;
2503+ let file_a = attachment_id_named(&snapshot.body, "mine.png");
2504+ let file_b = attachment_id_named(&snapshot.body, "theirs.png");
2505+
2506+ let answer = app
2507+ .post(
2508+ path::<dizey_web::detail::DeleteFile>(),
2509+ Some(&member_b),
2510+ &[("file_id", &file_a)],
2511+ )
2512+ .await;
2513+ assert_eq!(answer.body, "\"Forbidden\"", "{}", answer.body);
2514+
2515+ let answer = app
2516+ .post(
2517+ path::<dizey_web::detail::DeleteFile>(),
2518+ Some(&member_a),
2519+ &[("file_id", &file_a)],
2520+ )
2521+ .await;
2522+ assert_eq!(answer.body, "null", "the uploader was refused: {}", answer.body);
2523+
2524+ let answer = app
2525+ .post(
2526+ path::<dizey_web::detail::DeleteFile>(),
2527+ Some(&admin_cookie),
2528+ &[("file_id", &file_b)],
2529+ )
2530+ .await;
2531+ assert_eq!(answer.body, "null", "the admin was refused: {}", answer.body);
2532+
2533+ let snapshot = app
2534+ .post(
2535+ path::<dizey_web::detail::FetchTask>(),
2536+ Some(&admin_cookie),
2537+ &[("task_id", &task)],
2538+ )
2539+ .await;
2540+ assert!(snapshot.body.contains("\"files\":[]"), "{}", snapshot.body);
2541+}
style/main.scssmodified+77 -0
@@ -1271,6 +1271,83 @@ a {
1271 &:hover { color: #a04a24; }1271 &:hover { color: #a04a24; }
1272 }1272 }
1273 1273
1274+// -- files --------------------------------------------------------------
1275+
1276+.file-list {
1277+ display: flex;
1278+ flex-wrap: wrap;
1279+ gap: 8px;
1280+}
1281+
1282+.file-chip {
1283+ display: inline-flex;
1284+ align-items: center;
1285+ gap: 5px;
1286+ height: 26px;
1287+ padding: 0 9px;
1288+ border: 1px solid var(--border-strong);
1289+ border-radius: 5px;
1290+ background: var(--surface);
1291+ font-size: 12px;
1292+ color: var(--muted);
1293+}
1294+
1295+.file-chip-name {
1296+ color: inherit;
1297+ text-decoration: none;
1298+
1299+ &:hover { color: var(--ink); }
1300+}
1301+
1302+.file-chip-size {
1303+ font-family: var(--font-mono);
1304+ font-size: 11px;
1305+ color: var(--muted-soft);
1306+}
1307+
1308+.file-chip-note {
1309+ font-size: 11px;
1310+ color: var(--muted-soft);
1311+}
1312+
1313+.file-chip-drop-form { display: inline-flex; }
1314+
1315+.file-chip-drop {
1316+ display: inline-flex;
1317+ align-items: center;
1318+ justify-content: center;
1319+ width: 20px;
1320+ height: 20px;
1321+ border: none;
1322+ border-radius: 4px;
1323+ background: transparent;
1324+ color: var(--muted-soft);
1325+ cursor: pointer;
1326+
1327+ &:hover { color: #a04a24; }
1328+}
1329+
1330+.file-upload {
1331+ display: flex;
1332+ align-items: center;
1333+ gap: 8px;
1334+ margin-top: 10px;
1335+}
1336+
1337+.file-upload-submit {
1338+ height: 30px;
1339+ padding: 0 14px;
1340+ border: none;
1341+ border-radius: var(--radius);
1342+ background: var(--ink);
1343+ color: #fffefb;
1344+ font-family: inherit;
1345+ font-size: 12px;
1346+ cursor: pointer;
1347+
1348+ &:disabled { opacity: 0.5; cursor: default; }
1349+}
1350+
1274 // -- comments ---------------------------------------------------------------1351 // -- comments ---------------------------------------------------------------
1275 1352
1276 .comment-list {1353 .comment-list {