roas 0.17.0

Rust OpenAPI Specification — parser, validator, and loader for OpenAPI v2.0 / v3.0.x / v3.1.x / v3.2.x
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
//! XML Object

use crate::common::helpers::{has_uri_unsafe_bytes, validate_optional_uri};
use crate::v3_2::spec::Spec;
use crate::validation::Options;
use crate::validation::{Context, PushError, ValidateWithContext};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// A metadata object that allows for more fine-tuned XML model definitions.
///
/// When using arrays, XML element names are not inferred (for singular/plural forms)
/// and the `name` property SHOULD be used to add that information.
/// See examples for expected behavior.
///
/// Examples:
///
/// * String item:
/// ```yaml
/// animals:
///   type: string
/// ```
///
/// ```xml
/// <animals>...</animals>
/// ```
///
/// * Array of strings:
/// ```yaml
/// animals:
///   type: array
///   items:
///     type: string
/// ```
///
/// ```xml
/// <animals>...</animals>
/// <animals>...</animals>
/// <animals>...</animals>
/// ```
///
/// * String with name replacement:
/// ```yaml
/// animals:
///   type: string
///   xml:
///     name: animal
/// ```
///
/// ```xml
/// <animal>...</animal>
/// ```
///
/// * XML Attribute, Prefix and Namespace
/// ```yaml
/// Person:
///   type: object
///   properties:
///     id:
///       type: integer
///       format: int32
///       xml:
///         attribute: true
///     name:
///       type: string
///       xml:
///         namespace: https://swagger.io/schema/sample
///         prefix: sample
/// ```
///
/// ```xml
/// <Person id="123">
///     <sample:name xmlns:sample="https://swagger.io/schema/sample">example</sample:name>
/// </Person>
/// ```
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)]
pub struct XML {
    /// Replaces the name of the element/attribute used for the described schema property.
    /// When defined within `items`, it will affect the name of the individual XML elements
    /// within the list.
    /// When defined alongside `type` being `array` (outside the `items`),
    /// it will affect the wrapping element and only if `wrapped` is `true`.
    /// If `wrapped` is `false`, it will be ignored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// The URI of the namespace definition.
    /// Value MUST be in the form of an absolute URI.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,

    /// The prefix to be used for the name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,

    /// Declares whether the property definition translates to an attribute instead of an element.
    /// Default value is `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attribute: Option<bool>,

    /// MAY be used only for an array definition.
    /// Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or
    /// unwrapped (`<book/><book/>`).
    /// Default value is `false`.
    /// The definition takes effect only when defined alongside `type` being `array` (outside the `items`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wrapped: Option<bool>,

    /// XML node-type hint (added in OAS 3.2). One of `element` (default),
    /// `attribute`, `text`, `cdata`, or `none`. When `nodeType` is set,
    /// the legacy boolean fields `attribute` and `wrapped` MUST NOT be
    /// used — `nodeType` supersedes them.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "nodeType")]
    pub node_type: Option<String>,

    /// Allows extensions to the Swagger Schema.
    /// The field name MUST begin with `x-`, for example, `x-internal-id`.
    /// The value can be null, a primitive, an array or an object.
    #[serde(flatten)]
    #[serde(with = "crate::common::extensions")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<BTreeMap<String, serde_json::Value>>,
}

