use std::path::{Path, PathBuf};
use std::sync::Arc;
use laravel::http::{Request, Response, StatusCode, UploadedFile};
use serde::Deserialize;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use crate::component::{Call, Component, ComponentContext};
use crate::config::LivewireConfig;
use crate::error::LivewireError;
#[derive(Debug, Deserialize, laravel::validation::Validate)]
#[validate(anyone)]
struct UploadForm {
#[validate(required)]
files: Vec<UploadedFile>,
}
fn sign(key: &[u8], id: &str, expires: u64) -> String {
let mut hasher = Sha256::new();
hasher.update(key);
hasher.update(b"|");
hasher.update(id.as_bytes());
hasher.update(b"|");
hasher.update(expires.to_string().as_bytes());
let mut text = String::with_capacity(64);
for byte in hasher.finalize() {
use std::fmt::Write as _;
let _ = write!(text, "{byte:02x}");
}
text
}
pub fn signed_url(config: &LivewireConfig, id: &str) -> Result<String, LivewireError> {
let key = crate::render::app_key()?;
let key_text = crate::engine::app_key().ok_or_else(|| LivewireError::Database {
message: "the application key is unavailable".to_owned(),
})?;
let expires = now().ok_or_else(|| LivewireError::Database {
message: "the clock is unavailable".to_owned(),
})? + config.temporary_file_upload.max_upload_time * 60;
Ok(format!(
"{}?component={id}&expires={expires}&signature={}",
crate::frontend::Endpoints::new(&key_text).upload(),
sign(&key, id, expires)
))
}
#[must_use]
pub fn signature_is_valid(id: &str, expires: u64, signature: &str) -> bool {
if expires < now().unwrap_or(u64::MAX) {
return false;
}
crate::render::app_key().is_ok_and(|key| sign(&key, id, expires) == signature)
}
fn now() -> Option<u64> {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
}
#[must_use]
pub fn temporary_name(client: &str) -> String {
let extension = Path::new(client)
.extension()
.and_then(|extension| extension.to_str())
.filter(|extension| {
extension.len() <= 8 && extension.chars().all(|character| character.is_ascii_alphanumeric())
})
.map(|extension| format!(".{extension}"))
.unwrap_or_default();
format!("{}{extension}", laravel::str::random(20))
}
fn dispatch(name: &str, params: Value) -> Value {
Value::Object(Map::from_iter([
("name".to_owned(), Value::from(name)),
("params".to_owned(), params),
("self".to_owned(), Value::Bool(true)),
]))
}
pub fn start_upload(
context: &mut ComponentContext,
config: &LivewireConfig,
call: &Call,
) -> Result<Option<Value>, LivewireError> {
let name: String = call.params.arg("name", 0)?;
let url = signed_url(config, &context.id)?;
context.push_effect(
"dispatches",
dispatch(
"upload:generatedSignedUrl",
Value::Object(Map::from_iter([
("name".to_owned(), Value::from(name)),
("url".to_owned(), Value::from(url)),
])),
),
);
Ok(None)
}
pub fn finish_upload(
component: &mut dyn Component,
context: &mut ComponentContext,
call: &Call,
) -> Result<Option<Value>, LivewireError> {
let name: String = call.params.arg("name", 0)?;
let paths: Vec<String> = call.params.arg("tmpFilenames", 1)?;
let multiple: bool = call.params.optional("multiple", 2)?.unwrap_or(false);
let append: bool = call.params.optional("append", 3)?.unwrap_or(false);
let value = if multiple || append {
Value::Array(paths.iter().map(|path| Value::from(path.clone())).collect())
} else {
paths
.first()
.map(|path| Value::from(path.clone()))
.unwrap_or(Value::Null)
};
let root = name.split('.').next().unwrap_or(&name);
let replaced = if let Value::Array(mut existing) = component_field(component, root) {
existing.extend(value.as_array().cloned().unwrap_or_default());
Value::Array(existing)
} else {
value
};
component.set_field(&name, replaced)?;
context.push_effect(
"dispatches",
dispatch(
"upload:finished",
Value::Object(Map::from_iter([
("name".to_owned(), Value::from(name)),
(
"tmpFilenames".to_owned(),
Value::Array(paths.iter().map(|path| Value::from(path.clone())).collect()),
),
])),
),
);
Ok(None)
}
fn component_field(component: &dyn Component, root: &str) -> Value {
let mut data = Map::new();
component.dehydrate_fields(&mut data);
data.get(root).cloned().unwrap_or(Value::Null)
}
pub fn upload_errored(context: &mut ComponentContext, call: &Call) -> Result<Option<Value>, LivewireError> {
let name: String = call.params.arg("name", 0)?;
context.push_effect(
"dispatches",
dispatch(
"upload:errored",
Value::Object(Map::from_iter([("name".to_owned(), Value::from(name))])),
),
);
Ok(None)
}
pub async fn remove_upload(
context: &mut ComponentContext,
config: &LivewireConfig,
call: &Call,
) -> Result<Option<Value>, LivewireError> {
let name: String = call.params.arg("name", 0)?;
let filename: String = call.params.arg("tmpFilename", 1)?;
if filename_is_safe(&filename) {
let _ = tokio::fs::remove_file(temporary_path(config).join(&filename)).await;
}
context.push_effect(
"dispatches",
dispatch(
"upload:removed",
Value::Object(Map::from_iter([
("name".to_owned(), Value::from(name)),
("tmpFilename".to_owned(), Value::from(filename)),
])),
),
);
Ok(None)
}
#[must_use]
pub fn filename_is_safe(filename: &str) -> bool {
!filename.is_empty()
&& !filename.contains("..")
&& !filename.contains('/')
&& !filename.contains('\\')
&& filename != "."
}
const DIRECTORY_LIMIT: u64 = 64 * 1024 * 1024;
const UNUSED_LIFETIME_SECONDS: u64 = 60 * 60;
pub async fn trim(directory: &Path, max_bytes: u64, unused: std::time::Duration) -> std::io::Result<u64> {
let mut entries = match tokio::fs::read_dir(directory).await {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
Err(error) => return Err(error),
};
struct Candidate {
path: std::path::PathBuf,
bytes: u64,
modified: std::time::SystemTime,
}
let mut files: Vec<Candidate> = Vec::new();
let mut total = 0u64;
let mut removed = 0u64;
while let Some(entry) = entries.next_entry().await? {
let Ok(metadata) = entry.metadata().await else {
continue;
};
if !metadata.is_file() {
continue;
}
let modified = metadata.modified().unwrap_or(std::time::SystemTime::UNIX_EPOCH);
let abandoned = modified.elapsed().is_ok_and(|age| age > unused);
if abandoned {
if tokio::fs::remove_file(entry.path()).await.is_ok() {
removed += 1;
}
continue;
}
total += metadata.len();
files.push(Candidate {
path: entry.path(),
bytes: metadata.len(),
modified,
});
}
if total > max_bytes {
files.sort_by_key(|file| file.modified);
for file in files {
if total <= max_bytes {
break;
}
if tokio::fs::remove_file(&file.path).await.is_ok() {
total = total.saturating_sub(file.bytes);
removed += 1;
}
}
}
Ok(removed)
}
pub async fn prune(directory: &Path, age: std::time::Duration) -> std::io::Result<usize> {
let mut entries = match tokio::fs::read_dir(directory).await {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
Err(error) => return Err(error),
};
let mut deleted = 0;
while let Some(entry) = entries.next_entry().await? {
let Ok(metadata) = entry.metadata().await else {
continue;
};
if !metadata.is_file() {
continue;
}
let old_enough = metadata
.modified()
.ok()
.and_then(|modified| modified.elapsed().ok())
.is_some_and(|elapsed| elapsed >= age);
if old_enough && tokio::fs::remove_file(entry.path()).await.is_ok() {
deleted += 1;
}
}
Ok(deleted)
}
#[must_use]
pub fn max_bytes(rules: &[String]) -> Option<u64> {
rules.iter().find_map(|rule| {
let kilobytes: u64 = rule.strip_prefix("max:")?.trim().parse().ok()?;
Some(kilobytes.saturating_mul(1024))
})
}
#[must_use]
pub fn temporary_directory(config: &LivewireConfig) -> String {
config
.temporary_file_upload
.directory
.clone()
.unwrap_or_else(|| "livewire-tmp".to_owned())
}
#[must_use]
pub fn temporary_path(config: &LivewireConfig) -> PathBuf {
Path::new("storage/app/private").join(temporary_directory(config))
}
pub async fn preview(
registry: laravel::container::Inject<Arc<crate::registry::ComponentRegistry>>,
laravel::routing::Params(filename): laravel::routing::Params<String>,
) -> Response {
if !filename_is_safe(&filename) {
return empty(StatusCode::FORBIDDEN);
}
let config = registry.config();
let extension = Path::new(&filename)
.extension()
.and_then(|extension| extension.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
if !config
.temporary_file_upload
.preview_mimes
.iter()
.any(|mime| mime.eq_ignore_ascii_case(&extension))
{
return empty(StatusCode::FORBIDDEN);
}
let Ok(bytes) = tokio::fs::read(temporary_path(config).join(&filename)).await else {
return empty(StatusCode::NOT_FOUND);
};
let mut response = Response::new(bytes);
if let Ok(value) = content_type(&extension).parse() {
response.headers_mut().insert("content-type", value);
}
if let Ok(value) = "nosniff".parse() {
response.headers_mut().insert("x-content-type-options", value);
}
if let Ok(value) = "default-src 'none'; sandbox".parse() {
response.headers_mut().insert("content-security-policy", value);
}
if let Ok(value) = format!("inline; filename=\"{}\"", header_filename(&filename)).parse() {
response.headers_mut().insert("content-disposition", value);
}
response
}
fn header_filename(filename: &str) -> String {
filename
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') {
character
} else {
'_'
}
})
.collect()
}
fn content_type(extension: &str) -> &'static str {
match extension {
"png" => "image/png",
"gif" => "image/gif",
"bmp" => "image/bmp",
"svg" => "image/svg+xml",
"jpg" | "jpeg" => "image/jpeg",
"webp" => "image/webp",
"wav" => "audio/wav",
"mp3" | "mpga" => "audio/mpeg",
"m4a" => "audio/mp4",
"mp4" => "video/mp4",
"mov" => "video/quicktime",
"avi" => "video/x-msvideo",
"wmv" => "video/x-ms-wmv",
"pdf" => "application/pdf",
_ => "application/octet-stream",
}
}
pub async fn store(
registry: laravel::container::Inject<Arc<crate::registry::ComponentRegistry>>,
request: Request,
) -> Response {
store_with(&request, registry.config()).await
}
pub async fn store_with(request: &Request, config: &LivewireConfig) -> Response {
let query: UploadQuery = match serde_urlencoded::from_str(request.uri().query().unwrap_or_default()) {
Ok(query) => query,
Err(_) => return empty(StatusCode::UNAUTHORIZED),
};
let (Some(expires), Some(signature)) = (query.expires, query.signature) else {
return empty(StatusCode::UNAUTHORIZED);
};
let Some(component) = query.component else {
return empty(StatusCode::UNAUTHORIZED);
};
if !signature_is_valid(&component, expires, &signature) {
return empty(StatusCode::UNAUTHORIZED);
}
let form: UploadForm = match request.validate().await {
Ok(form) => form,
Err(error) => {
return LivewireError::MalformedPayload(error.to_string()).into_response(false);
}
};
let directory = temporary_directory(config);
if let Err(error) = tokio::fs::create_dir_all(&directory).await {
return LivewireError::Database {
message: error.to_string(),
}
.into_response(false);
}
if let Some(max) = max_bytes(&config.temporary_file_upload.rules)
&& form.files.iter().any(|file| file.size() > max)
{
let body = Value::Object(Map::from_iter([(
"message".to_owned(),
Value::from(format!("The file may not be larger than {} kilobytes.", max / 1024)),
)]));
let mut response = Response::new(body.to_string()).with_status(StatusCode::UNPROCESSABLE_ENTITY);
if let Ok(value) = "application/json".parse() {
response.headers_mut().insert("content-type", value);
}
return response;
}
let mut paths = Vec::with_capacity(form.files.len());
for file in &form.files {
let name = temporary_name(file.client_name());
if let Err(error) = file.store_as(directory.clone(), name.clone()).await {
return LivewireError::Database {
message: error.to_string(),
}
.into_response(false);
}
paths.push(Value::from(format!("livewire-file:{name}")));
}
let _ = trim(
Path::new(&directory),
DIRECTORY_LIMIT,
std::time::Duration::from_secs(UNUSED_LIFETIME_SECONDS),
)
.await;
let body = Value::Object(Map::from_iter([("paths".to_owned(), Value::Array(paths))]));
let mut response = Response::new(body.to_string());
if let Ok(value) = "application/json".parse() {
response.headers_mut().insert("content-type", value);
}
response
}
#[derive(Debug, Deserialize)]
struct UploadQuery {
component: Option<String>,
expires: Option<u64>,
signature: Option<String>,
}
fn empty(status: StatusCode) -> Response {
Response::new("").with_status(status)
}
#[must_use]
pub fn is_upload_call(method: &str) -> bool {
matches!(
method,
"_startUpload" | "_finishUpload" | "_uploadErrored" | "_removeUpload"
)
}
#[cfg(test)]
mod tests {
use super::{filename_is_safe, max_bytes, temporary_name};
#[test]
fn the_size_rule_is_read_from_the_configured_rules() {
let rules = ["required".to_owned(), "file".to_owned(), "max:12288".to_owned()];
assert_eq!(max_bytes(&rules), Some(12_288 * 1024));
assert_eq!(max_bytes(&[]), None, "no rule means no limit");
assert_eq!(
max_bytes(&["max:oops".to_owned()]),
None,
"an unreadable rule does not guess"
);
}
#[tokio::test]
async fn trim_keeps_the_newest_files_and_deletes_the_rest() {
let directory = std::env::temp_dir().join(format!("livewire-trim-{}", laravel::str::random(8)));
tokio::fs::create_dir_all(&directory).await.expect("a directory");
for name in ["a", "b", "c"] {
tokio::fs::write(directory.join(name), [0u8; 10]).await.expect("a file");
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert_eq!(
super::trim(&directory, 25, std::time::Duration::from_secs(3_600))
.await
.expect("a trim"),
1
);
assert!(!directory.join("a").exists(), "the oldest file went");
assert!(
directory.join("b").exists() && directory.join("c").exists(),
"the newest stay"
);
assert_eq!(
super::trim(&directory, 1_024, std::time::Duration::ZERO)
.await
.expect("a trim"),
2
);
assert!(
tokio::fs::read_dir(&directory)
.await
.expect("entries")
.next_entry()
.await
.expect("an entry")
.is_none()
);
tokio::fs::remove_dir(&directory).await.expect("cleanup");
}
#[test]
fn a_temporary_name_cannot_leave_its_directory() {
let name = temporary_name("../../etc/passwd");
assert!(filename_is_safe(&name), "{name}");
assert!(!name.contains('/'), "{name}");
assert!(!name.contains(".."), "{name}");
assert_eq!(name.len(), 20, "a name without an extension keeps none: {name}");
let photo = temporary_name("holiday.jpg");
assert!(photo.ends_with(".jpg"), "{photo}");
assert_eq!(photo.len(), 24, "twenty random characters and the extension: {photo}");
}
#[test]
fn a_name_the_browser_sends_is_checked() {
assert!(filename_is_safe("abc.txt"));
assert!(!filename_is_safe(""));
assert!(!filename_is_safe(".."));
assert!(!filename_is_safe("../x"));
assert!(!filename_is_safe("a/b"));
assert!(!filename_is_safe("a\\b"));
}
}
#[cfg(test)]
mod prune_tests {
use std::time::Duration;
use super::prune;
async fn count_entries(directory: &std::path::Path) -> usize {
let mut entries = tokio::fs::read_dir(directory).await.expect("the directory");
let mut count = 0;
while entries.next_entry().await.expect("an entry").is_some() {
count += 1;
}
count
}
#[tokio::test]
async fn prune_deletes_what_is_old_enough_and_keeps_the_rest() {
let directory = std::env::temp_dir().join(format!("livewire-prune-{}", laravel::str::random(8)));
tokio::fs::create_dir_all(&directory)
.await
.expect("a directory to prune");
tokio::fs::write(directory.join("one.txt"), b"one")
.await
.expect("a file");
tokio::fs::write(directory.join("two.txt"), b"two")
.await
.expect("another file");
assert_eq!(
prune(&directory, Duration::from_secs(3_600)).await.expect("a prune"),
0,
"fresh files stay"
);
assert_eq!(count_entries(&directory).await, 2);
assert_eq!(
prune(&directory, Duration::ZERO).await.expect("a prune"),
2,
"and old enough means old enough"
);
assert_eq!(count_entries(&directory).await, 0);
tokio::fs::remove_dir(&directory).await.expect("cleanup");
assert_eq!(
prune(&directory, Duration::ZERO)
.await
.expect("a missing directory is not an error"),
0
);
}
}