Skip to main content

roas_codegen/
source.rs

1//! Where a description comes from, and the one type that holds it.
2
3use crate::diagnostic::Diagnostic;
4use crate::report;
5use roas::{v2, v3_0, v3_1, v3_2};
6use std::fmt;
7use thiserror::Error;
8use url::Url;
9
10/// The bytes or value a description arrives as.
11///
12/// The variant records *where the numbers came from*, because exactness
13/// cannot be reconstructed after the fact: only [`Input::Json`], which
14/// this crate parses itself, can yield [`Fidelity::Exact`]. The YAML
15/// reader may round through `f64`, and a ready-made `Value` has unknown
16/// provenance whatever its caller believes about it. There is
17/// deliberately no way to assert exactness on a `Value`.
18#[derive(Debug, Clone)]
19#[non_exhaustive]
20pub enum Input {
21    /// JSON text. The only way to obtain exact numbers.
22    Json(Vec<u8>),
23    /// YAML text, read with `serde-saphyr`. An integer within the 64-bit
24    /// range is kept exactly; a fraction, an exponent, or an untagged
25    /// decimal integer past `u64::MAX` or below `i64::MIN` is read through
26    /// `f64`.
27    Yaml(Vec<u8>),
28    /// An already-parsed value of unknown provenance.
29    Value(serde_json::Value),
30}
31
32/// How faithfully the numbers in a document reflect what was written.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum Fidelity {
36    /// Every number is the literal that was written. Requires the
37    /// `exact-numbers` feature and JSON input; without the feature even
38    /// JSON input is [`Fidelity::F64`], since `serde_json` rounds.
39    Exact,
40    /// Numbers went through `f64` on the way in.
41    F64,
42    /// The provenance is not known.
43    Unknown,
44}
45
46/// The OpenAPI version a description was written in.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
48#[non_exhaustive]
49pub enum SourceVersion {
50    V2,
51    V3_0,
52    V3_1,
53    V3_2,
54}
55
56impl SourceVersion {
57    fn detect(raw: &serde_json::Value) -> Result<Self, SourceError> {
58        let Some(object) = raw.as_object() else {
59            return Err(SourceError::NotAnObject);
60        };
61        if let Some(swagger) = object.get("swagger") {
62            return match swagger.as_str() {
63                Some(v) if v.starts_with("2.0") => Ok(SourceVersion::V2),
64                _ => Err(SourceError::UnknownVersion {
65                    field: "swagger",
66                    value: swagger.to_string(),
67                }),
68            };
69        }
70        if let Some(openapi) = object.get("openapi") {
71            return match openapi.as_str() {
72                Some(v) if v.starts_with("3.0.") || v == "3.0" => Ok(SourceVersion::V3_0),
73                Some(v) if v.starts_with("3.1.") || v == "3.1" => Ok(SourceVersion::V3_1),
74                Some(v) if v.starts_with("3.2.") || v == "3.2" => Ok(SourceVersion::V3_2),
75                _ => Err(SourceError::UnknownVersion {
76                    field: "openapi",
77                    value: openapi.to_string(),
78                }),
79            };
80        }
81        Err(SourceError::NoVersion)
82    }
83}
84
85impl fmt::Display for SourceVersion {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str(match self {
88            SourceVersion::V2 => "OpenAPI 2.0",
89            SourceVersion::V3_0 => "OpenAPI 3.0",
90            SourceVersion::V3_1 => "OpenAPI 3.1",
91            SourceVersion::V3_2 => "OpenAPI 3.2",
92        })
93    }
94}
95
96/// Why a description could not become a [`SourceDocument`].
97#[derive(Debug, Error)]
98#[non_exhaustive]
99pub enum SourceError {
100    #[error("the input is not valid JSON")]
101    Json(#[source] serde_json::Error),
102    /// The YAML reader rejected the input: a syntax error, a duplicate
103    /// mapping key, or a document past the reader's size and alias budget.
104    #[error("the input is not valid YAML")]
105    Yaml(#[source] serde_saphyr::Error),
106    #[error("a description must be a JSON object")]
107    NotAnObject,
108    #[error("neither `swagger` nor `openapi` is present, so the version is unknown")]
109    NoVersion,
110    #[error("`{field}: {value}` is not a supported version")]
111    UnknownVersion { field: &'static str, value: String },
112    #[error("the input is not a valid {version} description")]
113    Parse {
114        version: SourceVersion,
115        #[source]
116        source: serde_json::Error,
117    },
118    /// The description parsed, but `roas` could not convert it to OpenAPI 3.2: a gap in the
119    /// conversion rather than in the description.
120    #[error("the {version} description could not be converted to OpenAPI 3.2")]
121    Convert {
122        version: SourceVersion,
123        #[source]
124        source: roas::conversion::ConversionError,
125    },
126}
127
128/// A description, parsed and normalized to OpenAPI 3.2, together with
129/// the source it came from.
130///
131/// The raw and typed views are the same document by construction: the
132/// fields are private and [`SourceDocument::parse`] is the only way to
133/// make one, so a caller cannot pair the raw JSON of one document with
134/// the typed model of another. The raw view keeps what the typed model
135/// cannot express — whether `type` was written at all, the exact text a
136/// diagnostic should quote — and every diagnostic pointer indexes it,
137/// in the version it was written in.
138#[derive(Debug, Clone)]
139pub struct SourceDocument {
140    uri: Url,
141    version: SourceVersion,
142    fidelity: Fidelity,
143    raw: serde_json::Value,
144    spec: v3_2::spec::Spec,
145    normalization: Vec<Diagnostic>,
146}
147
148impl SourceDocument {
149    /// Detect the version, parse the typed model at that version, record
150    /// what upconverting to 3.2 loses, and upconvert.
151    ///
152    /// `uri` identifies the document in every [`SchemaId`](crate::SchemaId)
153    /// it produces. Input with no natural URI takes a synthetic one, by
154    /// convention `stdin:///`.
155    pub fn parse(input: Input, uri: Url) -> Result<SourceDocument, SourceError> {
156        let (raw, fidelity) = match input {
157            Input::Json(bytes) => {
158                let value = serde_json::from_slice(&bytes).map_err(SourceError::Json)?;
159                let fidelity = if cfg!(feature = "exact-numbers") {
160                    Fidelity::Exact
161                } else {
162                    Fidelity::F64
163                };
164                (value, fidelity)
165            }
166            Input::Yaml(bytes) => (
167                parse_yaml(&bytes).map_err(SourceError::Yaml)?,
168                Fidelity::F64,
169            ),
170            Input::Value(value) => (value, Fidelity::Unknown),
171        };
172        let version = SourceVersion::detect(&raw)?;
173        let parse = |source| SourceError::Parse { version, source };
174        let convert = |source| SourceError::Convert { version, source };
175        let mut normalization = Vec::new();
176        let spec = match version {
177            SourceVersion::V2 => {
178                let spec: v2::spec::Spec = serde_json::from_value(raw.clone()).map_err(parse)?;
179                report::v2_losses(&raw, &uri, &mut normalization);
180                let v30 = v3_0::spec::Spec::try_from(spec).map_err(convert)?;
181                let v31 = v3_1::spec::Spec::try_from(v30).map_err(convert)?;
182                v3_2::spec::Spec::try_from(v31).map_err(convert)?
183            }
184            SourceVersion::V3_0 => {
185                let spec: v3_0::spec::Spec = serde_json::from_value(raw.clone()).map_err(parse)?;
186                let v31 = v3_1::spec::Spec::try_from(spec).map_err(convert)?;
187                v3_2::spec::Spec::try_from(v31).map_err(convert)?
188            }
189            SourceVersion::V3_1 => {
190                let spec: v3_1::spec::Spec = serde_json::from_value(raw.clone()).map_err(parse)?;
191                v3_2::spec::Spec::try_from(spec).map_err(convert)?
192            }
193            SourceVersion::V3_2 => serde_json::from_value(raw.clone()).map_err(parse)?,
194        };
195        Ok(SourceDocument {
196            uri,
197            version,
198            fidelity,
199            raw,
200            spec,
201            normalization,
202        })
203    }
204
205    /// The document's identity.
206    pub fn uri(&self) -> &Url {
207        &self.uri
208    }
209
210    /// The version the description was written in — not the version
211    /// [`spec`](Self::spec) is at, which is always 3.2.
212    pub fn version(&self) -> SourceVersion {
213        self.version
214    }
215
216    /// How faithfully the numbers reflect what was written.
217    pub fn fidelity(&self) -> Fidelity {
218        self.fidelity
219    }
220
221    /// The description exactly as given, before any conversion. Every
222    /// diagnostic pointer indexes this value.
223    pub fn raw(&self) -> &serde_json::Value {
224        &self.raw
225    }
226
227    /// The description normalized to OpenAPI 3.2.
228    pub fn spec(&self) -> &v3_2::spec::Spec {
229        &self.spec
230    }
231
232    /// What normalizing to 3.2 lost. Recorded by the source-version
233    /// adapter before the lossy conversion runs, since a 2.0
234    /// `collectionFormat: tsv` that 3.0 drops cannot be recovered
235    /// afterwards.
236    pub fn normalization(&self) -> &[Diagnostic] {
237        &self.normalization
238    }
239}
240
241/// Read YAML with the options every roas crate uses, so a document means
242/// the same thing here as in the fetchers and the CLI.
243///
244/// - YAML 1.2 booleans only: `yes` / `on` / `no` / `off` stay strings.
245/// - Integer spellings `017` and `1_000` stay strings rather than becoming numbers.
246/// - `!!binary` scalars are read as their base64 text, not decoded.
247/// - `.inf` / `.nan` pass through (a `serde_json::Value` holds them as `null`).
248/// - `<<: *anchor` merge keys are expanded.
249/// - A duplicate mapping key is an error rather than a silent last-wins.
250///
251/// A [`serde_saphyr::Budget`] stays on, raised so large specs fit: it rejects
252/// alias bombs, nesting past 64 levels, documents past 10M nodes or
253/// 64 MiB of scalar text, and an anchored node past 1M events.
254fn parse_yaml(bytes: &[u8]) -> Result<serde_json::Value, serde_saphyr::Error> {
255    let options = serde_saphyr::options! {
256        // Same options in every roas crate; keep the copies in step
257        // (`grep -rn 'strict_booleans: true' crates`). The budget is raised
258        // from the defaults (250k nodes, 1M events, 50k aliases, 50k anchors,
259        // 10k merge keys), which reject ordinary large or generated specs. Depth stays at 64: deeper nesting overflows a 2 MiB
260        // thread stack in debug builds. The alias-to-anchor ratio check is off:
261        // it rejects any document reusing one anchor 100+ times, a common
262        // pattern in specs. Alias replay is raised to 10M events so a large
263        // schema can be aliased thousands of times; the 1M cap on events
264        // recorded under anchors still stops an alias bomb, and also caps
265        // how large one anchored node can be. `!!binary` is
266        // read as its text, as before, not decoded.
267        budget: serde_saphyr::budget! {
268            max_nodes: 10_000_000,
269            max_events: 25_000_000,
270            max_aliases: 1_000_000,
271            max_anchors: 1_000_000,
272            max_merge_keys: 1_000_000,
273            enforce_alias_anchor_ratio: false,
274        },
275        alias_limits: serde_saphyr::alias_limits! {
276            max_total_replayed_events: 10_000_000,
277        },
278        strict_booleans: true,
279        ignore_binary_tag_for_string: true,
280        leading_zero_numbers_as_strings: true,
281        underscored_numbers_as_strings: true,
282        non_finite_float_policy: serde_saphyr::NonFiniteFloatPolicy::PassThrough,
283        merge_keys: serde_saphyr::MergeKeyPolicy::Merge,
284        duplicate_keys: serde_saphyr::DuplicateKeyPolicy::Error,
285    };
286    serde_saphyr::from_slice_with_options::<crate::yaml_value::JsonValue>(bytes, options)
287        .map(crate::yaml_value::JsonValue::into_inner)
288}
289
290#[cfg(test)]
291mod yaml_tests {
292    use super::*;
293    use serde_json::{Value, json};
294
295    fn parse(yaml: &str) -> Result<Value, String> {
296        parse_yaml(yaml.as_bytes()).map_err(|e| e.to_string())
297    }
298
299    /// Each scalar whose meaning depends on the YAML options, next to what
300    /// it must read as.
301    #[test]
302    fn yaml_scalars_read_as_yaml_1_2() {
303        for (scalar, expected) in [
304            ("yes", json!("yes")),
305            ("on", json!("on")),
306            ("no", json!("no")),
307            ("off", json!("off")),
308            ("true", json!(true)),
309            ("False", json!(false)),
310            ("017", json!("017")),
311            ("1_000", json!("1_000")),
312            ("17", json!(17)),
313            ("0x11", json!(17)),
314            ("1.5", json!(1.5)),
315            (".inf", json!(null)),
316            ("3.1.0", json!("3.1.0")),
317            ("!!binary SGVsbG8=", json!("SGVsbG8=")),
318            ("!!binary /wAB", json!("/wAB")),
319            ("1e400", json!(null)),
320            ("!include other.yaml", json!("other.yaml")),
321        ] {
322            assert_eq!(
323                parse(&format!("v: {scalar}\n")).unwrap(),
324                json!({ "v": expected }),
325                "{scalar}",
326            );
327        }
328    }
329
330    #[test]
331    fn yaml_merge_keys_expand_through_an_anchor() {
332        let yaml = "base: &base { type: string, minLength: 1 }\n\
333                    name:\n  <<: *base\n  minLength: 3\n";
334        assert_eq!(
335            parse(yaml).unwrap(),
336            json!({
337                "base": { "type": "string", "minLength": 1 },
338                "name": { "type": "string", "minLength": 3 },
339            }),
340        );
341    }
342
343    #[test]
344    fn yaml_duplicate_key_is_an_error() {
345        let err = parse("a: 1\na: 2\n").unwrap_err();
346        assert!(err.contains("duplicate mapping key"), "{err}");
347    }
348
349    /// `200` and `"200"` are different YAML keys but the same JSON one.
350    /// Through a `<<` merge the inherited entry would otherwise overwrite the
351    /// explicit one, in either direction.
352    #[test]
353    fn yaml_keys_colliding_as_json_are_an_error() {
354        for yaml in [
355            "base: &b { 200: { description: inherited } }\n\
356             responses:\n  <<: *b\n  \"200\": { description: explicit }\n",
357            "base: &b { \"200\": { description: inherited } }\n\
358             responses:\n  <<: *b\n  200: { description: explicit }\n",
359            "responses:\n  200: a\n  \"200\": b\n",
360        ] {
361            let err = parse(yaml).unwrap_err();
362            assert!(err.contains("appears twice once read as JSON"), "{err}");
363        }
364    }
365
366    #[test]
367    fn yaml_merge_keeps_the_explicit_entry_when_keys_match() {
368        let yaml = "base: &b { 200: { description: inherited }, 404: { description: nf } }\n\
369                    responses:\n  <<: *b\n  200: { description: explicit }\n";
370        assert_eq!(
371            parse(yaml).unwrap()["responses"],
372            json!({ "200": { "description": "explicit" }, "404": { "description": "nf" } }),
373        );
374    }
375
376    /// Keys are read as strings, so a number-looking key keeps its spelling
377    /// and two spellings of one number are two keys.
378    #[test]
379    fn yaml_keys_keep_their_spelling() {
380        assert_eq!(
381            parse("r: { 1.10: a, 1.1: b, 0x10: c, 1e3: d, True: e, 017: f }\n").unwrap(),
382            json!({ "r": { "1.10": "a", "1.1": "b", "0x10": "c", "1e3": "d", "True": "e", "017": "f" } }),
383        );
384    }
385
386    #[test]
387    fn yaml_null_and_collection_keys_are_an_error() {
388        for yaml in [
389            "r: { null: a }\n",
390            "r: { ~: a }\n",
391            "r:\n  ? [1, 2]\n  : a\n",
392        ] {
393            parse(yaml).unwrap_err();
394        }
395    }
396
397    /// The number map YAML output carries under `arbitrary_precision` reads
398    /// back the way `serde_json` reads it, with the feature on or off.
399    #[test]
400    fn yaml_arbitrary_precision_number_map_matches_serde_json() {
401        let json = r#"{"n":{"$serde_json::private::Number":"12.50"}}"#;
402        let expected: Value = serde_json::from_str(json).unwrap();
403        assert_eq!(
404            parse("n: { \"$serde_json::private::Number\": \"12.50\" }\n").unwrap(),
405            expected
406        );
407    }
408
409    #[test]
410    fn yaml_alias_bomb_is_rejected_by_the_budget() {
411        // Billion laughs: each level aliases the previous one ten times, so
412        // full expansion is 10^7 scalars. The anchor-replay limits stop it.
413        let mut yaml = String::from("l0: &l0 [lol, lol, lol, lol, lol, lol, lol, lol, lol, lol]\n");
414        for i in 1..7 {
415            let prev = format!("*l{}", i - 1);
416            yaml.push_str(&format!("l{i}: &l{i} [{}]\n", vec![prev; 10].join(", ")));
417        }
418        let err = parse(&yaml).unwrap_err();
419        assert!(err.contains("budget breached"), "{err}");
420    }
421
422    /// One shared anchor reused many times, as specs do for common
423    /// responses, is not a bomb.
424    #[test]
425    fn yaml_anchor_reused_many_times_is_accepted() {
426        // 40 properties aliased 6,000 times replays over a million events.
427        let props: String = (0..40)
428            .map(|i| format!("    p{i}: {{ type: string }}\n"))
429            .collect();
430        let mut yaml = format!("schema: &s\n  type: object\n  properties:\n{props}responses:\n");
431        for i in 0..6_000 {
432            yaml.push_str(&format!("  r{i}: *s\n"));
433        }
434        let value = parse(&yaml).unwrap();
435        assert_eq!(
436            value["responses"]["r5999"]["properties"]["p39"]["type"],
437            "string"
438        );
439    }
440
441    /// Past the library's default caps of 50k aliases and 50k anchors,
442    /// which generated specs (one anchor per shared object) can reach.
443    #[test]
444    fn yaml_many_aliases_and_anchors_fit_the_budget() {
445        let mut yaml = String::from("shared: &s x\n");
446        for i in 0..60_000 {
447            yaml.push_str(&format!("a{i}: *s\nb{i}: &b{i} y\n"));
448        }
449        let value = parse(&yaml).unwrap();
450        assert_eq!(value["a59999"], "x");
451        assert_eq!(value["b59999"], "y");
452    }
453
454    /// Past the library's default cap of 10k merge keys, which only applies
455    /// because merge keys are expanded.
456    #[test]
457    fn yaml_many_merge_keys_fit_the_budget() {
458        let mut yaml = String::from("base: &b { type: string }\n");
459        for i in 0..10_001 {
460            yaml.push_str(&format!("s{i}: {{ <<: *b, minLength: 1 }}\n"));
461        }
462        let value = parse(&yaml).unwrap();
463        assert_eq!(value["s10000"]["type"], "string");
464    }
465
466    #[test]
467    fn yaml_nesting_is_capped_at_64_levels() {
468        let nested = |depth: usize| format!("{}1{}", "[".repeat(depth), "]".repeat(depth));
469        parse(&nested(64)).unwrap();
470        let err = parse(&nested(65)).unwrap_err();
471        assert!(err.contains("budget breached"), "{err}");
472    }
473
474    /// Past the library's default budget of 250k nodes, which rejects
475    /// ordinary large specs.
476    #[test]
477    fn yaml_large_document_fits_the_budget() {
478        let yaml: String = (0..60_000).map(|i| format!("k{i}: [a, b, c]\n")).collect();
479        let value = parse(&yaml).unwrap();
480        assert_eq!(value.as_object().unwrap().len(), 60_000);
481    }
482}