greentic_runner_host/runner/
schema_validator.rs1use jsonschema::{Draft, Validator};
2use serde_json::Value;
3
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct SchemaValidationIssue {
6 pub code: String,
7 pub path: String,
8 pub message_key: String,
9 pub fallback: String,
10}
11
12pub fn validate_json_instance(
13 schema: &Value,
14 instance: &Value,
15 strict: bool,
16) -> Vec<SchemaValidationIssue> {
17 let mut issues = Vec::new();
18 let mut unsupported = Vec::new();
19 collect_unsupported_constraints(schema, "", &mut unsupported);
20 if strict && !unsupported.is_empty() {
21 for path in unsupported {
22 issues.push(SchemaValidationIssue {
23 code: "unsupported_schema_constraint".to_string(),
24 path,
25 message_key: "runner.schema.unsupported_constraint".to_string(),
26 fallback: "schema contains unsupported constraint".to_string(),
27 });
28 }
29 return issues;
30 }
31
32 let validator = match compile_validator(schema) {
33 Ok(validator) => validator,
34 Err(err) => {
35 issues.push(SchemaValidationIssue {
36 code: "invalid_schema".to_string(),
37 path: "/".to_string(),
38 message_key: "runner.schema.invalid_schema".to_string(),
39 fallback: format!("invalid schema: {err}"),
40 });
41 return issues;
42 }
43 };
44
45 for err in validator.iter_errors(instance) {
46 let path = err.instance_path().to_string();
47 issues.push(SchemaValidationIssue {
48 code: "schema_validation".to_string(),
49 path: if path.is_empty() {
50 "/".to_string()
51 } else {
52 path
53 },
54 message_key: "runner.schema.validation_failed".to_string(),
55 fallback: err.to_string(),
56 });
57 }
58 issues
59}
60
61struct DenyExternalRefs;
65
66impl jsonschema::Retrieve for DenyExternalRefs {
67 fn retrieve(
68 &self,
69 uri: &jsonschema::Uri<String>,
70 ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
71 Err(format!("external schema reference `{uri}` is not allowed").into())
72 }
73}
74
75fn compile_validator(schema: &Value) -> Result<Validator, String> {
76 jsonschema::options()
77 .with_draft(Draft::Draft7)
78 .with_retriever(DenyExternalRefs)
79 .build(schema)
80 .map_err(|err| err.to_string())
81}
82
83fn collect_unsupported_constraints(schema: &Value, path: &str, out: &mut Vec<String>) {
84 let Some(map) = schema.as_object() else {
85 return;
86 };
87 for key in ["pattern", "format", "patternProperties"] {
88 if map.contains_key(key) {
89 out.push(format!("{}/{}", path_or_root(path), key));
90 }
91 }
92 for (key, value) in map {
93 let next = format!("{}/{}", path_or_root(path), key);
94 if matches!(key.as_str(), "enum" | "const" | "default" | "examples") {
96 continue;
97 }
98 if matches!(key.as_str(), "properties" | "$defs" | "definitions")
101 && let Value::Object(named) = value
102 {
103 for (name, subschema) in named {
104 let sub_path = format!("{next}/{name}");
105 collect_unsupported_constraints(subschema, &sub_path, out);
106 }
107 continue;
108 }
109 match value {
110 Value::Object(_) => collect_unsupported_constraints(value, &next, out),
111 Value::Array(items) => {
112 for (idx, item) in items.iter().enumerate() {
113 let item_path = format!("{}/{}", next, idx);
114 collect_unsupported_constraints(item, &item_path, out);
115 }
116 }
117 _ => {}
118 }
119 }
120}
121
122fn path_or_root(path: &str) -> &str {
123 if path.is_empty() { "" } else { path }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129 use serde_json::json;
130
131 #[test]
132 fn external_file_refs_are_not_resolved() {
133 let path = std::env::temp_dir().join(format!(
134 "greentic-schema-ref-{}-{}.json",
135 std::process::id(),
136 "z3"
137 ));
138 let _ = std::fs::write(&path, r#"{"type":"integer"}"#);
139 let schema = json!({ "$ref": format!("file://{}", path.display()) });
140 let issues = validate_json_instance(&schema, &json!(5), false);
141 let _ = std::fs::remove_file(&path);
142 assert!(!issues.is_empty(), "file:// $ref must fail to compile");
143 }
144
145 #[test]
146 fn internal_refs_still_resolve() {
147 let schema = json!({
148 "$defs": { "n": { "type": "integer" } },
149 "properties": { "a": { "$ref": "#/$defs/n" } }
150 });
151 assert!(validate_json_instance(&schema, &json!({ "a": 1 }), false).is_empty());
152 assert!(!validate_json_instance(&schema, &json!({ "a": "x" }), false).is_empty());
153 }
154
155 #[test]
156 fn properties_named_like_keywords_are_not_flagged() {
157 let schema = json!({
158 "type": "object",
159 "properties": {
160 "format": { "type": "string" },
161 "pattern": { "type": "string" },
162 "mode": { "enum": ["format", "pattern"] }
163 },
164 "$defs": { "format": { "type": "integer" } }
165 });
166 let mut out = Vec::new();
167 collect_unsupported_constraints(&schema, "", &mut out);
168 assert!(out.is_empty(), "unexpected flags: {out:?}");
169 }
170
171 #[test]
172 fn a_real_pattern_under_a_property_is_still_flagged() {
173 let schema = json!({
174 "properties": { "format": { "type": "string", "pattern": "^a$" } }
175 });
176 let mut out = Vec::new();
177 collect_unsupported_constraints(&schema, "", &mut out);
178 assert_eq!(out, vec!["/properties/format/pattern".to_string()]);
179 }
180
181 #[test]
182 fn strict_mode_rejects_unsupported_constraints() {
183 let schema = json!({
184 "type": "object",
185 "properties": {
186 "id": {
187 "type": "string",
188 "pattern": "^[a-z]+$"
189 }
190 }
191 });
192 let issues = validate_json_instance(&schema, &json!({"id": "abc"}), true);
193 assert_eq!(issues.len(), 1);
194 assert_eq!(issues[0].code, "unsupported_schema_constraint");
195 }
196
197 #[test]
198 fn valid_instance_returns_no_issues() {
199 let schema = json!({
200 "type": "object",
201 "required": ["message"],
202 "properties": {
203 "message": { "type": "string" }
204 },
205 "additionalProperties": false
206 });
207 let issues = validate_json_instance(&schema, &json!({"message": "ok"}), true);
208 assert!(issues.is_empty());
209 }
210
211 #[test]
212 fn invalid_instance_reports_schema_issue() {
213 let schema = json!({
214 "type": "object",
215 "required": ["message"],
216 "properties": {
217 "message": { "type": "string" }
218 },
219 "additionalProperties": false
220 });
221 let issues = validate_json_instance(&schema, &json!({"message": 42}), true);
222 assert!(!issues.is_empty());
223 assert_eq!(issues[0].code, "schema_validation");
224 }
225}