1use 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#[derive(Debug, Clone)]
19#[non_exhaustive]
20pub enum Input {
21 Json(Vec<u8>),
23 Yaml(Vec<u8>),
28 Value(serde_json::Value),
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum Fidelity {
36 Exact,
40 F64,
42 Unknown,
44}
45
46#[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#[derive(Debug, Error)]
98#[non_exhaustive]
99pub enum SourceError {
100 #[error("the input is not valid JSON")]
101 Json(#[source] serde_json::Error),
102 #[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 #[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#[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 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 pub fn uri(&self) -> &Url {
207 &self.uri
208 }
209
210 pub fn version(&self) -> SourceVersion {
213 self.version
214 }
215
216 pub fn fidelity(&self) -> Fidelity {
218 self.fidelity
219 }
220
221 pub fn raw(&self) -> &serde_json::Value {
224 &self.raw
225 }
226
227 pub fn spec(&self) -> &v3_2::spec::Spec {
229 &self.spec
230 }
231
232 pub fn normalization(&self) -> &[Diagnostic] {
237 &self.normalization
238 }
239}
240
241fn parse_yaml(bytes: &[u8]) -> Result<serde_json::Value, serde_saphyr::Error> {
255 let options = serde_saphyr::options! {
256 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 #[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 #[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 #[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 #[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 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 #[test]
425 fn yaml_anchor_reused_many_times_is_accepted() {
426 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 #[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 #[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 #[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}