From 0bcc7e5236e7b4e043e64b5b1d9f532b04a38c29 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sun, 18 Oct 2026 12:25:16 +0200 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=94=92=EF=B8=8F=20(locale):=20Escapa?= =?UTF-8?q?=20argumentos=20texto=20en=20using()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Los argumentos de `with_arg()` pueden venir de datos de usuario y `using()` los insertaba sin escapar. Ahora se escapan, y `with_markup()` añade argumentos con marcado HTML de confianza que se insertan tal cual. --- src/base/component/poweredby.rs | 17 +++--- src/locale/lc.rs | 96 +++++++++++++++++++++++---------- tests/locale.rs | 36 +++++++++++++ 3 files changed, 109 insertions(+), 40 deletions(-) diff --git a/src/base/component/poweredby.rs b/src/base/component/poweredby.rs index cb02726f..c85e632c 100644 --- a/src/base/component/poweredby.rs +++ b/src/base/component/poweredby.rs @@ -1,15 +1,5 @@ use crate::prelude::*; -// Enlace a la página oficial de PageTop. -const PAGETOP_LINK: &str = concat!( - "", - "PageTop", - "", -); - /// Componente que muestra el típico mensaje *Powered by* (*Funciona con*) en el pie de página. /// /// Por defecto, usando [`default()`](Self::default) sólo se muestra un reconocimiento a PageTop. @@ -34,13 +24,18 @@ impl Component for PoweredBy { } async fn prepare(&self, cx: &mut Context) -> Result { + let pagetop_link = html! { + a href="https://pagetop.cillero.es" target="_blank" rel="noopener noreferrer" { + "PageTop" + } + }; Ok(html! { div id=[self.id()] class="poweredby" { @if let Some(c) = self.copyright() { span class="poweredby__copyright" { (c) "." } " " } span class="poweredby__pagetop" { - (Lc::l("poweredby_pagetop").with_arg("pagetop_link", PAGETOP_LINK).using(cx)) + (Lc::l("poweredby_pagetop").with_markup("pagetop_link", pagetop_link).using(cx)) } } }) diff --git a/src/locale/lc.rs b/src/locale/lc.rs index e7d51b48..507ea7da 100644 --- a/src/locale/lc.rs +++ b/src/locale/lc.rs @@ -7,6 +7,7 @@ include_locales!(LOCALES_PAGETOP); use fluent_templates::Loader; use fluent_templates::StaticLoader as Locales; +use fluent_templates::fluent_bundle::FluentValue; use std::collections::HashMap; @@ -34,18 +35,22 @@ enum LcKind { // `Text` resuelve a `FluentValue::String` para interpolar cualquier texto; pero no aplica el // selector de plural de Fluent (`{ $n -> [one] ... *[other] ... }`). Para eso está `Number`, que // resuelve a `FluentValue::Number` y es el único tipo con el que Fluent consulta las reglas de -// plural del idioma. +// plural del idioma. `Markup` es marcado HTML de confianza, que `using()` no escapa. #[derive(Clone, Debug)] enum LcArg { Text(CowStr), Number(u32), + Markup(String), } -impl<'a> From<&'a LcArg> for fluent_templates::fluent_bundle::FluentValue<'a> { - fn from(arg: &'a LcArg) -> Self { - match arg { +impl LcArg { + // Valor para Fluent. Con `escape`, el texto se escapa para insertarse en marcado HTML. + fn to_fluent(&self, escape: bool) -> FluentValue<'_> { + match self { + LcArg::Text(s) if escape => s.as_ref().render().into_string().into(), LcArg::Text(s) => s.as_ref().into(), LcArg::Number(n) => (*n).into(), + LcArg::Markup(s) => s.as_str().into(), } } } @@ -79,8 +84,8 @@ impl<'a> From<&'a LcArg> for fluent_templates::fluent_bundle::FluentValue<'a> { /// - [`using()`](Self::using) devuelve [`Markup`] para presentar al usuario, listo para insertarse /// en el contenido de una plantilla (`(x.using(cx))` dentro de [`html!`](crate::html::html)). /// Nunca devuelve `None`, por lo que una traducción no encontrada se convierte en marcado vacío. -/// Para `n()` se escapa el texto para evitar HTML no controlado. Para valores de atributo, usa -/// siempre [`lookup()`](Self::lookup). +/// Para `n()` se escapa el texto, y también los argumentos de texto de `l()`/`t()`, para evitar +/// HTML no controlado. Para valores de atributo, usa siempre [`lookup()`](Self::lookup). /// /// # Ejemplo /// @@ -169,9 +174,11 @@ impl Lc { /// Añade un argumento `{$arg}` => `value` a la traducción. /// - /// `value` se interpreta siempre como texto. Si se necesita un argumento numérico que además - /// deba seleccionar plural (`{ $n -> [one] ... *[other] ... }`), hay que utilizar en su lugar - /// [`with_number()`](Self::with_number). + /// `value` se interpreta siempre como texto: [`using()`](Self::using) lo escapa, así que puede + /// venir de datos de usuario sin riesgo de inyectar marcado. Para insertar marcado HTML de + /// confianza hay que utilizar [`with_markup()`](Self::with_markup). Si se necesita un argumento + /// numérico que además deba seleccionar plural (`{ $n -> [one] ... *[other] ... }`), hay que + /// utilizar [`with_number()`](Self::with_number). pub fn with_arg(mut self, arg: impl Into, value: impl Into) -> Self { self.args.push((arg.into(), LcArg::Text(value.into()))); self @@ -211,6 +218,30 @@ impl Lc { self } + /// Añade un argumento `{$arg}` => `markup` con marcado HTML de confianza, que + /// [`using()`](Self::using) inserta sin escapar. + /// + /// A diferencia de [`with_arg()`](Self::with_arg), sirve para incluir en la traducción un + /// fragmento HTML generado por la aplicación, como un enlace. No debe contener datos de usuario + /// sin escapar (construirlo con [`html!`](crate::html::html) los escapa): permitirían inyectar + /// marcado, p. ej. un enlace fraudulento en un correo legítimo de la aplicación. Con + /// [`get()`](Self::get) y [`lookup()`](Self::lookup) el marcado se interpola como texto. + /// + /// # Ejemplo + /// + /// ```rust,no_run + /// # use pagetop::prelude::*; + /// let link = html! { a href="https://pagetop.cillero.es" { "PageTop" } }; + /// let text = Lc::l("poweredby_pagetop") + /// .with_markup("pagetop_link", link) + /// .using(&Locale::resolve("es")); + /// ``` + pub fn with_markup(mut self, arg: impl Into, markup: Markup) -> Self { + self.args + .push((arg.into(), LcArg::Markup(markup.into_string()))); + self + } + // **< Lc GETTERS >***************************************************************************** /// Indica si la instancia está **sin contenido** ([`Lc::none()`]). @@ -267,22 +298,7 @@ impl Lc { /// let text = Lc::l("greeting").with_arg("name", "Usuario").lookup(&r); /// ``` pub fn lookup(&self, language: &impl LangId) -> Option { - match &self.op { - LcKind::None => None, - LcKind::Text(text) => Some(text.clone().into_owned()), - LcKind::Translate(key) => { - if self.args.is_empty() { - self.locales.try_lookup(language.langid(), key.as_ref()) - } else { - let mut args = HashMap::with_capacity(self.args.len()); - for (k, v) in self.args.iter() { - args.insert(k.clone(), v.into()); - } - self.locales - .try_lookup_with_args(language.langid(), key.as_ref(), &args) - } - } - } + self.resolve(language, false) } /// Traduce el texto y lo devuelve como [`Markup`] usando la fuente de idioma proporcionada. @@ -291,9 +307,11 @@ impl Lc { /// /// Las claves de traducción (`l()`/`t()`) son texto de confianza, con traducciones en ficheros /// `.ftl` que pueden incluir marcado HTML (p. ej. ``, enlaces, etc.) que se insertan - /// tal cual. El texto literal (`n()`), en cambio, suele venir de datos en tiempo de ejecución - /// que no debe interpretarse como marcado, por lo que se escapa igual que cualquier otro valor - /// interpolado con [`html!`](crate::html::html). + /// tal cual. El texto literal (`n()`) y los argumentos de texto + /// ([`with_arg()`](Self::with_arg)), en cambio, suelen venir de datos en tiempo de ejecución + /// que no deben interpretarse como marcado, por lo que se escapan igual que cualquier otro + /// valor interpolado con [`html!`](crate::html::html). El marcado de confianza que se pasa como + /// argumento con [`with_markup()`](Self::with_markup) se inserta sin escapar. /// /// No debe usarse para un valor de atributo (`attr=[...]` en [`html!`](crate::html::html)): el /// marcado de confianza que se aplica en `l()`/`t()` no tiene sentido ahí, y podría romper el @@ -309,7 +327,27 @@ impl Lc { pub fn using(&self, language: &impl LangId) -> Markup { match &self.op { LcKind::Text(text) => text.render(), - _ => PreEscaped(self.lookup(language).unwrap_or_default()), + _ => PreEscaped(self.resolve(language, true).unwrap_or_default()), + } + } + + // Resuelve la traducción. Con `escape`, los argumentos de texto se escapan para `using()`. + fn resolve(&self, language: &impl LangId, escape: bool) -> Option { + match &self.op { + LcKind::None => None, + LcKind::Text(text) => Some(text.clone().into_owned()), + LcKind::Translate(key) => { + if self.args.is_empty() { + self.locales.try_lookup(language.langid(), key.as_ref()) + } else { + let mut args = HashMap::with_capacity(self.args.len()); + for (k, v) in self.args.iter() { + args.insert(k.clone(), v.to_fluent(escape)); + } + self.locales + .try_lookup_with_args(language.langid(), key.as_ref(), &args) + } + } } } diff --git a/tests/locale.rs b/tests/locale.rs index ca55fd92..5dd93524 100644 --- a/tests/locale.rs +++ b/tests/locale.rs @@ -30,6 +30,42 @@ async fn translation_with_args() { assert_eq!(translation, Some("¡Hola, Manuel!".to_string())); } +// Text arguments may come from user data: `using()` must not let them inject markup. +#[pagetop::test] +async fn using_escapes_text_args() { + setup().await; + + let lc = Lc::l("test_hello_user").with_arg("userName", r#"Ana & "Luis""#); + assert_eq!( + lc.using(&Locale::resolve("es-ES")).into_string(), + "¡Hola, <a href="x">Ana & "Luis"</a>!" + ); +} + +// `lookup()` returns plain text, escaped later where it is used (e.g. in an attribute). +#[pagetop::test] +async fn lookup_does_not_escape_text_args() { + setup().await; + + let lc = Lc::l("test_hello_user").with_arg("userName", "Ana & "); + assert_eq!( + lc.lookup(&Locale::resolve("es-ES")), + Some("¡Hola, Ana & !".to_string()) + ); +} + +#[pagetop::test] +async fn using_keeps_markup_args() { + setup().await; + + let name = "Ana & Luis"; + let lc = Lc::l("test_hello_user").with_markup("userName", html! { strong { (name) } }); + assert_eq!( + lc.using(&Locale::resolve("es-ES")).into_string(), + "¡Hola, Ana & Luis!" + ); +} + #[pagetop::test] async fn translation_with_plural_and_select() { setup().await; From bae8358471e331e5ffa596333b9d13c963b94b99 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sun, 18 Oct 2026 12:30:20 +0200 Subject: [PATCH 2/3] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20(locale):=20Prueba=20a?= =?UTF-8?q?ntes=20el=20idioma=20exacto=20en=20Lc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ` try_lookup_complete()` negocia el idioma en cada llamada aunque casi siempre sea uno disponible. Ahora se prueba antes el idioma exacto y sólo si falla se recorre la cadena de respaldo, con el mismo resultado. --- src/locale/lc.rs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/locale/lc.rs b/src/locale/lc.rs index 507ea7da..94ee99fb 100644 --- a/src/locale/lc.rs +++ b/src/locale/lc.rs @@ -337,16 +337,25 @@ impl Lc { LcKind::None => None, LcKind::Text(text) => Some(text.clone().into_owned()), LcKind::Translate(key) => { - if self.args.is_empty() { - self.locales.try_lookup(language.langid(), key.as_ref()) - } else { + let langid = language.langid(); + let args = (!self.args.is_empty()).then(|| { let mut args = HashMap::with_capacity(self.args.len()); for (k, v) in self.args.iter() { args.insert(k.clone(), v.to_fluent(escape)); } - self.locales - .try_lookup_with_args(language.langid(), key.as_ref(), &args) - } + args + }); + // `try_lookup_complete()` negocia el idioma en cada llamada, con varias reservas de + // memoria, aunque `langid` sea casi siempre un idioma disponible. Se prueba antes + // el idioma exacto, que es lo primero que elige la negociación, por lo que el + // resultado no cambia; sólo si falla se recorre la cadena de idiomas de respaldo. + self.locales + .lookup_single_language(langid, key.as_ref(), args.as_ref()) + .ok() + .or_else(|| { + self.locales + .try_lookup_complete(langid, key.as_ref(), args.as_ref()) + }) } } } From b3a7d409301be54c64d572450c9bbe14f69336cb Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sun, 18 Oct 2026 12:49:03 +0200 Subject: [PATCH 3/3] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20(locale):=20Lc=20escap?= =?UTF-8?q?a=20argumentos=20s=C3=B3lo=20si=20hace=20falta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `using()` copiaba siempre cada argumento de texto al escaparlo. Ahora sólo lo hace si contiene algún carácter que Maud escapa; si no, se pasa prestado. --- src/locale/lc.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/locale/lc.rs b/src/locale/lc.rs index 94ee99fb..59e3fa46 100644 --- a/src/locale/lc.rs +++ b/src/locale/lc.rs @@ -47,7 +47,7 @@ impl LcArg { // Valor para Fluent. Con `escape`, el texto se escapa para insertarse en marcado HTML. fn to_fluent(&self, escape: bool) -> FluentValue<'_> { match self { - LcArg::Text(s) if escape => s.as_ref().render().into_string().into(), + LcArg::Text(s) if escape && needs_escape(s) => s.as_ref().render().into_string().into(), LcArg::Text(s) => s.as_ref().into(), LcArg::Number(n) => (*n).into(), LcArg::Markup(s) => s.as_str().into(), @@ -55,6 +55,12 @@ impl LcArg { } } +// Indica si el texto contiene algún carácter que Maud escapa. Sin ninguno, el texto escapado es +// idéntico al original y se interpola prestado, sin reservar memoria para una copia. +fn needs_escape(text: &str) -> bool { + text.bytes().any(|b| matches!(b, b'&' | b'<' | b'>' | b'"')) +} + // **< Lc >***************************************************************************************** /// Crea instancias para traducir *textos localizados*. @@ -412,3 +418,19 @@ impl Lc { key } } + +#[cfg(test)] +mod tests { + use super::*; + + // `needs_escape()` must flag every character that Maud escapes; otherwise `using()` would + // interpolate it unescaped. Compares every character up to U+02FF with Maud's own escaping. + #[test] + fn needs_escape_matches_maud() { + for c in (0..=0x2ffu32).filter_map(char::from_u32) { + let text = c.to_string(); + let escaped = text.as_str().render().into_string(); + assert_eq!(needs_escape(&text), escaped != text, "mismatch for {c:?}"); + } + } +}