footing 0.6.2

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Explicit language selection for localized HTTP responses (`http-locale`).
//!
//! [`LocalePolicy`] selects from an application's supported languages without
//! I/O, global state, translation resources, or an implicit middleware layer.
//! It reads **all** `Accept-Language` fields. It does not read cookies,
//! `x-locale`, user profiles, or [`super::RequestContext::locale`]: that accessor
//! retains only one client preference and cannot represent a negotiation list.
//!
//! # Matching contract
//!
//! Matching uses [RFC 4647 Basic Filtering](https://www.rfc-editor.org/rfc/rfc4647.html#section-3.3.1).
//! A range matches a tag case-insensitively when equal or when followed by `-`
//! and additional subtags. Thus `en` matches `en-US`, but `en-US` does not match
//! `en`. Clients wanting a broader alternative should include it explicitly,
//! for example `en-US, en;q=0.8`. Script subtags are preserved; `zh-Hant` does
//! not match `zh-Hans`, and `zh-TW` is not inferred to mean `zh-Hant`.
//!
//! For each supported tag, the longest matching range determines its weight;
//! `*` applies only when no concrete range matches. `q=0` excludes that tag.
//! Duplicate ranges use their first occurrence, including across header lines.
//! Among acceptable tags, the highest weight wins, then the controlling range's
//! request order, then the configured supported-language order. These tie rules
//! are deterministic application choices, not additional RFC requirements.
//!
//! Missing `Accept-Language` selects the configured default. A present but empty
//! list, or one with no acceptable supported tag, returns
//! [`LocaleNegotiationError::NoMatch`]. Malformed and oversized inputs are errors,
//! never silently treated as missing. The application may explicitly choose
//! [`LocalePolicy::default_locale`] after an error, or reject the request; the
//! policy itself sends no HTTP response. Defaults must belong to the supported
//! set and never override a valid exclusion during negotiation.
//!
//! ```
//! use axum::http::{HeaderMap, header::ACCEPT_LANGUAGE};
//! use footing::http::{LocalePolicy, LocaleSource, RequestContext};
//!
//! let policy = LocalePolicy::new(["zh-CN", "en"], "zh-CN")?;
//! let mut headers = HeaderMap::new();
//! headers.insert(ACCEPT_LANGUAGE, "fr, en;q=0.8".parse()?);
//! let locale = policy.negotiate(&headers)?;
//! assert_eq!(locale.as_str(), "en");
//! assert_eq!(locale.source(), LocaleSource::AcceptLanguage);
//!
//! let mut context = RequestContext::from_headers(&headers);
//! context.set_resolved_locale(locale);
//! assert_eq!(context.locale(), Some("fr")); // Client preference, not selection.
//! assert_eq!(context.resolved_locale().map(|l| l.as_str()), Some("en"));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! # Explicit preferences and Axum
//!
//! For a user-selected language, call [`LocalePolicy::select`] instead of
//! `negotiate`. Selection requires an exact supported tag (ignoring case), so
//! an unsupported preference is visible to the application. The application
//! determines the precedence of account settings, cookies and custom headers,
//! and whether an unavailable explicit preference permits HTTP negotiation.
//! Run selection after loading any required identity or account preferences.
//!
//! An application middleware can install a selection for handlers to reuse:
//!
//! ```no_run
//! use axum::{
//!     Router, extract::{Request, State}, http::StatusCode,
//!     middleware::{self, Next}, response::Response,
//! };
//! use footing::http::{LocaleNegotiationError, LocalePolicy, RequestContext};
//!
//! async fn select_language(
//!     State(policy): State<LocalePolicy>,
//!     mut context: RequestContext,
//!     mut request: Request,
//!     next: Next,
//! ) -> Result<Response, StatusCode> {
//!     let locale = policy.negotiate(request.headers()).map_err(|error| match error {
//!         LocaleNegotiationError::NoMatch => StatusCode::NOT_ACCEPTABLE,
//!         LocaleNegotiationError::HeaderTooLarge | LocaleNegotiationError::TooManyRanges =>
//!             StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE,
//!         _ => StatusCode::BAD_REQUEST,
//!     })?;
//!     context.set_resolved_locale(locale);
//!     request.extensions_mut().insert(context);
//!     Ok(next.run(request).await)
//! }
//!
//! let policy = LocalePolicy::new(["en", "zh-CN"], "en")?;
//! let app: Router = Router::new()
//!     .layer(middleware::from_fn_with_state(policy, select_language));
//! # Ok::<(), footing::http::LocaleConfigError>(())
//! ```
//!
//! Status mappings above belong to the example; applications may instead return
//! their own [`super::ApiProblem`]. Negotiation does not translate library errors,
//! alter stable problem codes, or change logging. The resolved context value is
//! request-local and is not serialized. Background notifications should use the
//! recipient's preference rather than inheriting the caller's selection.
//!
//! # Response metadata and caching
//!
//! Call [`ResolvedLocale::apply_response_headers`] **after rendering content in
//! that language**. It sets `Content-Language` and merges `Vary: Accept-Language`
//! for header negotiation and default selections, including requests without
//! the header. Applying it indiscriminately to untranslated errors, files, or
//! responses produced by other middleware would mislabel their content.
//!
//! Explicit preferences can depend on cookies, custom headers, or account
//! state. Their cache policy belongs to the application: vary on the actual
//! selecting headers where appropriate, or use private/non-stored responses
//! for personalized content. `Vary: Accept-Language` alone cannot cover those
//! inputs. Preserve language-specific validators such as ETags as well.
//!
//! ```
//! use axum::{http::{HeaderMap, header}, response::IntoResponse};
//! use footing::http::LocalePolicy;
//!
//! let policy = LocalePolicy::new(["en", "zh-CN"], "en")?;
//! let locale = policy.negotiate(&HeaderMap::new())?;
//! let message = match locale.as_str() {
//!     "zh-CN" => "你好",
//!     _ => "Hello", // This application's other supported language is English.
//! };
//! let mut response = message.into_response();
//! locale.apply_response_headers(response.headers_mut());
//! assert_eq!(response.headers()[header::CONTENT_LANGUAGE], "en");
//! assert_eq!(response.headers()[header::VARY], "Accept-Language");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::{cmp::Reverse, sync::Arc};

