Skip to main content

aurelin_framework/uploads/
mod.rs

1//! Safe temporary multipart uploads and explicit storage.
2//!
3//! Applications define typed forms with [`axum_typed_multipart::TryFromMultipart`].
4//! Use `#[try_from_multipart(strict)]` to reject unknown and duplicate fields,
5//! `#[form_data(limit = "...")]` on every file and text field, and
6//! [`request_body_limit`] on the route. File fields should use
7//! `FieldData<NamedTempFile>` so request bodies are streamed to temporary files.
8//! Authorization and application validation should run before [`store_upload`].
9
10use std::{io, path::Path as FilePath};
11
12use axum::{body::Bytes, extract::DefaultBodyLimit};
13use axum_typed_multipart::FieldData;
14use futures_util::stream;
15use rand::{Rng, distr::Alphanumeric};
16use tempfile::NamedTempFile;
17use tokio::{fs::File, io::AsyncReadExt};
18
19use crate::storage::{Disk, StorageError, StoragePath, StorageResult};
20
21const READ_CHUNK_SIZE: usize = 64 * 1024;
22const GENERATED_NAME_LENGTH: usize = 40;
23
24/// Metadata returned after an accepted temporary upload is stored.
25#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct StoredUpload {
27    /// Generated disk-relative path. It never contains the original filename.
28    pub path: StoragePath,
29    /// Number of bytes written to the disk.
30    pub size: u64,
31    /// Client-reported filename, retained only as untrusted metadata.
32    pub untrusted_original_name: Option<String>,
33    /// Client-reported content type, retained only as untrusted metadata.
34    pub untrusted_content_type: Option<String>,
35}
36
37/// Applies an Axum total request-body limit while multipart fields are read.
38///
39/// Per-field limits remain part of the typed form declaration, where they are
40/// enforced while `axum-typed-multipart` consumes each field.
41pub fn request_body_limit(max_bytes: usize) -> DefaultBodyLimit {
42    DefaultBodyLimit::max(max_bytes)
43}
44
45/// Stores a validated temporary upload under an opaque generated name.
46///
47/// `directory` is selected by the application and must be a safe relative path.
48/// The original filename and content type are metadata only. No extension or
49/// MIME claim supplied by the client influences the stored path.
50pub async fn store_upload(
51    disk: &Disk,
52    directory: Option<&str>,
53    upload: FieldData<NamedTempFile>,
54) -> StorageResult<StoredUpload> {
55    let directory = directory.map(StoragePath::parse).transpose()?;
56    let generated_name: String =
57        rand::rng().sample_iter(Alphanumeric).take(GENERATED_NAME_LENGTH).map(char::from).collect();
58    let path = match directory {
59        Some(directory) => StoragePath::parse(format!("{directory}/{generated_name}"))?,
60        None => StoragePath::parse(generated_name)?,
61    };
62
63    let original_name = upload.metadata.file_name;
64    let content_type = upload.metadata.content_type;
65    let file = open_temporary_file(upload.contents.path()).await?;
66    let stream = file_stream(file);
67    let size = disk.put_stream(path.as_str(), stream).await?;
68
69    Ok(StoredUpload { path, size, untrusted_original_name: original_name, untrusted_content_type: content_type })
70}
71
72async fn open_temporary_file(path: &FilePath) -> StorageResult<File> {
73    File::open(path).await.map_err(StorageError::input)
74}
75
76fn file_stream(file: File) -> impl futures_util::Stream<Item = Result<Bytes, io::Error>> + Send {
77    stream::try_unfold(file, |mut file| async move {
78        let mut buffer = vec![0_u8; READ_CHUNK_SIZE];
79        let read = file.read(&mut buffer).await?;
80        if read == 0 {
81            return Ok(None);
82        }
83        buffer.truncate(read);
84        Ok(Some((Bytes::from(buffer), file)))
85    })
86}
87
88/// Re-export of the streaming temporary-file type used in typed multipart forms.
89pub use tempfile::NamedTempFile as TemporaryUploadFile;