Compare commits
No commits in common. "1df91ce4c8ce76c4c3bf9d50a605728e0e22935e" and "67118caef728e800ddd5d7f41ea2e50eb4f21826" have entirely different histories.
1df91ce4c8
...
67118caef7
32 changed files with 57 additions and 2670 deletions
28
Cargo.lock
generated
28
Cargo.lock
generated
|
|
@ -350,7 +350,6 @@ dependencies = [
|
||||||
"matchit",
|
"matchit",
|
||||||
"memchr",
|
"memchr",
|
||||||
"mime",
|
"mime",
|
||||||
"multer",
|
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"serde_core",
|
"serde_core",
|
||||||
|
|
@ -913,15 +912,6 @@ version = "0.2.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
|
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]]
|
[[package]]
|
||||||
name = "equivalent"
|
name = "equivalent"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
|
|
@ -1961,23 +1951,6 @@ dependencies = [
|
||||||
"windows-sys 0.61.2",
|
"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]]
|
[[package]]
|
||||||
name = "native-tls"
|
name = "native-tls"
|
||||||
version = "0.2.18"
|
version = "0.2.18"
|
||||||
|
|
@ -2177,7 +2150,6 @@ dependencies = [
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_qs",
|
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"terminal_size",
|
"terminal_size",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
|
|
||||||
|
|
@ -121,7 +121,7 @@ testing = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait.workspace = true
|
async-trait.workspace = true
|
||||||
axum = { workspace = true, features = ["multipart"] }
|
axum.workspace = true
|
||||||
chrono.workspace = true
|
chrono.workspace = true
|
||||||
chrono-tz.workspace = true
|
chrono-tz.workspace = true
|
||||||
colored.workspace = true
|
colored.workspace = true
|
||||||
|
|
@ -136,7 +136,6 @@ pagetop-macros.workspace = true
|
||||||
pagetop-minimal.workspace = true
|
pagetop-minimal.workspace = true
|
||||||
pagetop-statics.workspace = true
|
pagetop-statics.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_qs.workspace = true
|
|
||||||
terminal_size.workspace = true
|
terminal_size.workspace = true
|
||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
|
|
|
||||||
|
|
@ -12,13 +12,8 @@
|
||||||
#
|
#
|
||||||
# Donde {rm} es el valor de la variable de entorno PAGETOP_RUN_MODE ("default" si no se define o
|
# Donde {rm} es el valor de la variable de entorno PAGETOP_RUN_MODE ("default" si no se define o
|
||||||
# está vacía). El directorio config/ puede cambiarse con la variable de entorno CONFIG_DIR (vacía
|
# está vacía). El directorio config/ puede cambiarse con la variable de entorno CONFIG_DIR (vacía
|
||||||
# equivale a no definirla).
|
# equivale a no definirla). No hay más variables de entorno: el resto de opciones sólo se leen de
|
||||||
#
|
# estos ficheros.
|
||||||
# Por último, las variables de entorno con el prefijo PAGETOP_ sobrescriben cualquier opción de los
|
|
||||||
# ficheros: sección y clave en mayúsculas, con cada nivel separado por dos guiones bajos (p. ej.
|
|
||||||
# PAGETOP_DATABASE__DB_PASS para db_pass de [database], o PAGETOP_MAIL__SMTP__PASSWORD para password
|
|
||||||
# de [mail.smtp]). Una variable vacía equivale a no definirla. No sirven para listas ni para claves
|
|
||||||
# con punto, como "mail.queue" en [cron.jobs."mail.queue"].
|
|
||||||
#
|
#
|
||||||
# Las opciones comentadas no tienen valor por defecto; se muestran con un valor de ejemplo.
|
# Las opciones comentadas no tienen valor por defecto; se muestran con un valor de ejemplo.
|
||||||
#
|
#
|
||||||
|
|
@ -103,25 +98,6 @@ format = "Full" # Formato: "Full", "Compact", "Pretty" o
|
||||||
[server]
|
[server]
|
||||||
bind_address = "localhost" # Dirección de enlace del servidor web.
|
bind_address = "localhost" # Dirección de enlace del servidor web.
|
||||||
bind_port = 8080 # Puerto de escucha 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 >******************************************************************************
|
# **< pagetop-seaorm >******************************************************************************
|
||||||
|
|
@ -298,10 +274,6 @@ failed_login_window_secs = 900 # Segundos desde el último fallo en los
|
||||||
locked_for_secs = 600 # Duración del bloqueo de la cuenta en segundos (10 minutos).
|
locked_for_secs = 600 # Duración del bloqueo de la cuenta en segundos (10 minutos).
|
||||||
# Después se dispone otra vez de todos los intentos.
|
# Después se dispone otra vez de todos los intentos.
|
||||||
|
|
||||||
max_password_resets = 3 # Solicitudes de recuperación de contraseña por cuenta en la
|
|
||||||
# ventana; las siguientes no envían correo. 0 -> sin límite.
|
|
||||||
password_reset_window_secs = 3600 # Segundos en los que se cuentan las solicitudes (1 hora).
|
|
||||||
|
|
||||||
login_strict = false # Dificulta que el navegador recuerde o autorrellene las
|
login_strict = false # Dificulta que el navegador recuerde o autorrellene las
|
||||||
# credenciales en el formulario de acceso.
|
# credenciales en el formulario de acceso.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,6 @@ name = "Testing"
|
||||||
[server]
|
[server]
|
||||||
bind_port = 9000
|
bind_port = 9000
|
||||||
|
|
||||||
[upload]
|
|
||||||
dir = "target/test-uploads"
|
|
||||||
|
|
||||||
[test]
|
[test]
|
||||||
string_value = "Modified value"
|
string_value = "Modified value"
|
||||||
float_value = 8.7654
|
float_value = 8.7654
|
||||||
|
|
|
||||||
|
|
@ -166,8 +166,6 @@ async fn form_controls(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
.with_id("form-text")
|
.with_id("form-text")
|
||||||
.with_action("/")
|
.with_action("/")
|
||||||
.with_method(form::Method::Post)
|
.with_method(form::Method::Post)
|
||||||
// Necesaria para enviar los archivos de form::File.
|
|
||||||
.with_enctype(form::Enctype::Multipart)
|
|
||||||
// Campos de texto (form::input::Field).
|
// Campos de texto (form::input::Field).
|
||||||
.with_child(
|
.with_child(
|
||||||
form::Fieldset::new()
|
form::Fieldset::new()
|
||||||
|
|
@ -253,26 +251,6 @@ async fn form_controls(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
.with_help_text(Lc::t("help_rating", &LOC)),
|
.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).
|
// Campo oculto (form::Hidden).
|
||||||
.with_child(form::Hidden::field("origin", "form-text"))
|
.with_child(form::Hidden::field("origin", "form-text"))
|
||||||
// Botonera de acciones.
|
// Botonera de acciones.
|
||||||
|
|
|
||||||
|
|
@ -73,12 +73,6 @@ fieldset_range = Slider
|
||||||
label_rating = Overall rating
|
label_rating = Overall rating
|
||||||
help_rating = From 1 (very poor) to 10 (excellent).
|
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_submit = Submit
|
||||||
btn_reset = Reset
|
btn_reset = Reset
|
||||||
btn_cancel = Cancel
|
btn_cancel = Cancel
|
||||||
|
|
|
||||||
|
|
@ -73,12 +73,6 @@ fieldset_range = Control deslizante
|
||||||
label_rating = Valoración general
|
label_rating = Valoración general
|
||||||
help_rating = De 1 (muy malo) a 10 (excelente).
|
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_submit = Enviar
|
||||||
btn_reset = Restablecer
|
btn_reset = Restablecer
|
||||||
btn_cancel = Cancelar
|
btn_cancel = Cancelar
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
//! Definiciones para crear formularios ([`Form`]).
|
//! Definiciones para crear formularios ([`Form`]).
|
||||||
|
|
||||||
pub use pagetop::base::component::form::{
|
pub use pagetop::base::component::form::{Autocomplete, AutofillField, CheckboxKind, Method};
|
||||||
Autocomplete, AutofillField, CheckboxKind, Enctype, Method,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub use pagetop::base::component::form::Form;
|
pub use pagetop::base::component::form::Form;
|
||||||
|
|
||||||
|
|
@ -39,6 +37,4 @@ pub use pagetop::base::component::form::Number;
|
||||||
|
|
||||||
pub use pagetop::base::component::form::Range;
|
pub use pagetop::base::component::form::Range;
|
||||||
|
|
||||||
pub use pagetop::base::component::form::File;
|
|
||||||
|
|
||||||
pub use pagetop::base::component::form::Hidden;
|
pub use pagetop::base::component::form::Hidden;
|
||||||
|
|
|
||||||
|
|
@ -201,8 +201,7 @@ una clave secreta, una ruta expuesta) y pierde precisión. Mejor `"internal"`.
|
||||||
```toml
|
```toml
|
||||||
[cron]
|
[cron]
|
||||||
mode = "external"
|
mode = "external"
|
||||||
trigger_token = "..." # Clave secreta propia, mejor en config/local.toml o en
|
trigger_token = "..." # Clave secreta propia, mejor en config/local.toml.
|
||||||
# PAGETOP_CRON__TRIGGER_TOKEN.
|
|
||||||
trigger_interval_secs = 60 # Una llamada por minuto (el valor por defecto).
|
trigger_interval_secs = 60 # Una llamada por minuto (el valor por defecto).
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -47,8 +47,7 @@ pub struct CronSettings {
|
||||||
/// Clave secreta que autoriza las llamadas a `POST /cron` con [`CronMode::External`], enviada
|
/// Clave secreta que autoriza las llamadas a `POST /cron` con [`CronMode::External`], enviada
|
||||||
/// en la cabecera `Authorization: Bearer <clave>`. Obligatoria en ese modo, con 16 caracteres
|
/// en la cabecera `Authorization: Bearer <clave>`. Obligatoria en ese modo, con 16 caracteres
|
||||||
/// o más (letras, dígitos, `-` o `_`), o la aplicación no arranca. Conviene guardarla en
|
/// o más (letras, dígitos, `-` o `_`), o la aplicación no arranca. Conviene guardarla en
|
||||||
/// `config/local.toml`, que no se versiona, o pasarla con la variable de entorno
|
/// `config/local.toml`, que no se versiona.
|
||||||
/// `PAGETOP_CRON__TRIGGER_TOKEN`.
|
|
||||||
pub trigger_token: Option<String>,
|
pub trigger_token: Option<String>,
|
||||||
/// Segundos entre dos llamadas a `POST /cron` con [`CronMode::External`]. Cada llamada ejecuta
|
/// Segundos entre dos llamadas a `POST /cron` con [`CronMode::External`]. Cada llamada ejecuta
|
||||||
/// los trabajos programados en el último intervalo de esta duración, contado en múltiplos
|
/// los trabajos programados en el último intervalo de esta duración, contado en múltiplos
|
||||||
|
|
|
||||||
|
|
@ -206,8 +206,7 @@ una clave secreta, una ruta expuesta) y pierde precisión. Mejor `"internal"`.
|
||||||
```toml
|
```toml
|
||||||
[cron]
|
[cron]
|
||||||
mode = "external"
|
mode = "external"
|
||||||
trigger_token = "..." # Clave secreta propia, mejor en config/local.toml o en
|
trigger_token = "..." # Clave secreta propia, mejor en config/local.toml.
|
||||||
# PAGETOP_CRON__TRIGGER_TOKEN.
|
|
||||||
trigger_interval_secs = 60 # Una llamada por minuto (el valor por defecto).
|
trigger_interval_secs = 60 # Una llamada por minuto (el valor por defecto).
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,8 +59,7 @@ base_url = "https://example.com"
|
||||||
host = "smtp.example.com"
|
host = "smtp.example.com"
|
||||||
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
|
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
|
||||||
username = "no-reply@example.com"
|
username = "no-reply@example.com"
|
||||||
password = "secreto" # Mejor en config/local.toml, que no se versiona, o en la
|
password = "secreto" # Mejor en config/local.toml, que no se versiona.
|
||||||
# variable de entorno PAGETOP_MAIL__SMTP__PASSWORD.
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
|
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
|
||||||
|
|
|
||||||
|
|
@ -152,8 +152,7 @@ pub struct SmtpSettings {
|
||||||
pub security: SmtpSecurity,
|
pub security: SmtpSecurity,
|
||||||
/// Usuario para autenticarse en el servidor. Sin valor, no se autentica.
|
/// Usuario para autenticarse en el servidor. Sin valor, no se autentica.
|
||||||
pub username: Option<String>,
|
pub username: Option<String>,
|
||||||
/// Contraseña del usuario. Conviene guardarla en `config/local.toml`, que no se versiona, o
|
/// Contraseña del usuario. Conviene guardarla en `config/local.toml`, que no se versiona.
|
||||||
/// pasarla con la variable de entorno `PAGETOP_MAIL__SMTP__PASSWORD`.
|
|
||||||
pub password: Option<String>,
|
pub password: Option<String>,
|
||||||
/// Nombre con el que se presenta la aplicación al servidor (`EHLO`). Sin valor, el nombre del
|
/// Nombre con el que se presenta la aplicación al servidor (`EHLO`). Sin valor, el nombre del
|
||||||
/// equipo.
|
/// equipo.
|
||||||
|
|
|
||||||
|
|
@ -60,8 +60,7 @@ base_url = "https://example.com"
|
||||||
host = "smtp.example.com"
|
host = "smtp.example.com"
|
||||||
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
|
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
|
||||||
username = "no-reply@example.com"
|
username = "no-reply@example.com"
|
||||||
password = "secreto" # Mejor en config/local.toml, que no se versiona, o en la
|
password = "secreto" # Mejor en config/local.toml, que no se versiona.
|
||||||
# variable de entorno PAGETOP_MAIL__SMTP__PASSWORD.
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
|
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
|
||||||
|
|
|
||||||
|
|
@ -67,20 +67,6 @@ pub struct UserSettings {
|
||||||
#[default = 600]
|
#[default = 600]
|
||||||
pub locked_for_secs: i64,
|
pub locked_for_secs: i64,
|
||||||
|
|
||||||
/// Solicitudes de recuperación de contraseña que puede recibir una misma cuenta en
|
|
||||||
/// [`password_reset_window_secs`](Self::password_reset_window_secs).
|
|
||||||
///
|
|
||||||
/// Cada solicitud envía un correo con un enlace nuevo que anula los anteriores. Alcanzado el
|
|
||||||
/// límite, las siguientes no envían nada hasta que la más antigua de la ventana queda fuera de
|
|
||||||
/// ella, y la respuesta es la misma para no revelar si la cuenta existe. Así nadie puede
|
|
||||||
/// inundar el buzón de otra persona ni dañar la reputación del servidor de correo. Con `0` no
|
|
||||||
/// hay límite.
|
|
||||||
#[default = 3]
|
|
||||||
pub max_password_resets: u32,
|
|
||||||
/// Segundos en los que se cuentan las solicitudes de recuperación de contraseña de una cuenta.
|
|
||||||
#[default = 3_600]
|
|
||||||
pub password_reset_window_secs: i64,
|
|
||||||
|
|
||||||
/// Sesiones, en la subsección `[user.session]`.
|
/// Sesiones, en la subsección `[user.session]`.
|
||||||
pub session: SessionSettings,
|
pub session: SessionSettings,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ use crate::handlers::admin::map_auth_error;
|
||||||
use crate::mail::send_token_mail;
|
use crate::mail::send_token_mail;
|
||||||
use crate::password;
|
use crate::password;
|
||||||
use crate::session;
|
use crate::session;
|
||||||
use crate::token::{TokenKind, consume_token, count_tokens_since, create_token, is_valid_token};
|
use crate::token::{TokenKind, consume_token, create_token, is_valid_token};
|
||||||
use crate::{LOCALES_USER, LOGIN_PATH, PROFILE_PATH};
|
use crate::{LOCALES_USER, LOGIN_PATH, PROFILE_PATH};
|
||||||
|
|
||||||
// **< Tipos de formularios >***********************************************************************
|
// **< Tipos de formularios >***********************************************************************
|
||||||
|
|
@ -241,21 +241,6 @@ pub async fn password_reset_post(
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let max = SETTINGS.max_password_resets;
|
|
||||||
if max > 0 {
|
|
||||||
let since = Utc::now() - Duration::seconds(SETTINGS.password_reset_window_secs);
|
|
||||||
match count_tokens_since(user_model.id, TokenKind::PasswordReset, since).await {
|
|
||||||
Ok(count) if count >= u64::from(max) => {
|
|
||||||
trace::warn!("Password reset limit reached for user {}", user_model.id);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Ok(_) => {}
|
|
||||||
Err(err) => {
|
|
||||||
trace::error!("Cannot count password reset requests: {err}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
match create_token(user_model.id, TokenKind::PasswordReset).await {
|
match create_token(user_model.id, TokenKind::PasswordReset).await {
|
||||||
Ok(token) => {
|
Ok(token) => {
|
||||||
send_token_mail(&mail_request, TokenKind::PasswordReset, &user_model, &token);
|
send_token_mail(&mail_request, TokenKind::PasswordReset, &user_model, &token);
|
||||||
|
|
|
||||||
|
|
@ -3,11 +3,8 @@
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::query::Expr;
|
use pagetop_seaorm::db::query::Expr;
|
||||||
use pagetop_seaorm::db::{
|
use pagetop_seaorm::db::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn};
|
||||||
ActiveValue, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set, dbconn,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::config::SETTINGS;
|
|
||||||
use crate::entity::user_token;
|
use crate::entity::user_token;
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
|
|
||||||
|
|
@ -65,44 +62,23 @@ impl TokenKind {
|
||||||
TokenKind::EmailVerification => 86400 * 3, // 3 días
|
TokenKind::EmailVerification => 86400 * 3, // 3 días
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Segundos que se conserva un token desde su creación: hasta que caduca y, los de recuperación,
|
|
||||||
// mientras cuentan para el límite de solicitudes.
|
|
||||||
fn keep_secs(self) -> i64 {
|
|
||||||
match self {
|
|
||||||
TokenKind::PasswordReset => self.ttl_secs().max(SETTINGS.password_reset_window_secs),
|
|
||||||
TokenKind::EmailVerification => self.ttl_secs(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< create_token >*******************************************************************************
|
// **< create_token >*******************************************************************************
|
||||||
|
|
||||||
/// Crea un token en BD y devuelve el valor en claro para enviarlo al usuario.
|
/// Crea un token en BD y devuelve el valor en claro para enviarlo al usuario.
|
||||||
///
|
///
|
||||||
/// Anula los tokens del mismo tipo que el usuario tenga sin consumir, de modo que sólo vale el
|
/// Si el usuario ya tiene un token del mismo tipo vigente, lo reemplaza.
|
||||||
/// último enlace enviado.
|
|
||||||
pub async fn create_token(user_id: i32, kind: TokenKind) -> Result<String, AuthError> {
|
pub async fn create_token(user_id: i32, kind: TokenKind) -> Result<String, AuthError> {
|
||||||
let now = Utc::now();
|
// Invalidar tokens anteriores del mismo tipo para este usuario.
|
||||||
|
|
||||||
// Los anteriores se anulan en lugar de borrarse para que sigan contando en
|
|
||||||
// `count_tokens_since()`; sólo se borran los que ya no pueden usarse ni cuentan.
|
|
||||||
user_token::Entity::update_many()
|
|
||||||
.col_expr(user_token::Column::ConsumedAt, Expr::value(now))
|
|
||||||
.col_expr(user_token::Column::UpdatedAt, Expr::value(now))
|
|
||||||
.filter(user_token::Column::UserId.eq(user_id))
|
|
||||||
.filter(user_token::Column::Kind.eq(kind.as_str()))
|
|
||||||
.filter(user_token::Column::ConsumedAt.is_null())
|
|
||||||
.exec(dbconn())
|
|
||||||
.await?;
|
|
||||||
user_token::Entity::delete_many()
|
user_token::Entity::delete_many()
|
||||||
.filter(user_token::Column::UserId.eq(user_id))
|
.filter(user_token::Column::UserId.eq(user_id))
|
||||||
.filter(user_token::Column::Kind.eq(kind.as_str()))
|
.filter(user_token::Column::Kind.eq(kind.as_str()))
|
||||||
.filter(user_token::Column::CreatedAt.lt(now - Duration::seconds(kind.keep_secs())))
|
|
||||||
.exec(dbconn())
|
.exec(dbconn())
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let token = generate_token();
|
let token = generate_token();
|
||||||
|
let now = Utc::now();
|
||||||
let expires_at = now + Duration::seconds(kind.ttl_secs());
|
let expires_at = now + Duration::seconds(kind.ttl_secs());
|
||||||
|
|
||||||
let new_token = user_token::ActiveModel {
|
let new_token = user_token::ActiveModel {
|
||||||
|
|
@ -119,25 +95,6 @@ pub async fn create_token(user_id: i32, kind: TokenKind) -> Result<String, AuthE
|
||||||
Ok(token)
|
Ok(token)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cuenta los tokens del tipo indicado creados para el usuario desde `since`, consumidos o no.
|
|
||||||
///
|
|
||||||
/// Los tokens se conservan al menos durante su tiempo de vida o, en los de recuperación de
|
|
||||||
/// contraseña, durante
|
|
||||||
/// [`password_reset_window_secs`](crate::config::UserSettings::password_reset_window_secs) si es
|
|
||||||
/// mayor. Con un `since` más antiguo el recuento puede quedarse corto.
|
|
||||||
pub async fn count_tokens_since(
|
|
||||||
user_id: i32,
|
|
||||||
kind: TokenKind,
|
|
||||||
since: DateTime<Utc>,
|
|
||||||
) -> Result<u64, AuthError> {
|
|
||||||
Ok(user_token::Entity::find()
|
|
||||||
.filter(user_token::Column::UserId.eq(user_id))
|
|
||||||
.filter(user_token::Column::Kind.eq(kind.as_str()))
|
|
||||||
.filter(user_token::Column::CreatedAt.gte(since))
|
|
||||||
.count(dbconn())
|
|
||||||
.await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< is_valid_token / consume_token >*************************************************************
|
// **< is_valid_token / consume_token >*************************************************************
|
||||||
|
|
||||||
/// Comprueba, sin consumirlo, que el token en claro sea válido para el usuario: existe, es del tipo
|
/// Comprueba, sin consumirlo, que el token en claro sea válido para el usuario: existe, es del tipo
|
||||||
|
|
|
||||||
35
src/app.rs
35
src/app.rs
|
|
@ -9,12 +9,9 @@ use crate::core::theme;
|
||||||
use crate::datetime::Timezone;
|
use crate::datetime::Timezone;
|
||||||
use crate::locale::Locale;
|
use crate::locale::Locale;
|
||||||
use crate::response::{render_error_pages, response_for_panic, route_not_found};
|
use crate::response::{render_error_pages, response_for_panic, route_not_found};
|
||||||
use crate::web::{Request, Response, Router, http};
|
use crate::web::Router;
|
||||||
use crate::{PAGETOP_VERSION, global, trace};
|
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 tower_http::catch_panic::CatchPanicLayer;
|
||||||
use tracing_appender::non_blocking::WorkerGuard;
|
use tracing_appender::non_blocking::WorkerGuard;
|
||||||
|
|
||||||
|
|
@ -253,9 +250,6 @@ impl Application {
|
||||||
// cambio, se registra antes: la página 404 debe ver lo que el middleware añade a la petición
|
// 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).
|
// (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
|
// 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
|
// `CatchPanicLayer` en la última capa se capturan incluso los `panic!` que se produzcan dentro
|
||||||
// del propio renderizado de una página de error.
|
// del propio renderizado de una página de error.
|
||||||
|
|
@ -264,38 +258,11 @@ impl Application {
|
||||||
let router = extension::all::configure_middleware(router);
|
let router = extension::all::configure_middleware(router);
|
||||||
let router = extension::all::configure_static_files(router);
|
let router = extension::all::configure_static_files(router);
|
||||||
router
|
router
|
||||||
.layer(axum::middleware::from_fn(limit_body))
|
|
||||||
.layer(axum::middleware::from_fn(render_error_pages))
|
.layer(axum::middleware::from_fn(render_error_pages))
|
||||||
.layer(CatchPanicLayer::custom(response_for_panic))
|
.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
|
// 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.
|
// alguna, espera sólo a la otra en lugar de detener el servidor nada más arrancar.
|
||||||
async fn shutdown_signal() {
|
async fn shutdown_signal() {
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
//! Definiciones para crear formularios ([`Form`]).
|
//! Definiciones para crear formularios ([`Form`]).
|
||||||
|
|
||||||
mod props;
|
mod props;
|
||||||
pub use props::{Autocomplete, AutofillField, CheckboxKind, Enctype, Method};
|
pub use props::{Autocomplete, AutofillField, CheckboxKind, Method};
|
||||||
|
|
||||||
mod component;
|
mod component;
|
||||||
pub use component::Form;
|
pub use component::Form;
|
||||||
|
|
@ -42,8 +42,5 @@ pub use range::Range;
|
||||||
mod textarea;
|
mod textarea;
|
||||||
pub use textarea::Textarea;
|
pub use textarea::Textarea;
|
||||||
|
|
||||||
mod file;
|
|
||||||
pub use file::File;
|
|
||||||
|
|
||||||
mod hidden;
|
mod hidden;
|
||||||
pub use hidden::Hidden;
|
pub use hidden::Hidden;
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,6 @@ use crate::base::component::form;
|
||||||
/// - `classes`: clases CSS adicionales (p. ej. utilidades CSS).
|
/// - `classes`: clases CSS adicionales (p. ej. utilidades CSS).
|
||||||
/// - `action`: URL/ruta de destino para el envío.
|
/// - `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`]).
|
/// - `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"`).
|
/// - `accept-charset`: juego de caracteres aceptado (por defecto es `"UTF-8"`).
|
||||||
/// - `children`: contenido del formulario.
|
/// - `children`: contenido del formulario.
|
||||||
///
|
///
|
||||||
|
|
@ -52,8 +50,6 @@ pub struct Form {
|
||||||
action: Route,
|
action: Route,
|
||||||
/// Devuelve el método para enviar el formulario.
|
/// Devuelve el método para enviar el formulario.
|
||||||
method: form::Method,
|
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.
|
/// Devuelve el juego de caracteres aceptado por el formulario.
|
||||||
#[default(_code = "AttrValue::new(\"UTF-8\")")]
|
#[default(_code = "AttrValue::new(\"UTF-8\")")]
|
||||||
charset: AttrValue,
|
charset: AttrValue,
|
||||||
|
|
@ -80,16 +76,11 @@ impl Component for Form {
|
||||||
form::Method::Post => Some("post"),
|
form::Method::Post => Some("post"),
|
||||||
form::Method::Get => None,
|
form::Method::Get => None,
|
||||||
};
|
};
|
||||||
let enctype = match self.enctype() {
|
|
||||||
form::Enctype::UrlEncoded => None,
|
|
||||||
form::Enctype::Multipart => Some("multipart/form-data"),
|
|
||||||
};
|
|
||||||
Ok(html! {
|
Ok(html! {
|
||||||
form
|
form
|
||||||
(self.props().unpack(cx))
|
(self.props().unpack(cx))
|
||||||
action=[self.action().try_resolve(cx)]
|
action=[self.action().try_resolve(cx)]
|
||||||
method=[method]
|
method=[method]
|
||||||
enctype=[enctype]
|
|
||||||
accept-charset=[self.charset().as_deref()]
|
accept-charset=[self.charset().as_deref()]
|
||||||
{
|
{
|
||||||
(self.children().render(cx).await)
|
(self.children().render(cx).await)
|
||||||
|
|
@ -132,15 +123,6 @@ impl Form {
|
||||||
self
|
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.
|
/// Establece el juego de caracteres aceptado por el formulario.
|
||||||
///
|
///
|
||||||
/// Por defecto se utiliza `"UTF-8"`.
|
/// Por defecto se utiliza `"UTF-8"`.
|
||||||
|
|
|
||||||
|
|
@ -1,181 +0,0 @@
|
||||||
//! 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.
|
/// 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
|
/// - **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.
|
/// servidor. POST es más flexible para cargas grandes.
|
||||||
/// - **Archivos**: la subida de archivos requiere `method="post"` y la codificación
|
/// - **Ficheros**: la subida de ficheros requiere `method="post"` y un `enctype` adecuado
|
||||||
/// [`Enctype::Multipart`].
|
/// (habitualmente `multipart/form-data`).
|
||||||
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
|
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum Method {
|
pub enum Method {
|
||||||
/// Envía los datos en el cuerpo de la petición.
|
/// Envía los datos en el cuerpo de la petición.
|
||||||
|
|
@ -484,28 +484,3 @@ pub enum Method {
|
||||||
/// Recomendado para búsquedas y operaciones que no modifican datos ni el estado del sistema.
|
/// Recomendado para búsquedas y operaciones que no modifican datos ni el estado del sistema.
|
||||||
Get,
|
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,
|
|
||||||
}
|
|
||||||
|
|
|
||||||
341
src/config.rs
341
src/config.rs
|
|
@ -5,9 +5,9 @@
|
||||||
//! no se definan.
|
//! no se definan.
|
||||||
//!
|
//!
|
||||||
//! Separar la configuración del código permite que cada despliegue (*dev*, *staging*, *production*,
|
//! Separar la configuración del código permite que cada despliegue (*dev*, *staging*, *production*,
|
||||||
//! etc.) tenga su propia configuración sin recompilar. Los ajustes se leen de archivos y pueden
|
//! etc.) tenga su propia configuración sin recompilar. Los ajustes sólo se leen de archivos; las
|
||||||
//! sobrescribirse con [variables de entorno](#variables-de-entorno), útiles para pasar secretos o
|
//! variables de entorno no los sobrescriben, únicamente eligen qué archivos cargar (`CONFIG_DIR` y
|
||||||
//! ajustes de un despliegue concreto (Docker, systemd, Kubernetes...) sin escribirlos en archivos.
|
//! `PAGETOP_RUN_MODE`, cuyo valor queda además en `app.run_mode`).
|
||||||
//!
|
//!
|
||||||
//! # Orden de carga
|
//! # Orden de carga
|
||||||
//!
|
//!
|
||||||
|
|
@ -54,37 +54,6 @@
|
||||||
//! Los archivos se combinan clave a clave en el orden anterior. Cada archivo sobrescribe a los
|
//! Los archivos se combinan clave a clave en el orden anterior. Cada archivo sobrescribe a los
|
||||||
//! anteriores sólo en las claves que define.
|
//! anteriores sólo en las claves que define.
|
||||||
//!
|
//!
|
||||||
//! # Variables de entorno
|
|
||||||
//!
|
|
||||||
//! Por último, las variables de entorno con el prefijo `PAGETOP_` sobrescriben los valores de los
|
|
||||||
//! archivos. El nombre de la variable se forma con la sección y la clave en mayúsculas, separando
|
|
||||||
//! cada nivel con dos guiones bajos (`__`), porque las claves ya llevan guiones bajos simples:
|
|
||||||
//!
|
|
||||||
//! ```sh
|
|
||||||
//! PAGETOP_DATABASE__DB_PASS=secreto # [database] db_pass
|
|
||||||
//! PAGETOP_MAIL__SMTP__PASSWORD=secreto # [mail.smtp] password
|
|
||||||
//! PAGETOP_SERVER__BIND_PORT=80 # [server] bind_port
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! El valor se convierte al tipo del ajuste: un número se escribe en decimal (`80`), un booleano
|
|
||||||
//! como `true` o `false`, y una cadena tal cual, sin comillas. Como en los archivos, un valor no
|
|
||||||
//! válido o una clave desconocida detienen el arranque. Además:
|
|
||||||
//!
|
|
||||||
//! * Una variable vacía equivale a no definirla, así que no sirve para vaciar un valor de los
|
|
||||||
//! archivos.
|
|
||||||
//!
|
|
||||||
//! * Una variable de ajustes cuyo valor no es Unicode válido también detiene el arranque.
|
|
||||||
//!
|
|
||||||
//! * No sirven para las listas ni para las claves que llevan un punto, como `mail.queue` en
|
|
||||||
//! `[cron.jobs."mail.queue"]`. Ésas se configuran en los archivos. Un trabajo con una clave sin
|
|
||||||
//! punto, como `cleanup`, sí: `PAGETOP_CRON__JOBS__CLEANUP__ENABLED=false`.
|
|
||||||
//!
|
|
||||||
//! * Con la *feature* `testing` se ignoran, como `PAGETOP_RUN_MODE`, para que las variables de la
|
|
||||||
//! terminal no cambien el resultado de las pruebas.
|
|
||||||
//!
|
|
||||||
//! Al arrancar, las trazas indican qué ajustes vienen de variables de entorno (las claves, nunca
|
|
||||||
//! los valores), para que se sepa de dónde sale un valor que no aparece en los archivos.
|
|
||||||
//!
|
|
||||||
//! # Cómo declarar ajustes
|
//! # Cómo declarar ajustes
|
||||||
//!
|
//!
|
||||||
//! Cada extensión declara sus ajustes en una estructura con el atributo
|
//! Cada extensión declara sus ajustes en una estructura con el atributo
|
||||||
|
|
@ -148,10 +117,9 @@
|
||||||
//! PageTop carga los ajustes de todas las extensiones durante el arranque, en el orden en que se
|
//! PageTop carga los ajustes de todas las extensiones durante el arranque, en el orden en que se
|
||||||
//! registran y antes de inicializarlas. Si unos ajustes no pueden cargarse, la aplicación se
|
//! registran y antes de inicializarlas. Si unos ajustes no pueden cargarse, la aplicación se
|
||||||
//! detiene con un mensaje que indica el problema: el archivo y la línea si un TOML está mal
|
//! detiene con un mensaje que indica el problema: el archivo y la línea si un TOML está mal
|
||||||
//! formado, o la sección y el valor no válido o la **clave desconocida** (típicamente una errata),
|
//! formado, o la sección y el valor no válido o la **clave desconocida** (típicamente una errata).
|
||||||
//! junto con los nombres de las variables de entorno que sobrescriben esa sección, si las hay.
|
//! También avisa al arrancar de las secciones de los archivos que no corresponden a PageTop ni a
|
||||||
//! También avisa al arrancar de las secciones que no corresponden a PageTop ni a ninguna extensión,
|
//! ninguna extensión.
|
||||||
//! vengan de los archivos o de variables de entorno.
|
|
||||||
//!
|
//!
|
||||||
//! Fuera de una aplicación en marcha (p. ej. en pruebas unitarias) los ajustes se cargan en el
|
//! Fuera de una aplicación en marcha (p. ej. en pruebas unitarias) los ajustes se cargan en el
|
||||||
//! primer acceso a la variable, con las mismas reglas.
|
//! primer acceso a la variable, con las mismas reglas.
|
||||||
|
|
@ -160,12 +128,11 @@
|
||||||
|
|
||||||
use crate::{AutoDefault, BoxError, trace, util};
|
use crate::{AutoDefault, BoxError, trace, util};
|
||||||
|
|
||||||
use config::{Config, ConfigError, Environment, File, FileFormat, Map};
|
use config::{Config, ConfigError, File, FileFormat};
|
||||||
use serde::de::{DeserializeOwned, IgnoredAny};
|
use serde::de::{DeserializeOwned, IgnoredAny};
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::ffi::OsString;
|
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::{LazyLock, OnceLock};
|
use std::sync::{LazyLock, OnceLock};
|
||||||
|
|
@ -176,113 +143,11 @@ const DEFAULT_CONFIG_DIR: &str = "config";
|
||||||
// Modo de ejecución por defecto.
|
// Modo de ejecución por defecto.
|
||||||
const DEFAULT_RUN_MODE: &str = "default";
|
const DEFAULT_RUN_MODE: &str = "default";
|
||||||
|
|
||||||
// Prefijo de las variables de entorno que sobrescriben ajustes.
|
// Configuración combinada de los archivos TOML en el orden de carga, más el modo de ejecución
|
||||||
const ENV_PREFIX: &str = "PAGETOP_";
|
// (`app.run_mode`), o el texto del error si no se pudieron leer (`ConfigError` no implementa
|
||||||
|
// `Clone`). Se construye una sola vez, en el primer acceso, y sólo la leen las funciones de este
|
||||||
// Separador de niveles (sección, subsección y clave) en el nombre de esas variables.
|
// módulo: así ningún ajuste se salta las comprobaciones de `#[settings]`.
|
||||||
const ENV_SEPARATOR: &str = "__";
|
|
||||||
|
|
||||||
// Variables de entorno que sobrescriben ajustes, o el texto del error si alguna no se puede leer.
|
|
||||||
// Con la *feature* `testing` no se lee ninguna.
|
|
||||||
static ENV_VARS: LazyLock<Result<Map<String, String>, String>> = LazyLock::new(|| {
|
|
||||||
if cfg!(feature = "testing") {
|
|
||||||
return Ok(Map::new());
|
|
||||||
}
|
|
||||||
env_overrides(env::vars_os())
|
|
||||||
});
|
|
||||||
|
|
||||||
// Selecciona las variables que sobrescriben ajustes: las que empiezan por `ENV_PREFIX`, con al
|
|
||||||
// menos un `ENV_SEPARATOR` tras el prefijo (sección y clave) y un valor no vacío. Un valor que no
|
|
||||||
// es Unicode válido es un error, como cualquier otro valor no válido; un nombre que no lo es no
|
|
||||||
// puede ser el de un ajuste y se ignora, como el resto de variables ajenas.
|
|
||||||
fn env_overrides(
|
|
||||||
vars: impl IntoIterator<Item = (OsString, OsString)>,
|
|
||||||
) -> Result<Map<String, String>, String> {
|
|
||||||
let mut overrides = Map::new();
|
|
||||||
for (key, value) in vars {
|
|
||||||
let Some(key) = key.to_str().filter(|key| {
|
|
||||||
key.strip_prefix(ENV_PREFIX)
|
|
||||||
.is_some_and(|rest| rest.contains(ENV_SEPARATOR))
|
|
||||||
}) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if value.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let value = value
|
|
||||||
.into_string()
|
|
||||||
.map_err(|_| format!("Environment variable {key} is not valid Unicode"))?;
|
|
||||||
overrides.insert(key.to_string(), value);
|
|
||||||
}
|
|
||||||
Ok(overrides)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nombres de las variables de entorno que sobrescriben ajustes. Ninguno si no se pudieron leer: en
|
|
||||||
// ese caso falla la lectura de la configuración, que devuelve el error.
|
|
||||||
fn env_names() -> impl Iterator<Item = &'static str> {
|
|
||||||
ENV_VARS
|
|
||||||
.iter()
|
|
||||||
.flat_map(|vars| vars.keys())
|
|
||||||
.map(String::as_str)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Añade al error de una sección los nombres de las variables de entorno que la sobrescriben, si
|
|
||||||
// hay alguna. El error de una clave desconocida no dice de dónde viene, y una que llega de una
|
|
||||||
// variable no aparece en ningún archivo.
|
|
||||||
fn with_env_names<'a>(
|
|
||||||
err: ConfigError,
|
|
||||||
section: &str,
|
|
||||||
names: impl Iterator<Item = &'a str>,
|
|
||||||
) -> ConfigError {
|
|
||||||
let mut names: Vec<&str> = names
|
|
||||||
.filter(|name| {
|
|
||||||
name.strip_prefix(ENV_PREFIX)
|
|
||||||
.and_then(|rest| rest.split(ENV_SEPARATOR).next())
|
|
||||||
.is_some_and(|name_section| name_section.eq_ignore_ascii_case(section))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
if names.is_empty() {
|
|
||||||
return err;
|
|
||||||
}
|
|
||||||
names.sort_unstable();
|
|
||||||
ConfigError::Message(format!(
|
|
||||||
"{err} (environment variables in this section: {})",
|
|
||||||
names.join(", ")
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fuente de configuración con las variables ya filtradas. Sin `try_parsing`: los valores llegan
|
|
||||||
// como cadenas y se convierten al deserializar según el tipo de cada ajuste; con él, una
|
|
||||||
// contraseña `0123` llegaría como el número `123`.
|
|
||||||
fn env_source(vars: Map<String, String>) -> Environment {
|
|
||||||
Environment::with_prefix(ENV_PREFIX.trim_end_matches('_'))
|
|
||||||
.prefix_separator("_")
|
|
||||||
.separator(ENV_SEPARATOR)
|
|
||||||
.source(Some(vars))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clave de cada ajuste sobrescrito por una variable de entorno (p. ej. `database.db_pass`), en
|
|
||||||
// orden alfabético.
|
|
||||||
pub(crate) fn env_keys() -> Vec<String> {
|
|
||||||
let mut keys: Vec<String> = env_names()
|
|
||||||
.map(|name| {
|
|
||||||
name[ENV_PREFIX.len()..]
|
|
||||||
.to_lowercase()
|
|
||||||
.replace(ENV_SEPARATOR, ".")
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
keys.sort();
|
|
||||||
keys
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configuración combinada de los archivos TOML en el orden de carga y de las variables de entorno,
|
|
||||||
// más el modo de ejecución (`app.run_mode`), o el texto del error si no se pudieron leer
|
|
||||||
// (`ConfigError` no implementa `Clone`). Se construye una sola vez, en el primer acceso, y sólo la
|
|
||||||
// leen las funciones de este módulo: así ningún ajuste se salta las comprobaciones de
|
|
||||||
// `#[settings]`.
|
|
||||||
static CONFIG_VALUES: LazyLock<Result<Config, String>> = LazyLock::new(|| {
|
static CONFIG_VALUES: LazyLock<Result<Config, String>> = LazyLock::new(|| {
|
||||||
let env_vars = ENV_VARS.clone()?;
|
|
||||||
|
|
||||||
// CONFIG_DIR (si existe) o DEFAULT_CONFIG_DIR. Si no se puede resolver, se usa tal cual. Sólo
|
// CONFIG_DIR (si existe) o DEFAULT_CONFIG_DIR. Si no se puede resolver, se usa tal cual. Sólo
|
||||||
// se avisa si CONFIG_DIR está definida: que falte el directorio predeterminado es normal en una
|
// se avisa si CONFIG_DIR está definida: que falte el directorio predeterminado es normal en una
|
||||||
// aplicación sin configuración propia, pero un CONFIG_DIR erróneo podría dejar la aplicación
|
// aplicación sin configuración propia, pero un CONFIG_DIR erróneo podría dejar la aplicación
|
||||||
|
|
@ -322,31 +187,29 @@ static CONFIG_VALUES: LazyLock<Result<Config, String>> = LazyLock::new(|| {
|
||||||
.add_source(File::from(config_dir.join(format!("local.{rm}.toml"))).required(false))
|
.add_source(File::from(config_dir.join(format!("local.{rm}.toml"))).required(false))
|
||||||
// 4. Configuración local común (local.toml).
|
// 4. Configuración local común (local.toml).
|
||||||
.add_source(File::from(config_dir.join("local.toml")).required(false))
|
.add_source(File::from(config_dir.join("local.toml")).required(false))
|
||||||
// 5. Variables de entorno (p. ej. PAGETOP_DATABASE__DB_PASS).
|
|
||||||
.add_source(env_source(env_vars))
|
|
||||||
// Guarda el modo de ejecución explícitamente.
|
// Guarda el modo de ejecución explícitamente.
|
||||||
.set_override("app.run_mode", rm)
|
.set_override("app.run_mode", rm)
|
||||||
.and_then(|builder| builder.build())
|
.and_then(|builder| builder.build())
|
||||||
.map_err(|err| err.to_string())
|
.map_err(|err| err.to_string())
|
||||||
});
|
});
|
||||||
|
|
||||||
// Configuración combinada, o el error que impidió leer los archivos o las variables de entorno.
|
// Configuración combinada, o el error que impidió leer los archivos.
|
||||||
fn config_values() -> Result<&'static Config, ConfigError> {
|
fn config_values() -> Result<&'static Config, ConfigError> {
|
||||||
CONFIG_VALUES
|
CONFIG_VALUES
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map_err(|message| ConfigError::Message(message.clone()))
|
.map_err(|message| ConfigError::Message(message.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba que la configuración se puede leer (p. ej. que ningún TOML está mal formado), para
|
// Comprueba que los archivos de configuración se pueden leer (p. ej. que ningún TOML está mal
|
||||||
// detener el arranque con un error en lugar del `panic!` del primer acceso.
|
// formado), para detener el arranque con un error en lugar del `panic!` del primer acceso.
|
||||||
pub(crate) fn check_sources() -> Result<(), ConfigError> {
|
pub(crate) fn check_files() -> Result<(), ConfigError> {
|
||||||
config_values().map(|_| ())
|
config_values().map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba, sin guardarlos, que los ajustes de la sección de `T` se pueden cargar. Sirve para los
|
// Comprueba, sin guardarlos, que los ajustes de la sección de `T` se pueden cargar. Sirve para los
|
||||||
// ajustes que se guardan en otra variable, como los globales de PageTop.
|
// ajustes que se guardan en otra variable, como los globales de PageTop.
|
||||||
pub(crate) fn check<T: SettingsSection>() -> Result<(), ConfigError> {
|
pub(crate) fn check<T: SettingsSection>() -> Result<(), ConfigError> {
|
||||||
read_section::<T>(config_values()?).map(|_| ())
|
section_from::<T>(config_values()?).map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Secciones del primer nivel de la configuración.
|
// Secciones del primer nivel de la configuración.
|
||||||
|
|
@ -375,14 +238,14 @@ pub trait SettingsSection: DeserializeOwned + Default + Send + Sync + 'static {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga los ajustes de la sección `T::SECTION` de la configuración. Las claves ausentes toman su
|
// Carga los ajustes de la sección `T::SECTION` de la configuración. Las claves ausentes toman su
|
||||||
// valor por defecto, y si falta la sección entera se usan los de todos los campos. Si la
|
// valor por defecto, y si falta la sección entera se usan los de todos los campos. Si los archivos
|
||||||
// configuración no se puede leer o la sección no puede deserializarse (un valor no válido o una
|
// no se pueden leer o la sección no puede deserializarse (un valor no válido o una clave
|
||||||
// clave desconocida), lanza `panic!` con un mensaje que indica el problema. Al arrancar no llega a
|
// desconocida), lanza `panic!` con un mensaje que indica el problema. Al arrancar no llega a
|
||||||
// ocurrir: la aplicación lo comprueba antes y se detiene con un error.
|
// ocurrir: la aplicación lo comprueba antes y se detiene con un error.
|
||||||
pub(crate) fn load<T: SettingsSection>() -> T {
|
pub(crate) fn load<T: SettingsSection>() -> T {
|
||||||
let config =
|
let config = config_values()
|
||||||
config_values().unwrap_or_else(|err| panic!("Failed to read the configuration: {err}"));
|
.unwrap_or_else(|err| panic!("Failed to read the configuration files: {err}"));
|
||||||
read_section(config)
|
section_from(config)
|
||||||
.unwrap_or_else(|err| panic!("Invalid settings in section [{}]: {err}", T::SECTION))
|
.unwrap_or_else(|err| panic!("Invalid settings in section [{}]: {err}", T::SECTION))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -399,12 +262,6 @@ pub fn load_from_str<T: SettingsSection>(toml: &str) -> Result<T, ConfigError> {
|
||||||
section_from(&config)
|
section_from(&config)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lee la sección de `T` de la configuración combinada. Si no puede, el error nombra además las
|
|
||||||
// variables de entorno que sobrescriben la sección.
|
|
||||||
fn read_section<T: SettingsSection>(config: &Config) -> Result<T, ConfigError> {
|
|
||||||
section_from(config).map_err(|err| with_env_names(err, T::SECTION, env_names()))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lee la sección de `T` de una configuración; si falta entera, usa los valores por defecto.
|
// Lee la sección de `T` de una configuración; si falta entera, usa los valores por defecto.
|
||||||
fn section_from<T: SettingsSection>(config: &Config) -> Result<T, ConfigError> {
|
fn section_from<T: SettingsSection>(config: &Config) -> Result<T, ConfigError> {
|
||||||
match config.get::<T>(T::SECTION) {
|
match config.get::<T>(T::SECTION) {
|
||||||
|
|
@ -489,7 +346,7 @@ impl<T: SettingsSection> LoadSettings for LazySettings<T> {
|
||||||
// mismos.
|
// mismos.
|
||||||
fn load(&self) -> Result<(), BoxError> {
|
fn load(&self) -> Result<(), BoxError> {
|
||||||
if self.0.get().is_none() {
|
if self.0.get().is_none() {
|
||||||
let _ = self.0.set(read_section::<T>(config_values()?)?);
|
let _ = self.0.set(section_from::<T>(config_values()?)?);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -498,155 +355,3 @@ impl<T: SettingsSection> LoadSettings for LazySettings<T> {
|
||||||
T::SECTION
|
T::SECTION
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::{
|
|
||||||
Config, ConfigError, File, FileFormat, OsString, env_overrides, env_source, section_from,
|
|
||||||
with_env_names,
|
|
||||||
};
|
|
||||||
use crate::settings;
|
|
||||||
|
|
||||||
#[settings(section = "sample")]
|
|
||||||
struct SampleSettings {
|
|
||||||
#[default = "from-default"]
|
|
||||||
name: String,
|
|
||||||
#[default = "from-default"]
|
|
||||||
password: String,
|
|
||||||
#[default = 8080]
|
|
||||||
port: u16,
|
|
||||||
#[default = false]
|
|
||||||
enabled: bool,
|
|
||||||
limit: Option<u16>,
|
|
||||||
nested: NestedSettings,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[settings]
|
|
||||||
struct NestedSettings {
|
|
||||||
#[default = "from-default"]
|
|
||||||
user: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
const TOML: &str = r#"
|
|
||||||
[sample]
|
|
||||||
name = "from-file"
|
|
||||||
password = "from-file"
|
|
||||||
port = 3000
|
|
||||||
"#;
|
|
||||||
|
|
||||||
fn os_vars<'a>(vars: &'a [(&str, &str)]) -> impl Iterator<Item = (OsString, OsString)> + 'a {
|
|
||||||
vars.iter().map(|(k, v)| (k.into(), v.into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load(vars: &[(&str, &str)]) -> Result<SampleSettings, ConfigError> {
|
|
||||||
let config = Config::builder()
|
|
||||||
.add_source(File::from_str(TOML, FileFormat::Toml))
|
|
||||||
.add_source(env_source(env_overrides(os_vars(vars)).unwrap()))
|
|
||||||
.build()?;
|
|
||||||
section_from::<SampleSettings>(&config)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn env_vars_override_file_values() {
|
|
||||||
let s = load(&[
|
|
||||||
("PAGETOP_SAMPLE__PASSWORD", "from-env"),
|
|
||||||
("PAGETOP_SAMPLE__PORT", "80"),
|
|
||||||
("PAGETOP_SAMPLE__ENABLED", "true"),
|
|
||||||
("PAGETOP_SAMPLE__LIMIT", "5"),
|
|
||||||
("PAGETOP_SAMPLE__NESTED__USER", "from-env"),
|
|
||||||
])
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(s.name, "from-file");
|
|
||||||
assert_eq!(s.password, "from-env");
|
|
||||||
assert_eq!(s.port, 80);
|
|
||||||
assert!(s.enabled);
|
|
||||||
assert_eq!(s.limit, Some(5));
|
|
||||||
assert_eq!(s.nested.user, "from-env");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn env_values_are_not_parsed_before_deserializing() {
|
|
||||||
// A numeric-looking string must keep its leading zeros.
|
|
||||||
let s = load(&[("PAGETOP_SAMPLE__PASSWORD", "0123")]).unwrap();
|
|
||||||
assert_eq!(s.password, "0123");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn env_var_with_unknown_key_is_rejected() {
|
|
||||||
let error = load(&[("PAGETOP_SAMPLE__PASWORD", "typo")]).err().unwrap();
|
|
||||||
assert!(
|
|
||||||
error.to_string().contains("pasword"),
|
|
||||||
"unexpected error: {error}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn env_var_with_invalid_value_is_rejected() {
|
|
||||||
assert!(load(&[("PAGETOP_SAMPLE__PORT", "not-a-port")]).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn empty_env_vars_are_ignored() {
|
|
||||||
let s = load(&[("PAGETOP_SAMPLE__PASSWORD", "")]).unwrap();
|
|
||||||
assert_eq!(s.password, "from-file");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_prefixed_vars_with_section_and_key_are_taken() {
|
|
||||||
let vars = env_overrides(os_vars(&[
|
|
||||||
("PAGETOP_RUN_MODE", "production"),
|
|
||||||
("PAGETOP_SAMPLE__NAME", "x"),
|
|
||||||
("OTHER_SAMPLE__NAME", "x"),
|
|
||||||
("pagetop_sample__name", "x"),
|
|
||||||
]))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(vars.len(), 1);
|
|
||||||
assert!(vars.contains_key("PAGETOP_SAMPLE__NAME"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
#[test]
|
|
||||||
fn non_unicode_values_are_rejected_only_in_setting_vars() {
|
|
||||||
use std::os::unix::ffi::OsStringExt;
|
|
||||||
|
|
||||||
let invalid = || OsString::from_vec(vec![0xff]);
|
|
||||||
let error = env_overrides([("PAGETOP_SAMPLE__NAME".into(), invalid())]).unwrap_err();
|
|
||||||
assert!(
|
|
||||||
error.contains("PAGETOP_SAMPLE__NAME"),
|
|
||||||
"unexpected error: {error}"
|
|
||||||
);
|
|
||||||
// Foreign variables, and names that cannot be settings, are ignored.
|
|
||||||
assert!(
|
|
||||||
env_overrides([("OTHER_VAR".into(), invalid())])
|
|
||||||
.unwrap()
|
|
||||||
.is_empty()
|
|
||||||
);
|
|
||||||
assert!(env_overrides([(invalid(), "x".into())]).unwrap().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn section_errors_name_the_env_vars_of_that_section() {
|
|
||||||
let names = [
|
|
||||||
"PAGETOP_SAMPLE__PASWORD",
|
|
||||||
"PAGETOP_OTHER__NAME",
|
|
||||||
"PAGETOP_SAMPLE__NESTED__USER",
|
|
||||||
];
|
|
||||||
let error = with_env_names(
|
|
||||||
ConfigError::Message("unknown field `pasword`".into()),
|
|
||||||
"sample",
|
|
||||||
names.into_iter(),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
error.to_string(),
|
|
||||||
"unknown field `pasword` (environment variables in this section: \
|
|
||||||
PAGETOP_SAMPLE__NESTED__USER, PAGETOP_SAMPLE__PASWORD)"
|
|
||||||
);
|
|
||||||
// Without variables for the section, the error is left as it was.
|
|
||||||
let error = with_env_names(
|
|
||||||
ConfigError::Message("unknown field `x`".into()),
|
|
||||||
"sample",
|
|
||||||
["PAGETOP_OTHER__NAME"].into_iter(),
|
|
||||||
);
|
|
||||||
assert_eq!(error.to_string(), "unknown field `x`");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -12,9 +12,8 @@ static EXTENSIONS: OnceLock<Vec<ExtensionRef>> = OnceLock::new();
|
||||||
/// Errores de las extensiones que detienen el arranque de la aplicación.
|
/// Errores de las extensiones que detienen el arranque de la aplicación.
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum StartupError {
|
pub enum StartupError {
|
||||||
/// La configuración no se puede leer (p. ej. un TOML mal formado o una variable de entorno de
|
/// Los archivos de configuración no se pueden leer (p. ej. un TOML mal formado).
|
||||||
/// ajustes cuyo valor no es Unicode válido).
|
#[error("Failed to read the configuration files")]
|
||||||
#[error("Failed to read the configuration")]
|
|
||||||
ReadConfig(#[source] BoxError),
|
ReadConfig(#[source] BoxError),
|
||||||
/// Dos extensiones, o una extensión y PageTop, reclaman la misma sección de la configuración:
|
/// Dos extensiones, o una extensión y PageTop, reclaman la misma sección de la configuración:
|
||||||
/// cada una la leería con su propia estructura de ajustes.
|
/// cada una la leería con su propia estructura de ajustes.
|
||||||
|
|
@ -143,13 +142,6 @@ pub fn load_settings() -> Result<(), StartupError> {
|
||||||
// Separada de `load_settings()` para poder probarla sin el registro global de extensiones.
|
// Separada de `load_settings()` para poder probarla sin el registro global de extensiones.
|
||||||
fn load_settings_of(extensions: &[ExtensionRef]) -> Result<(), StartupError> {
|
fn load_settings_of(extensions: &[ExtensionRef]) -> Result<(), StartupError> {
|
||||||
trace::info!("Loading settings for all extensions");
|
trace::info!("Loading settings for all extensions");
|
||||||
let env_keys = config::env_keys();
|
|
||||||
if !env_keys.is_empty() {
|
|
||||||
trace::info!(
|
|
||||||
"Settings from environment variables: {}",
|
|
||||||
env_keys.join(", ")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut known: Vec<&str> = global::SECTIONS.to_vec();
|
let mut known: Vec<&str> = global::SECTIONS.to_vec();
|
||||||
for settings in extensions.iter().filter_map(|e| e.settings()) {
|
for settings in extensions.iter().filter_map(|e| e.settings()) {
|
||||||
let section = settings.section();
|
let section = settings.section();
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,7 @@ pub use log_format::LogFormat;
|
||||||
|
|
||||||
// **< SETTINGS >***********************************************************************************
|
// **< SETTINGS >***********************************************************************************
|
||||||
|
|
||||||
/// Ajustes de las secciones `[app]`, `[dev]`, `[log]`, `[server]` y `[upload]`.
|
/// Ajustes de las secciones `[app]`, `[dev]`, `[log]` y `[server]`.
|
||||||
///
|
///
|
||||||
/// Se cargan al arrancar la aplicación, antes que los ajustes de las extensiones.
|
/// Se cargan al arrancar la aplicación, antes que los ajustes de las extensiones.
|
||||||
pub static SETTINGS: LazyLock<Settings> = LazyLock::new(|| Settings {
|
pub static SETTINGS: LazyLock<Settings> = LazyLock::new(|| Settings {
|
||||||
|
|
@ -30,18 +30,16 @@ pub static SETTINGS: LazyLock<Settings> = LazyLock::new(|| Settings {
|
||||||
dev: config::load(),
|
dev: config::load(),
|
||||||
log: config::load(),
|
log: config::load(),
|
||||||
server: config::load(),
|
server: config::load(),
|
||||||
upload: config::load(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Comprueba que la configuración se puede leer y que los ajustes globales son válidos.
|
// Comprueba que los archivos de configuración se pueden leer y que los ajustes globales son válidos.
|
||||||
// La aplicación lo llama al arrancar, antes del primer acceso a `SETTINGS`, que lanzaría `panic!`.
|
// La aplicación lo llama al arrancar, antes del primer acceso a `SETTINGS`, que lanzaría `panic!`.
|
||||||
pub(crate) fn check_settings() -> Result<(), StartupError> {
|
pub(crate) fn check_settings() -> Result<(), StartupError> {
|
||||||
config::check_sources().map_err(|err| StartupError::ReadConfig(err.into()))?;
|
config::check_files().map_err(|err| StartupError::ReadConfig(err.into()))?;
|
||||||
check_section::<AppSettings>()?;
|
check_section::<AppSettings>()?;
|
||||||
check_section::<DevSettings>()?;
|
check_section::<DevSettings>()?;
|
||||||
check_section::<LogSettings>()?;
|
check_section::<LogSettings>()?;
|
||||||
check_section::<ServerSettings>()?;
|
check_section::<ServerSettings>()
|
||||||
check_section::<UploadSettings>()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_section<T: config::SettingsSection>() -> Result<(), StartupError> {
|
fn check_section<T: config::SettingsSection>() -> Result<(), StartupError> {
|
||||||
|
|
@ -55,24 +53,21 @@ fn check_section<T: config::SettingsSection>() -> Result<(), StartupError> {
|
||||||
|
|
||||||
/// Ajustes globales de [`SETTINGS`].
|
/// Ajustes globales de [`SETTINGS`].
|
||||||
///
|
///
|
||||||
/// Secciones [`AppSettings`], [`DevSettings`], [`LogSettings`], [`ServerSettings`] y
|
/// Secciones [`AppSettings`], [`DevSettings`], [`LogSettings`] y [`ServerSettings`].
|
||||||
/// [`UploadSettings`].
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Settings {
|
pub struct Settings {
|
||||||
pub app: AppSettings,
|
pub app: AppSettings,
|
||||||
pub dev: DevSettings,
|
pub dev: DevSettings,
|
||||||
pub log: LogSettings,
|
pub log: LogSettings,
|
||||||
pub server: ServerSettings,
|
pub server: ServerSettings,
|
||||||
pub upload: UploadSettings,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Secciones de los ajustes globales, para reconocerlas en los archivos de configuración.
|
// Secciones de los ajustes globales, para reconocerlas en los archivos de configuración.
|
||||||
pub(crate) const SECTIONS: [&str; 5] = [
|
pub(crate) const SECTIONS: [&str; 4] = [
|
||||||
<AppSettings as config::SettingsSection>::SECTION,
|
<AppSettings as config::SettingsSection>::SECTION,
|
||||||
<DevSettings as config::SettingsSection>::SECTION,
|
<DevSettings as config::SettingsSection>::SECTION,
|
||||||
<LogSettings as config::SettingsSection>::SECTION,
|
<LogSettings as config::SettingsSection>::SECTION,
|
||||||
<ServerSettings 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`].
|
/// Sección **`[app]`** de la configuración. Forma parte de [`Settings`].
|
||||||
|
|
@ -224,59 +219,11 @@ pub struct ServerSettings {
|
||||||
/// Puerto de escucha del servidor web.
|
/// Puerto de escucha del servidor web.
|
||||||
#[default = 8080]
|
#[default = 8080]
|
||||||
pub bind_port: u16,
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{AppSettings, DevSettings, LogSettings, ServerSettings, UploadSettings, config};
|
use super::{AppSettings, DevSettings, LogSettings, ServerSettings, config};
|
||||||
|
|
||||||
// `reference.toml` documents every option; with unknown keys rejected, loading it proves that
|
// `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.
|
// it only documents keys that exist, with values of the right type.
|
||||||
|
|
@ -288,7 +235,6 @@ mod tests {
|
||||||
config::load_from_str::<DevSettings>(REFERENCE).unwrap();
|
config::load_from_str::<DevSettings>(REFERENCE).unwrap();
|
||||||
config::load_from_str::<LogSettings>(REFERENCE).unwrap();
|
config::load_from_str::<LogSettings>(REFERENCE).unwrap();
|
||||||
config::load_from_str::<ServerSettings>(REFERENCE).unwrap();
|
config::load_from_str::<ServerSettings>(REFERENCE).unwrap();
|
||||||
config::load_from_str::<UploadSettings>(REFERENCE).unwrap();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
|
|
@ -66,16 +66,3 @@ poweredby_pagetop = Powered by { $pagetop_link }
|
||||||
|
|
||||||
# Table component.
|
# Table component.
|
||||||
table_empty = No data to display
|
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,16 +66,3 @@ poweredby_pagetop = Funciona con { $pagetop_link }
|
||||||
|
|
||||||
# Table component.
|
# Table component.
|
||||||
table_empty = No hay datos que mostrar
|
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,11 +2,9 @@
|
||||||
//!
|
//!
|
||||||
//! Define rutas y handlers: el [`Router`], las operaciones HTTP ([`get`], [`post`], [`put`],
|
//! Define rutas y handlers: el [`Router`], las operaciones HTTP ([`get`], [`post`], [`put`],
|
||||||
//! [`delete`], [`patch`]), los extractores ([`Path`], [`Query`], [`Form`], [`RawForm`],
|
//! [`delete`], [`patch`]), los extractores ([`Path`], [`Query`], [`Form`], [`RawForm`],
|
||||||
//! [`Multipart`], [`Request`]) e [`IntoResponse`], el módulo [`middleware`] para *middlewares* de
|
//! [`Request`]) e [`IntoResponse`], el módulo [`middleware`] para *middlewares* de función, y
|
||||||
//! función, y re-exporta el módulo `http` para tipos de bajo nivel como `StatusCode`, `HeaderName`
|
//! re-exporta el módulo `http` para tipos de bajo nivel como `StatusCode`, `HeaderName` o `Method`.
|
||||||
//! o `Method`. También ofrece utilidades para servir archivos estáticos, [`ServeDir`] y
|
//! También ofrece utilidades para servir archivos estáticos, [`ServeDir`] y [`ServeEmbedded`].
|
||||||
//! [`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
|
//! Los handlers son las funciones asíncronas que el servidor invoca al recibir una petición HTTP en
|
||||||
//! una ruta concreta.
|
//! una ruta concreta.
|
||||||
|
|
@ -20,10 +18,7 @@ pub use axum::http;
|
||||||
pub use axum::Router;
|
pub use axum::Router;
|
||||||
|
|
||||||
// Extractores de petición.
|
// Extractores de petición.
|
||||||
pub use axum::extract::{Form, Multipart, Path, Query, RawForm, Request};
|
pub use axum::extract::{Form, Path, Query, RawForm, Request};
|
||||||
|
|
||||||
// Partes y errores del extractor `Multipart`.
|
|
||||||
pub use axum::extract::multipart;
|
|
||||||
|
|
||||||
// Para implementar respuestas.
|
// Para implementar respuestas.
|
||||||
pub use axum::response::{IntoResponse, Response};
|
pub use axum::response::{IntoResponse, Response};
|
||||||
|
|
@ -34,14 +29,6 @@ pub use axum::routing::{delete, get, patch, post, put};
|
||||||
// Middlewares de función (`from_fn`) y tipos asociados (`Next`).
|
// Middlewares de función (`from_fn`) y tipos asociados (`Next`).
|
||||||
pub use axum::middleware;
|
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::body::Body;
|
||||||
use axum::extract::FromRequestParts;
|
use axum::extract::FromRequestParts;
|
||||||
|
|
||||||
|
|
@ -518,15 +505,6 @@ pub mod test {
|
||||||
self.header("content-type", "application/x-www-form-urlencoded")
|
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.
|
/// 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
|
/// Útil para simular lo que un middleware haría en producción antes de que el handler
|
||||||
|
|
|
||||||
|
|
@ -1,231 +0,0 @@
|
||||||
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"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,913 +0,0 @@
|
||||||
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");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,71 +0,0 @@
|
||||||
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""#));
|
|
||||||
}
|
|
||||||
|
|
@ -1,557 +0,0 @@
|
||||||
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