✨ (pagetop): Añade subida y descarga de archivos
- `web::Upload` guarda los archivos de un envío multipart en disco por trozos, con nombre aleatorio, extensiones y tamaño máximo por archivo. `receive()` deserializa además los campos de texto con serde_qs. - `web::Download` sirve un archivo subido con rangos y peticiones condicionales, inline sólo para tipos pasivos y con nosniff. - `form::File`, componente para elegir archivos, y soporte en Bootsier. - Límite del cuerpo según el tipo de contenido: `server.max_body_size` baja a 2 MiB y el nuevo `upload.max_request_size` (32 MiB) se aplica sólo a multipart/form-data.
This commit is contained in:
parent
5540c0c6a0
commit
f3228d6b59
21 changed files with 2240 additions and 17 deletions
28
Cargo.lock
generated
28
Cargo.lock
generated
|
|
@ -350,6 +350,7 @@ dependencies = [
|
|||
"matchit",
|
||||
"memchr",
|
||||
"mime",
|
||||
"multer",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"serde_core",
|
||||
|
|
@ -912,6 +913,15 @@ version = "0.2.9"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
|
|
@ -1951,6 +1961,23 @@ dependencies = [
|
|||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multer"
|
||||
version = "3.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"encoding_rs",
|
||||
"futures-util",
|
||||
"http",
|
||||
"httparse",
|
||||
"memchr",
|
||||
"mime",
|
||||
"spin",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "native-tls"
|
||||
version = "0.2.18"
|
||||
|
|
@ -2150,6 +2177,7 @@ dependencies = [
|
|||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_qs",
|
||||
"tempfile",
|
||||
"terminal_size",
|
||||
"thiserror",
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ testing = []
|
|||
|
||||
[dependencies]
|
||||
async-trait.workspace = true
|
||||
axum.workspace = true
|
||||
axum = { workspace = true, features = ["multipart"] }
|
||||
chrono.workspace = true
|
||||
chrono-tz.workspace = true
|
||||
colored.workspace = true
|
||||
|
|
@ -136,6 +136,7 @@ pagetop-macros.workspace = true
|
|||
pagetop-minimal.workspace = true
|
||||
pagetop-statics.workspace = true
|
||||
serde.workspace = true
|
||||
serde_qs.workspace = true
|
||||
terminal_size.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
|
|
|
|||
|
|
@ -98,6 +98,25 @@ format = "Full" # Formato: "Full", "Compact", "Pretty" o
|
|||
[server]
|
||||
bind_address = "localhost" # Dirección de enlace del servidor web.
|
||||
bind_port = 8080 # Puerto de escucha del servidor web.
|
||||
max_body_size = 2_097_152 # Tamaño máximo en bytes del cuerpo de una petición que se lee
|
||||
# entero en memoria (2 MiB): formularios, JSON... y la suma de
|
||||
# los campos de texto de un formulario con archivos. Una
|
||||
# petición mayor se rechaza con 413. 0 -> sin límite.
|
||||
|
||||
[upload]
|
||||
dir = "uploads" # Directorio de los archivos subidos, absoluto o relativo al
|
||||
# directorio de trabajo. Se crea al guardar el primero.
|
||||
max_request_size = 33_554_432 # Tamaño máximo en bytes de un envío 'multipart/form-data'
|
||||
# completo (32 MiB), con todos sus archivos y campos; sustituye
|
||||
# a 'server.max_body_size' en estas peticiones. Para admitir
|
||||
# varios archivos debe ser varias veces mayor que
|
||||
# 'max_file_size'. Uno mayor se rechaza con 413. 0 -> sin
|
||||
# límite.
|
||||
max_file_size = 8_388_608 # Tamaño máximo en bytes de cada archivo por separado
|
||||
# (8 MiB). La aplicación puede cambiarlo en una subida
|
||||
# concreta. 0 -> sólo limita 'max_request_size'.
|
||||
max_files = 20 # Número máximo de archivos de un mismo envío. La aplicación
|
||||
# puede cambiarlo en una subida concreta. 0 -> sin límite.
|
||||
|
||||
|
||||
# **< pagetop-seaorm >******************************************************************************
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ name = "Testing"
|
|||
[server]
|
||||
bind_port = 9000
|
||||
|
||||
[upload]
|
||||
dir = "target/test-uploads"
|
||||
|
||||
[test]
|
||||
string_value = "Modified value"
|
||||
float_value = 8.7654
|
||||
|
|
|
|||
|
|
@ -166,6 +166,8 @@ async fn form_controls(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|||
.with_id("form-text")
|
||||
.with_action("/")
|
||||
.with_method(form::Method::Post)
|
||||
// Necesaria para enviar los archivos de form::File.
|
||||
.with_enctype(form::Enctype::Multipart)
|
||||
// Campos de texto (form::input::Field).
|
||||
.with_child(
|
||||
form::Fieldset::new()
|
||||
|
|
@ -251,6 +253,26 @@ async fn form_controls(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|||
.with_help_text(Lc::t("help_rating", &LOC)),
|
||||
),
|
||||
)
|
||||
// Selección de archivos (form::File).
|
||||
.with_child(
|
||||
form::Fieldset::new()
|
||||
.with_legend(Lc::t("fieldset_file", &LOC))
|
||||
.with_child(
|
||||
form::File::new()
|
||||
.with_name("photo")
|
||||
.with_label(Lc::t("label_photo", &LOC))
|
||||
.with_accept("image/jpeg,image/png")
|
||||
.with_help_text(Lc::t("help_photo", &LOC)),
|
||||
)
|
||||
.with_child(
|
||||
form::File::new()
|
||||
.with_name("attachments")
|
||||
.with_label(Lc::t("label_attachments", &LOC))
|
||||
.with_accept(".pdf")
|
||||
.with_multiple(true)
|
||||
.with_help_text(Lc::t("help_attachments", &LOC)),
|
||||
),
|
||||
)
|
||||
// Campo oculto (form::Hidden).
|
||||
.with_child(form::Hidden::field("origin", "form-text"))
|
||||
// Botonera de acciones.
|
||||
|
|
|
|||
|
|
@ -73,6 +73,12 @@ fieldset_range = Slider
|
|||
label_rating = Overall rating
|
||||
help_rating = From 1 (very poor) to 10 (excellent).
|
||||
|
||||
fieldset_file = Files
|
||||
label_photo = Profile picture
|
||||
help_photo = JPEG or PNG image. This example does not save it.
|
||||
label_attachments = Attachments
|
||||
help_attachments = You can choose several PDF files.
|
||||
|
||||
btn_submit = Submit
|
||||
btn_reset = Reset
|
||||
btn_cancel = Cancel
|
||||
|
|
|
|||
|
|
@ -73,6 +73,12 @@ fieldset_range = Control deslizante
|
|||
label_rating = Valoración general
|
||||
help_rating = De 1 (muy malo) a 10 (excelente).
|
||||
|
||||
fieldset_file = Archivos
|
||||
label_photo = Foto de perfil
|
||||
help_photo = Imagen JPEG o PNG. En este ejemplo no se guarda.
|
||||
label_attachments = Documentos adjuntos
|
||||
help_attachments = Puedes elegir varios archivos PDF.
|
||||
|
||||
btn_submit = Enviar
|
||||
btn_reset = Restablecer
|
||||
btn_cancel = Cancelar
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
//! Definiciones para crear formularios ([`Form`]).
|
||||
|
||||
pub use pagetop::base::component::form::{Autocomplete, AutofillField, CheckboxKind, Method};
|
||||
pub use pagetop::base::component::form::{
|
||||
Autocomplete, AutofillField, CheckboxKind, Enctype, Method,
|
||||
};
|
||||
|
||||
pub use pagetop::base::component::form::Form;
|
||||
|
||||
|
|
@ -37,4 +39,6 @@ pub use pagetop::base::component::form::Number;
|
|||
|
||||
pub use pagetop::base::component::form::Range;
|
||||
|
||||
pub use pagetop::base::component::form::File;
|
||||
|
||||
pub use pagetop::base::component::form::Hidden;
|
||||
|
|
|
|||
35
src/app.rs
35
src/app.rs
|
|
@ -9,9 +9,12 @@ use crate::core::theme;
|
|||
use crate::datetime::Timezone;
|
||||
use crate::locale::Locale;
|
||||
use crate::response::{render_error_pages, response_for_panic, route_not_found};
|
||||
use crate::web::Router;
|
||||
use crate::web::{Request, Response, Router, http};
|
||||
use crate::{PAGETOP_VERSION, global, trace};
|
||||
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::middleware::Next;
|
||||
use tower::{Layer, ServiceExt};
|
||||
use tower_http::catch_panic::CatchPanicLayer;
|
||||
use tracing_appender::non_blocking::WorkerGuard;
|
||||
|
||||
|
|
@ -250,6 +253,9 @@ impl Application {
|
|||
// cambio, se registra antes: la página 404 debe ver lo que el middleware añade a la petición
|
||||
// (p. ej. el usuario actual).
|
||||
//
|
||||
// El límite del cuerpo de las peticiones (`limit_body()`) sustituye al de Axum en todas las
|
||||
// rutas.
|
||||
//
|
||||
// Las capas de páginas de error y `CatchPanicLayer` cubren todo, porque se añaden al final. Con
|
||||
// `CatchPanicLayer` en la última capa se capturan incluso los `panic!` que se produzcan dentro
|
||||
// del propio renderizado de una página de error.
|
||||
|
|
@ -258,11 +264,38 @@ impl Application {
|
|||
let router = extension::all::configure_middleware(router);
|
||||
let router = extension::all::configure_static_files(router);
|
||||
router
|
||||
.layer(axum::middleware::from_fn(limit_body))
|
||||
.layer(axum::middleware::from_fn(render_error_pages))
|
||||
.layer(CatchPanicLayer::custom(response_for_panic))
|
||||
}
|
||||
}
|
||||
|
||||
// Fija el límite del cuerpo de la petición según su tipo de contenido. Un envío
|
||||
// `multipart/form-data` escribe sus archivos en disco a medida que llegan, así que admite
|
||||
// `upload.max_request_size`; el resto de cuerpos se leen enteros en memoria y se limitan con
|
||||
// `server.max_body_size`. Otro tipo de contenido no se beneficia del límite mayor: el extractor
|
||||
// `Multipart` exige `multipart/form-data`, y `Form` o `Json` rechazan la petición sin leer el
|
||||
// cuerpo si no llega con el suyo.
|
||||
async fn limit_body(request: Request, next: Next) -> Response {
|
||||
let multipart = request
|
||||
.headers()
|
||||
.get(http::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.get(..19))
|
||||
.is_some_and(|essence| essence.eq_ignore_ascii_case("multipart/form-data"));
|
||||
let max = if multipart {
|
||||
global::SETTINGS.upload.max_request_size
|
||||
} else {
|
||||
global::SETTINGS.server.max_body_size
|
||||
};
|
||||
let limit = match max {
|
||||
0 => DefaultBodyLimit::disable(),
|
||||
max => DefaultBodyLimit::max(max),
|
||||
};
|
||||
let Ok(response) = limit.layer(next).oneshot(request).await;
|
||||
response
|
||||
}
|
||||
|
||||
// Espera la señal para detener el servidor: Ctrl+C o, en Unix, `SIGTERM`. Si no se puede escuchar
|
||||
// alguna, espera sólo a la otra en lugar de detener el servidor nada más arrancar.
|
||||
async fn shutdown_signal() {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! Definiciones para crear formularios ([`Form`]).
|
||||
|
||||
mod props;
|
||||
pub use props::{Autocomplete, AutofillField, CheckboxKind, Method};
|
||||
pub use props::{Autocomplete, AutofillField, CheckboxKind, Enctype, Method};
|
||||
|
||||
mod component;
|
||||
pub use component::Form;
|
||||
|
|
@ -42,5 +42,8 @@ pub use range::Range;
|
|||
mod textarea;
|
||||
pub use textarea::Textarea;
|
||||
|
||||
mod file;
|
||||
pub use file::File;
|
||||
|
||||
mod hidden;
|
||||
pub use hidden::Hidden;
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ use crate::base::component::form;
|
|||
/// - `classes`: clases CSS adicionales (p. ej. utilidades CSS).
|
||||
/// - `action`: URL/ruta de destino para el envío.
|
||||
/// - `method`: método usado por el formulario para el envío de los datos (ver [`form::Method`]).
|
||||
/// - `enctype`: codificación de los datos enviados (ver [`form::Enctype`]); los formularios con
|
||||
/// archivos necesitan [`form::Enctype::Multipart`].
|
||||
/// - `accept-charset`: juego de caracteres aceptado (por defecto es `"UTF-8"`).
|
||||
/// - `children`: contenido del formulario.
|
||||
///
|
||||
|
|
@ -50,6 +52,8 @@ pub struct Form {
|
|||
action: Route,
|
||||
/// Devuelve el método para enviar el formulario.
|
||||
method: form::Method,
|
||||
/// Devuelve la codificación de los datos enviados por el formulario.
|
||||
enctype: form::Enctype,
|
||||
/// Devuelve el juego de caracteres aceptado por el formulario.
|
||||
#[default(_code = "AttrValue::new(\"UTF-8\")")]
|
||||
charset: AttrValue,
|
||||
|
|
@ -76,11 +80,16 @@ impl Component for Form {
|
|||
form::Method::Post => Some("post"),
|
||||
form::Method::Get => None,
|
||||
};
|
||||
let enctype = match self.enctype() {
|
||||
form::Enctype::UrlEncoded => None,
|
||||
form::Enctype::Multipart => Some("multipart/form-data"),
|
||||
};
|
||||
Ok(html! {
|
||||
form
|
||||
(self.props().unpack(cx))
|
||||
action=[self.action().try_resolve(cx)]
|
||||
method=[method]
|
||||
enctype=[enctype]
|
||||
accept-charset=[self.charset().as_deref()]
|
||||
{
|
||||
(self.children().render(cx).await)
|
||||
|
|
@ -123,6 +132,15 @@ impl Form {
|
|||
self
|
||||
}
|
||||
|
||||
/// Establece la codificación de los datos enviados por el formulario.
|
||||
///
|
||||
/// - `UrlEncoded`: el atributo `enctype` se omite (por defecto).
|
||||
/// - `Multipart`: se establece `enctype="multipart/form-data"`, necesario para subir archivos.
|
||||
pub fn with_enctype(mut self, enctype: form::Enctype) -> Self {
|
||||
self.enctype = enctype;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el juego de caracteres aceptado por el formulario.
|
||||
///
|
||||
/// Por defecto se utiliza `"UTF-8"`.
|
||||
|
|
|
|||
181
src/base/component/form/file.rs
Normal file
181
src/base/component/form/file.rs
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
//! Definiciones para crear campos de selección de archivos en formularios.
|
||||
|
||||
use crate::prelude::*;
|
||||
|
||||
/// Componente para crear un **campo de selección de archivos** de formulario (`type="file"`).
|
||||
///
|
||||
/// Permite elegir uno o varios archivos del equipo para enviarlos con el formulario, con una
|
||||
/// etiqueta opcional, un texto de ayuda y los tipos de archivo aceptados (`accept`).
|
||||
///
|
||||
/// El formulario debe usar la codificación [`form::Enctype::Multipart`]; sin ella, el navegador
|
||||
/// envía sólo el nombre del archivo.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
///
|
||||
/// let form = Form::new()
|
||||
/// .with_action("/documents")
|
||||
/// .with_enctype(form::Enctype::Multipart)
|
||||
/// .with_child(
|
||||
/// form::File::new()
|
||||
/// .with_name("attachments")
|
||||
/// .with_label(Lc::n("Attachments"))
|
||||
/// .with_accept(".pdf,image/*")
|
||||
/// .with_multiple(true)
|
||||
/// .with_help_text(Lc::n("PDF documents or images.")),
|
||||
/// )
|
||||
/// .with_child(Button::submit(Lc::n("Send")));
|
||||
/// ```
|
||||
///
|
||||
/// Al enviar el formulario, cada archivo llega en una parte propia del cuerpo con el `name` del
|
||||
/// campo (varias con el mismo nombre si se eligen varios archivos). Si no se elige ninguno, el
|
||||
/// navegador envía igualmente una parte vacía, sin nombre de archivo. En el servidor,
|
||||
/// [`web::Upload::receive()`] recibe el envío completo, guarda los archivos e ignora esa parte
|
||||
/// vacía.
|
||||
///
|
||||
/// `accept` es sólo una ayuda para el usuario al elegir el archivo: no impide enviar otros tipos,
|
||||
/// así que el servidor debe comprobarlos igualmente con [`web::Upload::with_extensions()`].
|
||||
/// [`web::Upload::accept()`] devuelve esas mismas extensiones con el formato de `accept`.
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct File {
|
||||
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
|
||||
props: Props,
|
||||
/// Devuelve el nombre del campo.
|
||||
name: AttrName,
|
||||
/// Devuelve la etiqueta del campo.
|
||||
label: Lc,
|
||||
/// Devuelve el texto de ayuda del campo.
|
||||
help_text: Lc,
|
||||
/// Devuelve los tipos de archivo aceptados.
|
||||
accept: AttrValue,
|
||||
/// Devuelve si se pueden elegir varios archivos.
|
||||
multiple: bool,
|
||||
/// Devuelve si el campo recibe el foco automáticamente al cargar la página.
|
||||
autofocus: bool,
|
||||
/// Devuelve si el campo es obligatorio.
|
||||
required: bool,
|
||||
/// Devuelve si el campo está deshabilitado.
|
||||
disabled: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for File {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn id(&self) -> Option<String> {
|
||||
self.props.get_id()
|
||||
}
|
||||
|
||||
fn setup(&mut self, _cx: &mut Context) {
|
||||
if let Some(container_id) = self
|
||||
.id()
|
||||
.or_else(|| self.name().as_deref().map(|n| util::join!("edit-", n)))
|
||||
{
|
||||
self.alter_prop(PropsOp::ensure_id(container_id));
|
||||
}
|
||||
|
||||
// Clases CSS del contenedor del campo.
|
||||
self.alter_prop(PropsOp::prepend_classes("form-field form-field-file"));
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let container_id = self.id();
|
||||
let input_id = container_id.as_deref().map(|id| util::join!(id, "-file"));
|
||||
let help = form::parts::Help::new(self.help_text(), input_id.as_deref());
|
||||
let label = form::parts::Label::new(self.label(), input_id.as_deref())
|
||||
.with_required(*self.required());
|
||||
|
||||
Ok(html! {
|
||||
div (self.props().unpack(cx)) {
|
||||
(label.render(cx))
|
||||
input
|
||||
type="file"
|
||||
id=[input_id.as_deref()]
|
||||
aria-describedby=[help.id()]
|
||||
class="form-control"
|
||||
name=[self.name().as_deref()]
|
||||
accept=[self.accept().as_deref()]
|
||||
multiple[*self.multiple()]
|
||||
autofocus[*self.autofocus()]
|
||||
required[*self.required()]
|
||||
disabled[*self.disabled()];
|
||||
(help.render(cx))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl File {
|
||||
// **< File BUILDER >***************************************************************************
|
||||
|
||||
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
|
||||
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
|
||||
self.props.alter_id(id);
|
||||
self
|
||||
}
|
||||
|
||||
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
|
||||
pub fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
|
||||
self.props.alter_prop(op);
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el nombre del campo (atributo `name`).
|
||||
///
|
||||
/// Sin él, los archivos no se transmiten al servidor al enviar el formulario. Es el nombre que
|
||||
/// devuelve `name()` en cada parte recibida con [`web::Multipart`].
|
||||
pub fn with_name(mut self, name: impl AsRef<str>) -> Self {
|
||||
self.name.alter_name(name);
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece la etiqueta visible del campo (usa [`Lc::none()`] para quitarla).
|
||||
pub fn with_label(mut self, label: Lc) -> Self {
|
||||
self.label = label;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el texto de ayuda del campo (usa [`Lc::none()`] para quitarlo).
|
||||
pub fn with_help_text(mut self, help_text: Lc) -> Self {
|
||||
self.help_text = help_text;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece los tipos de archivo aceptados (atributo `accept`), separados por comas.
|
||||
///
|
||||
/// Admite extensiones (`.pdf`), tipos MIME (`application/pdf`) y familias de tipos (`image/*`),
|
||||
/// p. ej. `".pdf,image/*"`. Una cadena vacía quita el atributo y se acepta cualquier archivo.
|
||||
pub fn with_accept(mut self, accept: impl AsRef<str>) -> Self {
|
||||
self.accept.alter_str(accept);
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si se pueden elegir varios archivos a la vez.
|
||||
pub fn with_multiple(mut self, multiple: bool) -> Self {
|
||||
self.multiple = multiple;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el campo recibe el foco automáticamente al cargar la página.
|
||||
pub fn with_autofocus(mut self, autofocus: bool) -> Self {
|
||||
self.autofocus = autofocus;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el campo es obligatorio.
|
||||
pub fn with_required(mut self, required: bool) -> Self {
|
||||
self.required = required;
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el campo está deshabilitado.
|
||||
pub fn with_disabled(mut self, disabled: bool) -> Self {
|
||||
self.disabled = disabled;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
@ -468,8 +468,8 @@ impl AutofillField {
|
|||
/// cifran** por sí mismos; por eso es esencial el uso de HTTPS.
|
||||
/// - **Tamaño**: GET está limitado por la longitud máxima de URL que acepten el navegador y el
|
||||
/// servidor. POST es más flexible para cargas grandes.
|
||||
/// - **Ficheros**: la subida de ficheros requiere `method="post"` y un `enctype` adecuado
|
||||
/// (habitualmente `multipart/form-data`).
|
||||
/// - **Archivos**: la subida de archivos requiere `method="post"` y la codificación
|
||||
/// [`Enctype::Multipart`].
|
||||
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Method {
|
||||
/// Envía los datos en el cuerpo de la petición.
|
||||
|
|
@ -484,3 +484,28 @@ pub enum Method {
|
|||
/// Recomendado para búsquedas y operaciones que no modifican datos ni el estado del sistema.
|
||||
Get,
|
||||
}
|
||||
|
||||
// **< Enctype >************************************************************************************
|
||||
|
||||
/// Codificación usada por un [`Form`](super::Form) para enviar los datos con el método
|
||||
/// [`Method::Post`].
|
||||
///
|
||||
/// Corresponde al atributo `enctype` del formulario. El navegador lo ignora con [`Method::Get`],
|
||||
/// que siempre codifica los datos en la URL.
|
||||
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Enctype {
|
||||
/// Pares `name=value` codificados como en una URL (`application/x-www-form-urlencoded`). Es la
|
||||
/// **codificación por defecto**, y el atributo `enctype` se omite.
|
||||
///
|
||||
/// En el servidor se reciben con los extractores [`web::Form`] o [`web::RawForm`].
|
||||
#[default]
|
||||
UrlEncoded,
|
||||
|
||||
/// Cada campo en una parte propia del cuerpo (`multipart/form-data`). **Imprescindible para
|
||||
/// subir archivos** con [`form::File`](super::File); sin ella, el navegador envía sólo el nombre
|
||||
/// del archivo.
|
||||
///
|
||||
/// En el servidor se recibe con el extractor [`web::Multipart`], y los archivos se guardan con
|
||||
/// [`web::Upload`].
|
||||
Multipart,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ pub use log_format::LogFormat;
|
|||
|
||||
// **< SETTINGS >***********************************************************************************
|
||||
|
||||
/// Ajustes de las secciones `[app]`, `[dev]`, `[log]` y `[server]`.
|
||||
/// Ajustes de las secciones `[app]`, `[dev]`, `[log]`, `[server]` y `[upload]`.
|
||||
///
|
||||
/// Se cargan al arrancar la aplicación, antes que los ajustes de las extensiones.
|
||||
pub static SETTINGS: LazyLock<Settings> = LazyLock::new(|| Settings {
|
||||
|
|
@ -30,6 +30,7 @@ pub static SETTINGS: LazyLock<Settings> = LazyLock::new(|| Settings {
|
|||
dev: config::load(),
|
||||
log: config::load(),
|
||||
server: config::load(),
|
||||
upload: config::load(),
|
||||
});
|
||||
|
||||
// Comprueba que los archivos de configuración se pueden leer y que los ajustes globales son válidos.
|
||||
|
|
@ -39,7 +40,8 @@ pub(crate) fn check_settings() -> Result<(), StartupError> {
|
|||
check_section::<AppSettings>()?;
|
||||
check_section::<DevSettings>()?;
|
||||
check_section::<LogSettings>()?;
|
||||
check_section::<ServerSettings>()
|
||||
check_section::<ServerSettings>()?;
|
||||
check_section::<UploadSettings>()
|
||||
}
|
||||
|
||||
fn check_section<T: config::SettingsSection>() -> Result<(), StartupError> {
|
||||
|
|
@ -53,21 +55,24 @@ fn check_section<T: config::SettingsSection>() -> Result<(), StartupError> {
|
|||
|
||||
/// Ajustes globales de [`SETTINGS`].
|
||||
///
|
||||
/// Secciones [`AppSettings`], [`DevSettings`], [`LogSettings`] y [`ServerSettings`].
|
||||
/// Secciones [`AppSettings`], [`DevSettings`], [`LogSettings`], [`ServerSettings`] y
|
||||
/// [`UploadSettings`].
|
||||
#[derive(Debug)]
|
||||
pub struct Settings {
|
||||
pub app: AppSettings,
|
||||
pub dev: DevSettings,
|
||||
pub log: LogSettings,
|
||||
pub server: ServerSettings,
|
||||
pub upload: UploadSettings,
|
||||
}
|
||||
|
||||
// Secciones de los ajustes globales, para reconocerlas en los archivos de configuración.
|
||||
pub(crate) const SECTIONS: [&str; 4] = [
|
||||
pub(crate) const SECTIONS: [&str; 5] = [
|
||||
<AppSettings as config::SettingsSection>::SECTION,
|
||||
<DevSettings as config::SettingsSection>::SECTION,
|
||||
<LogSettings as config::SettingsSection>::SECTION,
|
||||
<ServerSettings as config::SettingsSection>::SECTION,
|
||||
<UploadSettings as config::SettingsSection>::SECTION,
|
||||
];
|
||||
|
||||
/// Sección **`[app]`** de la configuración. Forma parte de [`Settings`].
|
||||
|
|
@ -219,11 +224,59 @@ pub struct ServerSettings {
|
|||
/// Puerto de escucha del servidor web.
|
||||
#[default = 8080]
|
||||
pub bind_port: u16,
|
||||
/// Tamaño máximo en bytes del cuerpo de una petición que se lee entero en memoria (por defecto
|
||||
/// 2 MiB, el mismo que aplica Axum). Con *0* no hay límite.
|
||||
///
|
||||
/// Se aplica a los extractores que leen el cuerpo completo, como [`Form`](crate::web::Form),
|
||||
/// [`RawForm`](crate::web::RawForm) o el `Json` de Axum, y también a la suma de los campos de
|
||||
/// texto de un formulario con archivos recibido con
|
||||
/// [`Upload::receive()`](crate::web::Upload::receive). Los envíos `multipart/form-data`
|
||||
/// completos, con sus archivos, los limita en cambio
|
||||
/// [`max_request_size`](UploadSettings::max_request_size) de `[upload]`, porque los archivos se
|
||||
/// escriben en disco a medida que llegan. Una petición mayor se rechaza con
|
||||
/// `413 Payload Too Large`.
|
||||
#[default = 2_097_152]
|
||||
pub max_body_size: usize,
|
||||
}
|
||||
|
||||
/// Sección **`[upload]`** de la configuración. Forma parte de [`Settings`].
|
||||
///
|
||||
/// Ajustes para guardar en el servidor los archivos subidos con [`Upload`](crate::web::Upload).
|
||||
#[settings(section = "upload")]
|
||||
pub struct UploadSettings {
|
||||
/// Directorio donde se guardan los archivos subidos, absoluto o relativo al directorio de
|
||||
/// trabajo. Se crea, junto con sus subdirectorios, al guardar el primer archivo.
|
||||
#[default = "uploads"]
|
||||
pub dir: String,
|
||||
/// Tamaño máximo en bytes de una petición `multipart/form-data` completa, con todos sus
|
||||
/// archivos y campos (por defecto 32 MiB). Con *0* no hay límite.
|
||||
///
|
||||
/// Sustituye a [`max_body_size`](ServerSettings::max_body_size) de `[server]` en las peticiones
|
||||
/// con ese tipo de contenido. Para admitir varios archivos en un envío debe ser varias veces
|
||||
/// mayor que [`max_file_size`](Self::max_file_size). Una petición mayor se rechaza con
|
||||
/// `413 Payload Too Large`.
|
||||
#[default = 33_554_432]
|
||||
pub max_request_size: usize,
|
||||
/// Tamaño máximo en bytes de cada archivo (por defecto 8 MiB). Con *0* sólo limita
|
||||
/// [`max_request_size`](Self::max_request_size), que acota además la suma de todos los archivos
|
||||
/// de un mismo envío.
|
||||
///
|
||||
/// Es el valor por defecto de [`Upload`](crate::web::Upload), que puede cambiarse para una
|
||||
/// subida concreta con `with_max_size()`.
|
||||
#[default = 8_388_608]
|
||||
pub max_file_size: u64,
|
||||
/// Número máximo de archivos de un mismo envío (por defecto 20). Con *0* no se limita.
|
||||
///
|
||||
/// Lo aplica [`Upload::receive()`](crate::web::Upload::receive) para que un envío con cientos
|
||||
/// de archivos diminutos, que cabrían en `max_request_size`, no llene el disco de archivos.
|
||||
/// Puede cambiarse para una subida concreta con `with_max_files()`.
|
||||
#[default = 20]
|
||||
pub max_files: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{AppSettings, DevSettings, LogSettings, ServerSettings, config};
|
||||
use super::{AppSettings, DevSettings, LogSettings, ServerSettings, UploadSettings, config};
|
||||
|
||||
// `reference.toml` documents every option; with unknown keys rejected, loading it proves that
|
||||
// it only documents keys that exist, with values of the right type.
|
||||
|
|
@ -235,6 +288,7 @@ mod tests {
|
|||
config::load_from_str::<DevSettings>(REFERENCE).unwrap();
|
||||
config::load_from_str::<LogSettings>(REFERENCE).unwrap();
|
||||
config::load_from_str::<ServerSettings>(REFERENCE).unwrap();
|
||||
config::load_from_str::<UploadSettings>(REFERENCE).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -66,3 +66,16 @@ poweredby_pagetop = Powered by { $pagetop_link }
|
|||
|
||||
# Table component.
|
||||
table_empty = No data to display
|
||||
|
||||
# File uploads (web::Upload and web::Download).
|
||||
upload_too_large = "{ $file }" exceeds the maximum size of { $size } per file.
|
||||
upload_extension_not_allowed = "{ $file }" is not an allowed file type ({ $allowed }).
|
||||
upload_too_many_files = { $limit ->
|
||||
[one] Only one file can be sent at a time.
|
||||
*[other] Only { $limit } files can be sent at a time.
|
||||
}
|
||||
upload_fields_too_large = The form fields exceed the maximum size of { $size }.
|
||||
upload_body_too_large = The submission exceeds the maximum size of { $size }.
|
||||
upload_not_found = The file does not exist or is no longer available.
|
||||
upload_invalid = The form submission is not valid. Please try again.
|
||||
upload_failed = The file could not be processed. Please try again later.
|
||||
|
|
|
|||
|
|
@ -66,3 +66,16 @@ poweredby_pagetop = Funciona con { $pagetop_link }
|
|||
|
||||
# Table component.
|
||||
table_empty = No hay datos que mostrar
|
||||
|
||||
# File uploads (web::Upload and web::Download).
|
||||
upload_too_large = «{ $file }» supera el tamaño máximo de { $size } por archivo.
|
||||
upload_extension_not_allowed = «{ $file }» no es de un tipo de archivo permitido ({ $allowed }).
|
||||
upload_too_many_files = { $limit ->
|
||||
[one] Sólo se puede enviar un archivo a la vez.
|
||||
*[other] Sólo se pueden enviar { $limit } archivos a la vez.
|
||||
}
|
||||
upload_fields_too_large = Los campos del formulario superan el tamaño máximo de { $size }.
|
||||
upload_body_too_large = El envío supera el tamaño máximo de { $size }.
|
||||
upload_not_found = El archivo no existe o ya no está disponible.
|
||||
upload_invalid = El envío del formulario no es válido. Inténtalo de nuevo.
|
||||
upload_failed = No se ha podido procesar el archivo. Inténtalo más tarde.
|
||||
|
|
|
|||
30
src/web.rs
30
src/web.rs
|
|
@ -2,9 +2,11 @@
|
|||
//!
|
||||
//! Define rutas y handlers: el [`Router`], las operaciones HTTP ([`get`], [`post`], [`put`],
|
||||
//! [`delete`], [`patch`]), los extractores ([`Path`], [`Query`], [`Form`], [`RawForm`],
|
||||
//! [`Request`]) e [`IntoResponse`], el módulo [`middleware`] para *middlewares* de función, y
|
||||
//! re-exporta el módulo `http` para tipos de bajo nivel como `StatusCode`, `HeaderName` o `Method`.
|
||||
//! También ofrece utilidades para servir archivos estáticos, [`ServeDir`] y [`ServeEmbedded`].
|
||||
//! [`Multipart`], [`Request`]) e [`IntoResponse`], el módulo [`middleware`] para *middlewares* de
|
||||
//! función, y re-exporta el módulo `http` para tipos de bajo nivel como `StatusCode`, `HeaderName`
|
||||
//! o `Method`. También ofrece utilidades para servir archivos estáticos, [`ServeDir`] y
|
||||
//! [`ServeEmbedded`], para recibir y guardar los archivos subidos en formularios, [`Upload`], y
|
||||
//! para servirlos después con control de acceso, [`Download`].
|
||||
//!
|
||||
//! Los handlers son las funciones asíncronas que el servidor invoca al recibir una petición HTTP en
|
||||
//! una ruta concreta.
|
||||
|
|
@ -18,7 +20,10 @@ pub use axum::http;
|
|||
pub use axum::Router;
|
||||
|
||||
// Extractores de petición.
|
||||
pub use axum::extract::{Form, Path, Query, RawForm, Request};
|
||||
pub use axum::extract::{Form, Multipart, Path, Query, RawForm, Request};
|
||||
|
||||
// Partes y errores del extractor `Multipart`.
|
||||
pub use axum::extract::multipart;
|
||||
|
||||
// Para implementar respuestas.
|
||||
pub use axum::response::{IntoResponse, Response};
|
||||
|
|
@ -29,6 +34,14 @@ pub use axum::routing::{delete, get, patch, post, put};
|
|||
// Middlewares de función (`from_fn`) y tipos asociados (`Next`).
|
||||
pub use axum::middleware;
|
||||
|
||||
// Guardado de los archivos subidos en formularios `multipart/form-data`.
|
||||
mod upload;
|
||||
pub use upload::{Upload, UploadError, UploadedFile, UploadedForm};
|
||||
|
||||
// Respuestas con los archivos subidos.
|
||||
mod download;
|
||||
pub use download::Download;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::FromRequestParts;
|
||||
|
||||
|
|
@ -505,6 +518,15 @@ pub mod test {
|
|||
self.header("content-type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
|
||||
/// Envía como cuerpo de la petición el texto indicado, tal cual.
|
||||
///
|
||||
/// Combinado con [`header()`](Self::header) para fijar `Content-Type`, permite probar
|
||||
/// cuerpos con otros formatos, como los formularios `multipart/form-data` con archivos.
|
||||
pub fn body(mut self, body: impl Into<String>) -> Self {
|
||||
self.body = body.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Inserta un valor en las extensiones de la petición.
|
||||
///
|
||||
/// Útil para simular lo que un middleware haría en producción antes de que el handler
|
||||
|
|
|
|||
231
src/web/download.rs
Normal file
231
src/web/download.rs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
use crate::web::upload::{push_percent_encoded, sanitize_file_name};
|
||||
use crate::web::{Upload, UploadError, http};
|
||||
|
||||
use axum::body::Body;
|
||||
use tower::ServiceExt;
|
||||
use tower_http::services::ServeFile;
|
||||
|
||||
use std::io::ErrorKind;
|
||||
|
||||
// El navegador puede guardar el archivo, pero debe revalidarlo antes de reutilizarlo, así que el
|
||||
// handler vuelve a comprobar los permisos; las cachés compartidas no lo guardan.
|
||||
const DOWNLOAD_CACHE_CONTROL: http::HeaderValue =
|
||||
http::HeaderValue::from_static("private, no-cache");
|
||||
|
||||
// Cabeceras de la petición que usa `ServeFile` para responder a peticiones parciales y
|
||||
// condicionales; el resto (cookies incluidas) no le hacen falta.
|
||||
const FORWARDED_HEADERS: [http::HeaderName; 6] = [
|
||||
http::header::RANGE,
|
||||
http::header::IF_RANGE,
|
||||
http::header::IF_MATCH,
|
||||
http::header::IF_NONE_MATCH,
|
||||
http::header::IF_MODIFIED_SINCE,
|
||||
http::header::IF_UNMODIFIED_SINCE,
|
||||
];
|
||||
|
||||
/// Sirve un archivo subido con [`Upload`] como respuesta a una petición.
|
||||
///
|
||||
/// Es la forma de publicar los archivos subidos **con control de acceso**: el handler comprueba
|
||||
/// los permisos y busca el archivo (normalmente en la base de datos), y `Download` lo envía con las
|
||||
/// cabeceras adecuadas:
|
||||
///
|
||||
/// - `Content-Type` según la extensión del archivo guardado, que fija el servidor y no el usuario.
|
||||
/// - `Content-Disposition` con el nombre de [`with_file_name()`](Self::with_file_name),
|
||||
/// normalmente el original. Las imágenes (salvo SVG), el audio, el vídeo, los PDF y el texto
|
||||
/// plano se muestran en el navegador (`inline`); el resto se descarga (`attachment`), para que
|
||||
/// un `.html` o un `.svg` subido no se ejecute como una página más del sitio.
|
||||
/// [`with_attachment()`](Self::with_attachment) obliga a descargar también los primeros.
|
||||
/// - `X-Content-Type-Options: nosniff`, para que el navegador no deduzca otro tipo del contenido.
|
||||
/// - `Cache-Control: private, no-cache`: el navegador revalida el archivo antes de reutilizarlo,
|
||||
/// así que cada uso vuelve a pasar por el handler, y las cachés compartidas no lo guardan.
|
||||
///
|
||||
/// Atiende también las peticiones parciales (`Range`, para reanudar una descarga o avanzar en un
|
||||
/// vídeo) y condicionales (`If-None-Match` con el `ETag` de la respuesta, o `If-Modified-Since`),
|
||||
/// con `206 Partial Content` o `304 Not Modified`.
|
||||
///
|
||||
/// Sólo sirve archivos del directorio de archivos subidos. La ruta debe salir de la aplicación (la
|
||||
/// guardada en la base de datos), nunca directamente de la petición: aunque no puede salir de ese
|
||||
/// directorio, daría acceso a cualquier archivo subido.
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
///
|
||||
/// async fn invoice(
|
||||
/// request: HttpRequest,
|
||||
/// web::Path(id): web::Path<u32>,
|
||||
/// ) -> Result<Response, ErrorPage> {
|
||||
/// // Comprobar los permisos y buscar en la base de datos el archivo de la factura `id`...
|
||||
/// # let (path, original_name) = (id.to_string(), "invoice.pdf");
|
||||
/// web::Download::new(path)
|
||||
/// .with_file_name(original_name)
|
||||
/// .serve(&request)
|
||||
/// .await
|
||||
/// .map_err(|err| match err {
|
||||
/// web::UploadError::NotFound(_) => ErrorPage::NotFound(Some(request)),
|
||||
/// _ => ErrorPage::InternalError(Some(request)),
|
||||
/// })
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Clone, Debug, Getters)]
|
||||
pub struct Download {
|
||||
/// Devuelve la ruta del archivo, relativa al directorio de archivos subidos
|
||||
/// ([`UploadedFile::path()`](crate::web::UploadedFile::path)).
|
||||
path: String,
|
||||
/// Devuelve el nombre con el que se muestra o se guarda el archivo. Vacío, se usa el del
|
||||
/// archivo guardado.
|
||||
file_name: String,
|
||||
/// Devuelve si el archivo se descarga siempre, aunque el navegador pudiera mostrarlo.
|
||||
#[getters(copy)]
|
||||
attachment: bool,
|
||||
}
|
||||
|
||||
impl Download {
|
||||
/// Prepara la respuesta para el archivo guardado en `path`, relativa al directorio de archivos
|
||||
/// subidos ([`UploadedFile::path()`](crate::web::UploadedFile::path)).
|
||||
pub fn new(path: impl Into<String>) -> Self {
|
||||
Self {
|
||||
path: path.into(),
|
||||
file_name: String::new(),
|
||||
attachment: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Construye la respuesta con el archivo, atendiendo a las cabeceras de `request`.
|
||||
///
|
||||
/// Devuelve [`UploadError::NotFound`] si el archivo no existe, para que el handler responda
|
||||
/// con [`ErrorPage::NotFound`](crate::response::ErrorPage::NotFound), e
|
||||
/// [`UploadError::InvalidPath`] si la ruta sale del directorio de archivos subidos.
|
||||
pub async fn serve(&self, request: &HttpRequest) -> Result<Response, UploadError> {
|
||||
let local = Upload::local_path(self.path())?;
|
||||
match tokio::fs::metadata(&local).await {
|
||||
Ok(metadata) if metadata.is_file() => {}
|
||||
Ok(_) => return Err(UploadError::NotFound(self.path.clone())),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {
|
||||
return Err(UploadError::NotFound(self.path.clone()));
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
|
||||
// `ServeFile` deduce el tipo MIME de la extensión y resuelve las peticiones parciales y
|
||||
// condicionales con las cabeceras de la petición original.
|
||||
let mut file_request = http::Request::new(Body::empty());
|
||||
let headers = file_request.headers_mut();
|
||||
for name in FORWARDED_HEADERS {
|
||||
if let Some(value) = request.headers().get(&name) {
|
||||
headers.insert(name, value.clone());
|
||||
}
|
||||
}
|
||||
let Ok(response) = ServeFile::new(&local).oneshot(file_request).await;
|
||||
let mut response = response.map(Body::new);
|
||||
|
||||
let inline = !self.attachment()
|
||||
&& response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.is_some_and(shows_inline);
|
||||
let file_name = if self.file_name().is_empty() {
|
||||
self.path().rsplit('/').next().unwrap_or_default()
|
||||
} else {
|
||||
self.file_name()
|
||||
};
|
||||
|
||||
let headers = response.headers_mut();
|
||||
if let Ok(value) = http::HeaderValue::from_str(&content_disposition(inline, file_name)) {
|
||||
headers.insert(http::header::CONTENT_DISPOSITION, value);
|
||||
}
|
||||
headers.insert(
|
||||
http::header::X_CONTENT_TYPE_OPTIONS,
|
||||
http::HeaderValue::from_static("nosniff"),
|
||||
);
|
||||
headers.insert(http::header::CACHE_CONTROL, DOWNLOAD_CACHE_CONTROL);
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl Download {
|
||||
// **< Download BUILDER >***********************************************************************
|
||||
|
||||
/// Establece el nombre con el que el navegador muestra o guarda el archivo, normalmente el
|
||||
/// original ([`UploadedFile::original_name()`](crate::web::UploadedFile::original_name)). Una
|
||||
/// cadena vacía usa el nombre del archivo guardado.
|
||||
pub fn with_file_name(mut self, file_name: impl AsRef<str>) -> Self {
|
||||
self.file_name = file_name.as_ref().trim().to_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece si el archivo se descarga siempre (`Content-Disposition: attachment`), aunque sea
|
||||
/// de un tipo que el navegador podría mostrar.
|
||||
pub fn with_attachment(mut self, attachment: bool) -> Self {
|
||||
self.attachment = attachment;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// **< Utilidades privadas >************************************************************************
|
||||
|
||||
// Tipos que el navegador muestra sin ejecutar nada en el contexto del sitio. SVG queda fuera porque
|
||||
// es un documento que admite *scripts*, igual que HTML o XML.
|
||||
fn shows_inline(content_type: &str) -> bool {
|
||||
let essence = content_type
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
match essence.split_once('/') {
|
||||
Some(("image", subtype)) => subtype != "svg+xml",
|
||||
Some(("audio" | "video", _)) => true,
|
||||
_ => matches!(essence.as_str(), "application/pdf" | "text/plain"),
|
||||
}
|
||||
}
|
||||
|
||||
// `filename` lleva una versión ASCII del nombre para clientes antiguos, y `filename*` (RFC 6266)
|
||||
// el nombre completo en UTF-8, que es el que usan los navegadores actuales.
|
||||
fn content_disposition(inline: bool, file_name: &str) -> String {
|
||||
let name = sanitize_file_name(file_name);
|
||||
let mut value = String::with_capacity(32 + name.len() * 4);
|
||||
value.push_str(if inline { "inline" } else { "attachment" });
|
||||
value.push_str("; filename=\"");
|
||||
for c in name.chars() {
|
||||
let safe = c.is_ascii_alphanumeric() || matches!(c, ' ' | '.' | '-' | '_' | '(' | ')');
|
||||
value.push(if safe { c } else { '_' });
|
||||
}
|
||||
value.push_str("\"; filename*=UTF-8''");
|
||||
push_percent_encoded(&mut value, &name);
|
||||
value
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{content_disposition, shows_inline};
|
||||
|
||||
#[test]
|
||||
fn only_passive_types_are_shown_inline() {
|
||||
assert!(shows_inline("image/png"));
|
||||
assert!(shows_inline("video/mp4"));
|
||||
assert!(shows_inline("application/pdf"));
|
||||
assert!(shows_inline("text/plain; charset=utf-8"));
|
||||
assert!(!shows_inline("image/svg+xml"));
|
||||
assert!(!shows_inline("text/html"));
|
||||
assert!(!shows_inline("application/xhtml+xml"));
|
||||
assert!(!shows_inline("application/octet-stream"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_disposition_has_ascii_and_utf8_names() {
|
||||
assert_eq!(
|
||||
content_disposition(false, "Año \"2026\".pdf"),
|
||||
"attachment; filename=\"A_o _2026_.pdf\"; filename*=UTF-8''A%C3%B1o%20%222026%22.pdf"
|
||||
);
|
||||
assert_eq!(
|
||||
content_disposition(true, "../photo.jpg"),
|
||||
"inline; filename=\"photo.jpg\"; filename*=UTF-8''photo.jpg"
|
||||
);
|
||||
}
|
||||
}
|
||||
913
src/web/upload.rs
Normal file
913
src/web/upload.rs
Normal file
|
|
@ -0,0 +1,913 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
use crate::global;
|
||||
use crate::web::multipart::{Field, MultipartError};
|
||||
use crate::web::{Multipart, http};
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::io::{AsyncWriteExt, BufWriter};
|
||||
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Component as PathComponent, Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
// Longitud máxima, en caracteres, del nombre original que se conserva de un archivo subido.
|
||||
const MAX_NAME_CHARS: usize = 200;
|
||||
|
||||
// Longitud máxima de la extensión que se conserva en el nombre del archivo guardado.
|
||||
const MAX_EXTENSION_CHARS: usize = 16;
|
||||
|
||||
// Tamaño del búfer de escritura de cada archivo. El cuerpo llega en trozos pequeños (de unos pocos
|
||||
// KiB), y cada escritura de `tokio::fs::File` pasa por un hilo del *pool* de bloqueo: sin búfer, un
|
||||
// archivo de 8 MiB tardaba 17 veces más en escribirse.
|
||||
const WRITE_BUFFER_SIZE: usize = 256 * 1024;
|
||||
|
||||
// Intentos para encontrar un nombre libre antes de desistir; con nombres aleatorios de 64 bits una
|
||||
// colisión es ya improbable.
|
||||
const NAME_ATTEMPTS: usize = 4;
|
||||
|
||||
// **< UploadError >********************************************************************************
|
||||
|
||||
/// Errores al recibir, guardar o servir un archivo subido con [`Upload`] o [`Download`].
|
||||
///
|
||||
/// [`message()`](Self::message) da un mensaje traducido para mostrarlo junto al formulario, y
|
||||
/// [`is_client_error()`](Self::is_client_error) separa los fallos del envío de los del servidor.
|
||||
///
|
||||
/// [`Download`]: crate::web::Download
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum UploadError {
|
||||
/// La parte del formulario no es un archivo, sino un campo de texto.
|
||||
#[error("form field `{0}` is not a file")]
|
||||
NotAFile(String),
|
||||
/// El archivo llega en un campo que no está entre los admitidos con
|
||||
/// [`Upload::with_file_fields()`].
|
||||
#[error("unexpected file field `{0}`")]
|
||||
UnexpectedField(String),
|
||||
/// El archivo supera el tamaño máximo permitido.
|
||||
#[error("file `{file}` exceeds the maximum size of {limit} bytes")]
|
||||
TooLarge {
|
||||
/// Nombre original del archivo, saneado.
|
||||
file: String,
|
||||
/// Tamaño máximo en bytes.
|
||||
limit: u64,
|
||||
},
|
||||
/// La extensión del archivo no está entre las permitidas.
|
||||
#[error("file `{file}` has an extension that is not allowed")]
|
||||
ExtensionNotAllowed {
|
||||
/// Nombre original del archivo, saneado.
|
||||
file: String,
|
||||
/// Extensiones permitidas, en minúsculas y sin el punto.
|
||||
allowed: Vec<String>,
|
||||
},
|
||||
/// El envío trae más archivos de los permitidos.
|
||||
#[error("too many files, the maximum is {limit}")]
|
||||
TooManyFiles {
|
||||
/// Número máximo de archivos.
|
||||
limit: usize,
|
||||
},
|
||||
/// Los campos de texto del envío superan en conjunto el tamaño máximo permitido
|
||||
/// ([`max_body_size`](crate::global::ServerSettings::max_body_size)).
|
||||
#[error("form fields exceed the maximum size of {limit} bytes")]
|
||||
FieldsTooLarge {
|
||||
/// Tamaño máximo en bytes.
|
||||
limit: usize,
|
||||
},
|
||||
/// Los campos de texto del envío no se corresponden con los del formulario esperado (falta
|
||||
/// alguno obligatorio, un valor no tiene el tipo esperado...).
|
||||
#[error("invalid form data: {0}")]
|
||||
InvalidForm(String),
|
||||
/// El archivo pedido no existe.
|
||||
#[error("file `{0}` not found")]
|
||||
NotFound(String),
|
||||
/// La ruta indicada sale del directorio de archivos subidos o no es relativa.
|
||||
#[error("invalid upload path `{0}`")]
|
||||
InvalidPath(String),
|
||||
/// Error al leer el cuerpo de la petición, incluido superar el límite de
|
||||
/// [`max_request_size`](crate::global::UploadSettings::max_request_size).
|
||||
#[error(transparent)]
|
||||
Multipart(#[from] MultipartError),
|
||||
/// Error al leer o escribir el archivo en disco.
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
impl UploadError {
|
||||
/// Devuelve `true` si el error se debe a la petición (archivo demasiado grande, extensión no
|
||||
/// permitida, envío mal formado, archivo que no existe...) y no a un fallo del servidor.
|
||||
///
|
||||
/// Permite decidir si se informa al usuario para que corrija el envío o se responde con un
|
||||
/// error interno.
|
||||
pub fn is_client_error(&self) -> bool {
|
||||
match self {
|
||||
Self::NotAFile(_)
|
||||
| Self::UnexpectedField(_)
|
||||
| Self::TooLarge { .. }
|
||||
| Self::ExtensionNotAllowed { .. }
|
||||
| Self::TooManyFiles { .. }
|
||||
| Self::FieldsTooLarge { .. }
|
||||
| Self::InvalidForm(_)
|
||||
| Self::NotFound(_) => true,
|
||||
Self::Multipart(err) => err.status().is_client_error(),
|
||||
Self::InvalidPath(_) | Self::Io(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve un mensaje traducido para el usuario, con el nombre del archivo y el límite
|
||||
/// superado cuando procede.
|
||||
///
|
||||
/// Los errores del servidor dan un mensaje genérico, sin detalles internos.
|
||||
pub fn message(&self) -> Lc {
|
||||
match self {
|
||||
Self::TooLarge { file, limit } => Lc::l("upload_too_large")
|
||||
.with_arg("file", file.clone())
|
||||
.with_arg("size", format_size(*limit)),
|
||||
Self::ExtensionNotAllowed { file, allowed } => Lc::l("upload_extension_not_allowed")
|
||||
.with_arg("file", file.clone())
|
||||
.with_arg("allowed", allowed.join(", ")),
|
||||
Self::TooManyFiles { limit } => Lc::l("upload_too_many_files")
|
||||
.with_number("limit", u32::try_from(*limit).unwrap_or(u32::MAX)),
|
||||
Self::FieldsTooLarge { limit } => {
|
||||
Lc::l("upload_fields_too_large").with_arg("size", format_size(*limit as u64))
|
||||
}
|
||||
Self::NotFound(_) => Lc::l("upload_not_found"),
|
||||
Self::Multipart(err)
|
||||
if err.status() == http::StatusCode::PAYLOAD_TOO_LARGE
|
||||
&& global::SETTINGS.upload.max_request_size > 0 =>
|
||||
{
|
||||
Lc::l("upload_body_too_large").with_arg(
|
||||
"size",
|
||||
format_size(global::SETTINGS.upload.max_request_size as u64),
|
||||
)
|
||||
}
|
||||
err if err.is_client_error() => Lc::l("upload_invalid"),
|
||||
_ => Lc::l("upload_failed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// **< UploadedFile >*******************************************************************************
|
||||
|
||||
/// Archivo subido y guardado en el servidor por [`Upload::save()`] o [`Upload::receive()`].
|
||||
#[derive(Clone, Debug, Getters)]
|
||||
pub struct UploadedFile {
|
||||
/// Devuelve el nombre del campo del formulario en el que llegó el archivo.
|
||||
field: String,
|
||||
/// Devuelve la ruta del archivo guardado, relativa al directorio de archivos subidos y con `/`
|
||||
/// como separador (p. ej. `"photos/3f9c2a7d1b4e8a60.jpg"`).
|
||||
///
|
||||
/// Es el valor que conviene guardar en la base de datos; [`Upload::local_path()`] la convierte
|
||||
/// en la ruta del archivo en disco y [`Download`](crate::web::Download) lo sirve.
|
||||
path: String,
|
||||
/// Devuelve el nombre original del archivo, saneado: sin directorios ni caracteres de control.
|
||||
///
|
||||
/// Lo envía el navegador, así que sólo sirve para mostrarlo; nunca se usa para guardarlo.
|
||||
original_name: String,
|
||||
/// Devuelve el tipo MIME declarado por el navegador, si lo envía.
|
||||
///
|
||||
/// No se comprueba contra el contenido del archivo, así que no debe tomarse como garantía.
|
||||
content_type: Option<String>,
|
||||
/// Devuelve el tamaño del archivo en bytes.
|
||||
#[getters(copy)]
|
||||
size: u64,
|
||||
}
|
||||
|
||||
// **< UploadedForm >*******************************************************************************
|
||||
|
||||
/// Envío `multipart/form-data` recibido con [`Upload::receive()`]: los campos de texto
|
||||
/// deserializados en `T` y los archivos ya guardados.
|
||||
///
|
||||
/// **Los archivos se borran al descartar el `UploadedForm`** (al terminar el handler, al salir
|
||||
/// antes con `?`...) salvo que se conserven con [`keep()`](Self::keep). Basta con llamar a `keep()`
|
||||
/// cuando el envío está procesado por completo (validado y registrado en la base de datos) para que
|
||||
/// uno que no llegue a buen término no deje archivos huérfanos en disco.
|
||||
#[derive(Debug)]
|
||||
pub struct UploadedForm<T> {
|
||||
form: T,
|
||||
files: SavedFiles,
|
||||
}
|
||||
|
||||
impl<T> UploadedForm<T> {
|
||||
/// Devuelve los campos de texto del formulario.
|
||||
pub fn form(&self) -> &T {
|
||||
&self.form
|
||||
}
|
||||
|
||||
/// Devuelve los archivos guardados, en el orden en que llegaron.
|
||||
///
|
||||
/// Los de un campo con varios archivos ([`form::File::with_multiple()`]) se obtienen filtrando
|
||||
/// por [`UploadedFile::field()`]: `files().iter().filter(|f| f.field() == "attachments")`.
|
||||
pub fn files(&self) -> &[UploadedFile] {
|
||||
&self.files.0
|
||||
}
|
||||
|
||||
/// Devuelve el primer archivo guardado del campo `field`, o `None` si no se eligió ninguno.
|
||||
pub fn file(&self, field: impl AsRef<str>) -> Option<&UploadedFile> {
|
||||
let field = field.as_ref();
|
||||
self.files.0.iter().find(|file| file.field() == field)
|
||||
}
|
||||
|
||||
/// Conserva en disco los archivos guardados y devuelve los campos de texto y los archivos.
|
||||
pub fn keep(self) -> (T, Vec<UploadedFile>) {
|
||||
let UploadedForm { form, mut files } = self;
|
||||
(form, std::mem::take(&mut files.0))
|
||||
}
|
||||
}
|
||||
|
||||
// Archivo que se está escribiendo, que se borra si se descarta antes de `finish()`: al devolver un
|
||||
// error y también si se cancela el futuro de `save()` (p. ej. al descartarse el handler).
|
||||
struct PartialFile {
|
||||
local: PathBuf,
|
||||
file: Option<BufWriter<tokio::fs::File>>,
|
||||
}
|
||||
|
||||
impl PartialFile {
|
||||
async fn write_all(&mut self, chunk: &[u8]) -> std::io::Result<()> {
|
||||
match self.file.as_mut() {
|
||||
Some(file) => file.write_all(chunk).await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish(&mut self) -> std::io::Result<()> {
|
||||
if let Some(file) = self.file.as_mut() {
|
||||
file.flush().await?;
|
||||
}
|
||||
self.file = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PartialFile {
|
||||
fn drop(&mut self) {
|
||||
// Se cierra antes de borrarlo, porque Windows no borra un archivo abierto.
|
||||
if self.file.take().is_none() {
|
||||
return;
|
||||
}
|
||||
if let Err(err) = std::fs::remove_file(&self.local)
|
||||
&& err.kind() != ErrorKind::NotFound
|
||||
{
|
||||
trace::warn!(
|
||||
"Cannot remove incomplete upload `{}`: {err}",
|
||||
self.local.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Archivos guardados de un envío, que se borran al descartarse salvo que antes se vacíe la lista.
|
||||
#[derive(Debug, Default)]
|
||||
struct SavedFiles(Vec<UploadedFile>);
|
||||
|
||||
impl Drop for SavedFiles {
|
||||
// Borrado síncrono: `Drop` no puede esperar a una tarea asíncrona, y son pocos archivos (como
|
||||
// mucho `max_files`) que el sistema sólo tiene que desenlazar.
|
||||
fn drop(&mut self) {
|
||||
for file in self.0.drain(..) {
|
||||
let Ok(local) = Upload::local_path(file.path()) else {
|
||||
continue;
|
||||
};
|
||||
if let Err(err) = std::fs::remove_file(&local)
|
||||
&& err.kind() != ErrorKind::NotFound
|
||||
{
|
||||
trace::warn!(
|
||||
"Cannot remove discarded upload `{}`: {err}",
|
||||
local.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// **< Upload >*************************************************************************************
|
||||
|
||||
/// Recibe y guarda en el servidor los archivos de un formulario `multipart/form-data`.
|
||||
///
|
||||
/// Los archivos se guardan en el directorio [`dir`](crate::global::UploadSettings::dir) de la
|
||||
/// sección `[upload]` de la configuración, o en un subdirectorio suyo indicado con
|
||||
/// [`with_subdir()`](Self::with_subdir). Cada archivo recibe un **nombre aleatorio** que conserva
|
||||
/// la extensión del original: el nombre que envía el navegador no se usa nunca en disco, así que no
|
||||
/// puede sobrescribir otros archivos ni salir del directorio. El nombre original saneado queda en
|
||||
/// [`UploadedFile::original_name()`].
|
||||
///
|
||||
/// El archivo se escribe a medida que llega, sin cargarlo entero en memoria, y se descarta si
|
||||
/// supera el tamaño máximo ([`max_file_size`](crate::global::UploadSettings::max_file_size) por
|
||||
/// defecto) o si no llega completo. La suma de todos los archivos y campos del envío la limita
|
||||
/// además [`max_request_size`](crate::global::UploadSettings::max_request_size), que el servidor
|
||||
/// aplica a toda petición `multipart/form-data`.
|
||||
///
|
||||
/// Lo habitual es recibir el envío completo con [`receive()`](Self::receive), que deserializa los
|
||||
/// campos de texto, limita el número de archivos y borra los guardados si el envío no llega a buen
|
||||
/// término. [`save()`](Self::save) guarda una sola parte, para recorrer el envío a mano.
|
||||
///
|
||||
/// Para servir después los archivos con control de acceso, ver [`Download`](crate::web::Download).
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// Conviene definir la subida una sola vez, para que el formulario anuncie las mismas extensiones
|
||||
/// (`accept`) que admite el servidor. El formulario necesita además [`form::Enctype::Multipart`]:
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
///
|
||||
/// fn photo_upload() -> web::Upload {
|
||||
/// web::Upload::new()
|
||||
/// .with_subdir("photos")
|
||||
/// .with_extensions(["jpg", "jpeg", "png"])
|
||||
/// .with_file_fields(["photo"])
|
||||
/// }
|
||||
///
|
||||
/// fn photo_form() -> Form {
|
||||
/// Form::new()
|
||||
/// .with_action("/garden/photos")
|
||||
/// .with_enctype(form::Enctype::Multipart)
|
||||
/// .with_child(
|
||||
/// form::input::Field::text()
|
||||
/// .with_name("title")
|
||||
/// .with_label(Lc::n("Title")),
|
||||
/// )
|
||||
/// .with_child(
|
||||
/// form::File::new()
|
||||
/// .with_name("photo")
|
||||
/// .with_label(Lc::n("Photo"))
|
||||
/// .with_accept(photo_upload().accept())
|
||||
/// .with_required(true),
|
||||
/// )
|
||||
/// .with_child(Button::submit(Lc::n("Upload")))
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// El handler recibe el cuerpo con el extractor [`web::Multipart`] (siempre el último parámetro).
|
||||
/// Los campos de texto se deserializan en una estructura propia, como con [`web::Form`], y los
|
||||
/// archivos se conservan sólo si se llega a [`keep()`](UploadedForm::keep):
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use pagetop::prelude::*;
|
||||
/// # fn photo_upload() -> web::Upload { web::Upload::new() }
|
||||
///
|
||||
/// #[derive(serde::Deserialize)]
|
||||
/// struct PhotoForm {
|
||||
/// title: String,
|
||||
/// }
|
||||
///
|
||||
/// async fn upload_photo(
|
||||
/// request: HttpRequest,
|
||||
/// multipart: web::Multipart,
|
||||
/// ) -> Result<Response, ErrorPage> {
|
||||
/// let sent = match photo_upload().receive::<PhotoForm>(multipart).await {
|
||||
/// Ok(sent) => sent,
|
||||
/// Err(err) if err.is_client_error() => {
|
||||
/// // Volver a mostrar el formulario con `err.message()`...
|
||||
/// # todo!()
|
||||
/// }
|
||||
/// Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
||||
/// };
|
||||
/// let Some(photo) = sent.file("photo") else {
|
||||
/// // Campo obligatorio sin archivo: volver a mostrar el formulario...
|
||||
/// # todo!()
|
||||
/// };
|
||||
/// // Guardar `sent.form().title`, `photo.path()` y `photo.original_name()` en la base de
|
||||
/// // datos. Si falla y se sale con `?`, el archivo se borra.
|
||||
/// sent.keep();
|
||||
/// Ok(Redirect::see_other("/garden/photos"))
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Upload {
|
||||
/// Devuelve el subdirectorio donde se guardan los archivos, relativo al de archivos subidos.
|
||||
/// Vacío, se guardan en el directorio raíz.
|
||||
subdir: String,
|
||||
/// Devuelve el tamaño máximo en bytes de cada archivo, si sustituye al de la configuración.
|
||||
#[getters(copy)]
|
||||
max_size: Option<u64>,
|
||||
/// Devuelve el número máximo de archivos de un envío, si sustituye al de la configuración.
|
||||
#[getters(copy)]
|
||||
max_files: Option<usize>,
|
||||
/// Devuelve las extensiones permitidas, en minúsculas y sin el punto. Vacío, se admite
|
||||
/// cualquiera.
|
||||
extensions: Vec<String>,
|
||||
/// Devuelve los nombres de los campos en los que se admiten archivos. Vacío, se admiten en
|
||||
/// cualquiera.
|
||||
file_fields: Vec<String>,
|
||||
}
|
||||
|
||||
impl Upload {
|
||||
/// Crea un `Upload` que guarda en el directorio de archivos subidos, con los límites de la
|
||||
/// configuración y sin restringir las extensiones ni los campos.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Convierte la ruta de un archivo guardado ([`UploadedFile::path()`]) en su ruta en disco.
|
||||
///
|
||||
/// Sirve para leer, servir o borrar el archivo más adelante. Devuelve
|
||||
/// [`UploadError::InvalidPath`] si la ruta no es relativa o sale del directorio de archivos
|
||||
/// subidos (p. ej. con `..`), para que una ruta manipulada no dé acceso a otros archivos.
|
||||
pub fn local_path(path: impl AsRef<str>) -> Result<PathBuf, UploadError> {
|
||||
let path = path.as_ref();
|
||||
let relative = checked_relative(path)?;
|
||||
if relative.as_os_str().is_empty() {
|
||||
return Err(UploadError::InvalidPath(path.to_owned()));
|
||||
}
|
||||
Ok(upload_dir().join(relative))
|
||||
}
|
||||
|
||||
/// Borra un archivo guardado, a partir de su ruta ([`UploadedFile::path()`]).
|
||||
///
|
||||
/// No es un error que el archivo ya no exista, para poder usarlo sin más comprobaciones al
|
||||
/// sustituir un archivo por otro o al borrar el registro que lo referencia. Igual que
|
||||
/// [`local_path()`](Self::local_path), rechaza las rutas que salen del directorio de archivos
|
||||
/// subidos.
|
||||
pub async fn remove(path: impl AsRef<str>) -> Result<(), UploadError> {
|
||||
match tokio::fs::remove_file(Self::local_path(path)?).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Devuelve las extensiones permitidas con el formato del atributo `accept` de un campo
|
||||
/// [`form::File`] (p. ej. `".jpg,.png"`), o una cadena vacía si se admite cualquiera.
|
||||
///
|
||||
/// Con `form::File::new().with_accept(upload.accept())` el formulario ofrece al usuario los
|
||||
/// mismos tipos de archivo que admite el servidor.
|
||||
pub fn accept(&self) -> String {
|
||||
let mut accept = String::new();
|
||||
for ext in self.extensions() {
|
||||
if !accept.is_empty() {
|
||||
accept.push(',');
|
||||
}
|
||||
accept.push('.');
|
||||
accept.push_str(ext);
|
||||
}
|
||||
accept
|
||||
}
|
||||
|
||||
/// Recibe un envío `multipart/form-data` completo: guarda sus archivos y deserializa sus campos
|
||||
/// de texto en `T`, como hace [`web::Form`] en un formulario sin archivos.
|
||||
///
|
||||
/// Los campos de texto se interpretan con `serde_qs`, igual que el cuerpo de un formulario
|
||||
/// normal leído con [`web::RawForm`] y `serde_qs::from_bytes()`. A diferencia de
|
||||
/// [`web::Form`], los repetidos (las casillas de una misma lista, p. ej.) se recogen en un
|
||||
/// `Vec`, marcado con `#[serde(default)]` para admitir que no llegue ninguno; en un campo
|
||||
/// simple repetido gana el último valor. Los nombres con corchetes (`tags[]`) se toman tal
|
||||
/// cual, sin anidar. En conjunto, los campos de texto no pueden superar
|
||||
/// [`max_body_size`](crate::global::ServerSettings::max_body_size), el mismo límite de un
|
||||
/// formulario sin archivos ([`UploadError::FieldsTooLarge`]).
|
||||
///
|
||||
/// Cada parte con archivo se guarda con [`save()`](Self::save), con sus mismas comprobaciones,
|
||||
/// salvo las vacías (campos en los que no se eligió archivo), que se ignoran. Además, rechaza
|
||||
/// el envío si trae más archivos de [`max_files`](crate::global::UploadSettings::max_files) o
|
||||
/// de los indicados con [`with_max_files()`](Self::with_max_files).
|
||||
///
|
||||
/// Si algo falla, borra los archivos ya guardados antes de devolver el error. Si no, el
|
||||
/// [`UploadedForm`] devuelto los borra también al descartarse, salvo que se conserven con
|
||||
/// [`UploadedForm::keep()`].
|
||||
pub async fn receive<T: DeserializeOwned>(
|
||||
&self,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<UploadedForm<T>, UploadError> {
|
||||
let max_files = self
|
||||
.max_files()
|
||||
.unwrap_or(global::SETTINGS.upload.max_files);
|
||||
let max_text = global::SETTINGS.server.max_body_size;
|
||||
let mut files = SavedFiles::default();
|
||||
// Los campos de texto se codifican como el cuerpo de un formulario normal a medida que
|
||||
// llegan, sin guardar antes cada valor entero.
|
||||
let mut fields = String::new();
|
||||
let mut text_size: usize = 0;
|
||||
|
||||
while let Some(mut field) = multipart.next_field().await? {
|
||||
match field.file_name().map(str::is_empty) {
|
||||
Some(no_file) => {
|
||||
if !no_file && max_files > 0 && files.0.len() >= max_files {
|
||||
return Err(UploadError::TooManyFiles { limit: max_files });
|
||||
}
|
||||
if let Some(file) = self.save(field).await? {
|
||||
files.0.push(file);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let Some(name) = field.name() else {
|
||||
continue;
|
||||
};
|
||||
text_size += name.len() + 1;
|
||||
if max_text > 0 && text_size > max_text {
|
||||
return Err(UploadError::FieldsTooLarge { limit: max_text });
|
||||
}
|
||||
if !fields.is_empty() {
|
||||
fields.push('&');
|
||||
}
|
||||
push_percent_encoded(&mut fields, name);
|
||||
fields.push('=');
|
||||
while let Some(chunk) = field.chunk().await? {
|
||||
text_size += chunk.len();
|
||||
if max_text > 0 && text_size > max_text {
|
||||
return Err(UploadError::FieldsTooLarge { limit: max_text });
|
||||
}
|
||||
push_percent_encoded(&mut fields, &chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let form =
|
||||
serde_qs::from_str(&fields).map_err(|err| UploadError::InvalidForm(err.to_string()))?;
|
||||
Ok(UploadedForm { form, files })
|
||||
}
|
||||
|
||||
/// Guarda en disco el archivo de una parte del formulario.
|
||||
///
|
||||
/// Devuelve `Ok(None)` si el campo llega sin archivo, como hace el navegador cuando no se elige
|
||||
/// ninguno en un campo opcional. Si el archivo no se puede guardar por completo (supera el
|
||||
/// tamaño máximo, se interrumpe la petición...), se borra lo escrito antes de devolver el
|
||||
/// error. También si se cancela antes de terminar, como cuando se descarta el handler.
|
||||
///
|
||||
/// Cada archivo se guarda en cuanto llega su parte, así que si al recorrer el envío a mano
|
||||
/// falla una parte posterior, los anteriores ya están en disco: la aplicación debe borrarlos
|
||||
/// con [`Upload::remove()`]. [`receive()`](Self::receive) ya lo hace.
|
||||
///
|
||||
/// El directorio del archivo (el de [`dir`](crate::global::UploadSettings::dir) más el
|
||||
/// subdirectorio de [`with_subdir()`](Self::with_subdir)) se crea si no existe. Si no se puede
|
||||
/// crear o no se puede escribir en él, devuelve [`UploadError::Io`] y deja constancia en el
|
||||
/// registro de trazas con la ruta afectada.
|
||||
pub async fn save(&self, mut field: Field<'_>) -> Result<Option<UploadedFile>, UploadError> {
|
||||
let field_name = field.name().unwrap_or_default().to_owned();
|
||||
let Some(file_name) = field.file_name() else {
|
||||
return Err(UploadError::NotAFile(field_name));
|
||||
};
|
||||
if !self.file_fields.is_empty() && !self.file_fields.contains(&field_name) {
|
||||
return Err(UploadError::UnexpectedField(field_name));
|
||||
}
|
||||
if file_name.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let original_name = sanitize_file_name(file_name);
|
||||
let extension = file_extension(&original_name);
|
||||
if !self.extensions.is_empty()
|
||||
&& !extension
|
||||
.as_ref()
|
||||
.is_some_and(|ext| self.extensions.contains(ext))
|
||||
{
|
||||
return Err(UploadError::ExtensionNotAllowed {
|
||||
file: original_name,
|
||||
allowed: self.extensions.clone(),
|
||||
});
|
||||
}
|
||||
let content_type = field.content_type().map(str::to_owned);
|
||||
|
||||
let subdir = checked_relative(self.subdir())?;
|
||||
let dir = upload_dir().join(&subdir);
|
||||
// `io::Error` no incluye la ruta, así que se registra aquí para que el operador sepa qué
|
||||
// directorio falla (permisos, disco lleno...).
|
||||
if let Err(err) = tokio::fs::create_dir_all(&dir).await {
|
||||
trace::error!("Cannot create upload directory `{}`: {err}", dir.display());
|
||||
return Err(err.into());
|
||||
}
|
||||
let limit = self
|
||||
.max_size()
|
||||
.unwrap_or(global::SETTINGS.upload.max_file_size);
|
||||
let buffer_size = match usize::try_from(limit) {
|
||||
Ok(limit) if limit > 0 => limit.min(WRITE_BUFFER_SIZE),
|
||||
_ => WRITE_BUFFER_SIZE,
|
||||
};
|
||||
let (stored_name, local, file) = create_unique(&dir, extension.as_deref())
|
||||
.await
|
||||
.inspect_err(|err| {
|
||||
trace::error!("Cannot create upload file in `{}`: {err}", dir.display());
|
||||
})?;
|
||||
let mut partial = PartialFile {
|
||||
local,
|
||||
file: Some(BufWriter::with_capacity(buffer_size, file)),
|
||||
};
|
||||
|
||||
let mut size: u64 = 0;
|
||||
while let Some(chunk) = field.chunk().await? {
|
||||
size += chunk.len() as u64;
|
||||
if limit > 0 && size > limit {
|
||||
return Err(UploadError::TooLarge {
|
||||
file: original_name,
|
||||
limit,
|
||||
});
|
||||
}
|
||||
partial.write_all(&chunk).await?;
|
||||
}
|
||||
partial.finish().await?;
|
||||
|
||||
let mut path = String::new();
|
||||
for part in subdir.iter() {
|
||||
path.push_str(&part.to_string_lossy());
|
||||
path.push('/');
|
||||
}
|
||||
path.push_str(&stored_name);
|
||||
Ok(Some(UploadedFile {
|
||||
field: field_name,
|
||||
path,
|
||||
original_name,
|
||||
content_type,
|
||||
size,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl Upload {
|
||||
// **< Upload BUILDER >*************************************************************************
|
||||
|
||||
/// Establece el subdirectorio, relativo al de archivos subidos, donde se guardan los archivos
|
||||
/// (p. ej. `"photos"` o `"docs/2026"`). Una cadena vacía los guarda en el directorio raíz.
|
||||
///
|
||||
/// No puede salir del directorio de archivos subidos: una ruta absoluta o con `..` hace que
|
||||
/// [`save()`](Self::save) devuelva [`UploadError::InvalidPath`].
|
||||
pub fn with_subdir(mut self, subdir: impl AsRef<str>) -> Self {
|
||||
self.subdir = subdir.as_ref().trim().to_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el tamaño máximo en bytes de cada archivo. Con *0* sólo limita
|
||||
/// [`max_body_size`](crate::global::ServerSettings::max_body_size); pasa `None` para usar el
|
||||
/// de la configuración ([`max_file_size`](crate::global::UploadSettings::max_file_size)).
|
||||
pub fn with_max_size(mut self, max_size: impl Into<Option<u64>>) -> Self {
|
||||
self.max_size = max_size.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece el número máximo de archivos que admite [`receive()`](Self::receive) en un mismo
|
||||
/// envío. Con *0* no se limita; pasa `None` para usar el de la configuración
|
||||
/// ([`max_files`](crate::global::UploadSettings::max_files)).
|
||||
pub fn with_max_files(mut self, max_files: impl Into<Option<usize>>) -> Self {
|
||||
self.max_files = max_files.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece las extensiones permitidas, sin el punto y en mayúsculas o minúsculas (p. ej.
|
||||
/// `["jpg", "png"]`). Una lista vacía admite cualquier extensión.
|
||||
///
|
||||
/// Se compara sólo la última extensión del nombre: un archivo `copia.tar.gz` tiene la extensión
|
||||
/// `gz`, y `informe.pdf.exe`, `exe`. Un archivo sin extensión, o con una que no sea sólo de
|
||||
/// letras y dígitos ASCII, se rechaza siempre que la lista no esté vacía.
|
||||
///
|
||||
/// Conviene restringirlas siempre: aunque [`Download`](crate::web::Download) descarga sin
|
||||
/// mostrarlos los tipos que el navegador podría ejecutar, como `.html` o `.svg`, otras formas
|
||||
/// de publicar los archivos no tienen esa protección.
|
||||
pub fn with_extensions(
|
||||
mut self,
|
||||
extensions: impl IntoIterator<Item = impl AsRef<str>>,
|
||||
) -> Self {
|
||||
self.extensions = extensions
|
||||
.into_iter()
|
||||
.map(|ext| {
|
||||
ext.as_ref()
|
||||
.trim()
|
||||
.trim_start_matches('.')
|
||||
.to_ascii_lowercase()
|
||||
})
|
||||
.filter(|ext| !ext.is_empty())
|
||||
.collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// Establece los nombres de los campos del formulario en los que se admiten archivos (p. ej.
|
||||
/// `["photo"]`). Una lista vacía los admite en cualquiera.
|
||||
///
|
||||
/// Un archivo en otro campo se rechaza con [`UploadError::UnexpectedField`]: un formulario
|
||||
/// legítimo nunca lo envía, y así no se guardan archivos que la aplicación no va a usar.
|
||||
pub fn with_file_fields(mut self, fields: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
|
||||
self.file_fields = fields
|
||||
.into_iter()
|
||||
.map(|field| field.as_ref().trim().to_owned())
|
||||
.filter(|field| !field.is_empty())
|
||||
.collect();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// **< Utilidades privadas >************************************************************************
|
||||
|
||||
fn upload_dir() -> PathBuf {
|
||||
PathBuf::from(&global::SETTINGS.upload.dir)
|
||||
}
|
||||
|
||||
// Acepta sólo componentes normales: ni raíz, ni prefijo de unidad, ni `..`; `.` se ignora.
|
||||
fn checked_relative(path: &str) -> Result<PathBuf, UploadError> {
|
||||
let mut relative = PathBuf::new();
|
||||
for component in Path::new(path).components() {
|
||||
match component {
|
||||
PathComponent::Normal(part) => relative.push(part),
|
||||
PathComponent::CurDir => {}
|
||||
_ => return Err(UploadError::InvalidPath(path.to_owned())),
|
||||
}
|
||||
}
|
||||
Ok(relative)
|
||||
}
|
||||
|
||||
// Quita los directorios (con `/` o `\`, según el sistema del navegador), los caracteres de control,
|
||||
// los de control bidireccional y los puntos y espacios de los extremos, que ocultan el archivo o
|
||||
// Windows descarta. Los bidireccionales invierten el texto al mostrarlo: `factura\u{202E}fdp.exe`
|
||||
// se vería como «facturaexe.pdf».
|
||||
pub(super) fn sanitize_file_name(name: &str) -> String {
|
||||
let base = name.rsplit(['/', '\\']).next().unwrap_or_default();
|
||||
let clean: String = base
|
||||
.chars()
|
||||
.filter(|c| !c.is_control() && !is_bidi_control(*c))
|
||||
.take(MAX_NAME_CHARS)
|
||||
.collect();
|
||||
let clean = clean.trim_matches(|c: char| c == '.' || c.is_whitespace());
|
||||
if clean.is_empty() {
|
||||
"file".to_owned()
|
||||
} else {
|
||||
clean.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn is_bidi_control(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
|
||||
)
|
||||
}
|
||||
|
||||
// Extensión en minúsculas, si es corta y sólo tiene letras y dígitos ASCII; si no, ninguna, para
|
||||
// que el nombre guardado no lleve nada que el navegador o el sistema puedan interpretar.
|
||||
fn file_extension(name: &str) -> Option<String> {
|
||||
let (stem, ext) = name.rsplit_once('.')?;
|
||||
let valid = !stem.is_empty()
|
||||
&& !ext.is_empty()
|
||||
&& ext.len() <= MAX_EXTENSION_CHARS
|
||||
&& ext.chars().all(|c| c.is_ascii_alphanumeric());
|
||||
valid.then(|| ext.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
// Codifica como `%XX` todos los bytes salvo los no reservados de RFC 3986, igual que un navegador
|
||||
// codifica los campos de un formulario; vale también para `filename*` de `Content-Disposition`.
|
||||
pub(super) fn push_percent_encoded(out: &mut String, value: impl AsRef<[u8]>) {
|
||||
const HEX: &[u8; 16] = b"0123456789ABCDEF";
|
||||
for &byte in value.as_ref() {
|
||||
match byte {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(byte as char);
|
||||
}
|
||||
_ => {
|
||||
out.push('%');
|
||||
out.push(HEX[usize::from(byte >> 4)] as char);
|
||||
out.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tamaño legible para los mensajes: en MiB si es un múltiplo exacto y, si no, en KiB redondeados
|
||||
// hacia abajo, para no anunciar nunca un límite mayor que el real.
|
||||
fn format_size(bytes: u64) -> String {
|
||||
const KIB: u64 = 1024;
|
||||
const MIB: u64 = 1024 * KIB;
|
||||
if bytes >= MIB && bytes.is_multiple_of(MIB) {
|
||||
util::join!((bytes / MIB).to_string(), " MiB")
|
||||
} else if bytes >= KIB {
|
||||
util::join!((bytes / KIB).to_string(), " KiB")
|
||||
} else {
|
||||
util::join!(bytes.to_string(), " B")
|
||||
}
|
||||
}
|
||||
|
||||
// Nombre aleatorio de 16 cifras hexadecimales. `RandomState` toma sus claves de la aleatoriedad del
|
||||
// sistema, así que los nombres no se pueden deducir aunque se conozcan la hora y el contador.
|
||||
fn random_name() -> String {
|
||||
use std::hash::{BuildHasher, Hasher, RandomState};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let mut hasher = RandomState::new().build_hasher();
|
||||
hasher.write_u128(
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
|
||||
format!("{:016x}", hasher.finish())
|
||||
}
|
||||
|
||||
// Crea el archivo con un nombre que no exista ya (`create_new`), sin sobrescribir nunca otro.
|
||||
async fn create_unique(
|
||||
dir: &Path,
|
||||
extension: Option<&str>,
|
||||
) -> Result<(String, PathBuf, tokio::fs::File), UploadError> {
|
||||
let mut last_err = None;
|
||||
for _ in 0..NAME_ATTEMPTS {
|
||||
let name = match extension {
|
||||
Some(ext) => util::join!(random_name(), ".", ext),
|
||||
None => random_name(),
|
||||
};
|
||||
let local = dir.join(&name);
|
||||
match tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&local)
|
||||
.await
|
||||
{
|
||||
Ok(file) => return Ok((name, local, file)),
|
||||
Err(err) if err.kind() == ErrorKind::AlreadyExists => last_err = Some(err),
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
Err(last_err
|
||||
.unwrap_or_else(|| ErrorKind::AlreadyExists.into())
|
||||
.into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
MAX_NAME_CHARS, PartialFile, checked_relative, file_extension, format_size,
|
||||
push_percent_encoded, random_name, sanitize_file_name,
|
||||
};
|
||||
use std::path::Path;
|
||||
use tokio::io::BufWriter;
|
||||
|
||||
async fn partial_file() -> PartialFile {
|
||||
let local = std::env::temp_dir().join(random_name());
|
||||
let file = tokio::fs::File::create(&local).await.unwrap();
|
||||
PartialFile {
|
||||
local,
|
||||
file: Some(BufWriter::new(file)),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_file_is_removed_unless_finished() {
|
||||
let mut discarded = partial_file().await;
|
||||
discarded.write_all(b"half").await.unwrap();
|
||||
let local = discarded.local.clone();
|
||||
drop(discarded);
|
||||
assert!(!local.exists());
|
||||
|
||||
let mut finished = partial_file().await;
|
||||
finished.write_all(b"whole").await.unwrap();
|
||||
finished.finish().await.unwrap();
|
||||
let local = finished.local.clone();
|
||||
drop(finished);
|
||||
assert_eq!(std::fs::read(&local).unwrap(), b"whole");
|
||||
std::fs::remove_file(local).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_removes_directories_and_control_chars() {
|
||||
assert_eq!(sanitize_file_name("../../etc/passwd"), "passwd");
|
||||
assert_eq!(sanitize_file_name(r"C:\Users\me\photo.JPG"), "photo.JPG");
|
||||
assert_eq!(sanitize_file_name("re\u{0}port\n.pdf"), "report.pdf");
|
||||
assert_eq!(sanitize_file_name(" .hidden. "), "hidden");
|
||||
assert_eq!(sanitize_file_name("../"), "file");
|
||||
assert_eq!(
|
||||
sanitize_file_name("invoice\u{202E}fdp.exe"),
|
||||
"invoicefdp.exe"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_limits_the_name_length() {
|
||||
let long = "a".repeat(MAX_NAME_CHARS + 50);
|
||||
assert_eq!(sanitize_file_name(&long).chars().count(), MAX_NAME_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_is_lowercase_and_alphanumeric() {
|
||||
assert_eq!(file_extension("photo.JPG").as_deref(), Some("jpg"));
|
||||
assert_eq!(file_extension("archive.tar.gz").as_deref(), Some("gz"));
|
||||
assert_eq!(file_extension("noext"), None);
|
||||
assert_eq!(file_extension("bad.ex-t"), None);
|
||||
assert_eq!(file_extension("file.verylongextensionname"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_paths_cannot_escape_the_upload_dir() {
|
||||
assert_eq!(
|
||||
checked_relative("photos/2026").unwrap(),
|
||||
Path::new("photos/2026")
|
||||
);
|
||||
assert_eq!(checked_relative("./photos").unwrap(), Path::new("photos"));
|
||||
assert!(checked_relative("../secret").is_err());
|
||||
assert!(checked_relative("photos/../../secret").is_err());
|
||||
assert!(checked_relative("/etc").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_names_differ() {
|
||||
assert_ne!(random_name(), random_name());
|
||||
assert_eq!(random_name().len(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percent_encoding_keeps_only_unreserved_bytes() {
|
||||
let mut out = String::new();
|
||||
push_percent_encoded(&mut out, "tags[]=a b&ñ~._-");
|
||||
assert_eq!(out, "tags%5B%5D%3Da%20b%26%C3%B1~._-");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_never_overstate_the_limit() {
|
||||
assert_eq!(format_size(8 * 1024 * 1024), "8 MiB");
|
||||
assert_eq!(format_size(1_500_000), "1464 KiB");
|
||||
assert_eq!(format_size(2048), "2 KiB");
|
||||
assert_eq!(format_size(500), "500 B");
|
||||
}
|
||||
}
|
||||
71
tests/component_form_file.rs
Normal file
71
tests/component_form_file.rs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
#[pagetop::test]
|
||||
async fn file_field_renders_a_file_input() {
|
||||
let mut field = form::File::new().with_name("photo");
|
||||
let html = field.render(&mut Context::default()).await.into_string();
|
||||
|
||||
assert!(html.contains(r#"class="form-field form-field-file""#));
|
||||
assert!(html.contains(r#"id="edit-photo""#));
|
||||
assert!(html.contains(r#"type="file""#));
|
||||
assert!(html.contains(r#"id="edit-photo-file""#));
|
||||
assert!(html.contains(r#"name="photo""#));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn file_field_optional_attributes_are_absent_by_default() {
|
||||
let mut field = form::File::new().with_name("photo");
|
||||
let html = field.render(&mut Context::default()).await.into_string();
|
||||
|
||||
assert!(!html.contains("accept="));
|
||||
assert!(!html.contains("multiple"));
|
||||
assert!(!html.contains("required"));
|
||||
assert!(!html.contains("disabled"));
|
||||
assert!(!html.contains(r#"class="form-label""#));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn file_field_renders_accept_multiple_and_required() {
|
||||
let mut field = form::File::new()
|
||||
.with_name("docs")
|
||||
.with_label(Lc::n("Documents"))
|
||||
.with_accept(".pdf,image/*")
|
||||
.with_multiple(true)
|
||||
.with_required(true);
|
||||
let html = field.render(&mut Context::default()).await.into_string();
|
||||
|
||||
assert!(html.contains(r#"accept=".pdf,image/*""#));
|
||||
assert!(html.contains("multiple"));
|
||||
assert!(html.contains("required"));
|
||||
assert!(html.contains(r#"for="edit-docs-file""#));
|
||||
assert!(html.contains("Documents"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn file_field_empty_accept_removes_the_attribute() {
|
||||
let mut field = form::File::new()
|
||||
.with_name("photo")
|
||||
.with_accept("image/*")
|
||||
.with_accept("");
|
||||
let html = field.render(&mut Context::default()).await.into_string();
|
||||
|
||||
assert!(!html.contains("accept="));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn form_enctype_is_omitted_by_default() {
|
||||
let mut form = Form::new().with_action("/send");
|
||||
let html = form.render(&mut Context::default()).await.into_string();
|
||||
|
||||
assert!(!html.contains("enctype="));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn form_multipart_enctype_is_rendered() {
|
||||
let mut form = Form::new()
|
||||
.with_action("/send")
|
||||
.with_enctype(form::Enctype::Multipart);
|
||||
let html = form.render(&mut Context::default()).await.into_string();
|
||||
|
||||
assert!(html.contains(r#"enctype="multipart/form-data""#));
|
||||
}
|
||||
557
tests/web_upload.rs
Normal file
557
tests/web_upload.rs
Normal file
|
|
@ -0,0 +1,557 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use std::fs;
|
||||
|
||||
// `web::Upload` saves the files of a `multipart/form-data` body under `upload.dir` (set to
|
||||
// `target/test-uploads` in `config/test.toml`). Each test uses its own subdirectory, so they can
|
||||
// run in parallel.
|
||||
|
||||
const BOUNDARY: &str = "pagetop-test-boundary";
|
||||
|
||||
async fn save_all(upload: web::Upload, mut multipart: web::Multipart) -> String {
|
||||
let mut out = String::new();
|
||||
while let Some(field) = multipart.next_field().await.unwrap() {
|
||||
match upload.save(field).await {
|
||||
Ok(Some(file)) => out.push_str(&format!(
|
||||
"saved {} {} {} {};",
|
||||
file.path(),
|
||||
file.original_name(),
|
||||
file.size(),
|
||||
file.content_type().map(String::as_str).unwrap_or("-"),
|
||||
)),
|
||||
Ok(None) => out.push_str("none;"),
|
||||
Err(web::UploadError::NotAFile(name)) => out.push_str(&format!("not-a-file {name};")),
|
||||
Err(web::UploadError::TooLarge { file, limit }) => {
|
||||
out.push_str(&format!("too-large {file} {limit};"))
|
||||
}
|
||||
Err(web::UploadError::ExtensionNotAllowed { file, allowed }) => {
|
||||
out.push_str(&format!("extension {file} {};", allowed.join(",")))
|
||||
}
|
||||
Err(err) => out.push_str(&format!("error {err};")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct Note {
|
||||
title: String,
|
||||
#[serde(default)]
|
||||
tags: Vec<String>,
|
||||
}
|
||||
|
||||
// Receives a note into `subdir`; files are kept unless the title is "discard".
|
||||
async fn receive_note(subdir: String, multipart: web::Multipart) -> String {
|
||||
let upload = web::Upload::new()
|
||||
.with_subdir(subdir)
|
||||
.with_extensions(["txt"])
|
||||
.with_file_fields(["doc", "extra"])
|
||||
.with_max_files(2);
|
||||
match upload.receive::<Note>(multipart).await {
|
||||
Ok(sent) => {
|
||||
let mut out = format!(
|
||||
"title={};tags={};",
|
||||
sent.form().title,
|
||||
sent.form().tags.join(",")
|
||||
);
|
||||
for file in sent.files() {
|
||||
out.push_str(&format!("{}={};", file.field(), file.path()));
|
||||
}
|
||||
if sent.form().title != "discard" {
|
||||
sent.keep();
|
||||
}
|
||||
out
|
||||
}
|
||||
Err(err) => format!("error {err:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(request: HttpRequest, download: web::Download) -> Response {
|
||||
match download.serve(&request).await {
|
||||
Ok(response) => response,
|
||||
Err(web::UploadError::NotFound(_)) => web::http::StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => web::http::StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
struct Uploads;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Uploads {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route(
|
||||
"/plain",
|
||||
web::post(|multipart: web::Multipart| {
|
||||
save_all(web::Upload::new().with_subdir("plain"), multipart)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/images",
|
||||
web::post(|multipart: web::Multipart| {
|
||||
let upload = web::Upload::new()
|
||||
.with_subdir("images")
|
||||
.with_extensions([".JPG", "png"]);
|
||||
save_all(upload, multipart)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/small",
|
||||
web::post(|multipart: web::Multipart| {
|
||||
let upload = web::Upload::new().with_subdir("small").with_max_size(4);
|
||||
save_all(upload, multipart)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/escape",
|
||||
web::post(|multipart: web::Multipart| {
|
||||
save_all(web::Upload::new().with_subdir("../escape"), multipart)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/receive/{subdir}",
|
||||
web::post(
|
||||
|web::Path(subdir): web::Path<String>, multipart: web::Multipart| {
|
||||
receive_note(subdir, multipart)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/form",
|
||||
web::post(
|
||||
|web::Form(form): web::Form<Vec<(String, String)>>| async move {
|
||||
form.len().to_string()
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/files/{*path}",
|
||||
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
||||
serve(request, web::Download::new(path))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/named/{*path}",
|
||||
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
||||
serve(
|
||||
request,
|
||||
web::Download::new(path).with_file_name("Plan ñ.txt"),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/attach/{*path}",
|
||||
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
||||
serve(request, web::Download::new(path).with_attachment(true))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Builds a multipart body; a part with a file name is a file, one without is a text field.
|
||||
fn multipart_body(parts: &[(&str, Option<&str>, &str)]) -> String {
|
||||
let mut body = String::new();
|
||||
for (name, file_name, content) in parts {
|
||||
body.push_str(&format!("--{BOUNDARY}\r\n"));
|
||||
match file_name {
|
||||
Some(file_name) => body.push_str(&format!(
|
||||
"Content-Disposition: form-data; name=\"{name}\"; filename=\"{file_name}\"\r\n\
|
||||
Content-Type: text/plain\r\n\r\n"
|
||||
)),
|
||||
None => body.push_str(&format!(
|
||||
"Content-Disposition: form-data; name=\"{name}\"\r\n\r\n"
|
||||
)),
|
||||
}
|
||||
body.push_str(content);
|
||||
body.push_str("\r\n");
|
||||
}
|
||||
body.push_str(&format!("--{BOUNDARY}--\r\n"));
|
||||
body
|
||||
}
|
||||
|
||||
async fn router() -> Router {
|
||||
web::test::init_router(Application::prepare(&Uploads).await.test())
|
||||
}
|
||||
|
||||
async fn post(route: &str, content_type: &str, body: String) -> Response {
|
||||
let request = web::test::TestRequest::post()
|
||||
.uri(route)
|
||||
.header("content-type", content_type)
|
||||
.body(body)
|
||||
.to_request();
|
||||
web::test::send_request(&router().await, request).await
|
||||
}
|
||||
|
||||
async fn send(route: &str, parts: &[(&str, Option<&str>, &str)]) -> String {
|
||||
let content_type = format!("multipart/form-data; boundary={BOUNDARY}");
|
||||
let response = post(route, &content_type, multipart_body(parts)).await;
|
||||
assert_eq!(response.status(), web::http::StatusCode::OK);
|
||||
web::test::read_body_text(response).await
|
||||
}
|
||||
|
||||
async fn get(route: &str, headers: &[(&str, &str)]) -> Response {
|
||||
let mut request = web::test::TestRequest::get().uri(route);
|
||||
for (name, value) in headers {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
web::test::send_request(&router().await, request.to_request()).await
|
||||
}
|
||||
|
||||
fn header<'a>(response: &'a Response, name: &str) -> &'a str {
|
||||
response
|
||||
.headers()
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// Writes a file straight into the upload dir, as if it had been uploaded before.
|
||||
fn stored(path: &str, content: &str) {
|
||||
let local = web::Upload::local_path(path).unwrap();
|
||||
fs::create_dir_all(local.parent().unwrap()).unwrap();
|
||||
fs::write(local, content).unwrap();
|
||||
}
|
||||
|
||||
// A missing subdir counts as empty: rejected uploads may never create it.
|
||||
fn is_empty_dir(subdir: &str) -> bool {
|
||||
fs::read_dir(web::Upload::local_path(subdir).unwrap()).map_or(true, |dir| dir.count() == 0)
|
||||
}
|
||||
|
||||
fn stored_path(result: &str) -> &str {
|
||||
result
|
||||
.strip_prefix("saved ")
|
||||
.and_then(|rest| rest.split(' ').next())
|
||||
.unwrap_or_else(|| panic!("file not saved: {result}"))
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn file_is_saved_with_a_random_name_and_its_extension() {
|
||||
let result = send("/plain", &[("doc", Some("../My Notes.TXT"), "hello")]).await;
|
||||
|
||||
let path = stored_path(&result);
|
||||
assert!(path.starts_with("plain/"), "{result}");
|
||||
assert!(path.ends_with(".txt"), "{result}");
|
||||
assert!(!path.contains("Notes"), "{result}");
|
||||
assert!(result.ends_with(" My Notes.TXT 5 text/plain;"), "{result}");
|
||||
|
||||
let local = web::Upload::local_path(path).unwrap();
|
||||
assert_eq!(fs::read_to_string(local).unwrap(), "hello");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn same_file_name_never_overwrites() {
|
||||
let first = send("/plain", &[("doc", Some("same.txt"), "one")]).await;
|
||||
let second = send("/plain", &[("doc", Some("same.txt"), "two")]).await;
|
||||
|
||||
assert_ne!(stored_path(&first), stored_path(&second));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn empty_file_field_is_none_and_text_field_is_not_a_file() {
|
||||
let result = send(
|
||||
"/plain",
|
||||
&[("doc", Some(""), ""), ("title", None, "Lettuce")],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(result, "none;not-a-file title;");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn only_allowed_extensions_are_saved() {
|
||||
let result = send(
|
||||
"/images",
|
||||
&[
|
||||
("photo", Some("garden.jpg"), "jpg"),
|
||||
("photo", Some("page.html"), "<b>x</b>"),
|
||||
("photo", Some("noext"), "x"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut parts = result.split(';');
|
||||
assert!(
|
||||
parts.next().unwrap().starts_with("saved images/"),
|
||||
"{result}"
|
||||
);
|
||||
assert_eq!(
|
||||
parts.next(),
|
||||
Some("extension page.html jpg,png"),
|
||||
"{result}"
|
||||
);
|
||||
assert_eq!(parts.next(), Some("extension noext jpg,png"), "{result}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn too_large_file_is_rejected_and_removed() {
|
||||
let result = send("/small", &[("doc", Some("big.txt"), "too large")]).await;
|
||||
|
||||
assert_eq!(result, "too-large big.txt 4;");
|
||||
assert!(is_empty_dir("small"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn subdir_cannot_escape_the_upload_dir() {
|
||||
let result = send("/escape", &[("doc", Some("a.txt"), "x")]).await;
|
||||
|
||||
assert!(result.starts_with("error invalid upload path"), "{result}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn unwritable_upload_dir_is_a_server_error() {
|
||||
// A regular file where the subdirectory should be makes `create_dir_all` fail.
|
||||
let blocked = web::Upload::local_path("blocked").unwrap();
|
||||
fs::create_dir_all(blocked.parent().unwrap()).unwrap();
|
||||
fs::write(&blocked, "not a directory").unwrap();
|
||||
|
||||
let result = send("/receive/blocked", &[("doc", Some("a.txt"), "x")]).await;
|
||||
|
||||
assert!(result.starts_with("error Io("), "{result}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn remove_deletes_a_saved_file_and_ignores_missing_ones() {
|
||||
let result = send("/plain", &[("doc", Some("temp.txt"), "bye")]).await;
|
||||
let path = stored_path(&result);
|
||||
|
||||
web::Upload::remove(path).await.unwrap();
|
||||
assert!(!web::Upload::local_path(path).unwrap().exists());
|
||||
web::Upload::remove(path).await.unwrap();
|
||||
assert!(matches!(
|
||||
web::Upload::remove("../config/test.toml").await,
|
||||
Err(web::UploadError::InvalidPath(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn local_path_rejects_paths_outside_the_upload_dir() {
|
||||
assert!(web::Upload::local_path("photos/a.jpg").is_ok());
|
||||
assert!(matches!(
|
||||
web::Upload::local_path("../config/test.toml"),
|
||||
Err(web::UploadError::InvalidPath(_))
|
||||
));
|
||||
assert!(web::Upload::local_path("/etc/passwd").is_err());
|
||||
assert!(web::Upload::local_path("").is_err());
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn receive_deserializes_text_fields_and_keeps_the_files() {
|
||||
let result = send(
|
||||
"/receive/receive-keep",
|
||||
&[
|
||||
("title", None, "Lettuce"),
|
||||
("tags", None, "green"),
|
||||
("doc", Some("notes.txt"), "water daily"),
|
||||
("tags", None, "leafy"),
|
||||
("extra", Some(""), ""),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
result.starts_with("title=Lettuce;tags=green,leafy;doc=receive-keep/"),
|
||||
"{result}"
|
||||
);
|
||||
assert_eq!(result.matches(';').count(), 3, "{result}");
|
||||
let path = result.split("doc=").nth(1).unwrap().trim_end_matches(';');
|
||||
assert!(web::Upload::local_path(path).unwrap().exists(), "{result}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn receive_removes_the_files_when_not_kept() {
|
||||
let result = send(
|
||||
"/receive/receive-discard",
|
||||
&[
|
||||
("title", None, "discard"),
|
||||
("doc", Some("notes.txt"), "draft"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.contains("doc=receive-discard/"), "{result}");
|
||||
assert!(is_empty_dir("receive-discard"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn receive_removes_the_saved_files_when_a_later_part_fails() {
|
||||
let result = send(
|
||||
"/receive/receive-error",
|
||||
&[
|
||||
("title", None, "Lettuce"),
|
||||
("doc", Some("notes.txt"), "ok"),
|
||||
("extra", Some("page.html"), "<b>x</b>"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.starts_with("error ExtensionNotAllowed"), "{result}");
|
||||
assert!(is_empty_dir("receive-error"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn receive_limits_the_number_of_files() {
|
||||
let result = send(
|
||||
"/receive/receive-many",
|
||||
&[
|
||||
("title", None, "Lettuce"),
|
||||
("doc", Some("a.txt"), "a"),
|
||||
("doc", Some("b.txt"), "b"),
|
||||
("doc", Some("c.txt"), "c"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(result, "error TooManyFiles { limit: 2 }");
|
||||
assert!(is_empty_dir("receive-many"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn receive_rejects_files_in_unexpected_fields() {
|
||||
let result = send(
|
||||
"/receive/receive-unexpected",
|
||||
&[("title", None, "Lettuce"), ("other", Some("a.txt"), "a")],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(result, "error UnexpectedField(\"other\")");
|
||||
assert!(is_empty_dir("receive-unexpected"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn receive_rejects_missing_text_fields() {
|
||||
let result = send(
|
||||
"/receive/receive-invalid",
|
||||
&[("doc", Some("notes.txt"), "no title")],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.starts_with("error InvalidForm"), "{result}");
|
||||
assert!(is_empty_dir("receive-invalid"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn download_shows_plain_text_inline_with_safe_headers() {
|
||||
stored("download/notes.txt", "hello world");
|
||||
let response = get("/named/download/notes.txt", &[]).await;
|
||||
|
||||
assert_eq!(response.status(), web::http::StatusCode::OK);
|
||||
assert!(header(&response, "content-type").starts_with("text/plain"));
|
||||
assert_eq!(
|
||||
header(&response, "content-disposition"),
|
||||
"inline; filename=\"Plan _.txt\"; filename*=UTF-8''Plan%20%C3%B1.txt"
|
||||
);
|
||||
assert_eq!(header(&response, "x-content-type-options"), "nosniff");
|
||||
assert_eq!(header(&response, "cache-control"), "private, no-cache");
|
||||
assert_eq!(web::test::read_body_text(response).await, "hello world");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn download_never_shows_active_content_inline() {
|
||||
stored("download/page.html", "<script>alert(1)</script>");
|
||||
let response = get("/files/download/page.html", &[]).await;
|
||||
|
||||
assert_eq!(response.status(), web::http::StatusCode::OK);
|
||||
assert!(
|
||||
header(&response, "content-disposition").starts_with("attachment; filename=\"page.html\""),
|
||||
"{}",
|
||||
header(&response, "content-disposition")
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn multipart_requests_have_a_larger_body_limit() {
|
||||
// 3 MiB: over `server.max_body_size` (2 MiB), under `upload.max_request_size` (32 MiB).
|
||||
let big = "a".repeat(3 * 1024 * 1024);
|
||||
|
||||
let form = post(
|
||||
"/form",
|
||||
"application/x-www-form-urlencoded",
|
||||
format!("big={big}"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(form.status(), web::http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||
|
||||
let result = send("/plain", &[("doc", Some("big.txt"), &big)]).await;
|
||||
assert!(stored_path(&result).starts_with("plain/"), "{result}");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn receive_limits_the_size_of_the_text_fields() {
|
||||
let big = "a".repeat(3 * 1024 * 1024);
|
||||
let result = send(
|
||||
"/receive/fields-limit",
|
||||
&[("doc", Some("a.txt"), "a"), ("title", None, &big)],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.starts_with("error FieldsTooLarge"), "{result}");
|
||||
assert!(is_empty_dir("fields-limit"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn download_answers_conditional_requests() {
|
||||
stored("download/etag.txt", "hello");
|
||||
let response = get("/files/download/etag.txt", &[]).await;
|
||||
let etag = header(&response, "etag").to_owned();
|
||||
assert!(!etag.is_empty());
|
||||
|
||||
let again = get("/files/download/etag.txt", &[("if-none-match", &etag)]).await;
|
||||
assert_eq!(again.status(), web::http::StatusCode::NOT_MODIFIED);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn download_can_force_an_attachment() {
|
||||
stored("download/forced.txt", "hello");
|
||||
let response = get("/attach/download/forced.txt", &[]).await;
|
||||
|
||||
assert!(header(&response, "content-disposition").starts_with("attachment;"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn download_supports_range_requests() {
|
||||
stored("download/range.txt", "hello world");
|
||||
let response = get("/files/download/range.txt", &[("range", "bytes=0-4")]).await;
|
||||
|
||||
assert_eq!(response.status(), web::http::StatusCode::PARTIAL_CONTENT);
|
||||
assert_eq!(web::test::read_body_text(response).await, "hello");
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn download_of_a_missing_or_escaping_path_fails() {
|
||||
let missing = get("/files/download/missing.txt", &[]).await;
|
||||
assert_eq!(missing.status(), web::http::StatusCode::NOT_FOUND);
|
||||
|
||||
let escaping = get("/files/..%2Fconfig%2Ftest.toml", &[]).await;
|
||||
assert_eq!(
|
||||
escaping.status(),
|
||||
web::http::StatusCode::INTERNAL_SERVER_ERROR
|
||||
);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn upload_errors_have_translated_messages() {
|
||||
let too_large = web::UploadError::TooLarge {
|
||||
file: "plan.txt".to_owned(),
|
||||
limit: 8 * 1024 * 1024,
|
||||
};
|
||||
let text = too_large
|
||||
.message()
|
||||
.lookup(&Locale::resolve("en-US"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
text.contains("plan.txt") && text.contains("8 MiB"),
|
||||
"{text}"
|
||||
);
|
||||
|
||||
let one_file = web::UploadError::TooManyFiles { limit: 1 };
|
||||
let text = one_file
|
||||
.message()
|
||||
.lookup(&Locale::resolve("es-ES"))
|
||||
.unwrap();
|
||||
assert!(text.contains("un archivo"), "{text}");
|
||||
|
||||
let io = web::UploadError::Io(std::io::ErrorKind::PermissionDenied.into());
|
||||
assert!(!io.is_client_error());
|
||||
let text = io.message().lookup(&Locale::resolve("en-US")).unwrap();
|
||||
assert!(!text.contains("denied"), "{text}");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue