Compare commits
2 commits
a0416e5670
...
87711e4a37
| Author | SHA1 | Date | |
|---|---|---|---|
| 87711e4a37 | |||
| d074f252a7 |
10 changed files with 214 additions and 127 deletions
|
|
@ -119,22 +119,4 @@ mod tests {
|
|||
fn reference_toml_documents_only_existing_keys() {
|
||||
config::load_from_str::<CronSettings>(REFERENCE).unwrap();
|
||||
}
|
||||
|
||||
// Job keys usually contain dots, which TOML only accepts quoted. They must reach the map as a
|
||||
// single key, not as nested tables.
|
||||
#[test]
|
||||
fn quoted_job_keys_with_dots_are_kept_whole() {
|
||||
let settings = config::load_from_str::<CronSettings>(
|
||||
r#"
|
||||
[cron.jobs."shop.cleanup"]
|
||||
enabled = false
|
||||
schedule = "@hourly"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let job = &settings.jobs["shop.cleanup"];
|
||||
assert!(!job.enabled);
|
||||
assert_eq!(job.schedule.as_deref(), Some("@hourly"));
|
||||
assert_eq!(job.timeout_secs, None);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
20
extensions/pagetop-cron/tests/config.rs
Normal file
20
extensions/pagetop-cron/tests/config.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
use pagetop::prelude::*;
|
||||
use pagetop_cron::config::CronSettings;
|
||||
|
||||
// Job keys usually contain dots, which TOML only accepts quoted. They must reach the map as a
|
||||
// single key, not as nested tables.
|
||||
#[pagetop::test]
|
||||
async fn quoted_job_keys_with_dots_are_kept_whole() {
|
||||
let settings = config::load_from_str::<CronSettings>(
|
||||
r#"
|
||||
[cron.jobs."shop.cleanup"]
|
||||
enabled = false
|
||||
schedule = "@hourly"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let job = &settings.jobs["shop.cleanup"];
|
||||
assert!(!job.enabled);
|
||||
assert_eq!(job.schedule.as_deref(), Some("@hourly"));
|
||||
assert_eq!(job.timeout_secs, None);
|
||||
}
|
||||
|
|
@ -41,32 +41,50 @@ fn login_redirect(request: HttpRequest, next: &'static str) -> Response {
|
|||
}
|
||||
|
||||
// Respuesta a un usuario anónimo sin acceso a una ruta (acción `AnonymousDenied`): el formulario de
|
||||
// inicio de sesión, que vuelve después a la ruta pedida.
|
||||
// inicio de sesión, que vuelve después a la página de la que venía (ver `return_path()`). Si
|
||||
// enviaba algo, se le avisa de que no se ha guardado: el envío se pierde, y no se repite al volver.
|
||||
//
|
||||
// Una petición HTMX seguiría la redirección sin avisar y pintaría el formulario dentro del
|
||||
// fragmento que esperaba, así que se le pide con `HX-Redirect` que cargue la página completa.
|
||||
// Vuelve después a la página que tenía abierta el navegador (`HX-Current-URL`), no a la ruta del
|
||||
// fragmento, que puede no admitir `GET`.
|
||||
pub(crate) fn offer_login(request: &HttpRequest) -> Option<Response> {
|
||||
let is_htmx = request.is_htmx();
|
||||
let waypoint = if is_htmx {
|
||||
Waypoint::new(
|
||||
request
|
||||
.hx_current_url()
|
||||
.and_then(|url| url.parse::<web::http::Uri>().ok())
|
||||
.and_then(|uri| uri.path_and_query().map(|pq| pq.as_str().to_owned())),
|
||||
)
|
||||
} else {
|
||||
Waypoint::new(request.uri().to_owned())
|
||||
};
|
||||
let login = waypoint.append_to(Context::new(request.clone()).route(LOGIN_PATH));
|
||||
Some(if is_htmx {
|
||||
let cx = Context::new(request.clone());
|
||||
let login = Waypoint::new(return_path(request)).append_to(cx.route(LOGIN_PATH));
|
||||
let response = if request.is_htmx() {
|
||||
HtmxResponse::empty().redirect(login).into_response()
|
||||
} else {
|
||||
Redirect::see_other(login).into_response()
|
||||
};
|
||||
Some(if request.method().is_safe() {
|
||||
response
|
||||
} else {
|
||||
response.with_message(
|
||||
&cx,
|
||||
MessageLevel::Warning,
|
||||
Lc::t("msg-login-required", &LOCALES_USER),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Ruta a la que volver tras iniciar sesión: la pedida, si se puede abrir de nuevo. La de un
|
||||
// fragmento HTMX o la de un envío puede no admitir `GET`, así que entonces es la página que tenía
|
||||
// abierta el navegador (`HX-Current-URL` o `Referer`). Un `Referer` de otro sitio, posible con
|
||||
// `server.trusted_origins`, no dice nada de esta aplicación: se vuelve sin destino.
|
||||
fn return_path(request: &HttpRequest) -> Option<String> {
|
||||
use web::http::{Uri, header};
|
||||
|
||||
let path_of = |uri: Uri| uri.path_and_query().map(|pq| pq.as_str().to_owned());
|
||||
if request.is_htmx() {
|
||||
return path_of(request.hx_current_url()?.parse().ok()?);
|
||||
}
|
||||
if request.method().is_safe() {
|
||||
return Some(request.uri().to_owned());
|
||||
}
|
||||
let headers = request.headers();
|
||||
let referer: Uri = headers.get(header::REFERER)?.to_str().ok()?.parse().ok()?;
|
||||
let host = headers.get(header::HOST)?.to_str().ok()?;
|
||||
(referer.authority()?.as_str() == host).then(|| path_of(referer))?
|
||||
}
|
||||
|
||||
// **< profile_get >********************************************************************************
|
||||
|
||||
/// GET /user - Perfil del usuario autenticado. Redirige al formulario de inicio de sesión si no hay
|
||||
|
|
@ -187,8 +205,8 @@ pub(crate) async fn public_profile_get(
|
|||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
// El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen. Sin él, la
|
||||
// misma respuesta que una ruta sin acceso: el inicio de sesión a un anónimo y 403 al resto.
|
||||
// El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen. Sin él,
|
||||
// la misma respuesta que una ruta sin acceso: el inicio de sesión a un anónimo y 403 al resto.
|
||||
if current_user_id(&request) != Some(id)
|
||||
&& !has_permission(&request, &UserPermission::ViewProfiles)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ msg-email-change-pending =
|
|||
|
||||
msg-confirm-email-change = Press the button to use this email address in your account.
|
||||
|
||||
msg-login-required = Sign in to continue. What you just sent has not been saved.
|
||||
msg-account-created = Your account has been created. You can now sign in.
|
||||
msg-email-verified = Your email address has been confirmed.
|
||||
msg-password-reset-done = Your password has been changed. Sign in with the new one.
|
||||
|
|
|
|||
|
|
@ -74,6 +74,7 @@ msg-email-change-pending =
|
|||
|
||||
msg-confirm-email-change = Pulsa el botón para usar esta dirección de correo en tu cuenta.
|
||||
|
||||
msg-login-required = Inicia sesión para continuar. Lo que acabas de enviar no se ha guardado.
|
||||
msg-account-created = Tu cuenta se ha creado. Ya puedes iniciar sesión.
|
||||
msg-email-verified = Tu dirección de correo se ha confirmado.
|
||||
msg-password-reset-done = Tu contraseña se ha cambiado. Inicia sesión con la nueva.
|
||||
|
|
|
|||
|
|
@ -828,4 +828,51 @@ async fn anonymous_visitors_are_offered_to_sign_in(client: &Client) {
|
|||
reply.header("hx-redirect"),
|
||||
"/user/login?waypoint=%2Fadmin%2Fuser%2Fusers%3Fsort%3Dname"
|
||||
);
|
||||
// Reading a page or a fragment loses nothing, so there is nothing to warn about.
|
||||
assert_eq!(reply.header("set-cookie"), "");
|
||||
|
||||
// A submission returns to the page it came from: its own route may only accept `POST`.
|
||||
let submit = || {
|
||||
web::test::TestRequest::post()
|
||||
.uri("/admin/user/users/new")
|
||||
.header("host", "app.example")
|
||||
};
|
||||
let reply = client
|
||||
.send(submit().header("referer", "https://app.example/admin/user/users?page=2"))
|
||||
.await;
|
||||
assert_eq!(reply.status, Status::SEE_OTHER);
|
||||
assert_eq!(
|
||||
reply.location(),
|
||||
"/user/login?waypoint=%2Fadmin%2Fuser%2Fusers%3Fpage%3D2"
|
||||
);
|
||||
// The login page warns that it was not saved.
|
||||
let flash = reply.header("set-cookie").split(';').next().unwrap();
|
||||
let page = client.get("/user/login", Some(flash)).await;
|
||||
assert!(page.body.contains("Sign in to continue"), "{}", page.body);
|
||||
|
||||
// Without a page to return to, or with one of another site, it signs in without a destination.
|
||||
for reply in [
|
||||
client.send(submit()).await,
|
||||
client
|
||||
.send(submit().header("referer", "https://other.example/admin/user/users"))
|
||||
.await,
|
||||
] {
|
||||
assert_eq!(reply.status, Status::SEE_OTHER);
|
||||
assert_eq!(reply.location(), "/user/login");
|
||||
assert!(reply.header("set-cookie").starts_with("pagetop_flash="));
|
||||
}
|
||||
|
||||
// With HTMX, a submission also warns, and returns to the page open in the browser.
|
||||
let reply = client
|
||||
.send(
|
||||
submit()
|
||||
.header("hx-request", "true")
|
||||
.header("hx-current-url", "https://app.example/admin/user/users"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
reply.header("hx-redirect"),
|
||||
"/user/login?waypoint=%2Fadmin%2Fuser%2Fusers"
|
||||
);
|
||||
assert!(reply.header("set-cookie").starts_with("pagetop_flash="));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -411,95 +411,4 @@ mod tests {
|
|||
config::load_from_str::<ServerSettings>(REFERENCE).unwrap();
|
||||
config::load_from_str::<UploadSettings>(REFERENCE).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enum_values_are_case_insensitive() {
|
||||
let log = config::load_from_str::<LogSettings>("[log]\nrolling = \"daily\"\n").unwrap();
|
||||
assert_eq!(log.rolling, super::LogRolling::Daily);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_enum_values_are_rejected() {
|
||||
let error = config::load_from_str::<LogSettings>("[log]\nrolling = \"Daly\"\n")
|
||||
.expect_err("invalid value accepted")
|
||||
.to_string();
|
||||
assert!(error.contains("Daly"));
|
||||
assert!(error.contains("Daily"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_ip_header_must_be_a_valid_header_name() {
|
||||
let load = |value: &str| {
|
||||
let toml = format!("[server]\nclient_ip_header = \"{value}\"\n");
|
||||
config::load_from_str::<ServerSettings>(&toml)
|
||||
};
|
||||
assert_eq!(load(" X-Real-IP ").unwrap().client_ip_header, "X-Real-IP");
|
||||
assert_eq!(load("").unwrap().client_ip_header, "");
|
||||
let error = load("X Real IP").expect_err("invalid name accepted");
|
||||
assert!(error.to_string().contains("X Real IP"), "{error}");
|
||||
// Its values are not plain addresses, so it would never give one.
|
||||
assert!(load("Forwarded").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admin_path_must_be_an_absolute_path_without_a_trailing_slash() {
|
||||
let load = |value: &str| {
|
||||
let toml = format!("[app]\nadmin_path = \"{value}\"\n");
|
||||
config::load_from_str::<AppSettings>(&toml)
|
||||
};
|
||||
assert_eq!(load(" /manage ").unwrap().admin_path, "/manage");
|
||||
assert_eq!(load("/site/admin-2").unwrap().admin_path, "/site/admin-2");
|
||||
for invalid in [
|
||||
"",
|
||||
"/",
|
||||
"admin",
|
||||
"/admin/",
|
||||
"/site//admin",
|
||||
"/.",
|
||||
"/site/../admin",
|
||||
"/{admin}",
|
||||
"/ad min",
|
||||
] {
|
||||
let error = load(invalid).expect_err(invalid);
|
||||
assert!(error.to_string().contains("invalid admin path"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusted_origins_are_normalized_and_validated() {
|
||||
let load = |value: &str| {
|
||||
let toml = format!("[server]\ntrusted_origins = [\"{value}\"]\n");
|
||||
config::load_from_str::<ServerSettings>(&toml)
|
||||
};
|
||||
let origins = |value| load(value).unwrap().trusted_origins;
|
||||
// Browsers send the Origin header in lowercase and without a trailing slash.
|
||||
assert_eq!(
|
||||
origins(" HTTPS://App.Example.com/ "),
|
||||
["https://app.example.com"]
|
||||
);
|
||||
assert_eq!(origins("http://localhost:3000"), ["http://localhost:3000"]);
|
||||
// Nor with the default port of the scheme, which they leave out.
|
||||
assert_eq!(
|
||||
origins("https://app.example.com:443"),
|
||||
["https://app.example.com"]
|
||||
);
|
||||
assert_eq!(origins("http://[::1]:80"), ["http://[::1]"]);
|
||||
assert_eq!(
|
||||
origins("http://app.example.com:443"),
|
||||
["http://app.example.com:443"]
|
||||
);
|
||||
// None of these could ever match an Origin header.
|
||||
for invalid in [
|
||||
"app.example.com",
|
||||
"ftp://app.example.com",
|
||||
"https://app.example.com/path",
|
||||
"https://app.example.com?x=1",
|
||||
"https://user@app.example.com",
|
||||
"https://app.example.com#top",
|
||||
"",
|
||||
] {
|
||||
let error = load(invalid).expect_err(invalid);
|
||||
assert!(error.to_string().contains("invalid origin"), "{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -125,12 +125,18 @@ pub struct HttpRequest(Arc<RequestParts>);
|
|||
// de los handlers, donde un tipo grande se copiaría en cada retorno.
|
||||
#[derive(Debug)]
|
||||
struct RequestParts {
|
||||
method: http::Method,
|
||||
uri: http::Uri,
|
||||
headers: http::HeaderMap,
|
||||
extensions: http::Extensions,
|
||||
}
|
||||
|
||||
impl HttpRequest {
|
||||
/// Devuelve el método HTTP de la petición.
|
||||
pub fn method(&self) -> &http::Method {
|
||||
&self.0.method
|
||||
}
|
||||
|
||||
/// Devuelve la URI completa de la petición, incluyendo la *query string* si la hay.
|
||||
pub fn uri(&self) -> &str {
|
||||
self.0
|
||||
|
|
@ -224,6 +230,7 @@ impl HttpRequest {
|
|||
// También la usa el *middleware* que comprueba el acceso de las rutas, antes del *handler*.
|
||||
pub(crate) fn from_parts(parts: &http::request::Parts) -> Self {
|
||||
HttpRequest(Arc::new(RequestParts {
|
||||
method: parts.method.clone(),
|
||||
uri: parts.uri.clone(),
|
||||
headers: parts.headers.clone(),
|
||||
extensions: parts.extensions.clone(),
|
||||
|
|
@ -631,6 +638,7 @@ pub mod test {
|
|||
pub fn to_http_request(self) -> super::HttpRequest {
|
||||
let uri = self.uri.parse().unwrap();
|
||||
super::HttpRequest(std::sync::Arc::new(super::RequestParts {
|
||||
method: self.method,
|
||||
uri,
|
||||
headers: self.headers,
|
||||
extensions: self.extensions,
|
||||
|
|
|
|||
94
tests/global_settings.rs
Normal file
94
tests/global_settings.rs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use global::{AppSettings, LogRolling, LogSettings, ServerSettings};
|
||||
|
||||
#[pagetop::test]
|
||||
async fn enum_values_are_case_insensitive() {
|
||||
let log = config::load_from_str::<LogSettings>("[log]\nrolling = \"daily\"\n").unwrap();
|
||||
assert_eq!(log.rolling, LogRolling::Daily);
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn invalid_enum_values_are_rejected() {
|
||||
let error = config::load_from_str::<LogSettings>("[log]\nrolling = \"Daly\"\n")
|
||||
.expect_err("invalid value accepted")
|
||||
.to_string();
|
||||
assert!(error.contains("Daly"));
|
||||
assert!(error.contains("Daily"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn client_ip_header_must_be_a_valid_header_name() {
|
||||
let load = |value: &str| {
|
||||
let toml = format!("[server]\nclient_ip_header = \"{value}\"\n");
|
||||
config::load_from_str::<ServerSettings>(&toml)
|
||||
};
|
||||
assert_eq!(load(" X-Real-IP ").unwrap().client_ip_header, "X-Real-IP");
|
||||
assert_eq!(load("").unwrap().client_ip_header, "");
|
||||
let error = load("X Real IP").expect_err("invalid name accepted");
|
||||
assert!(error.to_string().contains("X Real IP"), "{error}");
|
||||
// Its values are not plain addresses, so it would never give one.
|
||||
assert!(load("Forwarded").is_err());
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn admin_path_must_be_an_absolute_path_without_a_trailing_slash() {
|
||||
let load = |value: &str| {
|
||||
let toml = format!("[app]\nadmin_path = \"{value}\"\n");
|
||||
config::load_from_str::<AppSettings>(&toml)
|
||||
};
|
||||
assert_eq!(load(" /manage ").unwrap().admin_path, "/manage");
|
||||
assert_eq!(load("/site/admin-2").unwrap().admin_path, "/site/admin-2");
|
||||
for invalid in [
|
||||
"",
|
||||
"/",
|
||||
"admin",
|
||||
"/admin/",
|
||||
"/site//admin",
|
||||
"/.",
|
||||
"/site/../admin",
|
||||
"/{admin}",
|
||||
"/ad min",
|
||||
] {
|
||||
let error = load(invalid).expect_err(invalid);
|
||||
assert!(error.to_string().contains("invalid admin path"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn trusted_origins_are_normalized_and_validated() {
|
||||
let load = |value: &str| {
|
||||
let toml = format!("[server]\ntrusted_origins = [\"{value}\"]\n");
|
||||
config::load_from_str::<ServerSettings>(&toml)
|
||||
};
|
||||
let origins = |value| load(value).unwrap().trusted_origins;
|
||||
// Browsers send the Origin header in lowercase and without a trailing slash.
|
||||
assert_eq!(
|
||||
origins(" HTTPS://App.Example.com/ "),
|
||||
["https://app.example.com"]
|
||||
);
|
||||
assert_eq!(origins("http://localhost:3000"), ["http://localhost:3000"]);
|
||||
// Nor with the default port of the scheme, which they leave out.
|
||||
assert_eq!(
|
||||
origins("https://app.example.com:443"),
|
||||
["https://app.example.com"]
|
||||
);
|
||||
assert_eq!(origins("http://[::1]:80"), ["http://[::1]"]);
|
||||
assert_eq!(
|
||||
origins("http://app.example.com:443"),
|
||||
["http://app.example.com:443"]
|
||||
);
|
||||
// None of these could ever match an Origin header.
|
||||
for invalid in [
|
||||
"app.example.com",
|
||||
"ftp://app.example.com",
|
||||
"https://app.example.com/path",
|
||||
"https://app.example.com?x=1",
|
||||
"https://user@app.example.com",
|
||||
"https://app.example.com#top",
|
||||
"",
|
||||
] {
|
||||
let error = load(invalid).expect_err(invalid);
|
||||
assert!(error.to_string().contains("invalid origin"), "{error}");
|
||||
}
|
||||
}
|
||||
|
|
@ -70,3 +70,10 @@ async fn a_form_request_without_fields_is_rejected() {
|
|||
let (status, _) = send(web::test::TestRequest::post()).await;
|
||||
assert!(status.is_client_error());
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn http_request_exposes_the_method() {
|
||||
let request = web::test::TestRequest::post().to_http_request();
|
||||
assert_eq!(request.method(), web::http::Method::POST);
|
||||
assert!(!request.method().is_safe());
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue