blob: 1f3717e7e4a21516252b377a44ac11d7960c07af [file] [log] [blame]
[email protected]e0ced0c72011-11-14 21:03:501// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]639e6712010-11-11 22:21:432// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CHROME_COMMON_JSON_SCHEMA_VALIDATOR_H_
6#define CHROME_COMMON_JSON_SCHEMA_VALIDATOR_H_
7
8#include <map>
9#include <string>
10#include <vector>
11
12#include "base/basictypes.h"
13
[email protected]f3a1c642011-07-12 19:15:0314namespace base {
[email protected]639e6712010-11-11 22:21:4315class DictionaryValue;
[email protected]639e6712010-11-11 22:21:4316class ListValue;
17class StringValue;
18class Value;
[email protected]f3a1c642011-07-12 19:15:0319}
[email protected]639e6712010-11-11 22:21:4320
21//==============================================================================
22// This class implements a subset of JSON Schema.
23// See: http://www.json.com/json-schema-proposal/ for more details.
24//
25// There is also an older JavaScript implementation of the same functionality in
26// chrome/renderer/resources/json_schema.js.
27//
28// The following features of JSON Schema are not implemented:
29// - requires
30// - unique
31// - disallow
32// - union types (but replaced with 'choices')
33// - number.maxDecimal
34// - string.pattern
35//
36// The following properties are not applicable to the interface exposed by
37// this class:
38// - options
39// - readonly
40// - title
41// - description
42// - format
43// - default
44// - transient
45// - hidden
46//
47// There are also these departures from the JSON Schema proposal:
48// - null counts as 'unspecified' for optional values
49// - added the 'choices' property, to allow specifying a list of possible types
50// for a value
51// - by default an "object" typed schema does not allow additional properties.
52// if present, "additionalProperties" is to be a schema against which all
53// additional properties will be validated.
54//==============================================================================
55class JSONSchemaValidator {
56 public:
57 // Details about a validation error.
58 struct Error {
59 Error();
60
61 explicit Error(const std::string& message);
62
63 Error(const std::string& path, const std::string& message);
64
65 // The path to the location of the error in the JSON structure.
66 std::string path;
67
68 // An english message describing the error.
69 std::string message;
70 };
71
72 // Error messages.
73 static const char kUnknownTypeReference[];
74 static const char kInvalidChoice[];
75 static const char kInvalidEnum[];
76 static const char kObjectPropertyIsRequired[];
77 static const char kUnexpectedProperty[];
78 static const char kArrayMinItems[];
79 static const char kArrayMaxItems[];
80 static const char kArrayItemRequired[];
81 static const char kStringMinLength[];
82 static const char kStringMaxLength[];
83 static const char kStringPattern[];
84 static const char kNumberMinimum[];
85 static const char kNumberMaximum[];
86 static const char kInvalidType[];
87
88 // Classifies a Value as one of the JSON schema primitive types.
[email protected]f3a1c642011-07-12 19:15:0389 static std::string GetJSONSchemaType(base::Value* value);
[email protected]639e6712010-11-11 22:21:4390
91 // Utility methods to format error messages. The first method can have one
92 // wildcard represented by '*', which is replaced with s1. The second method
93 // can have two, which are replaced by s1 and s2.
94 static std::string FormatErrorMessage(const std::string& format,
95 const std::string& s1);
96 static std::string FormatErrorMessage(const std::string& format,
97 const std::string& s1,
98 const std::string& s2);
99
100 // Creates a validator for the specified schema.
101 //
102 // NOTE: This constructor assumes that |schema| is well formed and valid.
103 // Errors will result in CHECK at runtime; this constructor should not be used
104 // with untrusted schemas.
[email protected]f3a1c642011-07-12 19:15:03105 explicit JSONSchemaValidator(base::DictionaryValue* schema);
[email protected]639e6712010-11-11 22:21:43106
107 // Creates a validator for the specified schema and user-defined types. Each
108 // type must be a valid JSONSchema type description with an additional "id"
109 // field. Schema objects in |schema| can refer to these types with the "$ref"
110 // property.
111 //
112 // NOTE: This constructor assumes that |schema| and |types| are well-formed
113 // and valid. Errors will result in CHECK at runtime; this constructor should
114 // not be used with untrusted schemas.
[email protected]f3a1c642011-07-12 19:15:03115 JSONSchemaValidator(base::DictionaryValue* schema, base::ListValue* types);
[email protected]639e6712010-11-11 22:21:43116
[email protected]aa20e062010-12-07 23:07:27117 ~JSONSchemaValidator();
118
[email protected]639e6712010-11-11 22:21:43119 // Whether the validator allows additional items for objects and lists, beyond
120 // those defined by their schema, by default.
121 //
122 // This setting defaults to false: all items in an instance list or object
123 // must be defined by the corresponding schema.
124 //
125 // This setting can be overridden on individual object and list schemas by
126 // setting the "additionalProperties" field.
127 bool default_allow_additional_properties() const {
128 return default_allow_additional_properties_;
129 }
130
131 void set_default_allow_additional_properties(bool val) {
132 default_allow_additional_properties_ = val;
133 }
134
135 // Returns any errors from the last call to to Validate().
136 const std::vector<Error>& errors() const {
137 return errors_;
138 }
139
140 // Validates a JSON value. Returns true if the instance is valid, false
141 // otherwise. If false is returned any errors are available from the errors()
142 // getter.
[email protected]f3a1c642011-07-12 19:15:03143 bool Validate(base::Value* instance);
[email protected]639e6712010-11-11 22:21:43144
145 private:
[email protected]f3a1c642011-07-12 19:15:03146 typedef std::map<std::string, base::DictionaryValue*> TypeMap;
[email protected]639e6712010-11-11 22:21:43147
148 // Each of the below methods handle a subset of the validation process. The
149 // path paramater is the path to |instance| from the root of the instance tree
150 // and is used in error messages.
151
152 // Validates any instance node against any schema node. This is called for
153 // every node in the instance tree, and it just decides which of the more
154 // detailed methods to call.
[email protected]f3a1c642011-07-12 19:15:03155 void Validate(base::Value* instance, base::DictionaryValue* schema,
[email protected]639e6712010-11-11 22:21:43156 const std::string& path);
157
158 // Validates a node against a list of possible schemas. If any one of the
159 // schemas match, the node is valid.
[email protected]f3a1c642011-07-12 19:15:03160 void ValidateChoices(base::Value* instance, base::ListValue* choices,
[email protected]639e6712010-11-11 22:21:43161 const std::string& path);
162
163 // Validates a node against a list of exact primitive values, eg 42, "foobar".
[email protected]f3a1c642011-07-12 19:15:03164 void ValidateEnum(base::Value* instance, base::ListValue* choices,
[email protected]639e6712010-11-11 22:21:43165 const std::string& path);
166
167 // Validates a JSON object against an object schema node.
[email protected]f3a1c642011-07-12 19:15:03168 void ValidateObject(base::DictionaryValue* instance,
169 base::DictionaryValue* schema,
[email protected]639e6712010-11-11 22:21:43170 const std::string& path);
171
172 // Validates a JSON array against an array schema node.
[email protected]f3a1c642011-07-12 19:15:03173 void ValidateArray(base::ListValue* instance, base::DictionaryValue* schema,
[email protected]639e6712010-11-11 22:21:43174 const std::string& path);
175
176 // Validates a JSON array against an array schema node configured to be a
177 // tuple. In a tuple, there is one schema node for each item expected in the
178 // array.
[email protected]f3a1c642011-07-12 19:15:03179 void ValidateTuple(base::ListValue* instance, base::DictionaryValue* schema,
[email protected]639e6712010-11-11 22:21:43180 const std::string& path);
181
182 // Validate a JSON string against a string schema node.
[email protected]f3a1c642011-07-12 19:15:03183 void ValidateString(base::StringValue* instance,
184 base::DictionaryValue* schema,
[email protected]639e6712010-11-11 22:21:43185 const std::string& path);
186
187 // Validate a JSON number against a number schema node.
[email protected]f3a1c642011-07-12 19:15:03188 void ValidateNumber(base::Value* instance,
189 base::DictionaryValue* schema,
[email protected]639e6712010-11-11 22:21:43190 const std::string& path);
191
192 // Validates that the JSON node |instance| has |expected_type|.
[email protected]f3a1c642011-07-12 19:15:03193 bool ValidateType(base::Value* instance, const std::string& expected_type,
[email protected]639e6712010-11-11 22:21:43194 const std::string& path);
195
196 // Returns true if |schema| will allow additional items of any type.
197 bool SchemaAllowsAnyAdditionalItems(
[email protected]f3a1c642011-07-12 19:15:03198 base::DictionaryValue* schema,
199 base::DictionaryValue** addition_items_schema);
[email protected]639e6712010-11-11 22:21:43200
201 // The root schema node.
[email protected]f3a1c642011-07-12 19:15:03202 base::DictionaryValue* schema_root_;
[email protected]639e6712010-11-11 22:21:43203
204 // Map of user-defined name to type.
205 TypeMap types_;
206
207 // Whether we allow additional properties on objects by default. This can be
208 // overridden by the allow_additional_properties flag on an Object schema.
209 bool default_allow_additional_properties_;
210
211 // Errors accumulated since the last call to Validate().
212 std::vector<Error> errors_;
213
214
215 DISALLOW_COPY_AND_ASSIGN(JSONSchemaValidator);
216};
217
218#endif // CHROME_COMMON_JSON_SCHEMA_VALIDATOR_H_