✨ (web): Recuerda el estado de los listados

Añade `web::remember_query()`, que guarda en una cookie por listado los
filtros, el orden y la página, y los restaura con un 303 al volver al
listado sin parámetros. "Limpiar" de `ListFilter` añade `?reset` para
olvidarlos.
This commit is contained in:
Manuel Cillero 2026-11-11 07:46:27 +01:00
parent d8493291e4
commit e4a88b2150
6 changed files with 728 additions and 12 deletions

View file

@ -21,13 +21,16 @@ use crate::base::component::form;
///
/// Por defecto, los filtros **no** se envían solos: se aplican al pulsar el botón (o Enter en un
/// campo de texto), de modo que se pueden ajustar varios campos y pedir el listado una sola vez.
/// Con [`with_auto_submit(true)`](Self::with_auto_submit) se aplican en cuanto cambia cualquier
/// campo, sin botón.
/// Con [`with_auto_submit(true)`] se aplican en cuanto cambia cualquier campo, sin botón.
///
/// Junto al botón aparece por defecto el enlace "Limpiar", que vuelve a la ruta del filtro sin
/// ningún parámetro: el listado tal como se ve al entrar, también sin orden ni página. Recarga la
/// página entera, para que los campos del filtro se vacíen también. Se quita con
/// [`with_reset(false)`](Self::with_reset).
/// Junto al botón aparece por defecto el enlace "Limpiar", que muestra el listado limpio: sin
/// filtros y con el orden y la página por defecto. Recarga la página entera para que también se
/// vacíen los campos del filtro. Se puede quitar con [`with_reset(false)`].
///
/// "Limpiar" apunta a la ruta del filtro con el parámetro `reset` (p. ej. `/items?reset`, más
/// `lang` si la ruta lo lleva). Si el listado se monta con [`web::remember_query()`], ese parámetro
/// hace además que olvide el estado que recordaba. Si no, el *handler* lo recibe como un parámetro
/// más y lo ignora, salvo que rechace los desconocidos (`#[serde(deny_unknown_fields)]`).
///
/// Con el botón, y si hay JavaScript, cada campo cuyo valor ya no coincide con el del filtro
/// aplicado se marca (clase `list-filter-changed` en su contenedor, `list-filter-pending` en el
@ -57,6 +60,9 @@ use crate::base::component::form;
///
/// [`with_filter_action()`]: Self::with_filter_action
/// [`with_prop()`]: Self::with_prop
/// [`with_auto_submit(true)`]: Self::with_auto_submit
/// [`with_reset(false)`]: Self::with_reset
/// [`web::remember_query()`]: crate::web::remember_query
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct ListFilter {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
@ -111,7 +117,7 @@ impl Component for ListFilter {
// campos, que no se volverían a pintar si sólo se actualizara el listado.
let reset = match (&action, self.reset()) {
(Some(route), true) => Some(
Button::anchor(Lc::l("list_filter_reset"), route.clone())
Button::anchor(Lc::l("list_filter_reset"), route.clone().with_flag("reset"))
.with_style(button::Style::Link)
.with_prop(PropsOp::set("target", "_top"))
.render(cx)

View file

@ -12,10 +12,12 @@ use crate::html::RoutePath;
/// página a la que ir para continuar.
///
/// `Waypoint` transporta ese valor a través de la cadena de pantallas. Se extrae de la petición
/// entrante con [`web::Query`](crate::web::Query), igual que cualquier otro parámetro, y se repone
/// en cada enlace o acción de formulario intermedia con [`append_to()`](Self::append_to) para que
/// sobreviva a la siguiente petición. Se resuelve con [`or()`](Self::or) al decidir el destino de
/// un enlace de vuelta o de una redirección.
/// entrante con [`web::Query`], igual que cualquier otro parámetro, y se repone en cada enlace o
/// acción de formulario intermedia con [`append_to()`] para que sobreviva a la siguiente petición.
/// Se resuelve con [`or()`] al decidir el destino de un enlace de vuelta o de una redirección.
///
/// Para volver a un listado con los filtros, el orden y la página en que se dejó no hace falta
/// transportarlo: basta con montar su ruta con [`web::remember_query()`].
///
/// # Ejemplo
///
@ -42,6 +44,11 @@ use crate::html::RoutePath;
/// Redirect::see_other(waypoint.or(ITEMS_PATH))
/// }
/// ```
///
/// [`append_to()`]: Self::append_to
/// [`or()`]: Self::or
/// [`web::Query`]: crate::web::Query
/// [`web::remember_query()`]: crate::web::remember_query
#[derive(AutoDefault, Clone, Debug, Deserialize)]
#[serde(from = "RawWaypoint")]
pub struct Waypoint {

View file

@ -77,6 +77,10 @@ pub use routes::{Layers, Routes, StaticFiles};
mod endpoint;
pub use endpoint::Endpoint;
// Estado de los listados (filtros, orden, página) recordado entre pantallas.
mod remember;
pub use remember::remember_query;
use axum::body::Body;
use axum::extract::FromRequestParts;

384
src/web/remember.rs Normal file
View file

@ -0,0 +1,384 @@
use std::borrow::Cow;
use crate::web::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
use crate::web::{IntoResponse, MethodRouter, Request, Response};
use axum::extract::OriginalUri;
use axum::middleware::{self, Next};
// Prefijo del nombre de las *cookies*; cada listado añade el *hash* de su ruta.
const COOKIE_PREFIX: &str = "pagetop_list_";
// Longitud del nombre de las *cookies*: el prefijo y 16 cifras hexadecimales.
const NAME_LEN: usize = COOKIE_PREFIX.len() + 16;
const SEC_FETCH_SITE: HeaderName = HeaderName::from_static("sec-fetch-site");
// Atributos comunes. Sin `Max-Age` es una *cookie* de sesión.
const COOKIE_ATTRS: &str = "; HttpOnly; SameSite=Lax";
// Estado más largo que esto no se recuerda: un listado no necesita tanto y la *cookie* viaja en
// cada petición a su ruta y a las que cuelgan de ella.
const MAX_STATE_LEN: usize = 1024;
// Parámetro que olvida el estado guardado. Lo añade el enlace "Limpiar" de `ListFilter`.
const RESET_PARAM: &str = "reset";
/// Hace que un listado recuerde su último estado (filtros, orden y página) mientras dure la sesión
/// del navegador.
///
/// Envuelve el `MethodRouter` de la ruta de un listado. Cada vez que la página se pide con
/// parámetros en la *query string* (al filtrar, ordenar o paginar, también desde HTMX) y responde
/// con éxito, los guarda. Cuando se vuelve a pedir **sin parámetros**, como hacen los enlaces de
/// vuelta, las redirecciones tras guardar un formulario o el menú, redirige (`303`) a la misma
/// ruta con el estado guardado. Así no hay que transportar el estado del listado por cada pantalla
/// intermedia, como haría [`Waypoint`].
///
/// Si todos los parámetros llegan vacíos (`?q=&status=`, un filtro enviado sin rellenar), equivale
/// a no filtrar: no se guarda nada y se olvida el estado anterior.
///
/// Con el parámetro `reset` (`?reset`), que añade el enlace "Limpiar" de [`ListFilter`], olvida el
/// estado y redirige a la ruta sin parámetros. El parámetro `lang` no se guarda nunca: se conserva
/// el de la petición en curso. Las peticiones de HTMX se redirigen igual: HTMX sigue la redirección
/// y, si actualiza el historial del navegador, guarda la URL final, con el estado.
///
/// Si el estado guardado deja de dar una página válida (por ejemplo, un error `400` porque un
/// parámetro ha cambiado en una versión posterior de la aplicación), se olvida.
///
/// El estado guardado sólo cambia con las peticiones que salen de la propia aplicación o que se
/// escriben a mano (según la cabecera `Sec-Fetch-Site` que envían los navegadores): un enlace desde
/// otro sitio no puede fijar ni borrar los filtros que recuerda quien lo sigue.
///
/// Sólo actúa en las peticiones `GET`; las demás llegan al *handler* sin cambios.
///
/// # Qué necesita el listado
///
/// Basta con montar su ruta con esta función: los enlaces de vuelta, los botones de cancelar y las
/// redirecciones tras guardar no cambian, siguen apuntando a la ruta del listado sin parámetros.
/// Para que funcione:
///
/// - El estado del listado debe ir en la *query string*. Así lo hacen [`ListFilter`] (un
/// formulario `GET`), [`Pager`] y los enlaces de orden de [`Table`], también con HTMX. Un estado
/// que no esté en la URL (filtros enviados por `POST`, sólo en JavaScript) no se recuerda.
/// - Un enlace a la ruta con parámetros propios es un estado nuevo y no restaura el guardado.
/// - Cada ruta tiene su propio estado: `/projects/5/tasks` y `/projects/6/tasks` se recuerdan por
/// separado.
/// - Un formulario de filtros propio, en lugar de [`ListFilter`], debe enlazar su "Limpiar" a la
/// ruta con `?reset` (con [`RoutePath::with_flag("reset")`][with_flag]); si no, volvería a
/// restaurar el filtro que se quería quitar.
///
/// # *Cookies*
///
/// El estado se guarda en el navegador, en una *cookie* por listado (`pagetop_list_` seguido de un
/// código derivado de la ruta, limitada a esa ruta con `Path`), sin nada en el servidor. Es una
/// *cookie* técnica de sesión: sólo se crea cuando el usuario filtra, ordena o pagina, sólo
/// contiene los parámetros del listado y el navegador la borra al cerrarse (salvo los que restauran
/// la sesión anterior al abrirse de nuevo, que la conservan). Como *cookie* de personalización de
/// la interfaz que el propio usuario solicita, suele quedar exenta de consentimiento, aunque
/// conviene declararla en la política de *cookies* de la aplicación. Las ventanas y pestañas del
/// navegador comparten el mismo estado. No se recuerda un estado de más de 1024 caracteres ni uno
/// con caracteres que una *cookie* no admite (los navegadores ya los codifican en la URL).
///
/// # Ejemplo
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// # async fn list_items() -> &'static str { "" }
/// fn configure_router(routes: web::Routes) -> web::Routes {
/// routes.public_route("/items", web::remember_query(web::get(list_items)))
/// }
/// ```
///
/// [`ListFilter`]: crate::base::component::ListFilter
/// [`Pager`]: crate::base::component::Pager
/// [`Table`]: crate::base::component::Table
/// [`Waypoint`]: crate::response::Waypoint
/// [with_flag]: crate::html::RoutePath::with_flag
pub fn remember_query(method_router: MethodRouter) -> MethodRouter {
method_router.layer(middleware::from_fn(remember))
}
async fn remember(request: Request, next: Next) -> Response {
if request.method() != Method::GET {
return next.run(request).await;
}
// Copia de la URI (sólo una cuenta de referencias), para que la ruta y la *query* sigan
// disponibles tras pasar la petición al *handler*. Dentro de un `Router` anidado la URI llega
// sin el prefijo; la *cookie* necesita la ruta real.
let uri = request
.extensions()
.get::<OriginalUri>()
.map_or_else(|| request.uri().clone(), |uri| uri.0.clone());
let raw_query = uri.query().unwrap_or_default();
let path = uri.path();
// Un `;` en la ruta rompería el atributo `Path` de la *cookie*. Y una ruta que empiece por `//`
// o `/\` (posible si el listado se monta en una ruta comodín) haría de la redirección una URL
// de otro sitio para el navegador.
if path.contains(';') || path.starts_with("//") || path.starts_with("/\\") {
return next.run(request).await;
}
let name = cookie_name(path);
// El estado guardado se vuelve a separar: una *cookie* manipulada podría traer `lang`, `reset`
// o nada útil (`&`), y redirigir con ella repetiría la redirección sin fin. Una con caracteres
// no válidos queda sin estado, como la que no trae nada útil, y se borra igual.
let saved = cookie_value(request.headers(), &name).map(|v| match str::from_utf8(v) {
Ok(v) if is_valid_state(v) => Params::split(v).state.into_owned(),
_ => String::new(),
});
// Sin parámetros ni estado guardado no hay nada que hacer.
if raw_query.is_empty() && saved.is_none() {
return next.run(request).await;
}
let query = Params::split(raw_query);
let writable = is_own_request(request.headers());
if query.reset {
let mut response = see_other(query.location(path, None));
if writable {
set_cookie(&mut response, &name, "", path, true);
}
return response;
}
if query.state.is_empty() {
match saved {
Some(saved) if !is_blank(&saved) => {
return see_other(query.location(path, Some(&saved)));
}
Some(_) => {
let mut response = next.run(request).await;
if writable {
set_cookie(&mut response, &name, "", path, true);
}
return response;
}
None => return next.run(request).await,
}
}
let state = &query.state;
let unchanged = saved.as_deref() == Some(state.as_ref());
let mut response = next.run(request).await;
if !writable {
return response;
}
if !response.status().is_success() {
// Un estado guardado que ya no da una página válida (parámetros de una versión anterior de
// la aplicación, un *handler* que redirige...) se olvida: si no, cada vuelta al listado
// repetiría el error, o la redirección, hasta cerrar el navegador.
if unchanged {
set_cookie(&mut response, &name, "", path, true);
}
return response;
}
if is_blank(state) {
if saved.is_some() {
set_cookie(&mut response, &name, "", path, true);
}
} else if !unchanged && state.len() <= MAX_STATE_LEN && is_valid_state(state) {
set_cookie(&mut response, &name, state, path, false);
}
response
}
// Redirección `303` a `location`, sin pasar por `Redirect`, que copia la cadena. La ruta sale de la
// URI de la petición y el estado está validado, así que siempre es una cabecera válida; si no lo
// fuera, mejor un `500`, como haría `Redirect`, que una redirección sin destino.
fn see_other(location: String) -> Response {
match HeaderValue::try_from(location) {
Ok(location) => (StatusCode::SEE_OTHER, [(header::LOCATION, location)]).into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
// Sólo cambian el estado guardado las peticiones de la propia aplicación o escritas a mano
// (`Sec-Fetch-Site` igual a `same-origin` o `none`): un enlace o una redirección desde otro sitio,
// o desde otro subdominio, no puede fijar ni borrar los filtros de quien lo sigue. Sin la cabecera
// (navegadores antiguos, otros clientes) se admite, con el mismo criterio que la protección CSRF.
fn is_own_request(headers: &HeaderMap) -> bool {
headers
.get(SEC_FETCH_SITE)
.is_none_or(|site| matches!(site.as_bytes(), b"same-origin" | b"none"))
}
// Un estado con todos los valores vacíos (`q=&status=`, un filtro enviado sin rellenar) equivale a
// no filtrar: no merece una *cookie*.
fn is_blank(state: &str) -> bool {
state.split('&').all(|pair| {
pair.split_once('=')
.is_none_or(|(_, value)| value.is_empty())
})
}
// Parámetros de la petición separados en estado del listado, `lang` y la marca `reset`. Sin `lang`
// ni `reset`, lo habitual, el estado es la propia *query* y no se copia.
struct Params<'a> {
state: Cow<'a, str>,
lang: String,
reset: bool,
}
impl<'a> Params<'a> {
fn split(query: &'a str) -> Self {
let mut pairs = query.split('&');
if pairs.all(|pair| !pair.is_empty() && !matches!(key_of(pair), "lang" | RESET_PARAM)) {
return Params {
state: Cow::Borrowed(query),
lang: String::new(),
reset: false,
};
}
let mut state = String::with_capacity(query.len());
let mut split = Params {
state: Cow::Borrowed(""),
lang: String::new(),
reset: false,
};
for pair in query.split('&').filter(|pair| !pair.is_empty()) {
let target = match key_of(pair) {
"lang" => &mut split.lang,
RESET_PARAM => {
split.reset = true;
continue;
}
_ => &mut state,
};
if !target.is_empty() {
target.push('&');
}
target.push_str(pair);
}
split.state = Cow::Owned(state);
split
}
// Ruta del listado con el estado indicado y el `lang` de la petición en curso.
fn location(&self, path: &str, state: Option<&str>) -> String {
let state = state.unwrap_or_default();
let mut location = String::with_capacity(path.len() + state.len() + self.lang.len() + 2);
location.push_str(path);
for part in [state, self.lang.as_str()] {
if !part.is_empty() {
location.push(if location.len() == path.len() {
'?'
} else {
'&'
});
location.push_str(part);
}
}
location
}
}
fn key_of(pair: &str) -> &str {
pair.split_once('=').map_or(pair, |(key, _)| key)
}
// Nombre de la *cookie* de un listado, en la pila: el prefijo y el *hash* FNV-1a de 64 bits de la
// ruta en hexadecimal. Es estable entre procesos e instancias, a diferencia de `RandomState`, y
// basta para distinguir las rutas de una aplicación.
fn cookie_name(path: &str) -> [u8; NAME_LEN] {
let hash = path.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
});
let mut name = [0; NAME_LEN];
name[..COOKIE_PREFIX.len()].copy_from_slice(COOKIE_PREFIX.as_bytes());
for (i, digit) in name[COOKIE_PREFIX.len()..].iter_mut().enumerate() {
*digit = b"0123456789abcdef"[(hash >> (60 - 4 * i) & 0xf) as usize];
}
name
}
// Sólo caracteres admitidos en el valor de una *cookie* (RFC 6265: ASCII visible salvo `"`, `,`,
// `;` y `\`). Una *query string* que tenga otros no se recuerda; uno guardado que los tenga (una
// *cookie* manipulada) se ignora. Así el valor también es seguro en la cabecera `Location`.
fn is_valid_state(state: &str) -> bool {
!state.is_empty()
&& state
.bytes()
.all(|b| b.is_ascii_graphic() && !matches!(b, b'"' | b',' | b';' | b'\\'))
}
// Valor de la *cookie* `name`, si la petición la trae, sin validar toda la cabecera. Con HTTP/2 el
// navegador puede repartir las *cookies* en varias cabeceras `cookie`.
fn cookie_value<'a>(headers: &'a HeaderMap, name: &[u8]) -> Option<&'a [u8]> {
headers
.get_all(header::COOKIE)
.iter()
.flat_map(|value| value.as_bytes().split(|&b| b == b';'))
.filter_map(|part| part.trim_ascii().strip_prefix(name)?.strip_prefix(b"="))
.find(|value| !value.is_empty())
}
fn set_cookie(response: &mut Response, name: &[u8], value: &str, path: &str, expired: bool) {
let mut cookie = String::with_capacity(NAME_LEN + value.len() + path.len() + 40);
// El nombre es ASCII: el prefijo y cifras hexadecimales.
cookie.extend(name.iter().map(|&b| char::from(b)));
cookie.push('=');
cookie.push_str(value);
cookie.push_str("; Path=");
cookie.push_str(path);
cookie.push_str(COOKIE_ATTRS);
if expired {
cookie.push_str("; Max-Age=0");
}
if let Ok(cookie) = HeaderValue::try_from(cookie) {
response.headers_mut().append(header::SET_COOKIE, cookie);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lang_and_reset_are_kept_apart_from_the_state() {
let query = Params::split("q=acer&lang=es&page=2&reset");
assert_eq!(query.state, "q=acer&page=2");
assert_eq!(query.lang, "lang=es");
assert!(query.reset);
}
#[test]
fn a_query_without_lang_or_reset_is_not_copied() {
assert!(matches!(
Params::split("q=acer&page=2").state,
Cow::Borrowed("q=acer&page=2")
));
assert!(matches!(Params::split("q=a&lang=es").state, Cow::Owned(_)));
}
#[test]
fn location_joins_path_state_and_lang() {
let query = Params::split("lang=es");
assert_eq!(query.location("/items", Some("q=a")), "/items?q=a&lang=es");
assert_eq!(query.location("/items", None), "/items?lang=es");
assert_eq!(
Params::split("").location("/items", Some("q=a")),
"/items?q=a"
);
}
#[test]
fn cookie_names_are_stable_and_distinct_per_path() {
// Changing the hash would silently drop the state every browser has saved.
assert_eq!(&cookie_name("/items"), b"pagetop_list_fca267fbaf9eb12a");
assert_ne!(cookie_name("/items"), cookie_name("/items/archived"));
}
#[test]
fn a_state_is_blank_only_when_every_value_is_empty() {
assert!(is_blank("q=&status="));
assert!(is_blank("q"));
assert!(!is_blank("q=&status=active"));
assert!(!is_blank("page=1"));
}
#[test]
fn states_with_characters_not_allowed_in_cookies_are_rejected() {
assert!(is_valid_state("q=a%20b&sort=name&dir=asc"));
assert!(!is_valid_state("q=a,b"));
assert!(!is_valid_state("q=\"a\""));
assert!(!is_valid_state(""));
}
}

View file

@ -77,7 +77,8 @@ async fn the_reset_link_goes_back_to_the_list_with_no_filters() {
.find("<a")
.map(|start| &html[start..])
.expect("reset link");
assert!(link.contains(r#"href="/items""#), "{html}");
// `reset` also forgets the state a list may remember with `web::remember_query()`.
assert!(link.contains(r#"href="/items?reset""#), "{html}");
// Not intercepted by libraries that load only part of the page, so the fields are emptied too.
assert!(link.contains(r#"target="_top""#), "{html}");
}

314
tests/web_remember_query.rs Normal file
View file

@ -0,0 +1,314 @@
use pagetop::prelude::*;
use web::http::{StatusCode, header};
struct ListExtension;
#[async_trait]
impl Extension for ListExtension {
fn configure_router(&self, routes: Routes) -> Routes {
routes
.public_route(
"/items",
web::remember_query(web::get(list).post(|| async { "posted" })),
)
.public_route("/failing", web::remember_query(web::get(failing)))
.public_route("/picky", web::remember_query(web::get(picky)))
.public_route("/{*rest}", web::remember_query(web::get(list)))
.route(
"/private",
Access::Authenticated,
web::remember_query(web::get(list)),
)
.nest(
"/nested",
Access::Public,
Router::new().route("/items", web::remember_query(web::get(list))),
)
}
}
async fn list(request: HttpRequest) -> String {
format!("query: {}", request.query_string())
}
async fn failing(request: HttpRequest) -> Result<Markup, ErrorPage> {
Err(ErrorPage::NotFound(request))
}
// Accepts any query but `q=stale`, as a list does with parameters from an older release.
async fn picky(request: HttpRequest) -> Result<String, ErrorPage> {
match request.query_string() {
"q=stale" => Err(ErrorPage::BadRequest(request)),
query => Ok(format!("query: {query}")),
}
}
async fn send(request: web::test::TestRequest) -> Response {
send_edited(request, |_| {}).await
}
// Sends `request` after `edit` changes its headers, for what `TestRequest` cannot express.
async fn send_edited(
request: web::test::TestRequest,
edit: impl FnOnce(&mut web::http::HeaderMap),
) -> Response {
let mut request = request.to_request();
edit(request.headers_mut());
let app = web::test::init_router(Application::prepare(&ListExtension).await.test());
web::test::send_request(&app, request).await
}
fn get(uri: &str, cookie: Option<&str>) -> web::test::TestRequest {
let request = web::test::TestRequest::get().uri(uri);
match cookie {
Some(cookie) => request.header("cookie", cookie),
None => request,
}
}
fn set_cookie(response: &Response) -> Option<&str> {
response
.headers()
.get(header::SET_COOKIE)
.and_then(|value| value.to_str().ok())
}
// `name=value` of the cookie set by `response`.
fn list_cookie(response: &Response) -> String {
let cookie = set_cookie(response).expect("the response sets the list cookie");
assert!(cookie.starts_with("pagetop_list_"), "{cookie}");
cookie.split(';').next().unwrap().to_owned()
}
fn location(response: &Response) -> &str {
response
.headers()
.get(header::LOCATION)
.and_then(|value| value.to_str().ok())
.expect("redirect location")
}
#[pagetop::test]
async fn a_list_remembers_its_state_and_restores_it_when_requested_without_it() {
let filtered = send(get("/items?q=acer&page=2&lang=es", None)).await;
assert_eq!(filtered.status(), StatusCode::OK);
let cookie = set_cookie(&filtered).unwrap();
assert!(
cookie.contains("=q=acer&page=2;"),
"lang is not saved: {cookie}"
);
assert!(cookie.contains("Path=/items;"), "{cookie}");
assert!(cookie.contains("HttpOnly"), "{cookie}");
assert!(!cookie.contains("Max-Age"), "a session cookie: {cookie}");
let cookie = list_cookie(&filtered);
let back = send(get("/items", Some(&cookie))).await;
assert_eq!(back.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&back), "/items?q=acer&page=2");
// The language of the current request is kept.
let back = send(get("/items?lang=en", Some(&cookie))).await;
assert_eq!(location(&back), "/items?q=acer&page=2&lang=en");
}
#[pagetop::test]
async fn without_a_saved_state_the_list_is_served_as_is() {
let response = send(get("/items", None)).await;
assert_eq!(response.status(), StatusCode::OK);
assert!(set_cookie(&response).is_none());
assert_eq!(web::test::read_body_text(response).await, "query: ");
}
#[pagetop::test]
async fn the_same_state_is_not_saved_again() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let again = send(get("/items?q=acer", Some(&cookie))).await;
assert_eq!(again.status(), StatusCode::OK);
assert!(set_cookie(&again).is_none());
}
#[pagetop::test]
async fn reset_forgets_the_state() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let reset = send(get("/items?reset&lang=es", Some(&cookie))).await;
assert_eq!(reset.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&reset), "/items?lang=es");
let expired = set_cookie(&reset).unwrap();
assert!(expired.starts_with(&cookie[..cookie.find('=').unwrap() + 1]));
assert!(expired.contains("Max-Age=0"), "{expired}");
}
#[pagetop::test]
async fn an_empty_filter_saves_nothing_and_forgets_the_state() {
// Submitting the filter with every field empty is the same as not filtering.
let blank = send(get("/items?q=&status=&lang=es", None)).await;
assert_eq!(blank.status(), StatusCode::OK);
assert!(set_cookie(&blank).is_none());
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let blank = send(get("/items?q=&status=", Some(&cookie))).await;
assert_eq!(blank.status(), StatusCode::OK);
let expired = set_cookie(&blank).expect("the saved state is forgotten");
assert!(expired.starts_with(&cookie[..cookie.find('=').unwrap() + 1]));
assert!(expired.contains("Max-Age=0"), "{expired}");
}
#[pagetop::test]
async fn htmx_requests_without_parameters_are_redirected_too() {
// HTMX follows the redirection, so a boosted back link also shows the remembered state.
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let request = get("/items", Some(&cookie)).header("hx-request", "true");
let response = send(request).await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&response), "/items?q=acer");
}
#[pagetop::test]
async fn failed_responses_and_other_methods_save_nothing() {
let failed = send(get("/failing?q=acer", None)).await;
assert_eq!(failed.status(), StatusCode::NOT_FOUND);
assert!(set_cookie(&failed).is_none());
let posted = send(web::test::TestRequest::post().uri("/items?q=acer")).await;
assert_eq!(posted.status(), StatusCode::OK);
assert!(set_cookie(&posted).is_none());
}
#[pagetop::test]
async fn a_saved_state_that_no_longer_gives_a_page_is_forgotten() {
let cookie = list_cookie(&send(get("/picky?q=fine", None)).await);
let name = &cookie[..cookie.find('=').unwrap()];
let stale = format!("{name}=q=stale");
// Coming back restores it, and the list now refuses it: the state is dropped, so the next visit
// does not fail again.
let back = send(get("/picky", Some(&stale))).await;
assert_eq!(location(&back), "/picky?q=stale");
let refused = send(get("/picky?q=stale", Some(&stale))).await;
assert_eq!(refused.status(), StatusCode::BAD_REQUEST);
let expired = set_cookie(&refused).expect("the stale state is forgotten");
assert!(expired.contains("Max-Age=0"), "{expired}");
// A failing request with other parameters keeps the saved state.
let refused = send(get("/picky?q=stale", Some(&cookie))).await;
assert_eq!(refused.status(), StatusCode::BAD_REQUEST);
assert!(set_cookie(&refused).is_none());
}
#[pagetop::test]
async fn states_that_cannot_go_in_a_cookie_are_not_saved() {
let long = format!("/items?q={}", "a".repeat(1100));
assert!(set_cookie(&send(get(&long, None)).await).is_none());
assert!(set_cookie(&send(get("/items?q=a,b", None)).await).is_none());
}
#[pagetop::test]
async fn a_tampered_cookie_is_ignored() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let name = &cookie[..cookie.find('=').unwrap()];
let tampered = format!("{name}=q=\"x\"");
let response = send(get("/items", Some(&tampered))).await;
assert_eq!(response.status(), StatusCode::OK);
let expired = set_cookie(&response).expect("the invalid cookie is removed");
assert!(expired.contains("Max-Age=0"), "{expired}");
}
#[pagetop::test]
async fn a_tampered_cookie_with_no_usable_state_is_forgotten_without_redirecting() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let name = &cookie[..cookie.find('=').unwrap()];
// Redirecting with any of these would land on the same list again, forever.
for value in ["&", "lang=es", "reset", "q=&status="] {
let tampered = format!("{name}={value}");
let response = send(get("/items", Some(&tampered))).await;
assert_eq!(response.status(), StatusCode::OK, "{value}");
let expired = set_cookie(&response).expect("the useless cookie is removed");
assert!(expired.contains("Max-Age=0"), "{value}: {expired}");
}
// Saved `lang` is never replayed: the one of the current request wins.
let tampered = format!("{name}=q=a&lang=fr");
let response = send(get("/items?lang=es", Some(&tampered))).await;
assert_eq!(location(&response), "/items?q=a&lang=es");
}
#[pagetop::test]
async fn links_from_other_sites_cannot_change_the_saved_state() {
// Without this, a page elsewhere could link to `/items?q=...` and fix what the list shows to
// whoever follows the link, every time they come back to it.
for site in ["cross-site", "same-site"] {
let foreign = get("/items?q=planted", None).header("sec-fetch-site", site);
let response = send(foreign).await;
assert_eq!(response.status(), StatusCode::OK, "{site}");
assert!(set_cookie(&response).is_none(), "{site}");
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
for uri in ["/items?reset", "/items?q=", "/items?q=other"] {
let foreign = get(uri, Some(&cookie)).header("sec-fetch-site", site);
assert!(set_cookie(&send(foreign).await).is_none(), "{site} {uri}");
}
// Restoring only reads the state, so it works whatever the origin of the link.
let foreign = get("/items", Some(&cookie)).header("sec-fetch-site", site);
assert_eq!(location(&send(foreign).await), "/items?q=acer", "{site}");
}
// Requests from the application itself, or typed by hand, do change it.
for site in ["same-origin", "none"] {
let own = get("/items?q=acer", None).header("sec-fetch-site", site);
assert!(set_cookie(&send(own).await).is_some(), "{site}");
}
}
#[pagetop::test]
async fn the_access_of_the_route_is_checked_before_the_saved_state() {
// An anonymous visitor with a cookie for a protected list gets neither a redirection that
// reveals the saved state nor a new cookie: access is checked first.
let cookie = "pagetop_list_c36367b4cdbc13dd=q=secret"; // The cookie name of `/private`.
for uri in ["/private", "/private?q=other", "/private?reset"] {
let response = send(get(uri, Some(cookie))).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{uri}");
assert!(set_cookie(&response).is_none(), "{uri}");
assert!(response.headers().get(header::LOCATION).is_none(), "{uri}");
}
}
#[pagetop::test]
async fn a_path_that_a_browser_would_read_as_another_site_is_left_alone() {
// A list mounted on a catch-all route also matches `//other.example`; redirecting there would
// send the browser to another site.
let response = send(get("//other.example/?q=a", None)).await;
assert_eq!(response.status(), StatusCode::OK);
assert!(set_cookie(&response).is_none());
}
#[pagetop::test]
async fn each_list_has_its_own_cookie_with_its_full_path() {
let top = list_cookie(&send(get("/items?q=a", None)).await);
let nested = send(get("/nested/items?q=b", None)).await;
assert!(set_cookie(&nested).unwrap().contains("Path=/nested/items;"));
let nested = list_cookie(&nested);
assert_ne!(
top.split('=').next(),
nested.split('=').next(),
"different lists, different cookies"
);
let back = send(get("/nested/items", Some(&nested))).await;
assert_eq!(location(&back), "/nested/items?q=b");
// The state of one list is never restored in another.
let other = send(get("/items", Some(&nested))).await;
assert_eq!(other.status(), StatusCode::OK);
assert!(other.headers().get(header::LOCATION).is_none());
}
#[pagetop::test]
async fn the_cookie_is_found_in_any_cookie_header() {
// With HTTP/2 the browser may split the cookies into several `cookie` headers.
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let response = send_edited(get("/items", Some("theme=dark")), |headers| {
headers.append(header::COOKIE, cookie.parse().unwrap());
})
.await;
assert_eq!(location(&response), "/items?q=acer");
}