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.
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    result
168}
169
170/// Get the "type" field from a JSON Schema.
171///
172/// ```rust
173/// let schema = serde_json::json!({"type": "string"});
174/// assert_eq!(vld_openapi::validator::schema_type(&schema), Some("string".to_string()));
175/// ```
176pub fn schema_type(schema: &Value) -> Option<String> {
177    schema
178        .get("type")
179        .and_then(|t| t.as_str())
180        .map(String::from)
181}
182
183/// Check if a field is required in a JSON Schema.
184///
185/// ```rust
186/// let schema = serde_json::json!({
187///     "type": "object",
188///     "required": ["name"],
189///     "properties": { "name": { "type": "string" } }
190/// });
191/// assert!(vld_openapi::validator::is_required(&schema, "name"));
192/// assert!(!vld_openapi::validator::is_required(&schema, "age"));
193/// ```
194pub fn is_required(schema: &Value, field: &str) -> bool {
195    schema
196        .get("required")
197        .and_then(|r| r.as_array())
198        .map(|arr| arr.iter().any(|v| v.as_str() == Some(field)))
199        .unwrap_or(false)
200}
201
202/// Get the property schema for a specific field.
203///
204/// ```rust
205/// let schema = serde_json::json!({
206///     "type": "object",
207///     "properties": { "name": { "type": "string", "minLength": 1 } }
208/// });
209/// let name_schema = vld_openapi::validator::get_property(&schema, "name").unwrap();
210/// assert_eq!(name_schema["type"], "string");
211/// ```
212pub fn get_property<'a>(schema: &'a Value, field: &str) -> Option<&'a Value> {
213    schema
214        .get("properties")
215        .and_then(|p| p.as_object())
216        .and_then(|props| props.get(field))
217}
218
219// ========================= Comparison & Merge ================================
220
221/// Check if two JSON Schema values are structurally equal.
222///
223/// ```rust
224/// use vld::prelude::*;
225/// use vld::openapi::JsonSchema;
226///
227/// let a = vld::string().min(1).json_schema();
228/// let b = serde_json::json!({"type": "string", "minLength": 1});
229/// assert!(vld_openapi::validator::schemas_equal(&a, &b));
230/// ```
231pub fn schemas_equal(a: &Value, b: &Value) -> bool {
232    a == b
233}
234
235/// Overlay additional constraints from one schema onto another.
236///
237/// Copies `properties`, `required`, and validation keywords (`minLength`,
238/// `maxLength`, `minimum`, `maximum`, `pattern`, `format`) from `overlay`
239/// into a clone of `base`. Existing `base` values are preserved.
240///
241/// ```rust
242/// let base = serde_json::json!({"type": "object", "properties": {"name": {"type": "string"}}});
243/// let overlay = serde_json::json!({"properties": {"name": {"minLength": 2}}, "required": ["name"]});
244/// let result = vld_openapi::validator::overlay_constraints(&base, &overlay);
245/// assert!(vld_openapi::validator::is_required(&result, "name"));
246/// ```
247pub fn overlay_constraints(base: &Value, overlay: &Value) -> Value {
248    let mut result = base.clone();
249
250    if let (Some(result_obj), Some(overlay_obj)) = (result.as_object_mut(), overlay.as_object()) {
251        for (key, value) in overlay_obj {
252            match key.as_str() {
253                "properties" => {
254                    if let (Some(base_props), Some(overlay_props)) = (
255                        result_obj
256                            .get_mut("properties")
257                            .and_then(|p| p.as_object_mut()),
258                        value.as_object(),
259                    ) {
260                        for (prop_name, prop_schema) in overlay_props {
261                            if let Some(existing) = base_props.get_mut(prop_name) {
262                                if let (Some(existing_obj), Some(overlay_prop_obj)) =
263                                    (existing.as_object_mut(), prop_schema.as_object())
264                                {
265                                    for (k, v) in overlay_prop_obj {
266                                        existing_obj.entry(k.clone()).or_insert_with(|| v.clone());
267                                    }
268                                }
269                            } else {
270                                base_props.insert(prop_name.clone(), prop_schema.clone());
271                            }
272                        }
273                    }
274                }
275                "required" => {
276                    if let Some(overlay_required) = value.as_array() {
277                        let base_required = result_obj
278                            .entry("required")
279                            .or_insert_with(|| Value::Array(vec![]));
280                        if let Some(arr) = base_required.as_array_mut() {
281                            for item in overlay_required {
282                                if !arr.contains(item) {
283                                    arr.push(item.clone());
284                                }
285                            }
286                        }
287                    }
288                }
289                _ => {
290                    result_obj
291                        .entry(key.clone())
292                        .or_insert_with(|| value.clone());
293                }
294            }
295        }
296    }
297
298    result
299}
300
301// ========================= OpenAPI 3.0 =======================================
302
303/// Rewrite vld's JSON Schema (2020-12) into the OpenAPI 3.0 dialect, applied
304/// when the generator uses `SchemaSettings::openapi3()`:
305///
306/// - tuples (`prefixItems` + `items: false`) become `items: {anyOf: [...]}`
307///   with the existing `minItems` / `maxItems`;
308/// - `null` branches of `anyOf` / `oneOf` and `"null"` in a `type` array
309///   become `nullable: true` (a lone remaining `$ref` is wrapped in `allOf`);
310/// - numeric `exclusiveMinimum` / `exclusiveMaximum` (2020-12) become
311///   `minimum` / `maximum` plus the boolean 3.0 `exclusiveMinimum: true` /
312///   `exclusiveMaximum: true`;
313/// - a schema that only allows `null` becomes
314///   `{"type": "string", "nullable": true, "enum": [null]}` (3.0 ignores
315///   `nullable` without a `type`, and has no `null` type).
316///
317/// Doing it here keeps schemars' own OpenAPI 3.0 transforms from producing
318/// `additionalItems` or `{"enum": [null], "nullable": true}`.
319pub fn to_openapi3(value: &mut Value) {
320    match value {
321        Value::Array(items) => items.iter_mut().for_each(to_openapi3),
322        Value::Object(map) => {
323            if let Some(Value::Array(prefix)) = map.remove("prefixItems") {
324                let items = match <[Value; 1]>::try_from(prefix) {
325                    Ok([one]) => one,
326                    Err(many) => serde_json::json!({ "anyOf": many }),
327                };
328                map.insert("items".into(), items);
329            }
330
331            if let Some(Value::Array(types)) = map.get("type") {
332                let rest: Vec<Value> = types.iter().filter(|t| *t != "null").cloned().collect();
333                if rest.len() < types.len() {
334                    map.insert("nullable".into(), Value::Bool(true));
335                    match <[Value; 1]>::try_from(rest) {
336                        Ok([one]) => map.insert("type".into(), one),
337                        // `["null"]`: a null-only schema, rewritten below.
338                        Err(rest) if rest.is_empty() => map.insert("type".into(), "null".into()),
339                        Err(rest) => map.insert("type".into(), Value::Array(rest)),
340                    };
341                }
342            }
343
344            for key in ["anyOf", "oneOf"] {
345                let Some(Value::Array(branches)) = map.get(key) else {
346                    continue;
347                };
348                let rest: Vec<Value> = branches
349                    .iter()
350                    .filter(|b| !is_null_schema(b))
351                    .cloned()
352                    .collect();
353                if rest.len() == branches.len() {
354                    continue;
355                }
356                map.remove(key);
357                map.insert("nullable".into(), Value::Bool(true));
358                match <[Value; 1]>::try_from(rest) {
359                    Ok([Value::Object(one)]) if !one.contains_key("$ref") => {
360                        for (k, v) in one {
361                            map.entry(k).or_insert(v);
362                        }
363                    }
364                    Ok([one]) => {
365                        map.insert("allOf".into(), Value::Array(vec![one]));
366                    }
367                    // Only `null` branches: a null-only schema, rewritten below.
368                    Err(rest) if rest.is_empty() => {
369                        map.insert("type".into(), "null".into());
370                    }
371                    Err(rest) => {
372                        map.insert(key.into(), Value::Array(rest));
373                    }
374                }
375            }
376
377            // 2020-12 numeric `exclusiveMinimum: n` → 3.0 `minimum: n, exclusiveMinimum: true`
378            // (an inclusive bound that is already stricter wins).
379            for (ex, inc, stricter) in [
380                ("exclusiveMinimum", "minimum", std::cmp::Ordering::Greater),
381                ("exclusiveMaximum", "maximum", std::cmp::Ordering::Less),
382            ] {
383                let Some(n) = map.get(ex).and_then(Value::as_f64) else {
384                    continue;
385                };
386                let n_value = map.remove(ex).unwrap_or_default();
387                let inclusive_wins = map
388                    .get(inc)
389                    .and_then(Value::as_f64)
390                    .and_then(|m| m.partial_cmp(&n))
391                    .is_some_and(|o| o == stricter);
392                if !inclusive_wins {
393                    map.insert(inc.into(), n_value);
394                    map.insert(ex.into(), Value::Bool(true));
395                }
396            }
397
398            // `nullable` needs a `type` in 3.0: a null-only schema becomes a
399            // nullable string whose only allowed value is `null`.
400            if is_null_schema(&Value::Object(map.clone())) {
401                for k in ["type", "const", "enum", "nullable"] {
402                    map.remove(k);
403                }
404                map.insert("type".into(), "string".into());
405                map.insert("nullable".into(), Value::Bool(true));
406                map.insert("enum".into(), serde_json::json!([null]));
407                return;
408            }
409            // Children last: null branches must still look like `null` above.
410            map.values_mut().for_each(to_openapi3);
411        }
412        _ => {}
413    }
414}
415
416/// `{"type": "null"}`, `{"const": null}` or `{"enum": [null]}`.
417fn is_null_schema(v: &Value) -> bool {
418    v.get("type").is_some_and(|t| t == "null")
419        || v.get("const").is_some_and(Value::is_null)
420        || v.get("enum") == Some(&serde_json::json!([null]))
421}
422
423/// Point local refs (`#/components/schemas/X`, `#/$defs/X`, `#/definitions/X`)
424/// at `prefix` (e.g. `#/$defs/`).
425#[cfg(any(feature = "schemars-0", feature = "schemars-1"))]
426pub(crate) fn rewrite_refs(value: &mut Value, prefix: &str) {
427    match value {
428        Value::Object(map) => {
429            for (key, v) in map.iter_mut() {
430                match v {
431                    Value::String(r) if key == "$ref" => {
432                        let name = ["#/components/schemas/", "#/$defs/", "#/definitions/"]
433                            .iter()
434                            .find_map(|p| r.strip_prefix(p));
435                        if let Some(name) = name {
436                            *r = format!("{prefix}{name}");
437                        }
438                    }
439                    _ => rewrite_refs(v, prefix),
440                }
441            }
442        }
443        Value::Array(items) => items.iter_mut().for_each(|v| rewrite_refs(v, prefix)),
444        _ => {}
445    }
446}