blob: 4762dffa2849816d074aaaf85fbca23043ab4809 [file] [log] [blame]
Lawrence Tang8a2d7372022-07-12 16:44:49 +01001/**
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>
Lawrence Tang8f793ac2022-07-13 10:17:09 +010013#include <stdarg.h>
Lawrence Tang8a2d7372022-07-12 16:44:49 +010014#include "json.h"
15#include "json-schema.h"
16#include "edk/BaseTypes.h"
17
Lawrence Tang8f793ac2022-07-13 10:17:09 +010018//Field definitions.
19int json_validator_debug = 0;
20
Lawrence Tang8a2d7372022-07-12 16:44:49 +010021//Private pre-definitions.
22int validate_field(const char* name, json_object* schema, json_object* object, char* error_message);
23int validate_integer(const char* field_name, json_object* schema, json_object* object, char* error_message);
24int validate_string(const char* field_name, json_object* schema, json_object* object, char* error_message);
25int validate_object(const char* field_name, json_object* schema, json_object* object, char* error_message);
26int validate_array(const char* field_name, json_object* schema, json_object* object, char* error_message);
Lawrence Tang8f793ac2022-07-13 10:17:09 +010027void log_validator_error(char* error_message, const char* format, ...);
28void log_validator_debug(const char* format, ...);
29void log_validator_msg(const char* format, va_list args);
Lawrence Tang8a2d7372022-07-12 16:44:49 +010030
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.
33int 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +010039 log_validator_error(error_message, "Failed to load schema from file '%s'.", schema_file);
Lawrence Tang8a2d7372022-07-12 16:44:49 +010040 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.
59int 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +010065 log_validator_error(error_message, "Provided schema is not of the same version that is referenced by this validator, or is not a schema.");
Lawrence Tang8a2d7372022-07-12 16:44:49 +010066 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +010073 log_validator_error(error_message, "Failed fetching the current directory.");
Lawrence Tang8a2d7372022-07-12 16:44:49 +010074 return 0;
75 }
76 if (chdir(schema_directory))
77 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +010078 log_validator_error(error_message, "Failed to chdir into schema directory.");
Lawrence Tang8a2d7372022-07-12 16:44:49 +010079 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
Lawrence Tangd34f2b12022-07-19 15:36:31 +010089 if (result)
90 log_validator_debug("Successfully validated the provided object against schema.");
Lawrence Tang8a2d7372022-07-12 16:44:49 +010091 return result;
92}
93
94//Validates a single JSON field given a schema/object.
Lawrence Tang8f793ac2022-07-13 10:17:09 +010095//Returns -1 on fatal/error failure, 0 on validation failure, and 1 on validation.
Lawrence Tang8a2d7372022-07-12 16:44:49 +010096int validate_field(const char* field_name, json_object* schema, json_object* object, char* error_message)
97{
Lawrence Tang8f793ac2022-07-13 10:17:09 +010098 log_validator_debug("Validating field '%s'...", field_name);
99
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100100 //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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100104 log_validator_debug("$ref schema detected for field '%s'.", field_name);
105
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100106 //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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100111 log_validator_error(error_message, "Failed to open referenced schema file '%s'.", ref_path);
112 return -1;
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100113 }
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100114
115 log_validator_debug("loaded schema path '%s' for field '%s'.", ref_path, field_name);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100116 }
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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100122 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;
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100124 }
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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100137 log_validator_error(error_message, "Field type match failed for field '%s'.", field_name);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100138 return 0;
139 }
140
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100141 //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 }
Lawrence Tang45e04b02022-07-12 16:54:01 +0100175
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100176 //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:
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100186 return validate_array(field_name, schema, object, error_message);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100187
188 //We don't perform extra validation on this type.
189 default:
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100190 log_validator_debug("validation passed for '%s' (no extra validation).", field_name);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100191 return 1;
192 }
193}
194
195//Validates a single integer value according to the given specification.
196int 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100206 log_validator_error(error_message, "Failed to validate integer field '%s'. Value was below minimum of %d.", field_name, min_value_int);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100207 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100218 log_validator_error(error_message, "Failed to validate integer field '%s'. Value was above maximum of %d.", field_name, max_value_int);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100219 return 0;
220 }
221 }
222
223 return 1;
224}
225
226//Validates a single string value according to the given specification.
227int 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.
234int 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100240 log_validator_debug("Required fields found for '%s', matching...", field_name);
241
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100242 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100249 log_validator_error(error_message, "Required field for object '%s' is not a string (schema violation).", field_name);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100250 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 {
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100257 log_validator_error(error_message, "Required field '%s' was not present in object '%s'.", required_field_str, field_name);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100258 return 0;
259 }
260 }
261 }
262
Lawrence Tangc4814592022-07-13 10:24:09 +0100263 //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);
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100268
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 }
Lawrence Tangc4814592022-07-13 10:24:09 +0100284
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 }
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100299 }
300
301 return 1;
302}
303
304//Validates a single array value according to the given specification.
305int validate_array(const char* field_name, json_object* schema, json_object* object, char* error_message)
306{
Lawrence Tang45e04b02022-07-12 16:54:01 +0100307 //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
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100319 return 1;
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100320}
321
322//Enables/disables debugging globally for the JSON validator.
323void validate_schema_debug_enable() { json_validator_debug = 1; }
324void validate_schema_debug_disable() { json_validator_debug = 0; }
325
Lawrence Tang7cd13902022-07-13 16:59:25 +0100326//Logs an error message to the given error message location and (optionally) provides debug output.
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100327void 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
Lawrence Tang7cd13902022-07-13 16:59:25 +0100342//Logs a debug message to stdout, if validator debug is enabled.
Lawrence Tang8f793ac2022-07-13 10:17:09 +0100343void 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.
352void 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 }
Lawrence Tang8a2d7372022-07-12 16:44:49 +0100368}