use axum::http::{HeaderMap, HeaderValue, header};
use thiserror::Error;

use crate::result::{ClassifyError, ErrorCode, ErrorKind};

mod language_tag;

use language_tag::normalize_tag;

/// Maximum combined value bytes across all `Accept-Language` fields.
pub const MAX_ACCEPT_LANGUAGE_BYTES: usize = 8192;
/// Maximum comma-separated members across all `Accept-Language` fields.
/// Empty members and duplicate ranges count toward this limit.
pub const MAX_LANGUAGE_RANGES: usize = 64;
/// Maximum bytes in a configured language tag or a concrete language range.
pub const MAX_LOCALE_LENGTH: usize = 256;

/// A validated, ordered set of supported languages and an explicit default.
///
/// Clones share the immutable supported-language configuration. Enabling `http-locale`
/// does not install it automatically, including in the full HTTP stack.
#[derive(Clone, Debug)]
pub struct LocalePolicy {
    supported: Arc<[(String, HeaderValue)]>,
    default: usize,
}

impl LocalePolicy {
    /// Validates configuration once, preserving the supported-language order.
    ///
    /// Tags must be well-formed BCP 47 language tags, at most
    /// [`MAX_LOCALE_LENGTH`] bytes each. Case is normalized (`EN-us` becomes
    /// `en-US`); whitespace, underscores, wildcards, and case-insensitive
    /// duplicates are rejected. The default must be in the supported set.
    /// Validation checks syntax and rejects repeated variants and extension
    /// singletons, without checking registration in an IANA snapshot. Private-use
    /// and the fixed grandfathered tags are permitted. No aliases or likely
    /// subtags are inferred.
    pub fn new(
        supported: impl IntoIterator<Item = impl AsRef<str>>,
        default: impl AsRef<str>,
    ) -> Result<Self, LocaleConfigError> {
        let mut locales: Vec<(String, HeaderValue)> = Vec::new();
        for value in supported {
            let tag = normalize_tag(value.as_ref())?;
            if locales.iter().any(|(existing, _)| existing == &tag) {
                return Err(LocaleConfigError::DuplicateLocale);
            }
            let header =
                HeaderValue::from_str(&tag).map_err(|_| LocaleConfigError::InvalidLocale)?;
            locales.push((tag, header));
        }
        if locales.is_empty() {
            return Err(LocaleConfigError::EmptySupportedLocales);
        }
        let default = normalize_tag(default.as_ref())?;
        let default = locales
            .iter()
            .position(|(tag, _)| tag == &default)
            .ok_or(LocaleConfigError::UnsupportedDefault)?;
        Ok(Self {
            supported: locales.into(),
            default,
        })
    }

