1use std::collections::BTreeMap;
4
5use serde_json::Value;
6
7use crate::{Diagnostic, SchemaCompileError, SchemaViolation, validate_draft7};
8
9const KNOWN_TOP_LEVEL: [&str; 6] = [
10 "agent_rules",
11 "cross_references",
12 "metadata",
13 "scope",
14 "strong_references",
15 "template",
16];
17
18#[derive(Clone, Debug, PartialEq)]
20pub struct SchemaBundle {
21 root: Value,
22 profiles: BTreeMap<String, Value>,
23}
24
25impl SchemaBundle {
26 #[must_use]
28 pub fn new(root: Value, profiles: impl IntoIterator<Item = (String, Value)>) -> Self {
29 Self {
30 root,
31 profiles: profiles.into_iter().collect(),
32 }
33 }
34
35 #[must_use]
37 pub fn contains_profile(&self, name: &str) -> bool {
38 self.profiles.contains_key(name)
39 }
40}
41
42#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
44pub struct ValidationOptions<'a> {
45 pub compat_keys: bool,
47 pub profile: Option<&'a str>,
49}
50
51#[derive(Clone, Debug, Default, Eq, PartialEq)]
53pub struct ValidationDiagnostics {
54 pub errors: Vec<Diagnostic>,
56 pub warnings: Vec<Diagnostic>,
58}
59
60pub fn validate_structure(
67 frontmatter: &Value,
68 schemas: &SchemaBundle,
69 options: ValidationOptions<'_>,
70) -> Result<ValidationDiagnostics, SchemaCompileError> {
71 let mut diagnostics = ValidationDiagnostics::default();
72 let selected_profile = select_profile(frontmatter, schemas, options.profile, &mut diagnostics);
73 let schema = selected_profile
74 .and_then(|name| schemas.profiles.get(name))
75 .unwrap_or(&schemas.root);
76 let resources = schema_identifier(&schemas.root)
77 .map(|identifier| [(identifier, schemas.root.clone())])
78 .unwrap_or_default();
79 let violations = validate_draft7(schema, frontmatter, resources)?;
80 map_schema_violations(
81 &violations,
82 options.compat_keys,
83 &mut diagnostics.errors,
84 &mut diagnostics.warnings,
85 );
86 if let Some(profile) = selected_profile.and_then(|name| schemas.profiles.get(name)) {
87 validate_profile_rules(frontmatter, profile, &mut diagnostics);
88 }
89 Ok(diagnostics)
90}
91
92fn schema_identifier(schema: &Value) -> Option<String> {
93 schema.get("$id")?.as_str().map(str::to_owned)
94}
95
96fn select_profile<'a>(
97 frontmatter: &'a Value,
98 schemas: &'a SchemaBundle,
99 override_profile: Option<&'a str>,
100 diagnostics: &mut ValidationDiagnostics,
101) -> Option<&'a str> {
102 if let Some(profile) = override_profile {
103 return schemas.contains_profile(profile).then_some(profile);
104 }
105 let metadata = frontmatter.get("metadata")?.as_object()?;
106 if let Some(explicit) = metadata.get("profile").and_then(Value::as_str) {
107 if schemas.contains_profile(explicit) {
108 return Some(explicit);
109 }
110 diagnostics.warnings.push(
111 Diagnostic::new(
112 "norm/profile/unknown-explicit",
113 format!("The explicit profile is not available: {explicit}"),
114 )
115 .with_field("metadata.profile"),
116 );
117 return None;
118 }
119 metadata
120 .get("layer")
121 .and_then(Value::as_str)
122 .filter(|layer| schemas.contains_profile(layer))
123}
124
125fn map_schema_violations(
126 violations: &[SchemaViolation],
127 compat_keys: bool,
128 errors: &mut Vec<Diagnostic>,
129 warnings: &mut Vec<Diagnostic>,
130) {
131 for violation in violations {
132 if violation.keyword == "additionalProperties" && violation.instance_path.is_empty() {
133 for field in &violation.unexpected_properties {
134 let mut diagnostic = Diagnostic::new(
135 "norm/schema/unknown-key",
136 format!("Unknown top-level key: {field}"),
137 )
138 .with_field(field);
139 if let Some(suggestion) = closest_key(field, &KNOWN_TOP_LEVEL, 3) {
140 diagnostic = diagnostic.with_suggestion(suggestion);
141 }
142 if compat_keys {
143 warnings.push(diagnostic);
144 } else {
145 errors.push(diagnostic);
146 }
147 }
148 } else if violation.keyword == "pattern" && violation.instance_path == "/metadata/version" {
149 errors.push(
150 Diagnostic::new(
151 "norm/schema/version-format",
152 "metadata.version must use MAJOR.MINOR format.",
153 )
154 .with_field("metadata.version")
155 .with_suggestion("MAJOR.MINOR"),
156 );
157 } else {
158 let field = pointer_to_field(&violation.instance_path);
159 let mut diagnostic = Diagnostic::new(
160 "norm/schema/invalid",
161 format!(
162 "The value does not satisfy the Draft 7 '{}' keyword.",
163 violation.keyword
164 ),
165 );
166 if !field.is_empty() {
167 diagnostic = diagnostic.with_field(field);
168 }
169 errors.push(diagnostic);
170 }
171 }
172}
173
174fn validate_profile_rules(
175 frontmatter: &Value,
176 profile: &Value,
177 diagnostics: &mut ValidationDiagnostics,
178) {
179 let Some(rules) = profile.get("profile_rules").and_then(Value::as_object) else {
180 return;
181 };
182 for field in string_items(rules.get("required_fields")) {
183 if frontmatter.get(field).is_none() {
184 diagnostics.errors.push(
185 Diagnostic::new(
186 "norm/schema/invalid",
187 format!("The selected profile requires '{field}'."),
188 )
189 .with_field(field),
190 );
191 }
192 }
193 for field in string_items(rules.get("recommended_fields")) {
194 if frontmatter.get(field).is_none() {
195 push_profile_warning(diagnostics, field);
196 }
197 }
198 for (parent, rule) in [
199 ("template", "recommended_template"),
200 ("agent_rules", "recommended_agent_rules"),
201 ("scope", "recommended_scope"),
202 ] {
203 let Some(parent_value) = frontmatter.get(parent).and_then(Value::as_object) else {
204 continue;
205 };
206 for child in string_items(rules.get(rule)) {
207 if !parent_value.contains_key(child) {
208 push_profile_warning(diagnostics, &format!("{parent}.{child}"));
209 }
210 }
211 }
212}
213
214fn push_profile_warning(diagnostics: &mut ValidationDiagnostics, field: &str) {
215 diagnostics.warnings.push(
216 Diagnostic::new(
217 "norm/profile/recommended-field",
218 format!("The selected profile recommends '{field}'."),
219 )
220 .with_field(field),
221 );
222}
223
224fn string_items(value: Option<&Value>) -> impl Iterator<Item = &str> {
225 value
226 .and_then(Value::as_array)
227 .into_iter()
228 .flatten()
229 .filter_map(Value::as_str)
230}
231
232fn closest_key<'a>(key: &str, candidates: &'a [&str], threshold: usize) -> Option<&'a str> {
233 candidates
234 .iter()
235 .copied()
236 .map(|candidate| (candidate, levenshtein(key, candidate)))
237 .filter(|(_, distance)| *distance <= threshold)
238 .min_by(|left, right| left.1.cmp(&right.1).then_with(|| left.0.cmp(right.0)))
239 .map(|(candidate, _)| candidate)
240}
241
242fn levenshtein(left: &str, right: &str) -> usize {
243 let right = right.chars().collect::<Vec<_>>();
244 let mut previous = (0..=right.len()).collect::<Vec<_>>();
245 for (left_index, left_character) in left.chars().enumerate() {
246 let mut current = vec![left_index + 1];
247 for (right_index, right_character) in right.iter().enumerate() {
248 current.push(
249 (previous[right_index + 1] + 1)
250 .min(current[right_index] + 1)
251 .min(previous[right_index] + usize::from(left_character != *right_character)),
252 );
253 }
254 previous = current;
255 }
256 previous[right.len()]
257}
258
259fn pointer_to_field(pointer: &str) -> String {
260 let mut field = String::new();
261 for token in pointer
262 .strip_prefix('/')
263 .unwrap_or(pointer)
264 .split('/')
265 .filter(|token| !token.is_empty())
266 {
267 let token = token.replace("~1", "/").replace("~0", "~");
268 if token.chars().all(|character| character.is_ascii_digit()) {
269 field.push('[');
270 field.push_str(&token);
271 field.push(']');
272 } else {
273 if !field.is_empty() {
274 field.push('.');
275 }
276 field.push_str(&token);
277 }
278 }
279 field
280}
281
282#[cfg(test)]
283mod tests {
284 use serde_json::json;
285
286 use super::{ValidationOptions, validate_structure};
287 use crate::test_support::schemas;
288
289 fn valid() -> serde_json::Value {
290 json!({"metadata": {"layer": "example", "scope": "./", "version": "1.0"}})
291 }
292
293 #[test]
294 fn valid_free_form_layer_has_no_findings() {
295 let diagnostics = validate_structure(&valid(), &schemas(), ValidationOptions::default())
296 .unwrap_or_else(|error| panic!("schemas should compile: {error}"));
297 assert!(diagnostics.errors.is_empty());
298 assert!(diagnostics.warnings.is_empty());
299 }
300
301 #[test]
302 fn unknown_keys_and_versions_have_specialized_diagnostics() {
303 let mut frontmatter = valid();
304 frontmatter["metadata"]["version"] = json!("1.0.0");
305 frontmatter["agent_rulez"] = json!({});
306 let diagnostics =
307 validate_structure(&frontmatter, &schemas(), ValidationOptions::default())
308 .unwrap_or_else(|error| panic!("schemas should compile: {error}"));
309 assert!(diagnostics.errors.iter().any(|diagnostic| {
310 diagnostic.code == "norm/schema/unknown-key"
311 && diagnostic.field.as_deref() == Some("agent_rulez")
312 && diagnostic.suggestion.as_deref() == Some("agent_rules")
313 }));
314 assert!(diagnostics.errors.iter().any(|diagnostic| {
315 diagnostic.code == "norm/schema/version-format"
316 && diagnostic.field.as_deref() == Some("metadata.version")
317 }));
318 }
319
320 #[test]
321 fn compat_keys_downgrades_only_unknown_top_level_fields() {
322 let mut frontmatter = valid();
323 frontmatter["agent_rulez"] = json!({});
324 let diagnostics = validate_structure(
325 &frontmatter,
326 &schemas(),
327 ValidationOptions {
328 compat_keys: true,
329 profile: None,
330 },
331 )
332 .unwrap_or_else(|error| panic!("schemas should compile: {error}"));
333 assert!(diagnostics.errors.is_empty());
334 assert_eq!(diagnostics.warnings[0].code, "norm/schema/unknown-key");
335 }
336
337 #[test]
338 fn profiles_warn_for_recommendations_and_unknown_explicit_names() {
339 let profile_diagnostics = validate_structure(
340 &valid(),
341 &schemas(),
342 ValidationOptions {
343 compat_keys: false,
344 profile: Some("convention"),
345 },
346 )
347 .unwrap_or_else(|error| panic!("profile schema should compile: {error}"));
348 assert!(profile_diagnostics.warnings.iter().any(|diagnostic| {
349 diagnostic.code == "norm/profile/recommended-field"
350 && diagnostic.field.as_deref() == Some("template")
351 }));
352
353 let mut frontmatter = valid();
354 frontmatter["metadata"]["profile"] = json!("missing");
355 let unknown_diagnostics =
356 validate_structure(&frontmatter, &schemas(), ValidationOptions::default())
357 .unwrap_or_else(|error| panic!("root schema should compile: {error}"));
358 assert!(unknown_diagnostics.warnings.iter().any(|diagnostic| {
359 diagnostic.code == "norm/profile/unknown-explicit"
360 && diagnostic.field.as_deref() == Some("metadata.profile")
361 }));
362 }
363}