diff --git a/extensions/pagetop-cron/src/config.rs b/extensions/pagetop-cron/src/config.rs index 90bf3a29..1e4a9fae 100644 --- a/extensions/pagetop-cron/src/config.rs +++ b/extensions/pagetop-cron/src/config.rs @@ -119,4 +119,22 @@ mod tests { fn reference_toml_documents_only_existing_keys() { config::load_from_str::(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::( + 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); + } } diff --git a/extensions/pagetop-cron/tests/config.rs b/extensions/pagetop-cron/tests/config.rs deleted file mode 100644 index 20403ba3..00000000 --- a/extensions/pagetop-cron/tests/config.rs +++ /dev/null @@ -1,20 +0,0 @@ -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::( - 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); -} diff --git a/extensions/pagetop-user/src/handlers/account.rs b/extensions/pagetop-user/src/handlers/account.rs index c91cb11e..80ff6b76 100644 --- a/extensions/pagetop-user/src/handlers/account.rs +++ b/extensions/pagetop-user/src/handlers/account.rs @@ -41,50 +41,32 @@ 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 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. +// inicio de sesión, que vuelve después a la ruta pedida. // // 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 { - 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() { + let is_htmx = request.is_htmx(); + let waypoint = if is_htmx { + Waypoint::new( + request + .hx_current_url() + .and_then(|url| url.parse::().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 { 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 { - 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 @@ -205,8 +187,8 @@ pub(crate) async fn public_profile_get( request: HttpRequest, web::Path(id): web::Path, ) -> Result { - // 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) { diff --git a/extensions/pagetop-user/src/locale/en-US/common.ftl b/extensions/pagetop-user/src/locale/en-US/common.ftl index 290079fa..c8b9a0ac 100644 --- a/extensions/pagetop-user/src/locale/en-US/common.ftl +++ b/extensions/pagetop-user/src/locale/en-US/common.ftl @@ -74,7 +74,6 @@ 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. diff --git a/extensions/pagetop-user/src/locale/es-ES/common.ftl b/extensions/pagetop-user/src/locale/es-ES/common.ftl index 4b19242b..908aee0f 100644 --- a/extensions/pagetop-user/src/locale/es-ES/common.ftl +++ b/extensions/pagetop-user/src/locale/es-ES/common.ftl @@ -74,7 +74,6 @@ 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. diff --git a/extensions/pagetop-user/tests/flows.rs b/extensions/pagetop-user/tests/flows.rs index c9aa3a01..fb75a76d 100644 --- a/extensions/pagetop-user/tests/flows.rs +++ b/extensions/pagetop-user/tests/flows.rs @@ -828,51 +828,4 @@ 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=")); } diff --git a/src/global.rs b/src/global.rs index f89a83d3..43daf7cd 100644 --- a/src/global.rs +++ b/src/global.rs @@ -411,4 +411,95 @@ mod tests { config::load_from_str::(REFERENCE).unwrap(); config::load_from_str::(REFERENCE).unwrap(); } + + #[test] + fn enum_values_are_case_insensitive() { + let log = config::load_from_str::("[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::("[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::(&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::(&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::(&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}"); + } + } } diff --git a/src/web.rs b/src/web.rs index 695e1139..d691098c 100644 --- a/src/web.rs +++ b/src/web.rs @@ -125,18 +125,12 @@ pub struct HttpRequest(Arc); // 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 @@ -230,7 +224,6 @@ 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(), @@ -638,7 +631,6 @@ 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, diff --git a/tests/global_settings.rs b/tests/global_settings.rs deleted file mode 100644 index 5963ec65..00000000 --- a/tests/global_settings.rs +++ /dev/null @@ -1,94 +0,0 @@ -use pagetop::prelude::*; - -use global::{AppSettings, LogRolling, LogSettings, ServerSettings}; - -#[pagetop::test] -async fn enum_values_are_case_insensitive() { - let log = config::load_from_str::("[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::("[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::(&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::(&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::(&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}"); - } -} diff --git a/tests/web_test_request.rs b/tests/web_test_request.rs index 0f12ec3c..c8235901 100644 --- a/tests/web_test_request.rs +++ b/tests/web_test_request.rs @@ -70,10 +70,3 @@ 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()); -}