Skip to main content

vld_openapi/
validator.rs

1//! Version-independent JSON Schema tools: validate a JSON value against a
2//! JSON Schema, inspect and combine schemas, rewrite a 2020-12 schema into the
3//! OpenAPI 3.0 dialect. No schemars dependency; the schemars modules
4//! re-export every item.
5//!
6//! ```rust
7//! use vld_openapi::validator::*;
8//!
9//! let schema = serde_json::json!({
10//!     "type": "object",
11//!     "required": ["name"],
12//!     "properties": { "name": { "type": "string", "minLength": 1 } }
13//! });
14//! assert!(validate_with_schema(&schema, &serde_json::json!({"name": "Alice"})).is_ok());
15//! assert!(is_required(&schema, "name"));
16//! assert_eq!(list_properties(&schema)[0].name, "name");
17//! ```
18
19use serde_json::Value;
20use std::fmt;
21
22mod engine;
23
24// ========================= Error type ========================================
25
26/// Error returned by schemars → vld validation.
27#[derive(Debug, Clone)]
28pub enum VldSchemarsError {
29    /// JSON Schema validation failed.
30    Validation(vld::error::VldError),
31    /// Deserialization failed.
32    Deserialization(String),
33}
34
35impl fmt::Display for VldSchemarsError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            VldSchemarsError::Validation(e) => write!(f, "Schema validation error: {}", e),
39            VldSchemarsError::Deserialization(e) => write!(f, "Deserialization error: {}", e),
40        }
41    }
42}
43
44impl std::error::Error for VldSchemarsError {
45    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
46        match self {
47            VldSchemarsError::Validation(e) => Some(e),
48            VldSchemarsError::Deserialization(_) => None,
49        }
50    }
51}
52
53impl From<vld::error::VldError> for VldSchemarsError {
54    fn from(e: vld::error::VldError) -> Self {
55        VldSchemarsError::Validation(e)
56    }
57}
58
59// ========================= Validation ========================================
60
61/// Validate a `serde_json::Value` against a JSON Schema.
62///
63/// Performs structural validation: type checks, required fields,
64/// string constraints (minLength, maxLength, pattern, format),
65/// number constraints (minimum, maximum, exclusiveMinimum, exclusiveMaximum,
66/// multipleOf — exact for integers), array constraints (minItems, maxItems,
67/// uniqueItems, contains / minContains / maxContains), `propertyNames`,
68/// minProperties / maxProperties, `formatMinimum` / `formatMaximum` for
69/// `date` / `date-time` / `time`, enum values, `oneOf` / `anyOf` / `allOf` /
70/// `not`, and recursive validation of `properties`, `patternProperties`,
71/// `additionalProperties`, `items` / `prefixItems`, and local `$ref`s
72/// (resolved against `schema`).
73///
74/// Not checked: vendor `x-*` keywords (vld's `x-past` / `x-future`,
75/// `x-minUniqueItems` / `x-maxUniqueItems`, `x-minDecimal`, …), and most
76/// `format`s beyond a basic shape check (unknown formats pass).
77///
78/// ```rust
79/// let schema = serde_json::json!({
80///     "type": "object",
81///     "required": ["name"],
82///     "properties": {
83///         "name": { "type": "string", "minLength": 1 },
84///         "age":  { "type": "integer", "minimum": 0 }
85///     }
86/// });
87/// let valid = serde_json::json!({"name": "Alice", "age": 30});
88/// assert!(vld_openapi::validator::validate_with_schema(&schema, &valid).is_ok());
89///
90/// let invalid = serde_json::json!({"age": -5});
91/// assert!(vld_openapi::validator::validate_with_schema(&schema, &invalid).is_err());
92/// ```
93pub fn validate_with_schema(schema: &Value, value: &Value) -> Result<(), vld::error::VldError> {
94    engine::validate_value_against_schema(
95        schema,
96        value,
97        &[],
98        engine::Ctx {
99            root: schema,
100            depth: 0,
101        },
102    )
103}
104
105// ========================= Introspection =====================================
106
107/// Information about a single property in a JSON Schema object.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct PropertyInfo {
110    /// Property name.
111    pub name: String,
112    /// JSON Schema "type" value (e.g. "string", "integer", "number", "boolean", "object", "array").
113    pub schema_type: Option<String>,
114    /// Whether this property is listed in "required".
115    pub required: bool,
116    /// The raw JSON schema for this property.
117    pub schema: Value,
118}
119
120/// Extract property information from a JSON Schema object, sorted by name.
121///
122/// Works with both `schemars::Schema` (via `as_value()`) and raw `serde_json::Value`.
123///
124/// ```rust
125/// use vld::prelude::*;
126///
127/// vld::schema! {
128///     #[derive(Debug)]
129///     pub struct UserSchema {
130///         pub name: String => vld::string().min(1),
131///         pub age: i64 => vld::number().int().min(0),
132///     }
133/// }
134///
135/// let json = UserSchema::json_schema();
136/// let props = vld_openapi::validator::list_properties(&json);
137/// assert_eq!(props.len(), 2);
138/// ```
139pub fn list_properties(schema: &Value) -> Vec<PropertyInfo> {
140    let mut result = Vec::new();
141
142    let properties = match schema.get("properties").and_then(|p| p.as_object()) {
143        Some(p) => p,
144        None => return result,
145    };
146
147    let required_set: std::collections::HashSet<&str> = schema
148        .get("required")
149        .and_then(|r| r.as_array())
150        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
151        .unwrap_or_default();
152
153    for (name, prop_schema) in properties {
154        let schema_type = prop_schema
155            .get("type")
156            .and_then(|t| t.as_str())
157            .map(String::from);
158
159        result.push(PropertyInfo {
160            name: name.clone(),
161            schema_type,
162            required: required_set.contains(name.as_str()),
163            schema: prop_schema.clone(),
164        });
165    }
166
167    // Name order whatever map order serde_json uses (`preserve_order`).
168    result.sort_unstable_by(|a, b| a.name.cmp(&b.name));
169    result
170}
171
172/// Get the "type" field from a JSON Schema.
173///
174/// ```rust
175/// let schema = serde_json::json!({"type": "string"});
176/// assert_eq!(vld_openapi::validator::schema_type(&schema), Some("string".to_string()));
177/// ```
178pub fn schema_type(schema: &Value) -> Option<String> {
179    schema
180        .get("type")
181        .and_then(|t| t.as_str())
182        .map(String::from)
183}
184
185/// Check if a field is required in a JSON Schema.
186///
187/// ```rust
188/// let schema = serde_json::json!({
189///     "type": "object",
190///     "required": ["name"],
191///     "properties": { "name": { "type": "string" } }
192/// });
193/// assert!(vld_openapi::validator::is_required(&schema, "name"));
194/// assert!(!vld_openapi::validator::is_required(&schema, "age"));
195/// ```
196pub fn is_required(schema: &Value, field: &str) -> bool {
197    schema
198        .get("required")
199        .and_then(|r| r.as_array())
200        .map(|arr| arr.iter().any(|v| v.as_str() == Some(field)))
201        .unwrap_or(false)
202}
203
204/// Get the property schema for a specific field.
205///
206/// ```rust
207/// let schema = serde_json::json!({
208///     "type": "object",
209///     "properties": { "name": { "type": "string", "minLength": 1 } }
210/// });
211/// let name_schema = vld_openapi::validator::get_property(&schema, "name").unwrap();
212/// assert_eq!(name_schema["type"], "string");
213/// ```
214pub fn get_property<'a>(schema: &'a Value, field: &str) -> Option<&'a Value> {
215    schema
216        .get("properties")
217        .and_then(|p| p.as_object())
218        .and_then(|props| props.get(field))
219}
220
221// ========================= Comparison & Merge ================================
222
223/// Check if two JSON Schema values are structurally equal.
224///
225/// ```rust
226/// use vld::prelude::*;
227/// use vld::openapi::JsonSchema;
228///
229/// let a = vld::string().min(1).json_schema();
230/// let b = serde_json::json!({"type": "string", "minLength": 1});
231/// assert!(vld_openapi::validator::schemas_equal(&a, &b));
232/// ```
233pub fn schemas_equal(a: &Value, b: &Value) -> bool {
234    a == b
235}
236
237/// Overlay additional constraints from one schema onto another.
238///
239/// Copies `properties`, `required`, and validation keywords (`minLength`,
240/// `maxLength`, `minimum`, `maximum`, `pattern`, `format`) from `overlay`
241/// into a clone of `base`. Existing `base` values are preserved.
242///
243/// ```rust
244/// let base = serde_json::json!({"type": "object", "properties": {"name": {"type": "string"}}});
245/// let overlay = serde_json::json!({"properties": {"name": {"minLength": 2}}, "required": ["name"]});
246/// let result = vld_openapi::validator::overlay_constraints(&base, &overlay);
247/// assert!(vld_openapi::validator::is_required(&result, "name"));
248/// ```
249pub fn overlay_constraints(base: &Value, overlay: &Value) -> Value {
250    let mut result = base.clone();
251
252    if let (Some(result_obj), Some(overlay_obj)) = (result.as_object_mut(), overlay.as_object()) {
253        for (key, value) in overlay_obj {
254            match key.as_str() {
255                "properties" => {
256                    if let (Some(base_props), Some(overlay_props)) = (
257                        result_obj
258                            .get_mut("properties")
259                            .and_then(|p| p.as_object_mut()),
260                        value.as_object(),
261                    ) {
262                        for (prop_name, prop_schema) in overlay_props {
263                            if let Some(existing) = base_props.get_mut(prop_name) {
264                                if let (Some(existing_obj), Some(overlay_prop_obj)) =
265                                    (existing.as_object_mut(), prop_schema.as_object())
266                                {
267                                    for (k, v) in overlay_prop_obj {
268                                        existing_obj.entry(k.clone()).or_insert_with(|| v.clone());
269                                    }
270                                }
271                            } else {
272                                base_props.insert(prop_name.clone(), prop_schema.clone());
273                            }
274                        }
275                    }
276                }
277                "required" => {
278                    if let Some(overlay_required) = value.as_array() {
279                        let base_required = result_obj
280                            .entry("required")
281                            .or_insert_with(|| Value::Array(vec![]));
282                        if let Some(arr) = base_required.as_array_mut() {
283                            for item in overlay_required {
284                                if !arr.contains(item) {
285                                    arr.push(item.clone());
286                                }
287                            }
288                        }
289                    }
290                }
291                _ => {
292                    result_obj
293                        .entry(key.clone())
294                        .or_insert_with(|| value.clone());
295                }
296            }
297        }
298    }
299
300    result
301}
302
303// ========================= OpenAPI 3.0 =======================================
304
305/// Rewrite vld's JSON Schema (2020-12) into the OpenAPI 3.0 dialect, applied
306/// when the generator uses `SchemaSettings::openapi3()`:
307///
308/// - tuples (`prefixItems` + `items: false`) become `items: {anyOf: [...]}`
309///   with the existing `minItems` / `maxItems`;
310/// - `null` branches of `anyOf` / `oneOf` and `"null"` in a `type` array
311///   become `nullable: true` (a lone remaining `$ref` is wrapped in `allOf`);
312/// - numeric `exclusiveMinimum` / `exclusiveMaximum` (2020-12) become
313///   `minimum` / `maximum` plus the boolean 3.0 `exclusiveMinimum: true` /
314///   `exclusiveMaximum: true`;
315/// - a schema that only allows `null` becomes
316///   `{"type": "string", "nullable": true, "enum": [null]}` (3.0 ignores
317///   `nullable` without a `type`, and has no `null` type).
318///
319/// Doing it here keeps schemars' own OpenAPI 3.0 transforms from producing
320/// `additionalItems` or `{"enum": [null], "nullable": true}`.
321pub fn to_openapi3(value: &mut Value) {
322    match value {
323        Value::Array(items) => items.iter_mut().for_each(to_openapi3),
324        Value::Object(map) => {
325            if let Some(Value::Array(prefix)) = map.remove("prefixItems") {
326                let items = match <[Value; 1]>::try_from(prefix) {
327                    Ok([one]) => one,
328                    Err(many) => serde_json::json!({ "anyOf": many }),
329                };
330                map.insert("items".into(), items);
331            }
332
333            if let Some(Value::Array(types)) = map.get("type") {
334                let rest: Vec<Value> = types.iter().filter(|t| *t != "null").cloned().collect();
335                if rest.len() < types.len() {
336                    map.insert("nullable".into(), Value::Bool(true));
337                    match <[Value; 1]>::try_from(rest) {
338                        Ok([one]) => map.insert("type".into(), one),
339                        // `["null"]`: a null-only schema, rewritten below.
340                        Err(rest) if rest.is_empty() => map.insert("type".into(), "null".into()),
341                        Err(rest) => map.insert("type".into(), Value::Array(rest)),
342                    };
343                }
344            }
345
346            for key in ["anyOf", "oneOf"] {
347                let Some(Value::Array(branches)) = map.get(key) else {
348                    continue;
349                };
350                let rest: Vec<Value> = branches
351                    .iter()
352                    .filter(|b| !is_null_schema(b))
353                    .cloned()
354                    .collect();
355                if rest.len() == branches.len() {
356                    continue;
357                }
358                map.remove(key);
359                map.insert("nullable".into(), Value::Bool(true));
360                match <[Value; 1]>::try_from(rest) {
361                    Ok([Value::Object(one)]) if !one.contains_key("$ref") => {
362                        for (k, v) in one {
363                            map.entry(k).or_insert(v);
364                        }
365                    }
366                    Ok([one]) => {
367                        map.insert("allOf".into(), Value::Array(vec![one]));
368                    }
369                    // Only `null` branches: a null-only schema, rewritten below.
370                    Err(rest) if rest.is_empty() => {
371                        map.insert("type".into(), "null".into());
372                    }
373                    Err(rest) => {
374                        map.insert(key.into(), Value::Array(rest));
375                    }
376                }
377            }
378
379            // 2020-12 numeric `exclusiveMinimum: n` → 3.0 `minimum: n, exclusiveMinimum: true`
380            // (an inclusive bound that is already stricter wins).
381            for (ex, inc, stricter) in [
382                ("exclusiveMinimum", "minimum", std::cmp::Ordering::Greater),
383                ("exclusiveMaximum", "maximum", std::cmp::Ordering::Less),
384            ] {
385                let Some(n) = map.get(ex).and_then(Value::as_f64) else {
386                    continue;
387                };
388                let n_value = map.remove(ex).unwrap_or_default();
389                let inclusive_wins = map
390                    .get(inc)
391                    .and_then(Value::as_f64)
392                    .and_then(|m| m.partial_cmp(&n))
393                    .is_some_and(|o| o == stricter);
394                if !inclusive_wins {
395                    map.insert(inc.into(), n_value);
396                    map.insert(ex.into(), Value::Bool(true));
397                }
398            }
399
400            // `nullable` needs a `type` in 3.0: a null-only schema becomes a
401            // nullable string whose only allowed value is `null`.
402            if is_null_schema(&Value::Object(map.clone())) {
403                for k in ["type", "const", "enum", "nullable"] {
404                    map.remove(k);
405                }
406                map.insert("type".into(), "string".into());
407                map.insert("nullable".into(), Value::Bool(true));
408                map.insert("enum".into(), serde_json::json!([null]));
409                return;
410            }
411            // Children last: null branches must still look like `null` above.
412            map.values_mut().for_each(to_openapi3);
413        }
414        _ => {}
415    }
416}
417
418/// `{"type": "null"}`, `{"const": null}` or `{"enum": [null]}`.
419fn is_null_schema(v: &Value) -> bool {
420    v.get("type").is_some_and(|t| t == "null")
421        || v.get("const").is_some_and(Value::is_null)
422        || v.get("enum") == Some(&serde_json::json!([null]))
423}
424
425/// Point local refs (`#/components/schemas/X`, `#/$defs/X`, `#/definitions/X`)
426/// at `prefix` (e.g. `#/$defs/`).
427#[cfg(any(feature = "schemars-0", feature = "schemars-1"))]
428pub(crate) fn rewrite_refs(value: &mut Value, prefix: &str) {
429    match value {
430        Value::Object(map) => {
431            for (key, v) in map.iter_mut() {
432                match v {
433                    Value::String(r) if key == "$ref" => {
434                        let name = ["#/components/schemas/", "#/$defs/", "#/definitions/"]
435                            .iter()
436                            .find_map(|p| r.strip_prefix(p));
437                        if let Some(name) = name {
438                            *r = format!("{prefix}{name}");
439                        }
440                    }
441                    _ => rewrite_refs(v, prefix),
442                }
443            }
444        }
445        Value::Array(items) => items.iter_mut().for_each(|v| rewrite_refs(v, prefix)),
446        _ => {}
447    }
448}