citum-schema-style 0.65.0

Citum style schema types and styling engine
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
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
*/

//! Style validation and resource-limit checks.

use crate::template::{
    LocalizedTemplateSpec, TemplateComponent, TemplateVariant, TemplateVariants,
};
use crate::version::{MAX_TEMPLATE_COMPONENTS, MAX_TEMPLATE_NESTING_DEPTH};
use crate::{BibliographySpec, CitationSpec, ResolutionError};

use super::Style;

#[cfg(test)]
use crate::template::TemplateGroup;

/// A non-fatal validation warning emitted by [`Style::validate`].
#[derive(Debug, Clone, PartialEq)]
pub enum SchemaWarning {
    /// A `TypeSelector` references an unrecognized reference type name.
    ///
    /// This usually indicates a typo (e.g., `article_journal` instead of
    /// `article-journal`). The selector will silently match nothing at
    /// render time.
    UnknownTypeName {
        /// The unrecognized type name string.
        name: String,
        /// Human-readable location hint (e.g., `"bibliography.type-variants"`).
        location: String,
    },
}

impl std::fmt::Display for SchemaWarning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SchemaWarning::UnknownTypeName { name, location } => {
                write!(
                    f,
                    "unknown reference type \"{name}\" in {location} \
                     (will silently match nothing; check for typos)"
                )
            }
        }
    }
}

impl Style {
    /// Validate hard resource limits for style templates.
    ///
    /// # Errors
    ///
    /// Returns an error when authored template structure exceeds the maximum
    /// depth or component count accepted by the engine.
    pub fn validate_resource_limits(&self) -> Result<(), String> {
        let mut budget = TemplateResourceBudget::default();

        if let Some(templates) = &self.templates {
            for (name, template) in templates {
                budget.check_template(template, &format!("templates.{name}"), 0)?;
            }
        }
        if let Some(citation) = &self.citation {
            budget.check_citation_spec(citation, "citation", 0)?;
        }
        if let Some(bibliography) = &self.bibliography {
            budget.check_bibliography_spec(bibliography, "bibliography", 0)?;
        }

        Ok(())
    }

    /// Validate the style and return any non-fatal warnings.
    ///
    /// This method checks for issues that are syntactically valid but
    /// semantically suspect, such as unrecognized reference type names in
    /// `TypeSelector` values.
    ///
    /// Warnings do not prevent rendering; they are informational only.
    pub fn validate(&self) -> Vec<SchemaWarning> {
        let mut warnings = Vec::new();
        self.collect_type_selector_warnings(&mut warnings);
        warnings
    }

    /// Collect warnings for all `TypeSelector` values in the style.
    fn collect_type_selector_warnings(&self, warnings: &mut Vec<SchemaWarning>) {
        if let Some(bib) = &self.bibliography
            && let Some(type_variants) = &bib.type_variants
        {
            for selector in type_variants.keys() {
                for name in selector.unknown_type_names() {
                    warnings.push(SchemaWarning::UnknownTypeName {
                        name: name.to_string(),
                        location: "bibliography.type-variants".to_string(),
                    });
                }
            }
        }
        if let Some(cit) = &self.citation {
            collect_citation_spec_warnings(cit, "citation", warnings);
        }
    }

    pub(crate) fn validate_profile_shape(&self) -> Result<(), ResolutionError> {
        if self.templates.is_some() || yaml_path_present(self.raw_yaml.as_ref(), &["templates"]) {
            return Err(ResolutionError::InvalidProfileOverride {
                location: "templates".to_string(),
            });
        }

        if let Some(location) = forbidden_profile_template_path(self.raw_yaml.as_ref()) {
            return Err(ResolutionError::InvalidProfileOverride { location });
        }

        Ok(())
    }
}

fn forbidden_profile_template_path(raw_yaml: Option<&serde_yaml::Value>) -> Option<String> {
    let raw_yaml = raw_yaml?;
    for (section, recursive) in [("citation", true), ("bibliography", false)] {
        if let Some(section_value) = mapping_child(raw_yaml, section) {
            if recursive {
                if let Some(location) = forbidden_citation_template_path(section_value, section) {
                    return Some(location);
                }
            } else if let Some(location) = forbidden_section_template_path(section_value, section) {
                return Some(location);
            }
        }
    }
    None
}

