gatekeep-fluent 5.0.0

Fluent reason catalog adapter for gatekeep
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
//! Fluent-backed reason catalog for gatekeep denial reasons.
//!
//! ```
//! use gatekeep::{DenialReason, DenyShape, Locale, ReasonCatalog, ReasonCode};
//! use gatekeep_fluent::FluentCatalog;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let catalog = FluentCatalog::new()
//!     .with_resource("en-US", "case-read-denied = You cannot read this case.")?;
//! let reason = DenialReason {
//!     code: ReasonCode::new("case-read-denied")?,
//!     params: Default::default(),
//!     shape: DenyShape::Forbidden,
//! };
//!
//! assert_eq!(
//!     catalog.render(&reason, &Locale::new("en-US")?),
//!     "You cannot read this case."
//! );
//! # Ok(())
//! # }
//! ```

use std::collections::BTreeMap;

use fluent_bundle::{
    FluentArgs, FluentError, FluentResource, FluentValue, concurrent::FluentBundle,
};
use gatekeep::{DenialReason, DenyShape, Locale, ReasonCatalog, ReasonValue};
use thiserror::Error;
use unic_langid::{LanguageIdentifier, LanguageIdentifierError};

const DEFAULT_HIDDEN_MESSAGE: &str = "not found";
const DEFAULT_HIDDEN_MESSAGE_ID: &str = "not-found";

/// Fluent catalog keyed by gatekeep reason codes.
pub struct FluentCatalog {
    bundles: BTreeMap<String, FluentBundle<FluentResource>>,
    fallback_locale: Option<String>,
    hidden_message_id: String,
    hidden_fallback: String,
}

impl Default for FluentCatalog {
    fn default() -> Self {
        Self::new()
    }
}

impl FluentCatalog {
    /// Creates an empty catalog.
    #[must_use]
    pub fn new() -> Self {
        Self {
            bundles: BTreeMap::new(),
            fallback_locale: None,
            hidden_message_id: DEFAULT_HIDDEN_MESSAGE_ID.to_owned(),
            hidden_fallback: DEFAULT_HIDDEN_MESSAGE.to_owned(),
        }
    }

