1use 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#[derive(Debug, Deserialize, laravel::validation::Validate)]
19#[validate(anyone)]
20struct UploadForm {
21 #[validate(required)]
22 files: Vec<UploadedFile>,
23}
24
25fn 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
43pub 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#[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
74fn 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#[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
97fn 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
106pub 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
133pub 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
184fn 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
192pub 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
211pub 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#[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
252const DIRECTORY_LIMIT: u64 = 64 * 1024 * 1024;
254
255const UNUSED_LIFETIME_SECONDS: u64 = 60 * 60;
257
258pub 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
326pub 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#[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#[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#[must_use]
388pub fn temporary_path(config: &LivewireConfig) -> PathBuf {
389 Path::new("storage/app/private").join(temporary_directory(config))
390}
391
392pub 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 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
441fn 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
455fn 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
476pub 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
484pub 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 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 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#[derive(Debug, Deserialize)]
567struct UploadQuery {
568 component: Option<String>,
569 expires: Option<u64>,
570 signature: Option<String>,
571}
572
573fn empty(status: StatusCode) -> Response {
575 Response::new("").with_status(status)
576}
577
578#[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 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 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}