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