    /// Returns normalized supported tags in their configured order.
    pub fn supported_locales(&self) -> impl ExactSizeIterator<Item = &str> {
        self.supported.iter().map(|(tag, _)| tag.as_str())
    }

    /// Returns the default without inspecting or claiming to satisfy a request.
    ///
    /// Use this explicitly if the application chooses to disregard an
    /// unmatchable or malformed preference. Its response helper retains
    /// `Vary: Accept-Language`, so a default response cannot poison the cache
    /// for a subsequent request that successfully negotiates another language.
    #[must_use]
    pub fn default_locale(&self) -> ResolvedLocale {
        self.resolved(self.default, LocaleSource::Default)
    }

    /// Selects an exact supported tag as an explicit application/user preference.
    ///
    /// Matching ignores ASCII case but does not trim whitespace, translate
    /// underscores, or expand/truncate tags. Unknown or malformed values return
    /// [`LocaleNegotiationError::UnsupportedLocale`]. No headers are inspected.
    /// An explicit preference can override the browser's `Accept-Language` list.
    pub fn select(&self, locale: &str) -> Result<ResolvedLocale, LocaleNegotiationError> {
        let index = self
            .supported
            .iter()
            .position(|(tag, _)| tag.eq_ignore_ascii_case(locale))
            .ok_or(LocaleNegotiationError::UnsupportedLocale)?;
        Ok(self.resolved(index, LocaleSource::Explicit))
    }

    /// Negotiates all `Accept-Language` fields using the module's matching rules.
    ///
    /// The missing-header case returns the default with [`LocaleSource::Default`].
    /// Present empty lists and valid lists without a match return `NoMatch`.
    /// All members are validated, even after an earlier matching preference.
    /// Invalid syntax is an error, including invalid weights or non-ASCII bytes.
    /// Only HTTP optional whitespace (SP/HTAB) and empty list members are ignored.
    /// Repeated ranges use the first member's weight, even when that weight is 0.
    ///
    /// Parsing is bounded by [`MAX_ACCEPT_LANGUAGE_BYTES`], [`MAX_LANGUAGE_RANGES`]
    /// and [`MAX_LOCALE_LENGTH`]. No input is retained in errors or logged.
    pub fn negotiate(&self, headers: &HeaderMap) -> Result<ResolvedLocale, LocaleNegotiationError> {
        if !headers.contains_key(header::ACCEPT_LANGUAGE) {
            return Ok(self.default_locale());
        }
        let preferences = parse_preferences(headers)?;
        let index = self
            .supported
            .iter()
            .enumerate()
            .filter_map(|(index, (tag, _))| {
                controlling_preference(tag, &preferences)
                    .filter(|(_, preference)| preference.quality > 0)
                    .map(|(position, preference)| {
                        (
                            index,
                            (preference.quality, Reverse(position), Reverse(index)),
                        )
                    })
            })
            .max_by_key(|(_, rank)| *rank)
            .map(|(index, _)| index)
            .ok_or(LocaleNegotiationError::NoMatch)?;
        Ok(self.resolved(index, LocaleSource::AcceptLanguage))
    }

