rustango_cms/locale_mode.rs
1//! How the public router resolves which locale a request is asking for.
2//!
3//! Three modes; query mode is the v0.1/v0.2 default for back-compat.
4//! Path mode puts the locale code as the first URL
5//! segment, with the default locale living at the unprefixed root.
6//!
7//! - `/about` → default locale (regardless of mode)
8//! - `/es/about` → recognized only when mode includes Path
9//! - `/about?lang=es` → recognized only when mode includes Query
10//!
11//! In `PathOrQuery` mode, an explicit `?lang=` wins over the path
12//! prefix — the query parameter is read as an explicit override
13//! (handy for testing) and the path prefix becomes the default
14//! external-link shape.
15//!
16//! When no explicit locale is given (no `?lang=`, no path prefix), the
17//! request's `Accept-Language` header is negotiated against the active
18//! locales before falling through to the tenant default. So
19//! precedence is: explicit query > explicit path > Accept-Language >
20//! default.
21
22use rustango::core::Column as _;
23
24use crate::locale::Locale;
25
26/// Locale-resolution strategy for [`crate::router`](mod@crate::router) builders.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum LocaleMode {
29 /// `?lang=es` only. The v0.1 / v0.2 default — no path
30 /// recognition, no extra DB hit per request.
31 #[default]
32 Query,
33 /// `/es/...` only. The first URL segment is matched against
34 /// `cms_locale.code`; if it hits, it's stripped and used as the
35 /// active locale for rendering.
36 Path,
37 /// Both. Query wins when both are present, so a stale link
38 /// `/es/about?lang=fr` renders French. The path prefix is the
39 /// canonical external-link shape; the query parameter is the
40 /// explicit override.
41 PathOrQuery,
42}
43
44impl LocaleMode {
45 /// Whether the router should inspect URL path segments for a
46 /// locale prefix on every request.
47 #[must_use]
48 pub fn reads_path(self) -> bool {
49 matches!(self, Self::Path | Self::PathOrQuery)
50 }
51
52 /// Whether the router should inspect `?lang=` on every request.
53 #[must_use]
54 pub fn reads_query(self) -> bool {
55 matches!(self, Self::Query | Self::PathOrQuery)
56 }
57}
58
59/// Cookie that persists a visitor's chosen locale across navigation so
60/// links that don't carry the locale (bare nav paths, in-content links)
61/// stay in the selected language. Lower precedence than an explicit
62/// `?lang=` / `/<code>/` so a fresh explicit choice always wins.
63pub const LOCALE_COOKIE: &str = "rcms_locale";
64
65/// What [`resolve_request_locale`] returns: the active locale code
66/// (if any) plus the URL path with the locale segment removed (so
67/// downstream slug resolution sees the same `/about` whether the
68/// request came in as `/about?lang=es` or `/es/about`).
69#[derive(Debug, Clone)]
70pub struct RequestLocale {
71 /// Locale code resolved from the request, in `mode`'s priority
72 /// order. `None` means "fall through to the tenant default".
73 pub code: Option<String>,
74 /// The request path with any locale prefix stripped.
75 pub stripped_path: String,
76 /// `true` when `code` came from an EXPLICIT source (`?lang=` or a
77 /// `/<code>/` path prefix), as opposed to the persistence cookie or
78 /// `Accept-Language`. The router (re)writes the locale cookie only on
79 /// an explicit choice, so a plain nav click never churns it.
80 pub explicit: bool,
81}
82
83/// BCP-47-ish tag shape gate (ASCII alphanumeric + `-`, ≤16 chars) —
84/// keeps a malformed cookie/query value from poisoning the cache key or
85/// a `/<code>/` lookup.
86#[must_use]
87pub fn code_shaped(s: &str) -> bool {
88 !s.is_empty() && s.len() <= 16 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
89}
90
91/// Pull the `rcms_locale` value out of a raw `Cookie` header. Returns
92/// `None` when absent or malformed.
93#[must_use]
94pub fn locale_cookie_value(cookie_header: Option<&str>) -> Option<String> {
95 let raw = cookie_header?;
96 for part in raw.split(';') {
97 if let Some(v) = part.trim().strip_prefix("rcms_locale=") {
98 let v = v.trim();
99 return if code_shaped(v) {
100 Some(v.to_owned())
101 } else {
102 None
103 };
104 }
105 }
106 None
107}
108
109/// Resolve the request's locale code by inspecting path + query (as
110/// `mode` permits) and the `Accept-Language` header.
111///
112/// Precedence: **explicit `?lang=` > explicit `/<code>/` path prefix >
113/// `Accept-Language` negotiation > tenant default** (`None`). An
114/// explicit choice always wins; the header is a fallback for
115/// first-visit/unlinked requests.
116///
117/// At most two DB queries, both conditional: the path-segment lookup
118/// (only in path mode when the first segment looks like a code) and the
119/// active-locale list for `Accept-Language` matching (only when no
120/// explicit locale was given AND a header is present).
121pub async fn resolve_request_locale(
122 pool: &rustango::sql::Pool,
123 mode: LocaleMode,
124 path: &str,
125 query: Option<&str>,
126 cookie_code: Option<&str>,
127 accept_language: Option<&str>,
128) -> RequestLocale {
129 let query_code = if mode.reads_query() {
130 query.and_then(parse_lang_param)
131 } else {
132 None
133 };
134
135 let (path_code, stripped_path) = if mode.reads_path() {
136 // Query wins, so a `/es/about?lang=fr` renders French — but the
137 // segment is still stripped from the path either way.
138 try_strip_locale_segment(pool, path).await
139 } else {
140 (None, path.to_owned())
141 };
142
143 // Precedence: explicit query > explicit path > persistence cookie >
144 // Accept-Language > tenant default. The cookie keeps the chosen
145 // language sticky across links that don't carry it; an explicit
146 // choice always overrides it.
147 let explicit_code = query_code.or(path_code);
148 let explicit = explicit_code.is_some();
149 let code = if let Some(c) = explicit_code {
150 Some(c)
151 } else if let Some(c) = cookie_code.filter(|c| code_shaped(c)) {
152 Some(c.to_owned())
153 } else {
154 negotiate_accept_language(pool, accept_language).await
155 };
156
157 RequestLocale {
158 code,
159 stripped_path,
160 explicit,
161 }
162}
163
164/// Negotiate `Accept-Language` against the active `cms_locale.code`s.
165/// Returns the highest-quality match (exact, then base-language —
166/// `fr-CA` matches an active `fr`), or `None`. One DB query, only when
167/// a non-empty header is present.
168async fn negotiate_accept_language(
169 pool: &rustango::sql::Pool,
170 header: Option<&str>,
171) -> Option<String> {
172 use rustango::sql::FetcherPool as _;
173 let prefs = parse_accept_language(header?);
174 if prefs.is_empty() {
175 return None;
176 }
177 let active: Vec<String> = Locale::objects()
178 .where_(Locale::active.eq(true))
179 .fetch(pool)
180 .await
181 .ok()?
182 .into_iter()
183 .map(|l| l.code)
184 .collect();
185 if active.is_empty() {
186 return None;
187 }
188 for pref in &prefs {
189 // Exact (case-insensitive) match first.
190 if let Some(m) = active.iter().find(|c| c.eq_ignore_ascii_case(pref)) {
191 return Some(m.clone());
192 }
193 // Base-language fallback: `fr-CA` → an active `fr` (or `fr-FR`).
194 let pref_base = base_lang(pref);
195 if let Some(m) = active
196 .iter()
197 .find(|c| base_lang(c).eq_ignore_ascii_case(pref_base))
198 {
199 return Some(m.clone());
200 }
201 }
202 None
203}
204
205fn base_lang(tag: &str) -> &str {
206 tag.split('-').next().unwrap_or(tag)
207}
208
209/// Parse an `Accept-Language` header into BCP-47 tags ordered by
210/// quality (descending; ties keep header order). Drops `*`, `q=0`, and
211/// malformed tags so a bad value can't poison the cache key.
212fn parse_accept_language(header: &str) -> Vec<String> {
213 let mut items: Vec<(f32, String)> = Vec::new();
214 for part in header.split(',') {
215 let part = part.trim();
216 if part.is_empty() {
217 continue;
218 }
219 let mut bits = part.split(';');
220 let tag = bits.next().unwrap_or("").trim();
221 if tag.is_empty()
222 || tag == "*"
223 || !tag.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
224 {
225 continue;
226 }
227 let mut q = 1.0f32;
228 for b in bits {
229 if let Some(v) = b.trim().strip_prefix("q=") {
230 q = v.trim().parse().unwrap_or(1.0);
231 }
232 }
233 if q <= 0.0 {
234 continue;
235 }
236 items.push((q, tag.to_owned()));
237 }
238 // Stable sort by quality desc keeps header order for equal-q tags.
239 items.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
240 items.into_iter().map(|(_, t)| t).collect()
241}
242
243/// Peek the first path segment. If it looks like a BCP-47 tag AND
244/// matches an active `cms_locale.code`, return `(Some(code),
245/// path_without_segment)`. Otherwise `(None, original_path)`.
246async fn try_strip_locale_segment(
247 pool: &rustango::sql::Pool,
248 path: &str,
249) -> (Option<String>, String) {
250 use rustango::sql::FetcherPool as _;
251 let trimmed = path.trim_start_matches('/');
252 let mut iter = trimmed.splitn(2, '/');
253 let head = iter.next().unwrap_or("");
254 if head.is_empty()
255 || head.len() > 16
256 || !head.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
257 {
258 return (None, path.to_owned());
259 }
260 let exists = Locale::objects()
261 .where_(Locale::code.eq(head.to_owned()))
262 .where_(Locale::active.eq(true))
263 .fetch(pool)
264 .await
265 .ok()
266 .and_then(|mut v| v.pop())
267 .is_some();
268 if !exists {
269 return (None, path.to_owned());
270 }
271 let rest = iter.next().unwrap_or("");
272 let stripped = if rest.is_empty() {
273 "/".to_owned()
274 } else {
275 format!("/{rest}")
276 };
277 (Some(head.to_owned()), stripped)
278}
279
280/// Pull `?lang=<code>` out of a raw query string. Restricts to ASCII
281/// alphanumeric + `-` (BCP-47 tag shape) so a malformed value can't
282/// poison the cache key.
283fn parse_lang_param(q: &str) -> Option<String> {
284 for pair in q.split('&') {
285 if let Some(rest) = pair.strip_prefix("lang=") {
286 let trimmed = rest.trim();
287 if trimmed.is_empty() {
288 return None;
289 }
290 if trimmed
291 .chars()
292 .all(|c| c.is_ascii_alphanumeric() || c == '-')
293 {
294 return Some(trimmed.to_owned());
295 }
296 return None;
297 }
298 }
299 None
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn parse_lang_param_extracts_value() {
308 assert_eq!(parse_lang_param("lang=es"), Some("es".to_owned()));
309 assert_eq!(parse_lang_param("lang=es&foo=bar"), Some("es".to_owned()));
310 assert_eq!(parse_lang_param("foo=bar&lang=fr"), Some("fr".to_owned()));
311 }
312
313 #[test]
314 fn parse_lang_param_rejects_garbage() {
315 assert_eq!(parse_lang_param(""), None);
316 assert_eq!(parse_lang_param("lang="), None);
317 assert_eq!(parse_lang_param("lang=../etc/passwd"), None);
318 assert_eq!(parse_lang_param("lang=<script>"), None);
319 assert_eq!(parse_lang_param("foo=bar"), None);
320 }
321
322 #[test]
323 fn accept_language_orders_by_quality() {
324 // Default q=1 for the unweighted tag; explicit q orders the rest.
325 assert_eq!(
326 parse_accept_language("de;q=0.7, en;q=0.8, fr"),
327 vec!["fr", "en", "de"]
328 );
329 }
330
331 #[test]
332 fn accept_language_keeps_header_order_for_ties() {
333 assert_eq!(
334 parse_accept_language("en-US, en;q=0.9, fr;q=0.9"),
335 vec!["en-US", "en", "fr"]
336 );
337 }
338
339 #[test]
340 fn accept_language_drops_wildcard_zero_q_and_garbage() {
341 assert_eq!(
342 parse_accept_language("*;q=0.5, xx;q=0, en, ../bad, fr-CA"),
343 vec!["en", "fr-CA"]
344 );
345 assert!(parse_accept_language("").is_empty());
346 assert!(parse_accept_language("*").is_empty());
347 }
348
349 #[test]
350 fn base_lang_strips_region() {
351 assert_eq!(base_lang("fr-CA"), "fr");
352 assert_eq!(base_lang("en"), "en");
353 }
354}