Skip to main content

norm_spec_core/
schema.rs

1//! Offline JSON Schema Draft 7 evaluation primitives.
2
3use std::{collections::BTreeMap, error::Error, fmt};
4
5use jsonschema::{Retrieve, Uri, error::ValidationErrorKind};
6use serde_json::Value;
7
8/// One structured Draft 7 schema violation.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct SchemaViolation {
11    /// JSON Schema keyword that rejected the instance.
12    pub keyword: String,
13    /// JSON Pointer into the validated instance.
14    pub instance_path: String,
15    /// JSON Pointer to the evaluating schema keyword.
16    pub schema_path: String,
17    /// Unexpected property names for `additionalProperties` violations.
18    pub unexpected_properties: Vec<String>,
19}
20
21/// Failure to compile a Draft 7 schema from the supplied offline resources.
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct SchemaCompileError {
24    detail: String,
25}
26
27impl SchemaCompileError {
28    fn new(detail: impl Into<String>) -> Self {
29        Self {
30            detail: detail.into(),
31        }
32    }
33}
34
35impl fmt::Display for SchemaCompileError {
36    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37        formatter.write_str(&self.detail)
38    }
39}
40
41impl Error for SchemaCompileError {}
42
43#[derive(Clone, Debug, Default)]
44struct OfflineRetriever {
45    resources: BTreeMap<String, Value>,
46}
47
48impl Retrieve for OfflineRetriever {
49    fn retrieve(&self, uri: &Uri<String>) -> Result<Value, Box<dyn Error + Send + Sync + 'static>> {
50        self.resources
51            .get(uri.as_str())
52            .cloned()
53            .ok_or_else(|| format!("schema resource is not registered: {uri}").into())
54    }
55}
56
57/// Validate an instance with an explicit Draft 7 schema and offline resources.
58///
59/// Resource keys are absolute schema identifiers. Relative `$ref` values are
60/// resolved against the schema's `$id` and may retrieve only from this supplied
61/// map. The function never reads files, environment variables, or the network.
62///
63/// # Errors
64///
65/// Returns [`SchemaCompileError`] when the schema is invalid or a referenced
66/// resource is not present in the supplied map.
67pub fn validate_draft7(
68    schema: &Value,
69    instance: &Value,
70    resources: impl IntoIterator<Item = (String, Value)>,
71) -> Result<Vec<SchemaViolation>, SchemaCompileError> {
72    let retriever = OfflineRetriever {
73        resources: resources.into_iter().collect(),
74    };
75    let validator = jsonschema::draft7::options()
76        .with_retriever(retriever)
77        .should_validate_formats(true)
78        .build(schema)
79        .map_err(|error| SchemaCompileError::new(error.to_string()))?;
80
81    let mut violations = validator
82        .iter_errors(instance)
83        .map(|error| {
84            let mut unexpected_properties = match error.kind() {
85                ValidationErrorKind::AdditionalProperties { unexpected } => unexpected.clone(),
86                _ => Vec::new(),
87            };
88            unexpected_properties.sort();
89            SchemaViolation {
90                keyword: error.kind().keyword().to_owned(),
91                instance_path: error.instance_path().to_string(),
92                schema_path: error.schema_path().to_string(),
93                unexpected_properties,
94            }
95        })
96        .collect::<Vec<_>>();
97    violations.sort_by(|left, right| {
98        left.instance_path
99            .cmp(&right.instance_path)
100            .then_with(|| left.keyword.cmp(&right.keyword))
101            .then_with(|| left.schema_path.cmp(&right.schema_path))
102            .then_with(|| left.unexpected_properties.cmp(&right.unexpected_properties))
103    });
104    Ok(violations)
105}
106
107#[cfg(test)]
108mod tests {
109    use serde_json::json;
110
111    use super::validate_draft7;
112
113    const ROOT_ID: &str = "https://norm-spec.dev/schema/norm-schema.json";
114
115    fn root_schema() -> serde_json::Value {
116        json!({
117            "$schema": "http://json-schema.org/draft-07/schema#",
118            "$id": ROOT_ID,
119            "type": "object",
120            "required": ["metadata"]
121        })
122    }
123
124    #[test]
125    fn draft7_validation_returns_structured_paths_and_keywords() {
126        let violations = validate_draft7(&root_schema(), &json!({}), [])
127            .unwrap_or_else(|error| panic!("test schema should compile: {error}"));
128        assert_eq!(violations.len(), 1);
129        assert_eq!(violations[0].keyword, "required");
130        assert_eq!(violations[0].instance_path, "");
131        assert_eq!(violations[0].schema_path, "/required");
132    }
133
134    #[test]
135    fn relative_references_resolve_only_from_supplied_resources() {
136        let profile = json!({
137            "$schema": "http://json-schema.org/draft-07/schema#",
138            "$id": "https://norm-spec.dev/schema/profiles/test.json",
139            "allOf": [{"$ref": "../norm-schema.json"}]
140        });
141        let instance = json!({"metadata": {}});
142        let violations =
143            validate_draft7(&profile, &instance, [(ROOT_ID.to_owned(), root_schema())])
144                .unwrap_or_else(|error| {
145                    panic!("registered relative reference should compile: {error}")
146                });
147        assert!(violations.is_empty());
148    }
149
150    #[test]
151    fn missing_external_resources_fail_instead_of_falling_back() {
152        let profile = json!({
153            "$schema": "http://json-schema.org/draft-07/schema#",
154            "$id": "https://norm-spec.dev/schema/profiles/test.json",
155            "allOf": [{"$ref": "../norm-schema.json"}]
156        });
157        let error = match validate_draft7(&profile, &json!({}), []) {
158            Ok(violations) => {
159                panic!("unregistered reference unexpectedly compiled: {violations:?}")
160            }
161            Err(error) => error,
162        };
163        assert!(
164            error
165                .to_string()
166                .contains("schema resource is not registered")
167        );
168        assert!(error.to_string().contains(ROOT_ID));
169    }
170}