    /// Lists policy reason identifiers missing from this exact locale.
    ///
    /// This is a coverage check, not a rendering attempt. Fallback locales do
    /// not hide untranslated messages, and runtime Fluent arguments still need
    /// their own scenario tests. Hidden denials continue to use generic text.
    #[must_use]
    pub fn missing_reasons<'a, O>(
        &self,
        policy: &'a gatekeep::PreparedPolicy<O>,
        locale: &Locale,
    ) -> Vec<&'a str> {
        let bundle = self.bundles.get(locale.as_str());
        policy
            .inspect()
            .reasons
            .into_iter()
            .filter(|reason| {
                bundle
                    .and_then(|bundle| bundle.get_message(reason))
                    .and_then(|message| message.value())
                    .is_none()
            })
            .collect()
    }

    /// Sets the locale to try after the requested locale cannot render.
    ///
    /// # Errors
    ///
    /// Returns [`FluentCatalogError::InvalidLocale`] when `locale` is not a
    /// well-formed Unicode language identifier.
    pub fn set_fallback_locale(
        &mut self,
        locale: impl AsRef<str>,
    ) -> Result<(), FluentCatalogError> {
        let locale = parse_locale(locale.as_ref())?;
        self.fallback_locale = Some(locale.to_string());
        Ok(())
    }

    /// Returns this catalog with a fallback locale configured.
    ///
    /// # Errors
    ///
    /// Returns [`FluentCatalogError::InvalidLocale`] when `locale` is not a
    /// well-formed Unicode language identifier.
    pub fn with_fallback_locale(
        mut self,
        locale: impl AsRef<str>,
    ) -> Result<Self, FluentCatalogError> {
        self.set_fallback_locale(locale)?;
        Ok(self)
    }

    /// Sets the generic message used for hidden denials.
    ///
    /// Hidden denials must not render their specific reason code because that
    /// can disclose the protected resource's existence. The catalog looks up
    /// `message_id` in the requested locale and then the fallback locale; if no
    /// message exists, it returns `fallback`.
    ///
    /// # Errors
    ///
    /// Returns [`FluentCatalogError::EmptyMessageId`] when `message_id` is blank
    /// or [`FluentCatalogError::EmptyFallbackMessage`] when `fallback` is blank.
    pub fn set_hidden_message(
        &mut self,
        message_id: impl Into<String>,
        fallback: impl Into<String>,
    ) -> Result<(), FluentCatalogError> {
        self.hidden_message_id = validate_message_id(message_id.into())?;
        self.hidden_fallback = validate_hidden_fallback(fallback.into())?;
        Ok(())
    }

    /// Returns this catalog with a generic hidden-denial message configured.
    ///
    /// # Errors
    ///
    /// Returns [`FluentCatalogError::EmptyMessageId`] when `message_id` is blank
    /// or [`FluentCatalogError::EmptyFallbackMessage`] when `fallback` is blank.
    pub fn with_hidden_message(
        mut self,
        message_id: impl Into<String>,
        fallback: impl Into<String>,
    ) -> Result<Self, FluentCatalogError> {
        self.set_hidden_message(message_id, fallback)?;
        Ok(self)
    }

    /// Adds an FTL resource to the bundle for `locale`.
    ///
    /// Multiple resources may be added to one locale. Fluent duplicate-message
    /// errors are reported instead of overriding an earlier message.
    ///
    /// # Errors
    ///
    /// Returns [`FluentCatalogError`] when the locale is invalid, the FTL source
    /// has parse errors, or Fluent rejects the resource for that locale.
    pub fn add_resource(
        &mut self,
        locale: impl AsRef<str>,
        source: impl Into<String>,
    ) -> Result<(), FluentCatalogError> {
        let locale = parse_locale(locale.as_ref())?;
        let locale_key = locale.to_string();
        let resource = parse_resource(&locale_key, source.into())?;
        let bundle = self
            .bundles
            .entry(locale_key.clone())
            .or_insert_with(|| FluentBundle::new_concurrent(vec![locale]));
        bundle
            .add_resource(resource)
            .map_err(|errors| FluentCatalogError::Resource {
                locale: locale_key,
                errors: display_errors(errors),
            })
    }

    /// Returns this catalog with an FTL resource added.
    ///
    /// # Errors
    ///
    /// Returns [`FluentCatalogError`] when the resource cannot be added.
    pub fn with_resource(
        mut self,
        locale: impl AsRef<str>,
        source: impl Into<String>,
    ) -> Result<Self, FluentCatalogError> {
        self.add_resource(locale, source)?;
        Ok(self)
    }

    /// Renders `reason`, falling back to the stable reason code for forbidden
    /// denials or to the generic hidden message for hidden denials.
    #[must_use]
    pub fn render_reason(&self, reason: &DenialReason, locale: &Locale) -> String {
        if reason.shape == DenyShape::Hidden {
            return self.render_hidden(locale);
        }

        self.try_render_reason(reason, locale)
            .unwrap_or_else(|| reason.code.as_str().to_owned())
    }

    /// Renders `reason` only when a matching Fluent message exists and resolves
    /// without runtime formatting errors.
    ///
    /// Hidden denials use the configured generic hidden message id instead of
    /// `reason.code`.
    #[must_use]
    pub fn try_render_reason(&self, reason: &DenialReason, locale: &Locale) -> Option<String> {
        if reason.shape == DenyShape::Hidden {
            return self.try_render_hidden(locale);
        }

        for locale_key in self.locale_candidates(locale) {
            if let Some(rendered) = self.render_from_bundle(reason, &locale_key) {
                return Some(rendered);
            }
        }
        None
    }

    fn render_hidden(&self, locale: &Locale) -> String {
        self.try_render_hidden(locale)
            .unwrap_or_else(|| self.hidden_fallback.clone())
    }

    fn try_render_hidden(&self, locale: &Locale) -> Option<String> {
        for locale_key in self.locale_candidates(locale) {
            if let Some(rendered) = self.render_message(&self.hidden_message_id, None, &locale_key)
            {
                return Some(rendered);
            }
        }
        None
    }

    fn locale_candidates(&self, locale: &Locale) -> Vec<String> {
        let mut candidates = Vec::new();
        let fallback = self.fallback_locale.as_deref();
        let ordered_candidates = [
            Some(locale.as_str()),
            locale
                .as_str()
                .split_once('-')
                .map(|(language, _)| language),
            fallback,
            fallback.and_then(|value| value.split_once('-').map(|(language, _)| language)),
        ];
        for candidate in ordered_candidates.into_iter().flatten() {
            push_locale_candidate(&mut candidates, candidate);
        }

        candidates
    }

    fn render_from_bundle(&self, reason: &DenialReason, locale_key: &str) -> Option<String> {
        let args = fluent_args(reason);
        self.render_message(reason.code.as_str(), Some(&args), locale_key)
    }

    fn render_message(
        &self,
        message_id: &str,
        args: Option<&FluentArgs<'_>>,
        locale_key: &str,
    ) -> Option<String> {
        let bundle = self.bundles.get(locale_key)?;
        let message = bundle.get_message(message_id)?;
        let pattern = message.value()?;
        let mut errors = Vec::new();
        let rendered = bundle.format_pattern(pattern, args, &mut errors);
        errors.is_empty().then(|| rendered.into_owned())
    }
}