fn forbidden_section_template_path(section: &serde_yaml::Value, location: &str) -> Option<String> {
    for key in ["template", "template-ref", "type-variants", "locales"] {
        if mapping_child(section, key).is_some() {
            return Some(format!("{location}.{key}"));
        }
    }
    None
}

fn forbidden_citation_template_path(section: &serde_yaml::Value, location: &str) -> Option<String> {
    if let Some(location) = forbidden_section_template_path(section, location) {
        return Some(location);
    }

    for sub_section in ["integral", "non-integral", "subsequent", "ibid"] {
        if let Some(child) = mapping_child(section, sub_section)
            && let Some(location) =
                forbidden_citation_template_path(child, &format!("{location}.{sub_section}"))
        {
            return Some(location);
        }
    }
    None
}

fn mapping_child<'a>(value: &'a serde_yaml::Value, segment: &str) -> Option<&'a serde_yaml::Value> {
    let serde_yaml::Value::Mapping(map) = value else {
        return None;
    };
    let key = serde_yaml::Value::String(segment.to_string());
    map.get(&key)
}

fn yaml_path_present(value: Option<&serde_yaml::Value>, path: &[&str]) -> bool {
    let Some(mut current) = value else {
        return false;
    };
    for segment in path {
        let Some(next) = mapping_child(current, segment) else {
            return false;
        };
        current = next;
    }
    true
}

/// Collect warnings from a `CitationSpec` and its sub-specs.
fn collect_citation_spec_warnings(
    spec: &CitationSpec,
    location: &str,
    warnings: &mut Vec<SchemaWarning>,
) {
    if let Some(type_variants) = &spec.type_variants {
        for selector in type_variants.keys() {
            for name in selector.unknown_type_names() {
                warnings.push(SchemaWarning::UnknownTypeName {
                    name: name.to_string(),
                    location: format!("{location}.type-variants"),
                });
            }
        }
    }
    // Recurse into sub-specs
    for (sub_name, sub_spec) in [
        ("integral", spec.integral.as_deref()),
        ("non-integral", spec.non_integral.as_deref()),
        ("subsequent", spec.subsequent.as_deref()),
        ("ibid", spec.ibid.as_deref()),
    ]
    .into_iter()
    .filter_map(|(n, s)| s.map(|s| (n, s)))
    {
        collect_citation_spec_warnings(sub_spec, &format!("{location}.{sub_name}"), warnings);
    }
}

#[derive(Default)]
struct TemplateResourceBudget {
    component_count: usize,
}

impl TemplateResourceBudget {
    fn check_template(
        &mut self,
        template: &[TemplateComponent],
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        if depth > MAX_TEMPLATE_NESTING_DEPTH {
            return Err(format!(
                "{location} exceeds maximum template nesting depth of {MAX_TEMPLATE_NESTING_DEPTH}"
            ));
        }
        for component in template {
            self.check_component(component, location, depth)?;
        }
        Ok(())
    }

    fn check_component(
        &mut self,
        component: &TemplateComponent,
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        self.component_count = self.component_count.saturating_add(1);
        if self.component_count > MAX_TEMPLATE_COMPONENTS {
            return Err(format!(
                "style exceeds maximum template component count of {MAX_TEMPLATE_COMPONENTS}"
            ));
        }

        match component {
            TemplateComponent::Date(date) => {
                if let Some(fallback) = &date.fallback {
                    self.check_template(fallback, &format!("{location}.date.fallback"), depth + 1)?;
                }
            }
            TemplateComponent::Group(group) => {
                self.check_template(&group.group, &format!("{location}.group"), depth + 1)?;
            }
            TemplateComponent::Contributor(_)
            | TemplateComponent::Title(_)
            | TemplateComponent::Number(_)
            | TemplateComponent::Variable(_)
            | TemplateComponent::Term(_) => {}
        }

        Ok(())
    }

