xref: /openbmc/libcper/json-schema.c (revision fedd457d)
1 /**
2  * A very basic, non-complete implementation of a validator for the JSON Schema specification,
3  * for validating CPER-JSON.
4  *
5  * Author: Lawrence.Tang@arm.com
6  **/
7 
8 #include <stdio.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <libgen.h>
12 #include <limits.h>
13 #include <stdarg.h>
14 #include <json.h>
15 #include "json-schema.h"
16 #include "edk/BaseTypes.h"
17 #include <linux/limits.h>
18 
19 //Field definitions.
20 int json_validator_debug = 0;
21 
22 //Private pre-definitions.
23 int validate_field(const char *name, json_object *schema, json_object *object,
24 		   char *error_message);
25 int validate_integer(const char *field_name, json_object *schema,
26 		     json_object *object, char *error_message);
27 int validate_string(const char *field_name, json_object *schema,
28 		    json_object *object, const char *error_message);
29 int validate_object(const char *field_name, json_object *schema,
30 		    json_object *object, char *error_message);
31 int validate_array(const char *field_name, json_object *schema,
32 		   json_object *object, char *error_message);
33 void log_validator_error(char *error_message, const char *format, ...);
34 void log_validator_debug(const char *format, ...);
35 void log_validator_msg(const char *format, va_list args);
36 
37 //Validates a single JSON object against a provided schema file, returning 1 on success and 0 on failure to validate.
38 //Error message space must be allocated prior to call.
39 int validate_schema_from_file(const char *schema_file, json_object *object,
40 			      char *error_message)
41 {
42 	//Load schema IR from file.
43 	json_object *schema_ir = json_object_from_file(schema_file);
44 	if (schema_ir == NULL) {
45 		log_validator_error(error_message,
46 				    "Failed to load schema from file '%s'.",
47 				    schema_file);
48 		return 0;
49 	}
50 
51 	//Get the directory of the file.
52 	char *schema_file_copy = malloc(strlen(schema_file) + 1);
53 	strcpy(schema_file_copy, schema_file);
54 	char *schema_dir = dirname(schema_file_copy);
55 
56 	int result =
57 		validate_schema(schema_ir, schema_dir, object, error_message);
58 
59 	//Free memory from directory call.
60 	free(schema_file_copy);
61 	json_object_put(schema_ir);
62 
63 	return result;
64 }
65 
66 //Validates a single JSON object against a provided schema, returning 1 on success and 0 on failure to validate.
67 //Error message space must be allocated prior to call.
68 //If the schema does not include any other sub-schemas using "$ref", then leaving schema_directory as NULL is valid.
69 int validate_schema(json_object *schema, char *schema_directory,
70 		    json_object *object, char *error_message)
71 {
72 	//Check that the schema version is the same as this validator.
73 	json_object *schema_ver = json_object_object_get(schema, "$schema");
74 	if (schema_ver == NULL || strcmp(json_object_get_string(schema_ver),
75 					 JSON_SCHEMA_VERSION) != 0) {
76 		log_validator_error(
77 			error_message,
78 			"Provided schema is not of the same version that is referenced by this validator, or is not a schema.");
79 		return 0;
80 	}
81 
82 	//Change current directory into the schema directory.
83 	char *original_cwd = malloc(PATH_MAX);
84 	if (getcwd(original_cwd, PATH_MAX) == NULL) {
85 		log_validator_error(error_message,
86 				    "Failed fetching the current directory.");
87 		if (original_cwd) {
88 			free(original_cwd);
89 		}
90 		return 0;
91 	}
92 	if (chdir(schema_directory)) {
93 		log_validator_error(error_message,
94 				    "Failed to chdir into schema directory.");
95 		if (original_cwd) {
96 			free(original_cwd);
97 		}
98 		return 0;
99 	}
100 
101 	//Parse the top level structure appropriately.
102 	int result = validate_field("parent", schema, object, error_message);
103 
104 	//Change back to original CWD.
105 	if (chdir(original_cwd)) {
106 		log_validator_error(error_message,
107 				    "Failed to chdir into original directory.");
108 	}
109 
110 	free(original_cwd);
111 
112 	if (result) {
113 		log_validator_debug(
114 			"Successfully validated the provided object against schema.");
115 	}
116 	return result;
117 }
118 
119 //Validates a single JSON field given a schema/object.
120 //Returns -1 on fatal/error failure, 0 on validation failure, and 1 on validation.
121 int validate_field(const char *field_name, json_object *schema,
122 		   json_object *object, char *error_message)
123 {
124 	log_validator_debug("Validating field '%s'...", field_name);
125 
126 	//If there is a "$ref" field, attempt to load the referenced schema.
127 	json_object *ref_schema = json_object_object_get(schema, "$ref");
128 	if (ref_schema != NULL &&
129 	    json_object_get_type(ref_schema) == json_type_string) {
130 		log_validator_debug("$ref schema detected for field '%s'.",
131 				    field_name);
132 
133 		//Attempt to load. If loading fails, report error.
134 		const char *ref_path = json_object_get_string(ref_schema);
135 		json_object *tmp = json_object_from_file(ref_path);
136 		if (tmp == NULL) {
137 			log_validator_error(
138 				error_message,
139 				"Failed to open referenced schema file '%s'.",
140 				ref_path);
141 			return -1;
142 		}
143 		json_object_put(tmp);
144 
145 		log_validator_debug("loaded schema path '%s' for field '%s'.",
146 				    ref_path, field_name);
147 	}
148 
149 	//Get the schema field type.
150 	json_object *desired_field_type =
151 		json_object_object_get(schema, "type");
152 	if (desired_field_type == NULL ||
153 	    !json_object_is_type(desired_field_type, json_type_string)) {
154 		log_validator_error(
155 			error_message,
156 			"Desired field type not provided within schema/is not a string for field '%s' (schema violation).",
157 			field_name);
158 		return -1;
159 	}
160 
161 	//Check the field types are actually equal.
162 	const char *desired_field_type_str =
163 		json_object_get_string(desired_field_type);
164 	if (!((!strcmp(desired_field_type_str, "object") &&
165 	       json_object_is_type(object, json_type_object)) ||
166 	      (!strcmp(desired_field_type_str, "array") &&
167 	       json_object_is_type(object, json_type_array)) ||
168 	      (!strcmp(desired_field_type_str, "integer") &&
169 	       json_object_is_type(object, json_type_int)) ||
170 	      (!strcmp(desired_field_type_str, "string") &&
171 	       json_object_is_type(object, json_type_string)) ||
172 	      (!strcmp(desired_field_type_str, "boolean") &&
173 	       json_object_is_type(object, json_type_boolean)) ||
174 	      (!strcmp(desired_field_type_str, "double") &&
175 	       json_object_is_type(object, json_type_double)))) {
176 		log_validator_error(error_message,
177 				    "Field type match failed for field '%s'.",
178 				    field_name);
179 		return 0;
180 	}
181 
182 	//If the schema contains a "oneOf" array, we need to validate the field against each of the
183 	//possible options in turn.
184 	json_object *one_of = json_object_object_get(schema, "oneOf");
185 	if (one_of != NULL && json_object_get_type(one_of) == json_type_array) {
186 		log_validator_debug("oneOf options detected for field '%s'.",
187 				    field_name);
188 
189 		int len = json_object_array_length(one_of);
190 		int validated = 0;
191 		for (int i = 0; i < len; i++) {
192 			//If the "oneOf" member isn't an object, warn on schema violation.
193 			json_object *one_of_option =
194 				json_object_array_get_idx(one_of, i);
195 			if (one_of_option == NULL ||
196 			    json_object_get_type(one_of_option) !=
197 				    json_type_object) {
198 				log_validator_debug(
199 					"Schema Warning: 'oneOf' member for field '%s' is not an object, schema violation.",
200 					field_name);
201 				continue;
202 			}
203 
204 			//Validate field with schema.
205 			validated = validate_field(field_name, one_of_option,
206 						   object, error_message);
207 			if (validated == -1) {
208 				return -1;
209 			}
210 			if (validated) {
211 				break;
212 			}
213 		}
214 
215 		//Return if failed all checks.
216 		if (!validated) {
217 			log_validator_error(
218 				error_message,
219 				"No schema object structures matched provided object for field '%s'.",
220 				field_name);
221 			return 0;
222 		}
223 	}
224 
225 	//Switch and validate each type in turn.
226 	switch (json_object_get_type(object)) {
227 	case json_type_int:
228 		return validate_integer(field_name, schema, object,
229 					error_message);
230 	case json_type_string:
231 		return validate_string(field_name, schema, object,
232 				       error_message);
233 	case json_type_object:
234 		return validate_object(field_name, schema, object,
235 				       error_message);
236 	case json_type_array:
237 		return validate_array(field_name, schema, object,
238 				      error_message);
239 
240 	//We don't perform extra validation on this type.
241 	default:
242 		log_validator_debug(
243 			"validation passed for '%s' (no extra validation).",
244 			field_name);
245 		return 1;
246 	}
247 }
248 
249 //Validates a single integer value according to the given specification.
250 int validate_integer(const char *field_name, json_object *schema,
251 		     json_object *object, char *error_message)
252 {
253 	//Is there a minimum/maximum specified? If so, check those.
254 	//Validate minimum.
255 	json_object *min_value = json_object_object_get(schema, "minimum");
256 	if (min_value != NULL &&
257 	    json_object_is_type(min_value, json_type_int)) {
258 		int min_value_int = json_object_get_int(min_value);
259 		if (json_object_get_uint64(object) < (uint64_t)min_value_int) {
260 			log_validator_error(
261 				error_message,
262 				"Failed to validate integer field '%s'. Value was below minimum of %d.",
263 				field_name, min_value_int);
264 			return 0;
265 		}
266 	}
267 
268 	//Validate maximum.
269 	json_object *max_value = json_object_object_get(schema, "maximum");
270 	if (max_value != NULL &&
271 	    json_object_is_type(max_value, json_type_int)) {
272 		int max_value_int = json_object_get_int(max_value);
273 		if (json_object_get_uint64(object) > (uint64_t)max_value_int) {
274 			log_validator_error(
275 				error_message,
276 				"Failed to validate integer field '%s'. Value was above maximum of %d.",
277 				field_name, max_value_int);
278 			return 0;
279 		}
280 	}
281 
282 	return 1;
283 }
284 
285 //Validates a single string value according to the given specification.
286 int validate_string(const char *field_name, json_object *schema,
287 		    json_object *object, const char *error_message)
288 {
289 	//todo: if there is a "pattern" field, verify the string with RegEx.
290 	(void)field_name;
291 	(void)schema;
292 	(void)object;
293 	(void)error_message;
294 
295 	return 1;
296 }
297 
298 //Validates a single object value according to the given specification.
299 int validate_object(const char *field_name, json_object *schema,
300 		    json_object *object, char *error_message)
301 {
302 	//Are there a set of "required" fields? If so, check they all exist.
303 	json_object *required_fields =
304 		json_object_object_get(schema, "required");
305 	if (required_fields != NULL &&
306 	    json_object_get_type(required_fields) == json_type_array) {
307 		log_validator_debug(
308 			"Required fields found for '%s', matching...",
309 			field_name);
310 
311 		int len = json_object_array_length(required_fields);
312 		for (int i = 0; i < len; i++) {
313 			//Get the required field from schema.
314 			json_object *required_field =
315 				json_object_array_get_idx(required_fields, i);
316 			if (json_object_get_type(required_field) !=
317 			    json_type_string) {
318 				log_validator_error(
319 					error_message,
320 					"Required field for object '%s' is not a string (schema violation).",
321 					field_name);
322 				return 0;
323 			}
324 
325 			//Does it exist in the object?
326 			const char *required_field_str =
327 				json_object_get_string(required_field);
328 			if (json_object_object_get(
329 				    object, required_field_str) == NULL) {
330 				log_validator_error(
331 					error_message,
332 					"Required field '%s' was not present in object '%s'.",
333 					required_field_str, field_name);
334 				return 0;
335 			}
336 		}
337 	}
338 
339 	//Get additional properties value in advance.
340 	json_object *additional_properties =
341 		json_object_object_get(schema, "additionalProperties");
342 	int additional_properties_allowed = 0;
343 	if (additional_properties != NULL &&
344 	    json_object_get_type(additional_properties) == json_type_boolean) {
345 		additional_properties_allowed =
346 			json_object_get_boolean(additional_properties);
347 	}
348 
349 	//Run through the "properties" object and validate each of those in turn.
350 	json_object *properties = json_object_object_get(schema, "properties");
351 	if (properties != NULL &&
352 	    json_object_get_type(properties) == json_type_object) {
353 		json_object_object_foreach(properties, key, value)
354 		{
355 			//If the given property name does not exist on the target object, ignore and continue next.
356 			json_object *object_prop =
357 				json_object_object_get(object, key);
358 			if (object_prop == NULL) {
359 				continue;
360 			}
361 
362 			//Validate against the schema.
363 			if (!validate_field(key, value, object_prop,
364 					    error_message)) {
365 				return 0;
366 			}
367 		}
368 
369 		//If additional properties are banned, validate that no additional properties exist.
370 		if (!additional_properties_allowed) {
371 			json_object_object_foreach(object, key, value)
372 			{
373 				//Avoid compiler warning
374 				(void)value;
375 
376 				//If the given property name does not exist on the schema object, fail validation.
377 				const json_object *schema_prop =
378 					json_object_object_get(properties, key);
379 				if (schema_prop == NULL) {
380 					log_validator_error(
381 						error_message,
382 						"Invalid additional property '%s' detected on field '%s'.",
383 						key, field_name);
384 					return 0;
385 				}
386 			}
387 		}
388 	}
389 
390 	return 1;
391 }
392 
393 //Validates a single array value according to the given specification.
394 int validate_array(const char *field_name, json_object *schema,
395 		   json_object *object, char *error_message)
396 {
397 	//Iterate all items in the array, and validate according to the "items" schema.
398 	json_object *items_schema = json_object_object_get(schema, "items");
399 	if (items_schema != NULL &&
400 	    json_object_get_type(items_schema) == json_type_object) {
401 		int array_len = json_object_array_length(object);
402 		for (int i = 0; i < array_len; i++) {
403 			if (!validate_field(field_name, items_schema,
404 					    json_object_array_get_idx(object,
405 								      i),
406 					    error_message)) {
407 				return 0;
408 			}
409 		}
410 	}
411 
412 	return 1;
413 }
414 
415 //Enables/disables debugging globally for the JSON validator.
416 void validate_schema_debug_enable()
417 {
418 	json_validator_debug = 1;
419 }
420 void validate_schema_debug_disable()
421 {
422 	json_validator_debug = 0;
423 }
424 
425 //Logs an error message to the given error message location and (optionally) provides debug output.
426 void log_validator_error(char *error_message, const char *format, ...)
427 {
428 	va_list args;
429 
430 	//Log error to error out.
431 	va_start(args, format);
432 	vsnprintf(error_message, JSON_ERROR_MSG_MAX_LEN, format, args);
433 	va_end(args);
434 
435 	//Debug message if necessary.
436 	va_start(args, format);
437 	log_validator_msg(format, args);
438 	va_end(args);
439 }
440 
441 //Logs a debug message to stdout, if validator debug is enabled.
442 void log_validator_debug(const char *format, ...)
443 {
444 	va_list args;
445 	va_start(args, format);
446 	log_validator_msg(format, args);
447 	va_end(args);
448 }
449 
450 //Logs a single validator debug/error message.
451 void log_validator_msg(const char *format, va_list args)
452 {
453 	//Print debug output if debug is on.
454 	if (json_validator_debug) {
455 		//Make new format string for error.
456 		const char *header = "json_validator: ";
457 		char *new_format = malloc(strlen(header) + strlen(format) + 2);
458 		strcpy(new_format, header);
459 		strcat(new_format, format);
460 		strcat(new_format, "\n");
461 
462 		//Print & free format.
463 		vfprintf(stdout, new_format, args);
464 		free(new_format);
465 	}
466 }
467