    fn resolved(&self, index: usize, source: LocaleSource) -> ResolvedLocale {
        let (tag, header) = &self.supported[index];
        ResolvedLocale {
            tag: tag.clone(),
            header: header.clone(),
            source,
        }
    }
}

/// How a response language was selected, independent of translation resources.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LocaleSource {
    /// An exact language explicitly selected by the application or user.
    Explicit,
    /// A supported language matched the client's `Accept-Language` list.
    AcceptLanguage,
    /// No header was provided, or the application explicitly selected its default.
    Default,
}

/// A supported language selected by a [`LocalePolicy`].
///
/// Values can only be constructed through a validated policy. They contain no
/// raw preference list or rejected input and can be stored in
/// [`super::RequestContext::set_resolved_locale`]. They do not prove which
/// language an application actually used to render a response.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedLocale {
    tag: String,
    header: HeaderValue,
    source: LocaleSource,
}

impl ResolvedLocale {
    /// Returns the normalized tag from the application's supported set.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.tag
    }

    /// Returns whether this is an explicit, negotiated, or default selection.
    #[must_use]
    pub const fn source(&self) -> LocaleSource {
        self.source
    }

    /// Marks a response that the application has rendered in this language.
    ///
    /// Replaces `Content-Language`. For negotiated/default selections, adds
    /// `Accept-Language` to `Vary` unless already present (case-insensitively) or
    /// covered by `Vary: *`. All existing `Vary` fields and other headers remain.
    /// Explicit selections do not modify `Vary`: the caller must account for
    /// cookies, custom headers, or private user state in its cache policy.
    ///
    /// This operation neither translates content nor sets `Cache-Control` or
    /// validators. Apply it only to responses rendered in this language, not
    /// indiscriminately to a whole middleware stack.
    pub fn apply_response_headers(&self, headers: &mut HeaderMap) {
        headers.insert(header::CONTENT_LANGUAGE, self.header.clone());
        if self.source == LocaleSource::Explicit {
            return;
        }
        let already_varies = headers.get_all(header::VARY).iter().any(|value| {
            value.as_bytes().split(|&byte| byte == b',').any(|member| {
                let member = member.trim_ascii();
                member == b"*" || member.eq_ignore_ascii_case(b"accept-language")
            })
        });
        if !already_varies {
            headers.append(header::VARY, HeaderValue::from_static("Accept-Language"));
        }
    }
}

/// Invalid locale configuration. Errors never retain the rejected values.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Error)]
#[non_exhaustive]
pub enum LocaleConfigError {
    /// At least one supported language is required.
    #[error("at least one supported locale is required")]
    EmptySupportedLocales,
    /// A supported/default tag is malformed or exceeds [`MAX_LOCALE_LENGTH`].
    #[error("locale must be a well-formed language tag within the length limit")]
    InvalidLocale,
    /// Two supported tags are equal after case normalization.
    #[error("supported locales must not contain duplicates")]
    DuplicateLocale,
    /// The default is a well-formed tag but is not in the supported set.
    #[error("default locale must be a supported locale")]
    UnsupportedDefault,
}

impl ClassifyError for LocaleConfigError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::EmptySupportedLocales => "locale_empty_supported",
            Self::InvalidLocale => "locale_invalid_tag",
            Self::DuplicateLocale => "locale_duplicate_tag",
            Self::UnsupportedDefault => "locale_unsupported_default",
        })
    }
}