    fn check_variant(
        &mut self,
        variant: &TemplateVariant,
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        match variant {
            TemplateVariant::Full(template) => self.check_template(template, location, depth),
            TemplateVariant::Diff(diff) => {
                for (index, add) in diff.add.iter().enumerate() {
                    self.check_component(
                        &add.component,
                        &format!("{location}.add[{index}].component"),
                        depth,
                    )?;
                }
                Ok(())
            }
        }
    }

    fn check_variants(
        &mut self,
        variants: &TemplateVariants,
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        for (selector, variant) in variants {
            self.check_variant(variant, &format!("{location}.{selector:?}"), depth)?;
        }
        Ok(())
    }

    fn check_locales(
        &mut self,
        locales: &[LocalizedTemplateSpec],
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        for (index, locale) in locales.iter().enumerate() {
            self.check_template(
                &locale.template,
                &format!("{location}[{index}].template"),
                depth,
            )?;
        }
        Ok(())
    }

    fn check_citation_spec(
        &mut self,
        spec: &CitationSpec,
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        if let Some(template) = &spec.template {
            self.check_template(template, &format!("{location}.template"), depth)?;
        }
        if let Some(locales) = &spec.locales {
            self.check_locales(locales, &format!("{location}.locales"), depth)?;
        }
        if let Some(variants) = &spec.type_variants {
            self.check_variants(variants, &format!("{location}.type-variants"), depth)?;
        }
        for (sub_name, sub_spec) in [
            ("integral", spec.integral.as_deref()),
            ("non-integral", spec.non_integral.as_deref()),
            ("subsequent", spec.subsequent.as_deref()),
            ("ibid", spec.ibid.as_deref()),
        ]
        .into_iter()
        .filter_map(|(n, s)| s.map(|s| (n, s)))
        {
            self.check_citation_spec(sub_spec, &format!("{location}.{sub_name}"), depth + 1)?;
        }
        Ok(())
    }

    fn check_bibliography_spec(
        &mut self,
        spec: &BibliographySpec,
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        if let Some(template) = &spec.template {
            self.check_template(template, &format!("{location}.template"), depth)?;
        }
        if let Some(locales) = &spec.locales {
            self.check_locales(locales, &format!("{location}.locales"), depth)?;
        }
        if let Some(variants) = &spec.type_variants {
            self.check_variants(variants, &format!("{location}.type-variants"), depth)?;
        }
        Ok(())
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::todo,
    clippy::unimplemented,
    clippy::unreachable,
    clippy::get_unwrap,
    reason = "Panicking is acceptable and often desired in tests."
)]
mod security_resource_tests {
    use super::*;

    fn nested_group(depth: usize) -> TemplateComponent {
        if depth == 0 {
            TemplateComponent::default()
        } else {
            TemplateComponent::Group(TemplateGroup {
                group: vec![nested_group(depth - 1)],
                ..TemplateGroup::default()
            })
        }
    }

    #[test]
    fn validate_resource_limits_rejects_deeply_nested_templates() {
        let style = Style {
            bibliography: Some(BibliographySpec {
                template: Some(vec![nested_group(MAX_TEMPLATE_NESTING_DEPTH + 1)]),
                ..BibliographySpec::default()
            }),
            ..Style::default()
        };

        let err = style
            .validate_resource_limits()
            .expect_err("deep template must be rejected");

        assert!(err.contains("maximum template nesting depth"));
    }

    #[test]
    fn validate_resource_limits_rejects_too_many_components() {
        let style = Style {
            bibliography: Some(BibliographySpec {
                template: Some(vec![
                    TemplateComponent::default();
                    MAX_TEMPLATE_COMPONENTS + 1
                ]),
                ..BibliographySpec::default()
            }),
            ..Style::default()
        };

        let err = style
            .validate_resource_limits()
            .expect_err("oversized template must be rejected");

        assert!(err.contains("maximum template component count"));
    }
}