Attachments cross over
Browse files at this commitb1e5b9051ec750b3f4a2c1f607355e4e18b7021eParent: 923fdba- feat
- attachments cross over
2 changed files +337 -2
crates/izlek-topcoat/src/files.rsmodified+335 -1
| @@ -1 +1,335 @@ | |||
| 1 | -//! Lands in the page-port fan-out. | 1 | +//! Attachment upload and download, ported onto topcoat's router directly |
| 2 | +//! rather than through `#[route]`'s JSON-answering server functions: a | ||
| 3 | +//! multipart body and a byte stream are not things that codec is meant to | ||
| 4 | +//! carry. Both routes read the session cookie through the same | ||
| 5 | +//! `crate::server::require_user` every other route uses. | ||
| 6 | +//! | ||
| 7 | +//! Ported from `izlek-web/src/files.rs`. | ||
| 8 | + | ||
| 9 | +use time::OffsetDateTime; | ||
| 10 | +use topcoat::context::Cx; | ||
| 11 | +use topcoat::router::content::multipart::Multipart; | ||
| 12 | +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; | ||
| 13 | + | ||
| 14 | +use izlek_core::store::{NewAttachment, Store, User}; | ||
| 15 | + | ||
| 16 | +use crate::server::{Refusal, accounts, require_user}; | ||
| 17 | + | ||
| 18 | +path_param!(id); | ||
| 19 | + | ||
| 20 | +/// Ported from `izlek-web/src/settings.rs`. The settings lane may re-home | ||
| 21 | +/// this as a `pub` export from `crate::settings` once it lands. | ||
| 22 | +pub const WIDEST_ATTACHMENT_MB: u64 = 500; | ||
| 23 | + | ||
| 24 | +/// The task, if this person's workspace is the one holding it. A task in | ||
| 25 | +/// another workspace is not found rather than forbidden, same as | ||
| 26 | +/// `izlek-web/src/detail.rs`'s `guard::task_of`. | ||
| 27 | +async fn task_of(store: &dyn Store, user: &User, task_id: &str) -> Result<(), Refusal> { | ||
| 28 | + match store.task(task_id).await { | ||
| 29 | + Ok(Some(facts)) if facts.workspace_id == user.workspace_id => Ok(()), | ||
| 30 | + Ok(_) => Err(Refusal::NotFound), | ||
| 31 | + Err(error) => { | ||
| 32 | + eprintln!("store error: {error}"); | ||
| 33 | + Err(Refusal::Unavailable) | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// A 303 to `location`, with no body. | ||
| 39 | +fn redirect_to(location: &str) -> (StatusCode, HeaderMap, Vec<u8>) { | ||
| 40 | + let mut headers = HeaderMap::new(); | ||
| 41 | + if let Ok(value) = HeaderValue::from_str(location) { | ||
| 42 | + headers.insert(header::LOCATION, value); | ||
| 43 | + } | ||
| 44 | + (StatusCode::SEE_OTHER, headers, Vec::new()) | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// Where the browser lands once the upload is settled, success or refusal | ||
| 48 | +/// alike — the task detail modal it was posted from, reopened. | ||
| 49 | +fn back_to(task_id: &str, refusal: Option<Refusal>) -> (StatusCode, HeaderMap, Vec<u8>) { | ||
| 50 | + let location = match refusal { | ||
| 51 | + Some(refusal) => format!("/?task={task_id}&refusal={}&on=upload_file", refusal.code()), | ||
| 52 | + None => format!("/?task={task_id}"), | ||
| 53 | + }; | ||
| 54 | + redirect_to(&location) | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// The same redirect, for the refusals that land before a `task_id` is even | ||
| 58 | +/// known to carry in the query. | ||
| 59 | +fn home(refusal: Refusal) -> (StatusCode, HeaderMap, Vec<u8>) { | ||
| 60 | + redirect_to(&format!("/?refusal={}&on=upload_file", refusal.code())) | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// A basename, stripped of anything that could make it look like a path or | ||
| 64 | +/// carry a control character. What a browser calls a file is a label on a | ||
| 65 | +/// row, never a place to write bytes. | ||
| 66 | +fn label_of(file_name: &str) -> String { | ||
| 67 | + let base = file_name | ||
| 68 | + .rsplit(['/', '\\']) | ||
| 69 | + .next() | ||
| 70 | + .unwrap_or(file_name); | ||
| 71 | + base.chars().filter(|c| !c.is_control()).collect() | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// What the bytes are, decided from the bytes themselves — never from the | ||
| 75 | +/// part's `content_type()`, which is whatever the browser felt like sending. | ||
| 76 | +fn sniff(bytes: &[u8]) -> &'static str { | ||
| 77 | + if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { | ||
| 78 | + "image/png" | ||
| 79 | + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { | ||
| 80 | + "image/jpeg" | ||
| 81 | + } else if bytes.starts_with(b"GIF8") { | ||
| 82 | + "image/gif" | ||
| 83 | + } else if bytes.starts_with(b"%PDF-") { | ||
| 84 | + "application/pdf" | ||
| 85 | + } else if bytes.starts_with(b"PK\x03\x04") { | ||
| 86 | + "application/zip" | ||
| 87 | + } else if bytes.starts_with(&[0x1F, 0x8B]) { | ||
| 88 | + "application/gzip" | ||
| 89 | + } else if std::str::from_utf8(bytes).is_ok() { | ||
| 90 | + "text/plain" | ||
| 91 | + } else { | ||
| 92 | + "application/octet-stream" | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// The `Content-Disposition` header for one download: always `attachment`, so | ||
| 97 | +/// an uploaded HTML or SVG file is offered to save rather than run on Izlek's | ||
| 98 | +/// origin. The ASCII fallback keeps only characters no quoting scheme could | ||
| 99 | +/// turn into a delimiter or a control character; `filename*` carries the real | ||
| 100 | +/// name, percent-encoded, for browsers that read it. | ||
| 101 | +fn disposition_of(file_name: &str) -> String { | ||
| 102 | + let ascii: String = file_name | ||
| 103 | + .chars() | ||
| 104 | + .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { c } else { '_' }) | ||
| 105 | + .collect(); | ||
| 106 | + let mut encoded = String::new(); | ||
| 107 | + for &byte in file_name.as_bytes() { | ||
| 108 | + let c = byte as char; | ||
| 109 | + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '~' | '-') { | ||
| 110 | + encoded.push(c); | ||
| 111 | + } else { | ||
| 112 | + encoded.push_str(&format!("%{byte:02X}")); | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + format!("attachment; filename=\"{ascii}\"; filename*=UTF-8''{encoded}") | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) { | ||
| 119 | + (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// Takes one file onto a task. The route this hangs off already caps the | ||
| 123 | +/// whole request body at the widest limit any workspace could set | ||
| 124 | +/// ([`WIDEST_ATTACHMENT_MB`], registered in `main.rs`); this handler enforces | ||
| 125 | +/// the workspace's own, usually narrower, limit while the bytes are still | ||
| 126 | +/// arriving rather than after they have all landed. | ||
| 127 | +/// | ||
| 128 | +/// Fields arrive in request order: `task_id` before `file`, so the task and | ||
| 129 | +/// the workspace's limits are known before a byte of the file is kept. | ||
| 130 | +#[route(POST "/files")] | ||
| 131 | +async fn upload(cx: &Cx, mut multipart: Multipart) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> { | ||
| 132 | + let user = match require_user(cx).await { | ||
| 133 | + Ok(user) => user, | ||
| 134 | + Err(refusal) => return Ok(home(refusal)), | ||
| 135 | + }; | ||
| 136 | + if !user.role.can_comment() { | ||
| 137 | + return Ok(home(Refusal::Forbidden)); | ||
| 138 | + } | ||
| 139 | + | ||
| 140 | + let mut task_id: Option<String> = None; | ||
| 141 | + let mut comment_id: Option<String> = None; | ||
| 142 | + let mut file_name: Option<String> = None; | ||
| 143 | + let mut bytes: Option<Vec<u8>> = None; | ||
| 144 | + | ||
| 145 | + let store = accounts(cx).store().clone(); | ||
| 146 | + | ||
| 147 | + loop { | ||
| 148 | + let field = match multipart.next_field().await { | ||
| 149 | + Ok(Some(field)) => field, | ||
| 150 | + Ok(None) => break, | ||
| 151 | + Err(_) => return Ok(home(Refusal::NoFile)), | ||
| 152 | + }; | ||
| 153 | + match field.name() { | ||
| 154 | + Some("task_id") => { | ||
| 155 | + task_id = field.text().await.ok(); | ||
| 156 | + } | ||
| 157 | + Some("comment_id") => { | ||
| 158 | + comment_id = field.text().await.ok(); | ||
| 159 | + } | ||
| 160 | + Some("file") => { | ||
| 161 | + let Some(name) = field.file_name().map(str::to_string) else { | ||
| 162 | + continue; | ||
| 163 | + }; | ||
| 164 | + if name.is_empty() { | ||
| 165 | + continue; | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + let Some(task_id) = task_id.as_deref() else { | ||
| 169 | + return Ok(home(Refusal::NotFound)); | ||
| 170 | + }; | ||
| 171 | + if let Err(refusal) = task_of(store.as_ref(), &user, task_id).await { | ||
| 172 | + return Ok(back_to(task_id, Some(refusal))); | ||
| 173 | + } | ||
| 174 | + let Ok(Some(workspace)) = store.workspace().await else { | ||
| 175 | + return Ok(back_to(task_id, Some(Refusal::NotFound))); | ||
| 176 | + }; | ||
| 177 | + let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_lowercase()); | ||
| 178 | + let allowed = workspace.allowed_file_types.is_empty() | ||
| 179 | + || extension | ||
| 180 | + .as_deref() | ||
| 181 | + .is_some_and(|ext| workspace.allowed_file_types.iter().any(|a| a == ext)); | ||
| 182 | + if !allowed { | ||
| 183 | + return Ok(back_to(task_id, Some(Refusal::FileTypeNotAllowed))); | ||
| 184 | + } | ||
| 185 | + | ||
| 186 | + let limit = workspace.attachment_limit_bytes; | ||
| 187 | + let mut field = field; | ||
| 188 | + let mut collected = Vec::new(); | ||
| 189 | + loop { | ||
| 190 | + match field.chunk().await { | ||
| 191 | + Ok(Some(chunk)) => { | ||
| 192 | + if (collected.len() + chunk.len()) as u64 > limit { | ||
| 193 | + return Ok(back_to(task_id, Some(Refusal::FileTooBig))); | ||
| 194 | + } | ||
| 195 | + collected.extend_from_slice(&chunk); | ||
| 196 | + } | ||
| 197 | + Ok(None) => break, | ||
| 198 | + Err(_) => return Ok(back_to(task_id, Some(Refusal::FileTooBig))), | ||
| 199 | + } | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + file_name = Some(name); | ||
| 203 | + bytes = Some(collected); | ||
| 204 | + } | ||
| 205 | + _ => {} | ||
| 206 | + } | ||
| 207 | + } | ||
| 208 | + | ||
| 209 | + let Some(task_id) = task_id else { | ||
| 210 | + return Ok(home(Refusal::NotFound)); | ||
| 211 | + }; | ||
| 212 | + let Some(file_name) = file_name else { | ||
| 213 | + return Ok(back_to(&task_id, Some(Refusal::NoFile))); | ||
| 214 | + }; | ||
| 215 | + let bytes = bytes.unwrap_or_default(); | ||
| 216 | + | ||
| 217 | + // A `comment_id` only travels if it names a comment that is actually on | ||
| 218 | + // this task; anything else is dropped rather than refused, since the | ||
| 219 | + // upload itself is still perfectly good without it. | ||
| 220 | + let comment_id = match comment_id { | ||
| 221 | + Some(id) => { | ||
| 222 | + let on_task = store | ||
| 223 | + .comments_for_task(&task_id) | ||
| 224 | + .await | ||
| 225 | + .map(|comments| comments.iter().any(|c| c.id == id)) | ||
| 226 | + .unwrap_or(false); | ||
| 227 | + on_task.then_some(id) | ||
| 228 | + } | ||
| 229 | + None => None, | ||
| 230 | + }; | ||
| 231 | + | ||
| 232 | + let label = label_of(&file_name); | ||
| 233 | + let mime_type = sniff(&bytes); | ||
| 234 | + | ||
| 235 | + let added = store | ||
| 236 | + .add_attachment(NewAttachment { | ||
| 237 | + task_id: &task_id, | ||
| 238 | + comment_id: comment_id.as_deref(), | ||
| 239 | + file_name: &label, | ||
| 240 | + mime_type, | ||
| 241 | + bytes, | ||
| 242 | + uploaded_by: &user.id, | ||
| 243 | + at: OffsetDateTime::now_utc(), | ||
| 244 | + }) | ||
| 245 | + .await; | ||
| 246 | + | ||
| 247 | + Ok(match added { | ||
| 248 | + Ok(_) => back_to(&task_id, None), | ||
| 249 | + Err(_) => back_to(&task_id, Some(Refusal::NotFound)), | ||
| 250 | + }) | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +/// Serves one attachment's bytes, or the same not-found a stranger to the | ||
| 254 | +/// task would see for a task that does not exist — never a `403`, which would | ||
| 255 | +/// confirm the id belongs to someone else's workspace. | ||
| 256 | +#[route(GET "/files/{id}")] | ||
| 257 | +async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> { | ||
| 258 | + let id: &str = path_param::<Id>(cx); | ||
| 259 | + | ||
| 260 | + let user = match require_user(cx).await { | ||
| 261 | + Ok(user) => user, | ||
| 262 | + Err(refusal) => return Ok(home(refusal)), | ||
| 263 | + }; | ||
| 264 | + | ||
| 265 | + let store = accounts(cx).store().clone(); | ||
| 266 | + let Ok(Some(row)) = store.attachment(id).await else { | ||
| 267 | + return Ok(not_found()); | ||
| 268 | + }; | ||
| 269 | + if task_of(store.as_ref(), &user, &row.task_id).await.is_err() { | ||
| 270 | + return Ok(not_found()); | ||
| 271 | + } | ||
| 272 | + let Ok(Some(bytes)) = store.attachment_bytes(id).await else { | ||
| 273 | + return Ok(not_found()); | ||
| 274 | + }; | ||
| 275 | + | ||
| 276 | + let mut headers = HeaderMap::new(); | ||
| 277 | + headers.insert( | ||
| 278 | + header::CONTENT_TYPE, | ||
| 279 | + HeaderValue::from_str(&row.mime_type).unwrap_or(HeaderValue::from_static("application/octet-stream")), | ||
| 280 | + ); | ||
| 281 | + headers.insert( | ||
| 282 | + header::CONTENT_DISPOSITION, | ||
| 283 | + HeaderValue::from_str(&disposition_of(&row.file_name)).unwrap_or(HeaderValue::from_static("attachment")), | ||
| 284 | + ); | ||
| 285 | + Ok((StatusCode::OK, headers, bytes)) | ||
| 286 | +} | ||
| 287 | + | ||
| 288 | +#[cfg(test)] | ||
| 289 | +mod tests { | ||
| 290 | + use super::*; | ||
| 291 | + | ||
| 292 | + #[test] | ||
| 293 | + fn sniffs_the_magic_numbers() { | ||
| 294 | + assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png"); | ||
| 295 | + assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg"); | ||
| 296 | + assert_eq!(sniff(b"hello, this is plainly text"), "text/plain"); | ||
| 297 | + assert_eq!(sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), "application/octet-stream"); | ||
| 298 | + } | ||
| 299 | + | ||
| 300 | + #[test] | ||
| 301 | + fn labels_strip_the_path_and_the_control_characters() { | ||
| 302 | + assert_eq!(label_of("../../etc/passwd"), "passwd"); | ||
| 303 | + assert_eq!(label_of(r"a\b.txt"), "b.txt"); | ||
| 304 | + assert_eq!(label_of("name\r\nwith\tcontrol.txt"), "namewithcontrol.txt"); | ||
| 305 | + } | ||
| 306 | + | ||
| 307 | + #[test] | ||
| 308 | + fn disposition_carries_no_quote_or_control_character() { | ||
| 309 | + let header = disposition_of("a\"b\r\nX: y.txt"); | ||
| 310 | + assert!(!header.contains('\r')); | ||
| 311 | + assert!(!header.contains('\n')); | ||
| 312 | + assert_eq!( | ||
| 313 | + header, | ||
| 314 | + "attachment; filename=\"a_b__X__y.txt\"; filename*=UTF-8''a%22b%0D%0AX%3A%20y.txt" | ||
| 315 | + ); | ||
| 316 | + } | ||
| 317 | + | ||
| 318 | + #[test] | ||
| 319 | + fn disposition_of_a_traversal_name_keeps_no_path_meaning() { | ||
| 320 | + let header = disposition_of("../../etc/passwd"); | ||
| 321 | + assert_eq!( | ||
| 322 | + header, | ||
| 323 | + "attachment; filename=\".._.._etc_passwd\"; filename*=UTF-8''..%2F..%2Fetc%2Fpasswd" | ||
| 324 | + ); | ||
| 325 | + } | ||
| 326 | + | ||
| 327 | + #[test] | ||
| 328 | + fn disposition_of_a_non_ascii_name_falls_back_and_percent_encodes() { | ||
| 329 | + let header = disposition_of("résumé.pdf"); | ||
| 330 | + assert_eq!( | ||
| 331 | + header, | ||
| 332 | + "attachment; filename=\"r_sum_.pdf\"; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf" | ||
| 333 | + ); | ||
| 334 | + } | ||
| 335 | +} | ||
crates/izlek-topcoat/src/main.rsmodified+2 -1
| @@ -4,7 +4,7 @@ use std::sync::Arc; | |||
| 4 | use topcoat::Result; | 4 | use topcoat::Result; |
| 5 | use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; | 5 | use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; |
| 6 | use topcoat::cookie::RouterBuilderCookieExt; | 6 | use topcoat::cookie::RouterBuilderCookieExt; |
| 7 | -use topcoat::router::{Router, RouterBuilderDiscoverExt, route}; | 7 | +use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route}; |
| 8 | 8 | ||
| 9 | #[route(GET "/healthz")] | 9 | #[route(GET "/healthz")] |
| 10 | async fn healthz() -> Result<&'static str> { | 10 | async fn healthz() -> Result<&'static str> { |
| @@ -53,6 +53,7 @@ async fn main() { | |||
| 53 | 53 | ||
| 54 | let router = Router::builder() | 54 | let router = Router::builder() |
| 55 | .discover() | 55 | .discover() |
| 56 | + .layer(BodyLimit::max(izlek_topcoat::files::WIDEST_ATTACHMENT_MB as usize * 1024 * 1024).at("/files")) | ||
| 56 | .cookies() | 57 | .cookies() |
| 57 | .assets(AssetBundle::load().expect("failed to load the asset bundle")) | 58 | .assets(AssetBundle::load().expect("failed to load the asset bundle")) |
| 58 | .app_context(accounts) | 59 | .app_context(accounts) |