Skip to main content

livewire/
uploads.rs

1//! Local file uploads: a signed URL, a temporary directory, and the calls the browser makes.
2//!
3//! See `docs/uploads.md` for the contract this implements.
4
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use laravel::http::{Request, Response, StatusCode, UploadedFile};
9use serde::Deserialize;
10use serde_json::{Map, Value};
11use sha2::{Digest, Sha256};
12
13use crate::component::{Call, Component, ComponentContext};
14use crate::config::LivewireConfig;
15use crate::error::LivewireError;
16
17/// The multipart body the upload endpoint reads: the client repeats `files[]`.
18#[derive(Debug, Deserialize, laravel::validation::Validate)]
19#[validate(anyone)]
20struct UploadForm {
21    #[validate(required)]
22    files: Vec<UploadedFile>,
23}
24
25/// The signature an upload URL carries: the component, the expiry, and the application key.
26fn sign(key: &[u8], id: &str, expires: u64) -> String {
27    let mut hasher = Sha256::new();
28    hasher.update(key);
29    hasher.update(b"|");
30    hasher.update(id.as_bytes());
31    hasher.update(b"|");
32    hasher.update(expires.to_string().as_bytes());
33
34    let mut text = String::with_capacity(64);
35    for byte in hasher.finalize() {
36        use std::fmt::Write as _;
37        let _ = write!(text, "{byte:02x}");
38    }
39
40    text
41}
42
43/// The upload URL for `id`, valid for the configured window.
44///
45/// # Errors
46///
47/// Fails when the application key or the clock is unavailable.
48pub fn signed_url(config: &LivewireConfig, id: &str) -> Result<String, LivewireError> {
49    let key = crate::render::app_key()?;
50    let key_text = crate::engine::app_key().ok_or_else(|| LivewireError::Database {
51        message: "the application key is unavailable".to_owned(),
52    })?;
53    let expires = now().ok_or_else(|| LivewireError::Database {
54        message: "the clock is unavailable".to_owned(),
55    })? + config.temporary_file_upload.max_upload_time * 60;
56
57    Ok(format!(
58        "{}?component={id}&expires={expires}&signature={}",
59        crate::frontend::Endpoints::new(&key_text).upload(),
60        sign(&key, id, expires)
61    ))
62}
63
64/// Whether an upload URL was made for `id` and has not expired.
65#[must_use]
66pub fn signature_is_valid(id: &str, expires: u64, signature: &str) -> bool {
67    if expires < now().unwrap_or(u64::MAX) {
68        return false;
69    }
70
71    crate::render::app_key().is_ok_and(|key| sign(&key, id, expires) == signature)
72}
73
74/// The current Unix time, or `None` when the clock is unreadable.
75fn now() -> Option<u64> {
76    std::time::SystemTime::now()
77        .duration_since(std::time::UNIX_EPOCH)
78        .ok()
79        .map(|duration| duration.as_secs())
80}
81
82/// A temporary file name that cannot leave the directory.
83#[must_use]
84pub fn temporary_name(client: &str) -> String {
85    let extension = Path::new(client)
86        .extension()
87        .and_then(|extension| extension.to_str())
88        .filter(|extension| {
89            extension.len() <= 8 && extension.chars().all(|character| character.is_ascii_alphanumeric())
90        })
91        .map(|extension| format!(".{extension}"))
92        .unwrap_or_default();
93
94    format!("{}{extension}", laravel::str::random(20))
95}
96
97/// The dispatch entry the client listens for, which the upload manager handles.
98fn dispatch(name: &str, params: Value) -> Value {
99    Value::Object(Map::from_iter([
100        ("name".to_owned(), Value::from(name)),
101        ("params".to_owned(), params),
102        ("self".to_owned(), Value::Bool(true)),
103    ]))
104}
105
106/// Handles `_startUpload`, which answers with the URL the browser posts to.
107///
108/// # Errors
109///
110/// Fails when the application key is unavailable.
111pub fn start_upload(
112    context: &mut ComponentContext,
113    config: &LivewireConfig,
114    call: &Call,
115) -> Result<Option<Value>, LivewireError> {
116    let name: String = call.params.arg("name", 0)?;
117    let url = signed_url(config, &context.id)?;
118
119    context.push_effect(
120        "dispatches",
121        dispatch(
122            "upload:generatedSignedUrl",
123            Value::Object(Map::from_iter([
124                ("name".to_owned(), Value::from(name)),
125                ("url".to_owned(), Value::from(url)),
126            ])),
127        ),
128    );
129
130    Ok(None)
131}
132
133/// Handles `_finishUpload`, which writes the temporary names into the component's field.
134///
135/// # Errors
136///
137/// Fails when the field is unknown or the value does not fit its type.
138pub fn finish_upload(
139    component: &mut dyn Component,
140    context: &mut ComponentContext,
141    call: &Call,
142) -> Result<Option<Value>, LivewireError> {
143    let name: String = call.params.arg("name", 0)?;
144    let paths: Vec<String> = call.params.arg("tmpFilenames", 1)?;
145    let multiple: bool = call.params.optional("multiple", 2)?.unwrap_or(false);
146    let append: bool = call.params.optional("append", 3)?.unwrap_or(false);
147
148    let value = if multiple || append {
149        Value::Array(paths.iter().map(|path| Value::from(path.clone())).collect())
150    } else {
151        paths
152            .first()
153            .map(|path| Value::from(path.clone()))
154            .unwrap_or(Value::Null)
155    };
156
157    let root = name.split('.').next().unwrap_or(&name);
158    let replaced = if let Value::Array(mut existing) = component_field(component, root) {
159        existing.extend(value.as_array().cloned().unwrap_or_default());
160        Value::Array(existing)
161    } else {
162        value
163    };
164
165    component.set_field(&name, replaced)?;
166
167    context.push_effect(
168        "dispatches",
169        dispatch(
170            "upload:finished",
171            Value::Object(Map::from_iter([
172                ("name".to_owned(), Value::from(name)),
173                (
174                    "tmpFilenames".to_owned(),
175                    Value::Array(paths.iter().map(|path| Value::from(path.clone())).collect()),
176                ),
177            ])),
178        ),
179    );
180
181    Ok(None)
182}
183
184/// The field's current value, as it crosses the wire.
185fn component_field(component: &dyn Component, root: &str) -> Value {
186    let mut data = Map::new();
187    component.dehydrate_fields(&mut data);
188
189    data.get(root).cloned().unwrap_or(Value::Null)
190}
191
192/// Handles `_uploadErrored`, which tells the browser the upload failed.
193///
194/// # Errors
195///
196/// Fails when the call carries no field name.
197pub fn upload_errored(context: &mut ComponentContext, call: &Call) -> Result<Option<Value>, LivewireError> {
198    let name: String = call.params.arg("name", 0)?;
199
200    context.push_effect(
201        "dispatches",
202        dispatch(
203            "upload:errored",
204            Value::Object(Map::from_iter([("name".to_owned(), Value::from(name))])),
205        ),
206    );
207
208    Ok(None)
209}
210
211/// Handles `_removeUpload`, which deletes a temporary file and tells the browser.
212///
213/// # Errors
214///
215/// Fails when the call carries no field name or file name.
216pub async fn remove_upload(
217    context: &mut ComponentContext,
218    config: &LivewireConfig,
219    call: &Call,
220) -> Result<Option<Value>, LivewireError> {
221    let name: String = call.params.arg("name", 0)?;
222    let filename: String = call.params.arg("tmpFilename", 1)?;
223
224    if filename_is_safe(&filename) {
225        let _ = tokio::fs::remove_file(temporary_path(config).join(&filename)).await;
226    }
227
228    context.push_effect(
229        "dispatches",
230        dispatch(
231            "upload:removed",
232            Value::Object(Map::from_iter([
233                ("name".to_owned(), Value::from(name)),
234                ("tmpFilename".to_owned(), Value::from(filename)),
235            ])),
236        ),
237    );
238
239    Ok(None)
240}
241
242/// Whether a name the browser sent can name a file in the temporary directory.
243#[must_use]
244pub fn filename_is_safe(filename: &str) -> bool {
245    !filename.is_empty()
246        && !filename.contains("..")
247        && !filename.contains('/')
248        && !filename.contains('\\')
249        && filename != "."
250}
251
252/// The most the temporary directory may hold, in bytes.
253const DIRECTORY_LIMIT: u64 = 64 * 1024 * 1024;
254
255/// How long a temporary file may sit unused before the next upload deletes it.
256const UNUSED_LIFETIME_SECONDS: u64 = 60 * 60;
257
258/// Deletes what an abandoned upload left, then the oldest files until the directory fits `max_bytes`.
259///
260/// The upload endpoint is public, so it cannot rely on a scheduled cleanup alone: a burst of
261/// uploads with no visitor would otherwise fill the disk between runs. Deletion is oldest first,
262/// which keeps the newest files — the ones a browser is still working with — longest.
263pub async fn trim(directory: &Path, max_bytes: u64, unused: std::time::Duration) -> std::io::Result<u64> {
264    let mut entries = match tokio::fs::read_dir(directory).await {
265        Ok(entries) => entries,
266        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
267        Err(error) => return Err(error),
268    };
269
270    struct Candidate {
271        path: std::path::PathBuf,
272        bytes: u64,
273        modified: std::time::SystemTime,
274    }
275
276    let mut files: Vec<Candidate> = Vec::new();
277    let mut total = 0u64;
278    let mut removed = 0u64;
279
280    while let Some(entry) = entries.next_entry().await? {
281        let Ok(metadata) = entry.metadata().await else {
282            continue;
283        };
284
285        if !metadata.is_file() {
286            continue;
287        }
288
289        let modified = metadata.modified().unwrap_or(std::time::SystemTime::UNIX_EPOCH);
290        let abandoned = modified.elapsed().is_ok_and(|age| age > unused);
291
292        if abandoned {
293            if tokio::fs::remove_file(entry.path()).await.is_ok() {
294                removed += 1;
295            }
296
297            continue;
298        }
299
300        total += metadata.len();
301        files.push(Candidate {
302            path: entry.path(),
303            bytes: metadata.len(),
304            modified,
305        });
306    }
307
308    if total > max_bytes {
309        files.sort_by_key(|file| file.modified);
310
311        for file in files {
312            if total <= max_bytes {
313                break;
314            }
315
316            if tokio::fs::remove_file(&file.path).await.is_ok() {
317                total = total.saturating_sub(file.bytes);
318                removed += 1;
319            }
320        }
321    }
322
323    Ok(removed)
324}
325
326/// Deletes the temporary uploads older than `age`, and reports how many it deleted.
327///
328/// A scheduled task runs this: an upload the browser never finished has no owner after its signed
329/// URL expires, so the directory would otherwise keep it forever. A missing directory is not an
330/// error; neither is a file that vanished while it was being read.
331pub async fn prune(directory: &Path, age: std::time::Duration) -> std::io::Result<usize> {
332    let mut entries = match tokio::fs::read_dir(directory).await {
333        Ok(entries) => entries,
334        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
335        Err(error) => return Err(error),
336    };
337
338    let mut deleted = 0;
339
340    while let Some(entry) = entries.next_entry().await? {
341        let Ok(metadata) = entry.metadata().await else {
342            continue;
343        };
344
345        if !metadata.is_file() {
346            continue;
347        }
348
349        let old_enough = metadata
350            .modified()
351            .ok()
352            .and_then(|modified| modified.elapsed().ok())
353            .is_some_and(|elapsed| elapsed >= age);
354
355        if old_enough && tokio::fs::remove_file(entry.path()).await.is_ok() {
356            deleted += 1;
357        }
358    }
359
360    Ok(deleted)
361}
362
363/// The largest file the configured rules allow, in bytes, when they declare `max:<kilobytes>`.
364///
365/// The rules are the framework's rule strings; this endpoint reads the size rule out of them,
366/// because the typed form's own rules are compile-time and these are configuration.
367#[must_use]
368pub fn max_bytes(rules: &[String]) -> Option<u64> {
369    rules.iter().find_map(|rule| {
370        let kilobytes: u64 = rule.strip_prefix("max:")?.trim().parse().ok()?;
371
372        Some(kilobytes.saturating_mul(1024))
373    })
374}
375
376/// The directory the temporary uploads live in, relative to the application's private disk.
377#[must_use]
378pub fn temporary_directory(config: &LivewireConfig) -> String {
379    config
380        .temporary_file_upload
381        .directory
382        .clone()
383        .unwrap_or_else(|| "livewire-tmp".to_owned())
384}
385
386/// Where that directory is on this host, which is how a file is deleted and how a preview is read.
387#[must_use]
388pub fn temporary_path(config: &LivewireConfig) -> PathBuf {
389    Path::new("storage/app/private").join(temporary_directory(config))
390}
391
392/// The preview endpoint: serves a temporary file whose kind may be previewed.
393pub async fn preview(
394    registry: laravel::container::Inject<Arc<crate::registry::ComponentRegistry>>,
395    laravel::routing::Params(filename): laravel::routing::Params<String>,
396) -> Response {
397    if !filename_is_safe(&filename) {
398        return empty(StatusCode::FORBIDDEN);
399    }
400
401    let config = registry.config();
402    let extension = Path::new(&filename)
403        .extension()
404        .and_then(|extension| extension.to_str())
405        .unwrap_or_default()
406        .to_ascii_lowercase();
407
408    if !config
409        .temporary_file_upload
410        .preview_mimes
411        .iter()
412        .any(|mime| mime.eq_ignore_ascii_case(&extension))
413    {
414        return empty(StatusCode::FORBIDDEN);
415    }
416
417    let Ok(bytes) = tokio::fs::read(temporary_path(config).join(&filename)).await else {
418        return empty(StatusCode::NOT_FOUND);
419    };
420
421    let mut response = Response::new(bytes);
422    if let Ok(value) = content_type(&extension).parse() {
423        response.headers_mut().insert("content-type", value);
424    }
425
426    // A temporary file is a visitor's bytes: never let the browser guess its type, never let it
427    // run anything (an SVG may carry script), and name it so a download keeps the name.
428    if let Ok(value) = "nosniff".parse() {
429        response.headers_mut().insert("x-content-type-options", value);
430    }
431    if let Ok(value) = "default-src 'none'; sandbox".parse() {
432        response.headers_mut().insert("content-security-policy", value);
433    }
434    if let Ok(value) = format!("inline; filename=\"{}\"", header_filename(&filename)).parse() {
435        response.headers_mut().insert("content-disposition", value);
436    }
437
438    response
439}
440
441/// A name safe to put in a response header: letters, digits, dot, dash, underscore.
442fn header_filename(filename: &str) -> String {
443    filename
444        .chars()
445        .map(|character| {
446            if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') {
447                character
448            } else {
449                '_'
450            }
451        })
452        .collect()
453}
454
455/// The content type a previewed extension is served with.
456fn content_type(extension: &str) -> &'static str {
457    match extension {
458        "png" => "image/png",
459        "gif" => "image/gif",
460        "bmp" => "image/bmp",
461        "svg" => "image/svg+xml",
462        "jpg" | "jpeg" => "image/jpeg",
463        "webp" => "image/webp",
464        "wav" => "audio/wav",
465        "mp3" | "mpga" => "audio/mpeg",
466        "m4a" => "audio/mp4",
467        "mp4" => "video/mp4",
468        "mov" => "video/quicktime",
469        "avi" => "video/x-msvideo",
470        "wmv" => "video/x-ms-wmv",
471        "pdf" => "application/pdf",
472        _ => "application/octet-stream",
473    }
474}
475
476/// The upload endpoint: stores the files a signed URL was made for.
477pub async fn store(
478    registry: laravel::container::Inject<Arc<crate::registry::ComponentRegistry>>,
479    request: Request,
480) -> Response {
481    store_with(&request, registry.config()).await
482}
483
484/// Stores the files for `config`, which the route and the tests both use.
485pub async fn store_with(request: &Request, config: &LivewireConfig) -> Response {
486    let query: UploadQuery = match serde_urlencoded::from_str(request.uri().query().unwrap_or_default()) {
487        Ok(query) => query,
488        Err(_) => return empty(StatusCode::UNAUTHORIZED),
489    };
490
491    let (Some(expires), Some(signature)) = (query.expires, query.signature) else {
492        return empty(StatusCode::UNAUTHORIZED);
493    };
494
495    // The URL names the component it was made for, and the client posts to that URL as it is.
496    let Some(component) = query.component else {
497        return empty(StatusCode::UNAUTHORIZED);
498    };
499
500    if !signature_is_valid(&component, expires, &signature) {
501        return empty(StatusCode::UNAUTHORIZED);
502    }
503
504    let form: UploadForm = match request.validate().await {
505        Ok(form) => form,
506        Err(error) => {
507            return LivewireError::MalformedPayload(error.to_string()).into_response(false);
508        }
509    };
510
511    let directory = temporary_directory(config);
512    if let Err(error) = tokio::fs::create_dir_all(&directory).await {
513        return LivewireError::Database {
514            message: error.to_string(),
515        }
516        .into_response(false);
517    }
518
519    if let Some(max) = max_bytes(&config.temporary_file_upload.rules)
520        && form.files.iter().any(|file| file.size() > max)
521    {
522        let body = Value::Object(Map::from_iter([(
523            "message".to_owned(),
524            Value::from(format!("The file may not be larger than {} kilobytes.", max / 1024)),
525        )]));
526        let mut response = Response::new(body.to_string()).with_status(StatusCode::UNPROCESSABLE_ENTITY);
527        if let Ok(value) = "application/json".parse() {
528            response.headers_mut().insert("content-type", value);
529        }
530
531        return response;
532    }
533
534    let mut paths = Vec::with_capacity(form.files.len());
535    for file in &form.files {
536        let name = temporary_name(file.client_name());
537        if let Err(error) = file.store_as(directory.clone(), name.clone()).await {
538            return LivewireError::Database {
539                message: error.to_string(),
540            }
541            .into_response(false);
542        }
543
544        paths.push(Value::from(format!("livewire-file:{name}")));
545    }
546
547    // The endpoint is public: each write also bounds the directory, deleting what an abandoned
548    // upload left behind and the oldest files once the cap is reached.
549    let _ = trim(
550        Path::new(&directory),
551        DIRECTORY_LIMIT,
552        std::time::Duration::from_secs(UNUSED_LIFETIME_SECONDS),
553    )
554    .await;
555
556    let body = Value::Object(Map::from_iter([("paths".to_owned(), Value::Array(paths))]));
557    let mut response = Response::new(body.to_string());
558    if let Ok(value) = "application/json".parse() {
559        response.headers_mut().insert("content-type", value);
560    }
561
562    response
563}
564
565/// The query an upload URL carries.
566#[derive(Debug, Deserialize)]
567struct UploadQuery {
568    component: Option<String>,
569    expires: Option<u64>,
570    signature: Option<String>,
571}
572
573/// An empty response with `status`, which the endpoint answers with when a guard fails.
574fn empty(status: StatusCode) -> Response {
575    Response::new("").with_status(status)
576}
577
578/// Whether a call is one of the upload calls, which the dispatcher handles before any action.
579#[must_use]
580pub fn is_upload_call(method: &str) -> bool {
581    matches!(
582        method,
583        "_startUpload" | "_finishUpload" | "_uploadErrored" | "_removeUpload"
584    )
585}
586
587#[cfg(test)]
588mod tests {
589    use super::{filename_is_safe, max_bytes, temporary_name};
590
591    #[test]
592    fn the_size_rule_is_read_from_the_configured_rules() {
593        let rules = ["required".to_owned(), "file".to_owned(), "max:12288".to_owned()];
594
595        assert_eq!(max_bytes(&rules), Some(12_288 * 1024));
596        assert_eq!(max_bytes(&[]), None, "no rule means no limit");
597        assert_eq!(
598            max_bytes(&["max:oops".to_owned()]),
599            None,
600            "an unreadable rule does not guess"
601        );
602    }
603
604    #[tokio::test]
605    async fn trim_keeps_the_newest_files_and_deletes_the_rest() {
606        let directory = std::env::temp_dir().join(format!("livewire-trim-{}", laravel::str::random(8)));
607        tokio::fs::create_dir_all(&directory).await.expect("a directory");
608
609        for name in ["a", "b", "c"] {
610            tokio::fs::write(directory.join(name), [0u8; 10]).await.expect("a file");
611            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
612        }
613
614        // Ten bytes each, a cap of twenty-five: the oldest goes.
615        assert_eq!(
616            super::trim(&directory, 25, std::time::Duration::from_secs(3_600))
617                .await
618                .expect("a trim"),
619            1
620        );
621        assert!(!directory.join("a").exists(), "the oldest file went");
622        assert!(
623            directory.join("b").exists() && directory.join("c").exists(),
624            "the newest stay"
625        );
626
627        // Nothing is recent enough when the lifetime is zero.
628        assert_eq!(
629            super::trim(&directory, 1_024, std::time::Duration::ZERO)
630                .await
631                .expect("a trim"),
632            2
633        );
634        assert!(
635            tokio::fs::read_dir(&directory)
636                .await
637                .expect("entries")
638                .next_entry()
639                .await
640                .expect("an entry")
641                .is_none()
642        );
643
644        tokio::fs::remove_dir(&directory).await.expect("cleanup");
645    }
646
647    #[test]
648    fn a_temporary_name_cannot_leave_its_directory() {
649        let name = temporary_name("../../etc/passwd");
650
651        assert!(filename_is_safe(&name), "{name}");
652        assert!(!name.contains('/'), "{name}");
653        assert!(!name.contains(".."), "{name}");
654        assert_eq!(name.len(), 20, "a name without an extension keeps none: {name}");
655
656        let photo = temporary_name("holiday.jpg");
657        assert!(photo.ends_with(".jpg"), "{photo}");
658        assert_eq!(photo.len(), 24, "twenty random characters and the extension: {photo}");
659    }
660
661    #[test]
662    fn a_name_the_browser_sends_is_checked() {
663        assert!(filename_is_safe("abc.txt"));
664        assert!(!filename_is_safe(""));
665        assert!(!filename_is_safe(".."));
666        assert!(!filename_is_safe("../x"));
667        assert!(!filename_is_safe("a/b"));
668        assert!(!filename_is_safe("a\\b"));
669    }
670}
671
672#[cfg(test)]
673mod prune_tests {
674    use std::time::Duration;
675
676    use super::prune;
677
678    async fn count_entries(directory: &std::path::Path) -> usize {
679        let mut entries = tokio::fs::read_dir(directory).await.expect("the directory");
680        let mut count = 0;
681
682        while entries.next_entry().await.expect("an entry").is_some() {
683            count += 1;
684        }
685
686        count
687    }
688
689    #[tokio::test]
690    async fn prune_deletes_what_is_old_enough_and_keeps_the_rest() {
691        let directory = std::env::temp_dir().join(format!("livewire-prune-{}", laravel::str::random(8)));
692        tokio::fs::create_dir_all(&directory)
693            .await
694            .expect("a directory to prune");
695        tokio::fs::write(directory.join("one.txt"), b"one")
696            .await
697            .expect("a file");
698        tokio::fs::write(directory.join("two.txt"), b"two")
699            .await
700            .expect("another file");
701
702        assert_eq!(
703            prune(&directory, Duration::from_secs(3_600)).await.expect("a prune"),
704            0,
705            "fresh files stay"
706        );
707        assert_eq!(count_entries(&directory).await, 2);
708
709        assert_eq!(
710            prune(&directory, Duration::ZERO).await.expect("a prune"),
711            2,
712            "and old enough means old enough"
713        );
714        assert_eq!(count_entries(&directory).await, 0);
715
716        tokio::fs::remove_dir(&directory).await.expect("cleanup");
717
718        assert_eq!(
719            prune(&directory, Duration::ZERO)
720                .await
721                .expect("a missing directory is not an error"),
722            0
723        );
724    }
725}