impl ReasonCatalog for FluentCatalog {
    fn render(&self, reason: &DenialReason, locale: &Locale) -> String {
        self.render_reason(reason, locale)
    }
}

/// Errors returned while building a [`FluentCatalog`].
#[derive(Debug, Error, PartialEq)]
pub enum FluentCatalogError {
    /// The locale could not be parsed by `unic-langid`.
    #[error("invalid fluent locale {locale}: {source}")]
    InvalidLocale {
        /// Rejected locale string.
        locale: String,
        /// Parser error returned by `unic-langid`.
        source: LanguageIdentifierError,
    },
    /// FTL source could not be parsed.
    #[error("failed to parse fluent resource for {locale}: {}", errors.join("; "))]
    Parse {
        /// Locale the resource was intended for.
        locale: String,
        /// Parse errors reported by Fluent.
        errors: Vec<String>,
    },
    /// Fluent rejected the parsed resource.
    #[error("failed to add fluent resource for {locale}: {}", errors.join("; "))]
    Resource {
        /// Locale the resource was intended for.
        locale: String,
        /// Resource errors reported by Fluent.
        errors: Vec<String>,
    },
    /// Hidden-denial generic message id was blank.
    #[error("{field} must not be empty")]
    EmptyMessageId {
        /// Name of the message-id field.
        field: &'static str,
    },
    /// Hidden-denial fallback message was blank.
    #[error("{field} must not be empty")]
    EmptyFallbackMessage {
        /// Name of the fallback-message field.
        field: &'static str,
    },
}

fn parse_locale(locale: &str) -> Result<LanguageIdentifier, FluentCatalogError> {
    locale
        .parse::<LanguageIdentifier>()
        .map_err(|source| FluentCatalogError::InvalidLocale {
            locale: locale.to_owned(),
            source,
        })
}

fn parse_resource(locale: &str, source: String) -> Result<FluentResource, FluentCatalogError> {
    FluentResource::try_new(source).map_err(|(_resource, errors)| FluentCatalogError::Parse {
        locale: locale.to_owned(),
        errors: errors.into_iter().map(|error| error.to_string()).collect(),
    })
}

fn display_errors(errors: Vec<FluentError>) -> Vec<String> {
    errors.into_iter().map(|error| error.to_string()).collect()
}

fn validate_message_id(value: String) -> Result<String, FluentCatalogError> {
    if value.trim().is_empty() {
        Err(FluentCatalogError::EmptyMessageId {
            field: "hidden message id",
        })
    } else {
        Ok(value)
    }
}

fn validate_hidden_fallback(value: String) -> Result<String, FluentCatalogError> {
    if value.trim().is_empty() {
        Err(FluentCatalogError::EmptyFallbackMessage {
            field: "hidden fallback message",
        })
    } else {
        Ok(value)
    }
}

fn push_locale_candidate(candidates: &mut Vec<String>, locale: &str) {
    if let Ok(locale) = locale.parse::<LanguageIdentifier>() {
        let candidate = locale.to_string();
        if !candidates.contains(&candidate) {
            candidates.push(candidate);
        }
    }
}

fn fluent_args(reason: &DenialReason) -> FluentArgs<'static> {
    let mut args = FluentArgs::with_capacity(reason.params.len());
    for (key, value) in &reason.params {
        args.set(key.as_str().to_owned(), fluent_value(value));
    }
    args
}

fn fluent_value(value: &ReasonValue) -> FluentValue<'static> {
    match value {
        ReasonValue::Str(value) => FluentValue::from(value.clone()),
        ReasonValue::Int(value) => FluentValue::from(*value),
        ReasonValue::Fact(fact) => FluentValue::from(fact.as_str().to_owned()),
        ReasonValue::Outcome(value) => json_value(value),
    }
}

fn json_value(value: &serde_json::Value) -> FluentValue<'static> {
    match value {
        serde_json::Value::Null => FluentValue::from("null"),
        serde_json::Value::Bool(value) => FluentValue::from(value.to_string()),
        serde_json::Value::Number(value) => number_value(value),
        serde_json::Value::String(value) => FluentValue::from(value.clone()),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
            FluentValue::from(value.to_string())
        }
    }
}

fn number_value(value: &serde_json::Number) -> FluentValue<'static> {
    value
        .as_i64()
        .map_or_else(|| unsigned_or_float_value(value), FluentValue::from)
}

fn unsigned_or_float_value(value: &serde_json::Number) -> FluentValue<'static> {
    value.as_u64().map_or_else(
        || float_value(value),
        |value| {
            i64::try_from(value)
                .map_or_else(|_| FluentValue::from(value.to_string()), FluentValue::from)
        },
    )
}

fn float_value(value: &serde_json::Number) -> FluentValue<'static> {
    value
        .as_f64()
        .map_or_else(|| FluentValue::from(value.to_string()), FluentValue::from)
}