impl ValidateWithContext<Spec> for XML {
    fn validate_with_context(&self, ctx: &mut Context<Spec>, path: String) {
        validate_optional_uri(&self.namespace, ctx, format!("{path}.namespace"));
        // The OAS XML Object spec requires `namespace` to be an *absolute*
        // URI: a relative reference like `#/foo` or `bar/baz` is not
        // valid. Enforce a present `scheme:` prefix per RFC 3986
        // §3.1: `scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`.
        // Skip when the value already failed `validate_optional_uri`
        // (whitespace / control chars) so users see a single,
        // most-relevant error.
        if let Some(ns) = &self.namespace
            && !ns.is_empty()
            && !ctx.is_option(Options::IgnoreInvalidUrls)
            && !has_uri_unsafe_bytes(ns)
        {
            let mut chars = ns.chars();
            let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
            let scheme_end = ns.find(':');
            let scheme_ok = first_ok
                && scheme_end.is_some_and(|i| {
                    ns[..i]
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
                });
            if !scheme_ok {
                ctx.error(
                    format!("{path}.namespace"),
                    format_args!("must be an absolute URI (with `<scheme>:` prefix), found `{ns}`"),
                );
            }
        }
        if let Some(nt) = &self.node_type {
            const ALLOWED: &[&str] = &["element", "attribute", "text", "cdata", "none"];
            if !ALLOWED.contains(&nt.as_str()) {
                ctx.error(
                    format!("{path}.nodeType"),
                    format_args!(
                        "must be one of `element`, `attribute`, `text`, `cdata`, `none`, found `{nt}`"
                    ),
                );
            }
            // OAS 3.2 supersedes the legacy `attribute`/`wrapped` booleans
            // with `nodeType`; mixing them is ambiguous.
            if self.attribute.is_some() {
                ctx.error(
                    path.clone(),
                    "`attribute` MUST NOT be present when `nodeType` is set",
                );
            }
            if self.wrapped.is_some() {
                ctx.error(
                    path.clone(),
                    "`wrapped` MUST NOT be present when `nodeType` is set",
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validation::Options;

    #[test]
    fn serialize() {
        assert_eq!(
            serde_json::to_string(&XML::default()).unwrap(),
            "{}",
            "empty object"
        );

        assert_eq!(
            serde_json::to_value(&XML {
                name: Some("name".to_owned()),
                namespace: Some("https://example.com/schema/sample".to_owned()),
                prefix: Some("sample".to_owned()),
                attribute: Some(true),
                wrapped: Some(true),
                node_type: None,
                extensions: {
                    let mut map = BTreeMap::new();
                    map.insert("x-internal-id".to_owned(), serde_json::Value::Null);
                    Some(map)
                },
            })
            .unwrap(),
            serde_json::json!({
                "name": "name",
                "namespace": "https://example.com/schema/sample",
                "prefix": "sample",
                "attribute": true,
                "wrapped": true,
                "x-internal-id": null,
            }),
            "all fields"
        );
    }

    #[test]
    fn deserialize() {
        assert_eq!(
            serde_json::from_value::<XML>(serde_json::json!({})).unwrap(),
            XML::default(),
            "empty object"
        );

        assert_eq!(
            serde_json::from_value::<XML>(serde_json::json!({
                "name": "name",
                "namespace": "https://example.com/schema/sample",
                "prefix": "sample",
                "attribute": true,
                "wrapped": true,
                "x-internal-id": null,
            }))
            .unwrap(),
            XML {
                name: Some("name".to_owned()),
                namespace: Some("https://example.com/schema/sample".to_owned()),
                prefix: Some("sample".to_owned()),
                attribute: Some(true),
                wrapped: Some(true),
                node_type: None,
                extensions: {
                    let mut map = BTreeMap::new();
                    map.insert("x-internal-id".to_owned(), serde_json::Value::Null);
                    Some(map)
                },
            },
            "all fields"
        );
    }

    #[test]
    fn validate() {
        let spec = Spec::default();
        let mut ctx = Context::new(&spec, Options::new());
        XML {
            name: Some("name".to_owned()),
            namespace: Some("https://example.com/schema/sample".to_owned()),
            prefix: Some("sample".to_owned()),
            attribute: Some(true),
            wrapped: Some(true),
            node_type: None,
            extensions: None,
        }
        .validate_with_context(&mut ctx, "xml".to_owned());
        assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);

        XML {
            namespace: Some("https://example.com/schema/sample".to_owned()),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, "xml".to_owned());
        assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);

        // Non-HTTP absolute URIs (urn:, mailto:, etc.) are accepted —
        // OAS 3.2 specifies an absolute URI here, not specifically a URL.
        let mut ctx = Context::new(&spec, Options::new());
        XML {
            namespace: Some("urn:example:ns:1".to_owned()),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, "xml".to_owned());
        assert!(ctx.errors.is_empty(), "urn accepted: {:?}", ctx.errors);

        // Whitespace / control chars are rejected — and the absolute-URI
        // scheme check short-circuits, so the user sees a single
        // "must be a valid URI" error rather than two errors at the same
        // path.
        for ns in ["not a uri", "tab\there", "ctrl\x01char"] {
            let mut ctx = Context::new(&spec, Options::new());
            XML {
                namespace: Some(ns.to_owned()),
                ..Default::default()
            }
            .validate_with_context(&mut ctx, "xml".to_owned());
            let valid_uri_errs = ctx
                .errors
                .iter()
                .filter(|e| e.contains("must be a valid URI"))
                .count();
            let absolute_uri_errs = ctx
                .errors
                .iter()
                .filter(|e| e.contains("must be an absolute URI"))
                .count();
            assert_eq!(
                valid_uri_errs, 1,
                "exactly one 'must be a valid URI' for `{ns}`: {:?}",
                ctx.errors
            );
            assert_eq!(
                absolute_uri_errs, 0,
                "no redundant 'must be an absolute URI' for `{ns}`: {:?}",
                ctx.errors
            );
        }

        // Relative refs (no scheme) are rejected: namespace MUST be an
        // absolute URI per the OAS XML Object spec.
        for rel in ["#/foo", "bar/baz", "/relative/path"] {
            let mut ctx = Context::new(&spec, Options::new());
            XML {
                namespace: Some(rel.to_owned()),
                ..Default::default()
            }
            .validate_with_context(&mut ctx, "xml".to_owned());
            assert!(
                ctx.errors
                    .iter()
                    .any(|e| e.contains("must be an absolute URI")),
                "relative `{rel}` rejected: {:?}",
                ctx.errors
            );
        }
    }

    #[test]
    fn validate_node_type_valid_values() {
        let spec = Spec::default();
        // Each allowed nodeType value must validate without errors.
        for nt in ["element", "attribute", "text", "cdata", "none"] {
            let mut ctx = Context::new(&spec, Options::new());
            XML {
                node_type: Some(nt.to_owned()),
                ..Default::default()
            }
            .validate_with_context(&mut ctx, "xml".to_owned());
            assert!(
                ctx.errors.is_empty(),
                "nodeType `{nt}` should be valid: {:?}",
                ctx.errors
            );
        }
    }

    #[test]
    fn validate_node_type_invalid_value() {
        let spec = Spec::default();
        let mut ctx = Context::new(&spec, Options::new());
        XML {
            node_type: Some("invalid".to_owned()),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, "xml".to_owned());
        assert!(
            ctx.errors
                .iter()
                .any(|e| e.contains("must be one of") && e.contains("invalid")),
            "invalid nodeType should error: {:?}",
            ctx.errors
        );
    }

    #[test]
    fn validate_node_type_exclusive_with_attribute_and_wrapped() {
        let spec = Spec::default();

        // nodeType + attribute: must error
        let mut ctx = Context::new(&spec, Options::new());
        XML {
            node_type: Some("element".to_owned()),
            attribute: Some(true),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, "xml".to_owned());
        assert!(
            ctx.errors
                .iter()
                .any(|e| e.contains("`attribute` MUST NOT be present when `nodeType` is set")),
            "attribute + nodeType should error: {:?}",
            ctx.errors
        );

        // nodeType + wrapped: must error
        let mut ctx = Context::new(&spec, Options::new());
        XML {
            node_type: Some("element".to_owned()),
            wrapped: Some(true),
            ..Default::default()
        }
        .validate_with_context(&mut ctx, "xml".to_owned());
        assert!(
            ctx.errors
                .iter()
                .any(|e| e.contains("`wrapped` MUST NOT be present when `nodeType` is set")),
            "wrapped + nodeType should error: {:?}",
            ctx.errors
        );
    }

    #[test]
    fn serialize_deserialize_node_type() {
        let xml = XML {
            node_type: Some("text".to_owned()),
            ..Default::default()
        };
        let v = serde_json::to_value(&xml).unwrap();
        assert_eq!(v["nodeType"], "text");
        let back: XML = serde_json::from_value(v).unwrap();
        assert_eq!(back, xml);
    }
}