tablo_core/upload.rs
1//! Names where uploaded bytes go: a file field binds a `String` column and the
2//! app's [`Uploader`] decides what path the record stores.
3
4use std::{
5 collections::{HashMap, HashSet},
6 future::Future,
7 path::PathBuf,
8};
9
10use percent_encoding::percent_decode_str;
11use topcoat::context::Cx;
12
13use crate::{
14 BoxFuture,
15 form::{FieldErrors, FormValue, FormValues},
16 schema::Schema,
17 topcoat_compat::href::encode_path_segment,
18};
19
20mod body;
21pub(crate) mod carry;
22mod key;
23mod pending;
24pub(crate) mod signed;
25
26pub(crate) use self::body::{Capture, FormParts, parse_body, parse_file_body};
27
28/// Stores one uploaded file and names the value a record stores; installed once
29/// per panel with [`Panel::uploads`](crate::Panel::uploads).
30///
31/// Each method takes the request it serves, so a store reads who asks: an uploader that keeps
32/// tenants apart names each file under [`tenant_id(cx)`](crate::tenant_id), and answers
33/// [`holds`](Self::holds) only for a path under the request's tenant, so no record of one tenant
34/// stores, carries or deletes another's file.
35///
36/// `filename` arrives sanitized to a non-empty basename without directories or
37/// control characters; `bytes` are bounded by the panel's
38/// [`Limits::body_bytes`](crate::Limits::body_bytes). The
39/// framework stores the returned path verbatim. A file a file field's
40/// [`extensions`](crate::FileField::extensions) or [`max_bytes`](crate::FileField::max_bytes)
41/// refuse never reaches `store`.
42///
43/// - `store` returns the value to save. An `Err(reason)` is shown to the user inline as `<Label>
44/// could not be uploaded: <reason>`, so keep the reason free of paths and driver messages.
45/// - What a file field stores comes from a file part only: `store`'s answer, the stored value on an
46/// untouched edit, or nothing when cleared. A path typed into the form is never stored.
47/// - Keeping a file across a failed submit. When a form re-renders with errors, the file input is
48/// empty again. The form carries the path `store` just returned, under a tag the panel signs for
49/// that field and that browser's CSRF cookie, so a client cannot carry a path the field's rules
50/// never passed. The panel reuses it on the next submit only when the tag holds and
51/// `Uploader::holds(path)` answers `true`. The default answers `false`, so the user uploads
52/// again. The tag's key derives from the router's cookie `Key`, else from one drawn per process,
53/// so without a shared `Key` a carry reaches only the instance that minted it. Answer `true` only
54/// for a path your store could have written and still holds inside its own root; checking whether
55/// an arbitrary path exists would let a client pick any file. A `DirUploader` answers `true` for
56/// a URL spelled as its `store` spells one, naming a file in its directory.
57/// - Editing. The edit form shows the stored file as a link and an empty file input. Leaving it
58/// empty keeps the file; the "Remove the current file" checkbox (`clear_<field>`) empties the
59/// field. The input is required only while nothing is stored, and clearing a required field fails
60/// validation, so declare the record-form field `#[form(optional)]` when a record may lose its
61/// file. A [`Field::files`](crate::Field::files) list shows a row per stored file, each posting
62/// its path back under `keep_<field>` to order the list, and a remove checkbox posting it under
63/// `clear_<field>`, the only way a save drops a stored file; the rows keep the order they post
64/// in, chosen files are stored after them, and a refused submission's uploads are carried beside
65/// them as a single field's is.
66/// - Links. The stored value renders as a link, on the edit form and in a `FileColumn` on the
67/// detail page, only when it is a root-relative path (`/uploads/a.png`, not `//host`) or an
68/// `http(s)` URL; anything else renders as text.
69/// - Serving. `Panel::uploads_dir` serves its directory only at signed URLs that expire, which the
70/// panel's pages render; `Panel::serve_dir(path, dir)` serves a directory publicly unless the
71/// path sits under the panel prefix, which the auth gate covers.
72pub trait Uploader: Send + Sync + 'static {
73 /// Stores `bytes` and returns the value to store; the `Err` string renders
74 /// inside the field's inline error, so it must be user-actionable.
75 fn store(
76 &self,
77 cx: &Cx,
78 filename: &str,
79 bytes: &[u8],
80 ) -> impl Future<Output = Result<String, String>> + Send;
81
82 /// Answers `true` only for a path this store could have written and still resolves inside its
83 /// own root; the default answers `false`.
84 ///
85 /// A file field carries a refused submission's pending upload back through a hidden
86 /// `keep_<field>`, so this is what decides which paths a record may point at: a store that
87 /// answers `true` for a file it never wrote lets a forged carry point the record at it.
88 fn holds(&self, cx: &Cx, path: &str) -> impl Future<Output = bool> + Send {
89 async move {
90 let _ = (cx, path);
91 false
92 }
93 }
94
95 /// Confirms that the write about to commit stores `path`; the default does nothing.
96 ///
97 /// The panel calls it inside the write's transaction, before the commit, for each new path a
98 /// file field's create or edit stores and [`holds`](Self::holds) answers `true` for. A store
99 /// that deletes what nothing kept, as [`DirUploader::expire_pending`] does, keeps `path` here.
100 /// An `Err(reason)` fails the write, so a file is never deleted under a committed record.
101 ///
102 /// It has no default: an uploader wrapping another forwards it, or the inner one deletes the
103 /// files of saved records. A store that deletes nothing answers `Ok(())`.
104 fn keep(&self, cx: &Cx, path: &str) -> impl Future<Output = Result<(), String>> + Send;
105
106 /// Deletes the file at `path`, which a committed write no longer stores; the default keeps
107 /// every file.
108 ///
109 /// The panel calls it after the write commits, once per path, and only for a path
110 /// [`holds`](Self::holds) answers `true` for: a record's files when a delete removes its row
111 /// (a soft delete keeps them until the force delete), and a file field's previous file when
112 /// an edit clears or replaces it. An `Err(reason)` is logged; the write stands. A path two
113 /// records share goes with the first that lets it go.
114 fn delete(&self, cx: &Cx, path: &str) -> impl Future<Output = Result<(), String>> + Send {
115 async move {
116 let _ = (cx, path);
117 Ok(())
118 }
119 }
120}
121
122/// Writes each upload into one directory as `{uuid}-{basename}` and stores its URL under
123/// `url_prefix`; [`Panel::uploads_dir`](crate::Panel::uploads_dir) installs it and serves the
124/// directory there.
125///
126/// ```no_run
127/// # use tablo_core::{DirUploader, Panel};
128/// Panel::new("admin")
129/// .uploads(DirUploader::new("/uploads", "var/uploads"))
130/// .serve_dir("/uploads/{*file}", "var/uploads");
131/// ```
132#[derive(Debug, Clone)]
133pub struct DirUploader {
134 url_prefix: String,
135 dir: PathBuf,
136 pending: Option<std::sync::Arc<pending::Pending>>,
137}
138
139/// The longest basename [`DirUploader`] keeps: 255 bytes, less the 36-byte UUID and its dash.
140const MAX_STORED_BASENAME: usize = 255 - 37;
141
142/// Whether `name` is a basename [`DirUploader::store`] writes: the UUID it minted, then the `-`
143/// and the sanitized basename beside it, or nothing when that basename was empty.
144fn is_stored_name(name: &str) -> bool {
145 let Some((uuid, rest)) = name.split_at_checked(36) else {
146 return false;
147 };
148 uuid::Uuid::try_parse(uuid).is_ok_and(|parsed| parsed.to_string() == uuid)
149 && (rest.is_empty() || (rest.len() > 1 && rest.starts_with('-')))
150}
151
152impl DirUploader {
153 /// Writes into `dir`, naming each file by a URL under `url_prefix` (`"/uploads"`).
154 pub fn new(url_prefix: impl Into<String>, dir: impl Into<PathBuf>) -> Self {
155 let url_prefix = url_prefix.into().trim_end_matches('/').to_string();
156 Self {
157 url_prefix,
158 dir: dir.into(),
159 pending: None,
160 }
161 }
162
163 /// Marks each file it stores pending until the panel's write that stores it commits, and
164 /// deletes a pending file once it is `age` old: the upload of a submission that never saved,
165 /// such as a refused form the user left. [`Panel::uploads_dir`](crate::Panel::uploads_dir)
166 /// sets 24 hours.
167 ///
168 /// A store sweeps at most once an hour. Only the panel's record forms keep what they store:
169 /// an app page that stores through this uploader and saves the path itself keeps it with
170 /// [`Uploader::keep`], or uses an uploader without this setting.
171 pub fn expire_pending(mut self, age: std::time::Duration) -> Self {
172 self.pending = Some(std::sync::Arc::new(pending::Pending::new(age)));
173 self
174 }
175
176 /// The file a stored URL names: one segment under the prefix, spelled as `store` spells it.
177 fn file_name(&self, path: &str) -> Option<String> {
178 let segment = path.strip_prefix(&self.url_prefix)?.strip_prefix('/')?;
179 let name = percent_decode_str(segment).decode_utf8().ok()?;
180 (!name.is_empty()
181 && sanitize_filename(&name) == name
182 && encode_path_segment(&name) == segment)
183 .then(|| name.into_owned())
184 }
185}
186
187impl Uploader for DirUploader {
188 async fn store(&self, _cx: &Cx, filename: &str, bytes: &[u8]) -> Result<String, String> {
189 let basename = sanitize_filename(filename);
190 let mut cut = basename.len().saturating_sub(MAX_STORED_BASENAME);
191 while !basename.is_char_boundary(cut) {
192 cut += 1;
193 }
194 let name = match &basename[cut..] {
195 "" => uuid::Uuid::new_v4().to_string(),
196 basename => format!("{}-{basename}", uuid::Uuid::new_v4()),
197 };
198 tokio::fs::create_dir_all(&self.dir)
199 .await
200 .map_err(|_| "the upload directory is not writable".to_string())?;
201 tokio::fs::write(self.dir.join(&name), bytes)
202 .await
203 .map_err(|_| "the upload could not be written".to_string())?;
204 if let Some(pending) = &self.pending {
205 pending.sweep_if_due(&self.dir);
206 pending
207 .mark(&self.dir, &name)
208 .await
209 .map_err(|_| "the upload could not be written".to_string())?;
210 }
211 Ok(format!(
212 "{}/{}",
213 self.url_prefix,
214 encode_path_segment(&name)
215 ))
216 }
217
218 /// Whether the directory holds the file a URL `store` returned names. The name `store` writes
219 /// is the check, since the directory keeps no index of what it wrote: a file whose name it
220 /// would not write is not held.
221 async fn holds(&self, _cx: &Cx, path: &str) -> bool {
222 let Some(name) = self.file_name(path) else {
223 return false;
224 };
225 if !is_stored_name(&name) {
226 return false;
227 }
228 tokio::fs::metadata(self.dir.join(name))
229 .await
230 .is_ok_and(|metadata| metadata.is_file())
231 }
232
233 /// Drops the pending mark of the file a URL `store` returned names.
234 async fn keep(&self, _cx: &Cx, path: &str) -> Result<(), String> {
235 match self.file_name(path).filter(|name| is_stored_name(name)) {
236 Some(name) => pending::keep(&self.dir, &name)
237 .await
238 .map_err(|error| error.to_string()),
239 None => Ok(()),
240 }
241 }
242
243 /// Removes the file a URL `store` returned names, and its pending mark; a file already gone
244 /// is no error.
245 async fn delete(&self, _cx: &Cx, path: &str) -> Result<(), String> {
246 let Some(name) = self.file_name(path).filter(|name| is_stored_name(name)) else {
247 return Ok(());
248 };
249 match tokio::fs::remove_file(self.dir.join(&name)).await {
250 Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
251 return Err(error.to_string());
252 }
253 _ => {}
254 }
255 pending::unmark(&self.dir, &name)
256 .await
257 .map_err(|error| error.to_string())
258 }
259}
260
261/// Strips a client filename to a safe basename capped at 255 bytes, without control or
262/// bidirectional-override characters, rejecting `.`, `..`, and Windows reserved names to empty:
263/// what a file field's [`Uploader`] receives, for a page that parses its own multipart body.
264///
265/// ```
266/// assert_eq!(tablo_core::sanitize_filename("../../etc/passwd"), "passwd");
267/// assert_eq!(
268/// tablo_core::sanitize_filename("C:\\fakepath\\cover.png"),
269/// "cover.png"
270/// );
271/// assert_eq!(tablo_core::sanitize_filename(".."), "");
272/// ```
273pub fn sanitize_filename(raw: &str) -> String {
274 let base = raw.rsplit(['/', '\\']).next().unwrap_or(raw).trim();
275 let clean: String = base
276 .chars()
277 .filter(|&c| !c.is_control() && !is_bidi_control(c))
278 .collect();
279 let trimmed = clean.trim();
280 if trimmed.is_empty() {
281 return String::new();
282 }
283 if trimmed == "." || trimmed == ".." || is_windows_reserved_name(trimmed) {
284 return String::new();
285 }
286 // Caps at 255 bytes, advancing the cut to a char boundary to avoid panicking.
287 if trimmed.len() > 255 {
288 let mut start = trimmed.len() - 255;
289 while !trimmed.is_char_boundary(start) {
290 start += 1;
291 }
292 trimmed[start..].to_string()
293 } else {
294 trimmed.to_string()
295 }
296}
297
298/// Whether `c` reorders the text around it, so `a\u{202e}gnp.exe` would read as `aexe.png`.
299fn is_bidi_control(c: char) -> bool {
300 matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
301}
302
303/// Reports whether a basename is a Windows reserved device name.
304fn is_windows_reserved_name(name: &str) -> bool {
305 let stem = match name.split_once('.') {
306 Some((stem, _)) => stem,
307 None => name,
308 };
309 let stem = stem.to_ascii_uppercase();
310 if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") {
311 return true;
312 }
313 let Some(n) = stem
314 .strip_prefix("COM")
315 .or_else(|| stem.strip_prefix("LPT"))
316 else {
317 return false;
318 };
319 n.parse::<u8>().is_ok_and(|n| (1..=9).contains(&n))
320}
321
322/// A submitted file part, staged only when an [`Uploader`] is installed.
323#[derive(Debug, Clone)]
324pub(crate) struct StagedUpload {
325 pub(crate) filename: String,
326 pub(crate) bytes: Vec<u8>,
327}
328
329/// The one uploader a panel was mounted with, in its `PanelState`.
330pub(crate) struct InstalledUploader(Box<dyn DynUploader + Send + Sync>);
331
332impl InstalledUploader {
333 pub(crate) fn new(uploader: impl Uploader) -> Self {
334 Self(Box::new(uploader))
335 }
336}
337
338/// Dyn-compatible view of [`Uploader`].
339pub(crate) trait DynUploader: Send + Sync {
340 fn store<'a>(
341 &'a self,
342 cx: &'a Cx,
343 filename: &'a str,
344 bytes: &'a [u8],
345 ) -> BoxFuture<'a, Result<String, String>>;
346 fn holds<'a>(&'a self, cx: &'a Cx, path: &'a str) -> BoxFuture<'a, bool>;
347 fn keep<'a>(&'a self, cx: &'a Cx, path: &'a str) -> BoxFuture<'a, Result<(), String>>;
348 fn delete<'a>(&'a self, cx: &'a Cx, path: &'a str) -> BoxFuture<'a, Result<(), String>>;
349}
350
351impl<U: Uploader> DynUploader for U {
352 fn store<'a>(
353 &'a self,
354 cx: &'a Cx,
355 filename: &'a str,
356 bytes: &'a [u8],
357 ) -> BoxFuture<'a, Result<String, String>> {
358 Box::pin(Uploader::store(self, cx, filename, bytes))
359 }
360
361 fn holds<'a>(&'a self, cx: &'a Cx, path: &'a str) -> BoxFuture<'a, bool> {
362 Box::pin(Uploader::holds(self, cx, path))
363 }
364
365 fn keep<'a>(&'a self, cx: &'a Cx, path: &'a str) -> BoxFuture<'a, Result<(), String>> {
366 Box::pin(Uploader::keep(self, cx, path))
367 }
368
369 fn delete<'a>(&'a self, cx: &'a Cx, path: &'a str) -> BoxFuture<'a, Result<(), String>> {
370 Box::pin(Uploader::delete(self, cx, path))
371 }
372}
373
374/// Whether `uploader`, a panel's installed one, still holds `path`; `false` without one.
375pub(crate) async fn holds(cx: &Cx, uploader: Option<&InstalledUploader>, path: &str) -> bool {
376 match uploader {
377 Some(uploader) => uploader.0.holds(cx, path).await,
378 None => false,
379 }
380}
381
382/// The paths `values` stores under the file field `name`: its one path, or each of its list's,
383/// trimmed and none blank.
384fn stored_paths<'a>(values: &'a FormValues, name: &str) -> Vec<&'a str> {
385 let paths: &[String] = match values.get(name) {
386 Some(FormValue::Text(path)) => std::slice::from_ref(path),
387 Some(FormValue::List(paths)) => paths,
388 _ => &[],
389 };
390 paths
391 .iter()
392 .map(|path| path.trim())
393 .filter(|path| !path.is_empty())
394 .collect()
395}
396
397/// Keeps, through `uploader`, each new path `schema`'s file fields store in `after` and did not in
398/// `before`, which a create has none of; only a path the uploader holds.
399///
400/// # Errors
401///
402/// The reason the uploader could not keep a path, for the write to fail on.
403pub(crate) async fn keep(
404 cx: &Cx,
405 uploader: Option<&InstalledUploader>,
406 schema: &Schema,
407 before: Option<&FormValues>,
408 after: &FormValues,
409) -> Result<(), String> {
410 let Some(InstalledUploader(uploader)) = uploader else {
411 return Ok(());
412 };
413 for field in schema.fields().filter(|field| field.is_file()) {
414 let stored = before.map(|before| stored_paths(before, field.name()));
415 for path in stored_paths(after, field.name()) {
416 if stored.as_ref().is_some_and(|stored| stored.contains(&path))
417 || !uploader.holds(cx, path).await
418 {
419 continue;
420 }
421 uploader.keep(cx, path).await?;
422 }
423 }
424 Ok(())
425}
426
427/// Deletes, through `uploader`, each file `schema`'s file fields stored in `before` and no longer
428/// store in `after`, or every one when `after` is `None`; only a path the uploader holds, and each
429/// path once.
430pub(crate) async fn discard(
431 cx: &Cx,
432 uploader: Option<&InstalledUploader>,
433 schema: &Schema,
434 before: &[FormValues],
435 after: Option<&FormValues>,
436) {
437 let Some(InstalledUploader(uploader)) = uploader else {
438 return;
439 };
440 let mut gone = HashSet::new();
441 for field in schema.fields().filter(|field| field.is_file()) {
442 let kept = after.map(|after| stored_paths(after, field.name()));
443 for values in before {
444 for path in stored_paths(values, field.name()) {
445 if !kept.as_ref().is_some_and(|kept| kept.contains(&path)) {
446 gone.insert(path.to_owned());
447 }
448 }
449 }
450 }
451 for path in gone {
452 if !uploader.holds(cx, &path).await {
453 continue;
454 }
455 if let Err(reason) = uploader.delete(cx, &path).await {
456 tracing::error!(path, reason, "an upload the write let go was not deleted");
457 }
458 }
459}
460
461/// Runs `uploader`, a panel's installed one, over this form's file parts, returning inline
462/// errors and the fields whose value is now the stored path. A file the field's extensions or
463/// size refuse is not stored; it, or a failed store, becomes an inline field error and drops the
464/// submitted value. A file list's value becomes the paths it stored, in the order the files
465/// posted, whether or not one failed. Call outside the write transaction.
466pub(crate) async fn store_uploads(
467 cx: &Cx,
468 uploader: Option<&InstalledUploader>,
469 schema: &Schema,
470 files: &HashMap<String, Vec<StagedUpload>>,
471 values: &mut FormValues,
472) -> (FieldErrors, HashSet<String>) {
473 let Some(InstalledUploader(uploader)) = uploader else {
474 return (FieldErrors::new(), HashSet::new());
475 };
476 let mut errors = FieldErrors::new();
477 let mut stored = HashSet::new();
478 // Declared uploads only: a file part the schema does not declare is not a
479 // field this form may write (the unknown-key allow-list answers for it).
480 for field in schema.fields() {
481 let Some(file) = field.as_file() else {
482 continue;
483 };
484 let name = field.name().to_string();
485 let label = field.label();
486 // A file list holds what it stores, never the names the read gathered.
487 if file.multiple {
488 values.remove(&name);
489 }
490 let staged = files.get(&name).map(Vec::as_slice).unwrap_or_default();
491 // A file field takes the last file its key posts; a list takes each.
492 let staged = match staged.split_last() {
493 Some((last, _)) if !file.multiple => std::slice::from_ref(last),
494 _ => staged,
495 };
496 if staged.is_empty() {
497 continue;
498 }
499 let mut paths = Vec::new();
500 for staged in staged {
501 // A file the field's rules refuse is never stored, nor one whose name sanitizes to
502 // nothing, as a Windows device name does.
503 let filename = sanitize_filename(&staged.filename);
504 let refusal = if filename.is_empty() {
505 Some(crate::text!(
506 "tablo-field-upload-name",
507 label = label.clone()
508 ))
509 } else {
510 file.refusal(&label, &filename, staged.bytes.len())
511 };
512 let stored_path = match refusal {
513 Some(refusal) => Err(refusal),
514 None => uploader
515 .store(cx, &staged.filename, &staged.bytes)
516 .await
517 .map_err(|reason| {
518 crate::text!(
519 "tablo-field-upload-failed",
520 label = label.clone(),
521 reason = reason
522 )
523 }),
524 };
525 match stored_path {
526 Ok(path) => paths.push(path),
527 Err(message) if !errors.contains_key(&name) => {
528 errors.add_field(name.clone(), message)
529 }
530 Err(_) => {}
531 }
532 }
533 if file.multiple {
534 values.insert(name, FormValue::List(paths));
535 } else if let Some(path) = paths.pop() {
536 values.insert(name.clone(), path);
537 stored.insert(name);
538 } else {
539 values.remove(&name);
540 }
541 }
542 (errors, stored)
543}
544
545#[cfg(test)]
546mod tests;