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 if config.temporary_file_upload.cleanup {
551 let _ = trim(
552 Path::new(&directory),
553 DIRECTORY_LIMIT,
554 std::time::Duration::from_secs(UNUSED_LIFETIME_SECONDS),
555 )
556 .await;
557 }
558
559 let body = Value::Object(Map::from_iter([("paths".to_owned(), Value::Array(paths))]));
560 let mut response = Response::new(body.to_string());
561 if let Ok(value) = "application/json".parse() {
562 response.headers_mut().insert("content-type", value);
563 }
564
565 response
566}
567
568#[derive(Debug, Deserialize)]
570struct UploadQuery {
571 component: Option<String>,
572 expires: Option<u64>,
573 signature: Option<String>,
574}
575
576fn empty(status: StatusCode) -> Response {
578 Response::new("").with_status(status)
579}
580
581#[must_use]
583pub fn is_upload_call(method: &str) -> bool {
584 matches!(
585 method,
586 "_startUpload" | "_finishUpload" | "_uploadErrored" | "_removeUpload"
587 )
588}
589
590#[cfg(test)]
591mod tests {
592 use super::{filename_is_safe, max_bytes, temporary_name};
593
594 #[test]
595 fn the_size_rule_is_read_from_the_configured_rules() {
596 let rules = ["required".to_owned(), "file".to_owned(), "max:12288".to_owned()];
597
598 assert_eq!(max_bytes(&rules), Some(12_288 * 1024));
599 assert_eq!(max_bytes(&[]), None, "no rule means no limit");
600 assert_eq!(
601 max_bytes(&["max:oops".to_owned()]),
602 None,
603 "an unreadable rule does not guess"
604 );
605 }
606
607 #[tokio::test]
608 async fn trim_keeps_the_newest_files_and_deletes_the_rest() {
609 let directory = std::env::temp_dir().join(format!("livewire-trim-{}", laravel::str::random(8)));
610 tokio::fs::create_dir_all(&directory).await.expect("a directory");
611
612 for name in ["a", "b", "c"] {
613 tokio::fs::write(directory.join(name), [0u8; 10]).await.expect("a file");
614 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
615 }
616
617 assert_eq!(
619 super::trim(&directory, 25, std::time::Duration::from_secs(3_600))
620 .await
621 .expect("a trim"),
622 1
623 );
624 assert!(!directory.join("a").exists(), "the oldest file went");
625 assert!(
626 directory.join("b").exists() && directory.join("c").exists(),
627 "the newest stay"
628 );
629
630 assert_eq!(
632 super::trim(&directory, 1_024, std::time::Duration::ZERO)
633 .await
634 .expect("a trim"),
635 2
636 );
637 assert!(
638 tokio::fs::read_dir(&directory)
639 .await
640 .expect("entries")
641 .next_entry()
642 .await
643 .expect("an entry")
644 .is_none()
645 );
646
647 tokio::fs::remove_dir(&directory).await.expect("cleanup");
648 }
649
650 #[test]
651 fn a_temporary_name_cannot_leave_its_directory() {
652 let name = temporary_name("../../etc/passwd");
653
654 assert!(filename_is_safe(&name), "{name}");
655 assert!(!name.contains('/'), "{name}");
656 assert!(!name.contains(".."), "{name}");
657 assert_eq!(name.len(), 20, "a name without an extension keeps none: {name}");
658
659 let photo = temporary_name("holiday.jpg");
660 assert!(photo.ends_with(".jpg"), "{photo}");
661 assert_eq!(photo.len(), 24, "twenty random characters and the extension: {photo}");
662 }
663
664 #[test]
665 fn a_name_the_browser_sends_is_checked() {
666 assert!(filename_is_safe("abc.txt"));
667 assert!(!filename_is_safe(""));
668 assert!(!filename_is_safe(".."));
669 assert!(!filename_is_safe("../x"));
670 assert!(!filename_is_safe("a/b"));
671 assert!(!filename_is_safe("a\\b"));
672 }
673}
674
675#[cfg(test)]
676mod prune_tests {
677 use std::time::Duration;
678
679 use super::prune;
680
681 async fn count_entries(directory: &std::path::Path) -> usize {
682 let mut entries = tokio::fs::read_dir(directory).await.expect("the directory");
683 let mut count = 0;
684
685 while entries.next_entry().await.expect("an entry").is_some() {
686 count += 1;
687 }
688
689 count
690 }
691
692 #[tokio::test]
693 async fn prune_deletes_what_is_old_enough_and_keeps_the_rest() {
694 let directory = std::env::temp_dir().join(format!("livewire-prune-{}", laravel::str::random(8)));
695 tokio::fs::create_dir_all(&directory)
696 .await
697 .expect("a directory to prune");
698 tokio::fs::write(directory.join("one.txt"), b"one")
699 .await
700 .expect("a file");
701 tokio::fs::write(directory.join("two.txt"), b"two")
702 .await
703 .expect("another file");
704
705 assert_eq!(
706 prune(&directory, Duration::from_secs(3_600)).await.expect("a prune"),
707 0,
708 "fresh files stay"
709 );
710 assert_eq!(count_entries(&directory).await, 2);
711
712 assert_eq!(
713 prune(&directory, Duration::ZERO).await.expect("a prune"),
714 2,
715 "and old enough means old enough"
716 );
717 assert_eq!(count_entries(&directory).await, 0);
718
719 tokio::fs::remove_dir(&directory).await.expect("cleanup");
720
721 assert_eq!(
722 prune(&directory, Duration::ZERO)
723 .await
724 .expect("a missing directory is not an error"),
725 0
726 );
727 }
728}