/// A request could not select an acceptable supported language.
///
/// Errors carry no header/preference text. The caller decides whether to reject
/// the request or explicitly use [`LocalePolicy::default_locale`].
#[derive(Clone, Copy, Debug, Eq, PartialEq, Error)]
#[non_exhaustive]
pub enum LocaleNegotiationError {
    /// A nonempty range or weight has invalid HTTP syntax.
    #[error("Accept-Language contains a malformed range or weight")]
    MalformedHeader,
    /// Combined field values exceed [`MAX_ACCEPT_LANGUAGE_BYTES`].
    #[error("Accept-Language exceeds the byte limit")]
    HeaderTooLarge,
    /// Field values contain more than [`MAX_LANGUAGE_RANGES`] list members.
    #[error("Accept-Language exceeds the range limit")]
    TooManyRanges,
    /// A valid list offers no acceptable language in the supported set.
    #[error("no supported locale matches the language preferences")]
    NoMatch,
    /// An explicit preference is not an exact supported tag.
    #[error("explicit locale must be a supported locale")]
    UnsupportedLocale,
}

impl ClassifyError for LocaleNegotiationError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::MalformedHeader => "locale_malformed_header",
            Self::HeaderTooLarge => "locale_header_too_large",
            Self::TooManyRanges => "locale_too_many_ranges",
            Self::NoMatch => "locale_no_match",
            Self::UnsupportedLocale => "locale_unsupported_preference",
        })
    }
}

struct Preference<'a> {
    range: &'a str,
    quality: u16,
}

fn parse_preferences(headers: &HeaderMap) -> Result<Vec<Preference<'_>>, LocaleNegotiationError> {
    let mut preferences = Vec::new();
    let mut remaining_bytes = MAX_ACCEPT_LANGUAGE_BYTES;
    let mut remaining_members = MAX_LANGUAGE_RANGES;
    for value in headers.get_all(header::ACCEPT_LANGUAGE) {
        remaining_bytes = remaining_bytes
            .checked_sub(value.as_bytes().len())
            .ok_or(LocaleNegotiationError::HeaderTooLarge)?;
        let value = value
            .to_str()
            .map_err(|_| LocaleNegotiationError::MalformedHeader)?;
        for member in value.split(',') {
            remaining_members = remaining_members
                .checked_sub(1)
                .ok_or(LocaleNegotiationError::TooManyRanges)?;
            let member = trim_ows(member);
            if member.is_empty() {
                continue;
            }
            let (range, quality) = match member.split_once(';') {
                Some((range, weight)) => {
                    let weight = trim_ows(weight);
                    let quality = weight
                        .strip_prefix("q=")
                        .or_else(|| weight.strip_prefix("Q="))
                        .and_then(super::parse_quality)
                        .ok_or(LocaleNegotiationError::MalformedHeader)?;
                    (trim_ows(range), quality)
                }
                None => (member, 1000),
            };
            if range != "*" && !is_basic_range(range) {
                return Err(LocaleNegotiationError::MalformedHeader);
            }
            preferences.push(Preference { range, quality });
        }
    }
    Ok(preferences)
}

fn trim_ows(value: &str) -> &str {
    value.trim_matches([' ', '\t'])
}

fn is_basic_range(range: &str) -> bool {
    range.len() <= MAX_LOCALE_LENGTH
        && range.split('-').enumerate().all(|(index, subtag)| {
            (1..=8).contains(&subtag.len())
                && subtag.bytes().all(|byte| {
                    if index == 0 {
                        byte.is_ascii_alphabetic()
                    } else {
                        byte.is_ascii_alphanumeric()
                    }
                })
        })
}

fn controlling_preference<'a>(
    tag: &str,
    preferences: &'a [Preference<'_>],
) -> Option<(usize, &'a Preference<'a>)> {
    preferences
        .iter()
        .enumerate()
        .filter(|(_, preference)| {
            let range = preference.range;
            range == "*"
                || (tag
                    .get(..range.len())
                    .is_some_and(|prefix| prefix.eq_ignore_ascii_case(range))
                    && (tag.len() == range.len() || tag.as_bytes().get(range.len()) == Some(&b'-')))
        })
        .max_by_key(|(index, preference)| {
            let specificity = if preference.range == "*" {
                0
            } else {
                preference.range.len()
            };
            (specificity, Reverse(*index))
        })
}