diff options
author | Zeno Albisser <zeno.albisser@digia.com> | 2013-11-21 14:09:57 +0100 |
---|---|---|
committer | Andras Becsi <andras.becsi@digia.com> | 2013-11-29 15:14:36 +0100 |
commit | eb32ba6f51d0c21d58cd7d89785285ff8fa64624 (patch) | |
tree | 2c7c940e1dbee81b89d935626110816b494aa32c /chromium/components | |
parent | 9427c1a0222ebd67efef1a2c7990a0fa5c9aac84 (diff) | |
download | qtwebengine-chromium-eb32ba6f51d0c21d58cd7d89785285ff8fa64624.tar.gz |
Update chromium to branch 1599.
Change-Id: I04e775a946a208bb4500d3b722bcb05c82b9d7cb
Reviewed-by: Andras Becsi <andras.becsi@digia.com>
Diffstat (limited to 'chromium/components')
31 files changed, 188 insertions, 2639 deletions
diff --git a/chromium/components/OWNERS b/chromium/components/OWNERS index ff02f9e3125..7884fe2f806 100644 --- a/chromium/components/OWNERS +++ b/chromium/components/OWNERS @@ -8,11 +8,8 @@ per-file breakpad.gypi=jochen@chromium.org per-file breakpad.gypi=rsesek@chromium.org per-file breakpad.gypi=thestig@chromium.org -per-file json_schema.gypi=asargent@chromium.org -per-file json_schema.gypi=calamity@chromium.org -per-file json_schema.gypi=kalman@chromium.org -per-file json_schema.gypi=koz@chromium.org -per-file json_schema.gypi=mpcomplete@chromium.org +per-file tracing*=jbauman@chromium.org +per-file tracing*=nduca@chromium.org per-file nacl*=bradchen@chromium.org per-file nacl*=bradnelson@chromium.org @@ -24,19 +21,9 @@ per-file nacl*=sehr@chromium.org per-file navigation_interception.gypi=joth@chromium.org per-file navigation_interception.gypi=mkosiba@chromium.org -per-file policy.gypi=mnissler@chromium.org -per-file policy.gypi=pastarmovj@chromium.org -per-file policy.gypi=joaodasilva@chromium.org -per-file policy.gypi=bartfab@chromium.org -per-file policy.gypi=atwilson@chromium.org -per-file policy.gypi=pneubeck@chromium.org - per-file sessions.gypi=marja@chromium.org per-file sessions.gypi=sky@chromium.org -per-file tracing*=jbauman@chromium.org -per-file tracing*=nduca@chromium.org - per-file user_prefs.gypi=battre@chromium.org per-file user_prefs.gypi=bauerb@chromium.org per-file user_prefs.gypi=mnissler@chromium.org diff --git a/chromium/components/autofill/core/common/autofill_messages.h b/chromium/components/autofill/core/common/autofill_messages.h index 13524dfd7d2..a432887af6f 100644 --- a/chromium/components/autofill/core/common/autofill_messages.h +++ b/chromium/components/autofill/core/common/autofill_messages.h @@ -38,8 +38,7 @@ IPC_STRUCT_TRAITS_BEGIN(autofill::WebElementDescriptor) IPC_STRUCT_TRAITS_MEMBER(retrieval_method) IPC_STRUCT_TRAITS_END() -IPC_ENUM_TRAITS_MAX_VALUE(autofill::WebElementDescriptor::RetrievalMethod, - autofill::WebElementDescriptor::NONE) +IPC_ENUM_TRAITS(autofill::WebElementDescriptor::RetrievalMethod) IPC_STRUCT_TRAITS_BEGIN(autofill::FormFieldData) IPC_STRUCT_TRAITS_MEMBER(label) @@ -100,9 +99,7 @@ IPC_STRUCT_TRAITS_BEGIN(autofill::PasswordAndRealm) IPC_STRUCT_TRAITS_MEMBER(realm) IPC_STRUCT_TRAITS_END() -IPC_ENUM_TRAITS_MAX_VALUE( - WebKit::WebFormElement::AutocompleteResult, - WebKit::WebFormElement::AutocompleteResultErrorInvalid) +IPC_ENUM_TRAITS(WebKit::WebFormElement::AutocompleteResult) // Autofill messages sent from the browser to the renderer. diff --git a/chromium/components/components.gyp b/chromium/components/components.gyp index 602650c37d0..61c496c19d6 100644 --- a/chromium/components/components.gyp +++ b/chromium/components/components.gyp @@ -15,9 +15,7 @@ 'breakpad.gypi', 'browser_context_keyed_service.gypi', 'components_tests.gypi', - 'json_schema.gypi', 'navigation_interception.gypi', - 'policy.gypi', 'sessions.gypi', 'user_prefs.gypi', 'visitedlink.gypi', diff --git a/chromium/components/components_tests.gypi b/chromium/components/components_tests.gypi index 61346d07a88..b8e560008b9 100644 --- a/chromium/components/components_tests.gypi +++ b/chromium/components/components_tests.gypi @@ -13,9 +13,6 @@ 'auto_login_parser/auto_login_parser_unittest.cc', 'browser_context_keyed_service/browser_context_dependency_manager_unittest.cc', 'browser_context_keyed_service/dependency_graph_unittest.cc', - 'json_schema/json_schema_validator_unittest.cc', - 'json_schema/json_schema_validator_unittest_base.cc', - 'json_schema/json_schema_validator_unittest_base.h', 'navigation_interception/intercept_navigation_resource_throttle_unittest.cc', 'sessions/serialized_navigation_entry_unittest.cc', 'test/run_all_unittests.cc', @@ -41,17 +38,11 @@ # Dependencies of encryptor 'encryptor', - # Dependencies of json_schema - 'json_schema', - # Dependencies of intercept_navigation_resource_throttle_unittest.cc '../content/content.gyp:test_support_content', '../skia/skia.gyp:skia', 'navigation_interception', - # Dependencies of policy - 'policy_component', - # Dependencies of sessions '../third_party/protobuf/protobuf.gyp:protobuf_lite', 'sessions', @@ -96,11 +87,6 @@ 'ldflags': ['-rdynamic'], }, }], - ['configuration_policy==1', { - 'sources': [ - 'policy/core/common/policy_schema_unittest.cc', - ], - }], ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [4267, ], diff --git a/chromium/components/components_unittests.isolate b/chromium/components/components_unittests.isolate index f60a380f60d..0c18d8fe838 100644 --- a/chromium/components/components_unittests.isolate +++ b/chromium/components/components_unittests.isolate @@ -8,9 +8,6 @@ 'isolate_dependency_tracked': [ '<(PRODUCT_DIR)/content_resources.pak', ], - 'isolate_dependency_untracked': [ - 'test/data/', - ], }, }], ], diff --git a/chromium/components/json_schema.gypi b/chromium/components/json_schema.gypi deleted file mode 100644 index 510f97d6fe4..00000000000 --- a/chromium/components/json_schema.gypi +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'targets': [ - { - 'target_name': 'json_schema', - 'type': 'static_library', - 'dependencies': [ - '../base/base.gyp:base', - '../ui/ui.gyp:ui', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - 'json_schema/json_schema_constants.cc', - 'json_schema/json_schema_constants.h', - 'json_schema/json_schema_validator.cc', - 'json_schema/json_schema_validator.h', - ], - }, - ], -} diff --git a/chromium/components/json_schema/DEPS b/chromium/components/json_schema/DEPS deleted file mode 100644 index e7cf2c6ff61..00000000000 --- a/chromium/components/json_schema/DEPS +++ /dev/null @@ -1,3 +0,0 @@ -include_rules = [ - "+ui/base", -] diff --git a/chromium/components/json_schema/OWNERS b/chromium/components/json_schema/OWNERS deleted file mode 100644 index f7e95c9f18f..00000000000 --- a/chromium/components/json_schema/OWNERS +++ /dev/null @@ -1,5 +0,0 @@ -asargent@chromium.org -calamity@chromium.org -kalman@chromium.org -koz@chromium.org -mpcomplete@chromium.org diff --git a/chromium/components/json_schema/README b/chromium/components/json_schema/README deleted file mode 100644 index c7453db06dc..00000000000 --- a/chromium/components/json_schema/README +++ /dev/null @@ -1,6 +0,0 @@ -The //components/json_schema component provides: - -a) JSON schema constants, which can be used to inspect schema objects. - -b) The JSONSchemaValidator class, which can be used to parse and validate JSON -schemas, and to validate JSON objects against the parsed schema. diff --git a/chromium/components/json_schema/json_schema_constants.cc b/chromium/components/json_schema/json_schema_constants.cc deleted file mode 100644 index 0152cfc054d..00000000000 --- a/chromium/components/json_schema/json_schema_constants.cc +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/json_schema/json_schema_constants.h" - -namespace json_schema_constants { - -const char kAdditionalProperties[] = "additionalProperties"; -const char kAny[] = "any"; -const char kArray[] = "array"; -const char kBoolean[] = "boolean"; -const char kChoices[] = "choices"; -const char kDescription[] = "description"; -const char kEnum[] = "enum"; -const char kId[] = "id"; -const char kInteger[] = "integer"; -const char kItems[] = "items"; -const char kMaximum[] = "maximum"; -const char kMaxItems[] = "maxItems"; -const char kMaxLength[] = "maxLength"; -const char kMinimum[] = "minimum"; -const char kMinItems[] = "minItems"; -const char kMinLength[] = "minLength"; -const char kNull[] = "null"; -const char kNumber[] = "number"; -const char kObject[] = "object"; -const char kOptional[] = "optional"; -const char kPattern[] = "pattern"; -const char kPatternProperties[] = "patternProperties"; -const char kProperties[] = "properties"; -const char kRef[] = "$ref"; -const char kSchema[] = "$schema"; -const char kString[] = "string"; -const char kTitle[] = "title"; -const char kType[] = "type"; - -} // namespace json_schema_constants diff --git a/chromium/components/json_schema/json_schema_constants.h b/chromium/components/json_schema/json_schema_constants.h deleted file mode 100644 index 5c64ebb5606..00000000000 --- a/chromium/components/json_schema/json_schema_constants.h +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_CONSTANTS_H_ -#define COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_CONSTANTS_H_ - -// These constants are shared by code that uses JSON schemas. -namespace json_schema_constants { - -extern const char kAdditionalProperties[]; -extern const char kAny[]; -extern const char kArray[]; -extern const char kBoolean[]; -extern const char kChoices[]; -extern const char kDescription[]; -extern const char kEnum[]; -extern const char kId[]; -extern const char kInteger[]; -extern const char kItems[]; -extern const char kMaximum[]; -extern const char kMaxItems[]; -extern const char kMaxLength[]; -extern const char kMinimum[]; -extern const char kMinItems[]; -extern const char kMinLength[]; -extern const char kNull[]; -extern const char kNumber[]; -extern const char kObject[]; -extern const char kOptional[]; -extern const char kPattern[]; -extern const char kPatternProperties[]; -extern const char kProperties[]; -extern const char kRef[]; -extern const char kSchema[]; -extern const char kString[]; -extern const char kTitle[]; -extern const char kType[]; - -} // namespace json_schema_constants - -#endif // COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_CONSTANTS_H_ diff --git a/chromium/components/json_schema/json_schema_validator.cc b/chromium/components/json_schema/json_schema_validator.cc deleted file mode 100644 index 3816a760970..00000000000 --- a/chromium/components/json_schema/json_schema_validator.cc +++ /dev/null @@ -1,727 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/json_schema/json_schema_validator.h" - -#include <algorithm> -#include <cfloat> -#include <cmath> - -#include "base/json/json_reader.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/values.h" -#include "components/json_schema/json_schema_constants.h" -#include "ui/base/l10n/l10n_util.h" - -namespace schema = json_schema_constants; - -namespace { - -double GetNumberValue(const base::Value* value) { - double result = 0; - CHECK(value->GetAsDouble(&result)) - << "Unexpected value type: " << value->GetType(); - return result; -} - -bool IsValidType(const std::string& type) { - static const char* kValidTypes[] = { - schema::kAny, - schema::kArray, - schema::kBoolean, - schema::kInteger, - schema::kNull, - schema::kNumber, - schema::kObject, - schema::kString, - }; - const char** end = kValidTypes + arraysize(kValidTypes); - return std::find(kValidTypes, end, type) != end; -} - -// Maps a schema attribute name to its expected type. -struct ExpectedType { - const char* key; - base::Value::Type type; -}; - -// Helper for std::lower_bound. -bool CompareToString(const ExpectedType& entry, const std::string& key) { - return entry.key < key; -} - -bool IsValidSchema(const base::DictionaryValue* dict, std::string* error) { - // This array must be sorted, so that std::lower_bound can perform a - // binary search. - static const ExpectedType kExpectedTypes[] = { - // Note: kRef == "$ref", kSchema == "$schema" - { schema::kRef, base::Value::TYPE_STRING }, - { schema::kSchema, base::Value::TYPE_STRING }, - - { schema::kAdditionalProperties, base::Value::TYPE_DICTIONARY }, - { schema::kChoices, base::Value::TYPE_LIST }, - { schema::kDescription, base::Value::TYPE_STRING }, - { schema::kEnum, base::Value::TYPE_LIST }, - { schema::kId, base::Value::TYPE_STRING }, - { schema::kMaxItems, base::Value::TYPE_INTEGER }, - { schema::kMaxLength, base::Value::TYPE_INTEGER }, - { schema::kMaximum, base::Value::TYPE_DOUBLE }, - { schema::kMinItems, base::Value::TYPE_INTEGER }, - { schema::kMinLength, base::Value::TYPE_INTEGER }, - { schema::kMinimum, base::Value::TYPE_DOUBLE }, - { schema::kOptional, base::Value::TYPE_BOOLEAN }, - { schema::kProperties, base::Value::TYPE_DICTIONARY }, - { schema::kTitle, base::Value::TYPE_STRING }, - }; - - bool has_type = false; - const base::ListValue* list_value = NULL; - const base::DictionaryValue* dictionary_value = NULL; - std::string string_value; - - for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { - // Validate the "type" attribute, which may be a string or a list. - if (it.key() == schema::kType) { - switch (it.value().GetType()) { - case base::Value::TYPE_STRING: - it.value().GetAsString(&string_value); - if (!IsValidType(string_value)) { - *error = "Invalid value for type attribute"; - return false; - } - break; - case base::Value::TYPE_LIST: - it.value().GetAsList(&list_value); - for (size_t i = 0; i < list_value->GetSize(); ++i) { - if (!list_value->GetString(i, &string_value) || - !IsValidType(string_value)) { - *error = "Invalid value for type attribute"; - return false; - } - } - break; - default: - *error = "Invalid value for type attribute"; - return false; - } - has_type = true; - continue; - } - - // Validate the "items" attribute, which is a schema or a list of schemas. - if (it.key() == schema::kItems) { - if (it.value().GetAsDictionary(&dictionary_value)) { - if (!IsValidSchema(dictionary_value, error)) { - DCHECK(!error->empty()); - return false; - } - } else if (it.value().GetAsList(&list_value)) { - for (size_t i = 0; i < list_value->GetSize(); ++i) { - if (!list_value->GetDictionary(i, &dictionary_value)) { - *error = base::StringPrintf( - "Invalid entry in items attribute at index %d", - static_cast<int>(i)); - return false; - } - if (!IsValidSchema(dictionary_value, error)) { - DCHECK(!error->empty()); - return false; - } - } - } else { - *error = "Invalid value for items attribute"; - return false; - } - continue; - } - - // All the other attributes have a single valid type. - const ExpectedType* end = kExpectedTypes + arraysize(kExpectedTypes); - const ExpectedType* entry = std::lower_bound( - kExpectedTypes, end, it.key(), CompareToString); - if (entry == end || entry->key != it.key()) { - *error = base::StringPrintf("Invalid attribute %s", it.key().c_str()); - return false; - } - if (!it.value().IsType(entry->type)) { - *error = base::StringPrintf("Invalid value for %s attribute", - it.key().c_str()); - return false; - } - - // base::Value::TYPE_INTEGER attributes must be >= 0. - // This applies to "minItems", "maxItems", "minLength" and "maxLength". - if (it.value().IsType(base::Value::TYPE_INTEGER)) { - int integer_value; - it.value().GetAsInteger(&integer_value); - if (integer_value < 0) { - *error = base::StringPrintf("Value of %s must be >= 0, got %d", - it.key().c_str(), integer_value); - return false; - } - } - - // Validate the "properties" attribute. Each entry maps a key to a schema. - if (it.key() == schema::kProperties) { - it.value().GetAsDictionary(&dictionary_value); - for (base::DictionaryValue::Iterator it(*dictionary_value); - !it.IsAtEnd(); it.Advance()) { - if (!it.value().GetAsDictionary(&dictionary_value)) { - *error = "Invalid value for properties attribute"; - return false; - } - if (!IsValidSchema(dictionary_value, error)) { - DCHECK(!error->empty()); - return false; - } - } - } - - // Validate "additionalProperties" attribute, which is a schema. - if (it.key() == schema::kAdditionalProperties) { - it.value().GetAsDictionary(&dictionary_value); - if (!IsValidSchema(dictionary_value, error)) { - DCHECK(!error->empty()); - return false; - } - } - - // Validate the values contained in an "enum" attribute. - if (it.key() == schema::kEnum) { - it.value().GetAsList(&list_value); - for (size_t i = 0; i < list_value->GetSize(); ++i) { - const base::Value* value = NULL; - list_value->Get(i, &value); - switch (value->GetType()) { - case base::Value::TYPE_NULL: - case base::Value::TYPE_BOOLEAN: - case base::Value::TYPE_INTEGER: - case base::Value::TYPE_DOUBLE: - case base::Value::TYPE_STRING: - break; - default: - *error = "Invalid value in enum attribute"; - return false; - } - } - } - - // Validate the schemas contained in a "choices" attribute. - if (it.key() == schema::kChoices) { - it.value().GetAsList(&list_value); - for (size_t i = 0; i < list_value->GetSize(); ++i) { - if (!list_value->GetDictionary(i, &dictionary_value)) { - *error = "Invalid choices attribute"; - return false; - } - if (!IsValidSchema(dictionary_value, error)) { - DCHECK(!error->empty()); - return false; - } - } - } - } - - if (!has_type) { - *error = "Schema must have a type attribute"; - return false; - } - - return true; -} - -} // namespace - - -JSONSchemaValidator::Error::Error() { -} - -JSONSchemaValidator::Error::Error(const std::string& message) - : path(message) { -} - -JSONSchemaValidator::Error::Error(const std::string& path, - const std::string& message) - : path(path), message(message) { -} - - -const char JSONSchemaValidator::kUnknownTypeReference[] = - "Unknown schema reference: *."; -const char JSONSchemaValidator::kInvalidChoice[] = - "Value does not match any valid type choices."; -const char JSONSchemaValidator::kInvalidEnum[] = - "Value does not match any valid enum choices."; -const char JSONSchemaValidator::kObjectPropertyIsRequired[] = - "Property is required."; -const char JSONSchemaValidator::kUnexpectedProperty[] = - "Unexpected property."; -const char JSONSchemaValidator::kArrayMinItems[] = - "Array must have at least * items."; -const char JSONSchemaValidator::kArrayMaxItems[] = - "Array must not have more than * items."; -const char JSONSchemaValidator::kArrayItemRequired[] = - "Item is required."; -const char JSONSchemaValidator::kStringMinLength[] = - "String must be at least * characters long."; -const char JSONSchemaValidator::kStringMaxLength[] = - "String must not be more than * characters long."; -const char JSONSchemaValidator::kStringPattern[] = - "String must match the pattern: *."; -const char JSONSchemaValidator::kNumberMinimum[] = - "Value must not be less than *."; -const char JSONSchemaValidator::kNumberMaximum[] = - "Value must not be greater than *."; -const char JSONSchemaValidator::kInvalidType[] = - "Expected '*' but got '*'."; -const char JSONSchemaValidator::kInvalidTypeIntegerNumber[] = - "Expected 'integer' but got 'number', consider using Math.round()."; - - -// static -std::string JSONSchemaValidator::GetJSONSchemaType(const base::Value* value) { - switch (value->GetType()) { - case base::Value::TYPE_NULL: - return schema::kNull; - case base::Value::TYPE_BOOLEAN: - return schema::kBoolean; - case base::Value::TYPE_INTEGER: - return schema::kInteger; - case base::Value::TYPE_DOUBLE: { - double double_value = 0; - value->GetAsDouble(&double_value); - if (std::abs(double_value) <= std::pow(2.0, DBL_MANT_DIG) && - double_value == floor(double_value)) { - return schema::kInteger; - } else { - return schema::kNumber; - } - } - case base::Value::TYPE_STRING: - return schema::kString; - case base::Value::TYPE_DICTIONARY: - return schema::kObject; - case base::Value::TYPE_LIST: - return schema::kArray; - default: - NOTREACHED() << "Unexpected value type: " << value->GetType(); - return std::string(); - } -} - -// static -std::string JSONSchemaValidator::FormatErrorMessage(const std::string& format, - const std::string& s1) { - std::string ret_val = format; - ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1); - return ret_val; -} - -// static -std::string JSONSchemaValidator::FormatErrorMessage(const std::string& format, - const std::string& s1, - const std::string& s2) { - std::string ret_val = format; - ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1); - ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s2); - return ret_val; -} - -// static -scoped_ptr<base::DictionaryValue> JSONSchemaValidator::IsValidSchema( - const std::string& schema, - std::string* error) { - base::JSONParserOptions options = base::JSON_PARSE_RFC; - scoped_ptr<base::Value> json( - base::JSONReader::ReadAndReturnError(schema, options, NULL, error)); - if (!json) - return scoped_ptr<base::DictionaryValue>(); - base::DictionaryValue* dict = NULL; - if (!json->GetAsDictionary(&dict)) { - *error = "Schema must be a JSON object"; - return scoped_ptr<base::DictionaryValue>(); - } - if (!::IsValidSchema(dict, error)) - return scoped_ptr<base::DictionaryValue>(); - ignore_result(json.release()); - return make_scoped_ptr(dict); -} - -JSONSchemaValidator::JSONSchemaValidator(base::DictionaryValue* schema) - : schema_root_(schema), default_allow_additional_properties_(false) { -} - -JSONSchemaValidator::JSONSchemaValidator(base::DictionaryValue* schema, - base::ListValue* types) - : schema_root_(schema), default_allow_additional_properties_(false) { - if (!types) - return; - - for (size_t i = 0; i < types->GetSize(); ++i) { - base::DictionaryValue* type = NULL; - CHECK(types->GetDictionary(i, &type)); - - std::string id; - CHECK(type->GetString(schema::kId, &id)); - - CHECK(types_.find(id) == types_.end()); - types_[id] = type; - } -} - -JSONSchemaValidator::~JSONSchemaValidator() {} - -bool JSONSchemaValidator::Validate(const base::Value* instance) { - errors_.clear(); - Validate(instance, schema_root_, std::string()); - return errors_.empty(); -} - -void JSONSchemaValidator::Validate(const base::Value* instance, - const base::DictionaryValue* schema, - const std::string& path) { - // If this schema defines itself as reference type, save it in this.types. - std::string id; - if (schema->GetString(schema::kId, &id)) { - TypeMap::iterator iter = types_.find(id); - if (iter == types_.end()) - types_[id] = schema; - else - DCHECK(iter->second == schema); - } - - // If the schema has a $ref property, the instance must validate against - // that schema. It must be present in types_ to be referenced. - std::string ref; - if (schema->GetString(schema::kRef, &ref)) { - TypeMap::iterator type = types_.find(ref); - if (type == types_.end()) { - errors_.push_back( - Error(path, FormatErrorMessage(kUnknownTypeReference, ref))); - } else { - Validate(instance, type->second, path); - } - return; - } - - // If the schema has a choices property, the instance must validate against at - // least one of the items in that array. - const base::ListValue* choices = NULL; - if (schema->GetList(schema::kChoices, &choices)) { - ValidateChoices(instance, choices, path); - return; - } - - // If the schema has an enum property, the instance must be one of those - // values. - const base::ListValue* enumeration = NULL; - if (schema->GetList(schema::kEnum, &enumeration)) { - ValidateEnum(instance, enumeration, path); - return; - } - - std::string type; - schema->GetString(schema::kType, &type); - CHECK(!type.empty()); - if (type != schema::kAny) { - if (!ValidateType(instance, type, path)) - return; - - // These casts are safe because of checks in ValidateType(). - if (type == schema::kObject) { - ValidateObject(static_cast<const base::DictionaryValue*>(instance), - schema, - path); - } else if (type == schema::kArray) { - ValidateArray(static_cast<const base::ListValue*>(instance), - schema, path); - } else if (type == schema::kString) { - // Intentionally NOT downcasting to StringValue*. TYPE_STRING only implies - // GetAsString() can safely be carried out, not that it's a StringValue. - ValidateString(instance, schema, path); - } else if (type == schema::kNumber || type == schema::kInteger) { - ValidateNumber(instance, schema, path); - } else if (type != schema::kBoolean && type != schema::kNull) { - NOTREACHED() << "Unexpected type: " << type; - } - } -} - -void JSONSchemaValidator::ValidateChoices(const base::Value* instance, - const base::ListValue* choices, - const std::string& path) { - size_t original_num_errors = errors_.size(); - - for (size_t i = 0; i < choices->GetSize(); ++i) { - const base::DictionaryValue* choice = NULL; - CHECK(choices->GetDictionary(i, &choice)); - - Validate(instance, choice, path); - if (errors_.size() == original_num_errors) - return; - - // We discard the error from each choice. We only want to know if any of the - // validations succeeded. - errors_.resize(original_num_errors); - } - - // Now add a generic error that no choices matched. - errors_.push_back(Error(path, kInvalidChoice)); - return; -} - -void JSONSchemaValidator::ValidateEnum(const base::Value* instance, - const base::ListValue* choices, - const std::string& path) { - for (size_t i = 0; i < choices->GetSize(); ++i) { - const base::Value* choice = NULL; - CHECK(choices->Get(i, &choice)); - switch (choice->GetType()) { - case base::Value::TYPE_NULL: - case base::Value::TYPE_BOOLEAN: - case base::Value::TYPE_STRING: - if (instance->Equals(choice)) - return; - break; - - case base::Value::TYPE_INTEGER: - case base::Value::TYPE_DOUBLE: - if (instance->IsType(base::Value::TYPE_INTEGER) || - instance->IsType(base::Value::TYPE_DOUBLE)) { - if (GetNumberValue(choice) == GetNumberValue(instance)) - return; - } - break; - - default: - NOTREACHED() << "Unexpected type in enum: " << choice->GetType(); - } - } - - errors_.push_back(Error(path, kInvalidEnum)); -} - -void JSONSchemaValidator::ValidateObject(const base::DictionaryValue* instance, - const base::DictionaryValue* schema, - const std::string& path) { - const base::DictionaryValue* properties = NULL; - schema->GetDictionary(schema::kProperties, &properties); - if (properties) { - for (base::DictionaryValue::Iterator it(*properties); !it.IsAtEnd(); - it.Advance()) { - std::string prop_path = path.empty() ? it.key() : (path + "." + it.key()); - const base::DictionaryValue* prop_schema = NULL; - CHECK(it.value().GetAsDictionary(&prop_schema)); - - const base::Value* prop_value = NULL; - if (instance->Get(it.key(), &prop_value)) { - Validate(prop_value, prop_schema, prop_path); - } else { - // Properties are required unless there is an optional field set to - // 'true'. - bool is_optional = false; - prop_schema->GetBoolean(schema::kOptional, &is_optional); - if (!is_optional) { - errors_.push_back(Error(prop_path, kObjectPropertyIsRequired)); - } - } - } - } - - const base::DictionaryValue* additional_properties_schema = NULL; - if (SchemaAllowsAnyAdditionalItems(schema, &additional_properties_schema)) - return; - - // Validate additional properties. - for (base::DictionaryValue::Iterator it(*instance); !it.IsAtEnd(); - it.Advance()) { - if (properties && properties->HasKey(it.key())) - continue; - - std::string prop_path = path.empty() ? it.key() : path + "." + it.key(); - if (!additional_properties_schema) { - errors_.push_back(Error(prop_path, kUnexpectedProperty)); - } else { - Validate(&it.value(), additional_properties_schema, prop_path); - } - } -} - -void JSONSchemaValidator::ValidateArray(const base::ListValue* instance, - const base::DictionaryValue* schema, - const std::string& path) { - const base::DictionaryValue* single_type = NULL; - size_t instance_size = instance->GetSize(); - if (schema->GetDictionary(schema::kItems, &single_type)) { - int min_items = 0; - if (schema->GetInteger(schema::kMinItems, &min_items)) { - CHECK(min_items >= 0); - if (instance_size < static_cast<size_t>(min_items)) { - errors_.push_back(Error(path, FormatErrorMessage( - kArrayMinItems, base::IntToString(min_items)))); - } - } - - int max_items = 0; - if (schema->GetInteger(schema::kMaxItems, &max_items)) { - CHECK(max_items >= 0); - if (instance_size > static_cast<size_t>(max_items)) { - errors_.push_back(Error(path, FormatErrorMessage( - kArrayMaxItems, base::IntToString(max_items)))); - } - } - - // If the items property is a single schema, each item in the array must - // validate against that schema. - for (size_t i = 0; i < instance_size; ++i) { - const base::Value* item = NULL; - CHECK(instance->Get(i, &item)); - std::string i_str = base::Uint64ToString(i); - std::string item_path = path.empty() ? i_str : (path + "." + i_str); - Validate(item, single_type, item_path); - } - - return; - } - - // Otherwise, the list must be a tuple type, where each item in the list has a - // particular schema. - ValidateTuple(instance, schema, path); -} - -void JSONSchemaValidator::ValidateTuple(const base::ListValue* instance, - const base::DictionaryValue* schema, - const std::string& path) { - const base::ListValue* tuple_type = NULL; - schema->GetList(schema::kItems, &tuple_type); - size_t tuple_size = tuple_type ? tuple_type->GetSize() : 0; - if (tuple_type) { - for (size_t i = 0; i < tuple_size; ++i) { - std::string i_str = base::Uint64ToString(i); - std::string item_path = path.empty() ? i_str : (path + "." + i_str); - const base::DictionaryValue* item_schema = NULL; - CHECK(tuple_type->GetDictionary(i, &item_schema)); - const base::Value* item_value = NULL; - instance->Get(i, &item_value); - if (item_value && item_value->GetType() != base::Value::TYPE_NULL) { - Validate(item_value, item_schema, item_path); - } else { - bool is_optional = false; - item_schema->GetBoolean(schema::kOptional, &is_optional); - if (!is_optional) { - errors_.push_back(Error(item_path, kArrayItemRequired)); - return; - } - } - } - } - - const base::DictionaryValue* additional_properties_schema = NULL; - if (SchemaAllowsAnyAdditionalItems(schema, &additional_properties_schema)) - return; - - size_t instance_size = instance->GetSize(); - if (additional_properties_schema) { - // Any additional properties must validate against the additionalProperties - // schema. - for (size_t i = tuple_size; i < instance_size; ++i) { - std::string i_str = base::Uint64ToString(i); - std::string item_path = path.empty() ? i_str : (path + "." + i_str); - const base::Value* item_value = NULL; - CHECK(instance->Get(i, &item_value)); - Validate(item_value, additional_properties_schema, item_path); - } - } else if (instance_size > tuple_size) { - errors_.push_back(Error(path, FormatErrorMessage( - kArrayMaxItems, base::Uint64ToString(tuple_size)))); - } -} - -void JSONSchemaValidator::ValidateString(const base::Value* instance, - const base::DictionaryValue* schema, - const std::string& path) { - std::string value; - CHECK(instance->GetAsString(&value)); - - int min_length = 0; - if (schema->GetInteger(schema::kMinLength, &min_length)) { - CHECK(min_length >= 0); - if (value.size() < static_cast<size_t>(min_length)) { - errors_.push_back(Error(path, FormatErrorMessage( - kStringMinLength, base::IntToString(min_length)))); - } - } - - int max_length = 0; - if (schema->GetInteger(schema::kMaxLength, &max_length)) { - CHECK(max_length >= 0); - if (value.size() > static_cast<size_t>(max_length)) { - errors_.push_back(Error(path, FormatErrorMessage( - kStringMaxLength, base::IntToString(max_length)))); - } - } - - CHECK(!schema->HasKey(schema::kPattern)) << "Pattern is not supported."; -} - -void JSONSchemaValidator::ValidateNumber(const base::Value* instance, - const base::DictionaryValue* schema, - const std::string& path) { - double value = GetNumberValue(instance); - - // TODO(aa): It would be good to test that the double is not infinity or nan, - // but isnan and isinf aren't defined on Windows. - - double minimum = 0; - if (schema->GetDouble(schema::kMinimum, &minimum)) { - if (value < minimum) - errors_.push_back(Error(path, FormatErrorMessage( - kNumberMinimum, base::DoubleToString(minimum)))); - } - - double maximum = 0; - if (schema->GetDouble(schema::kMaximum, &maximum)) { - if (value > maximum) - errors_.push_back(Error(path, FormatErrorMessage( - kNumberMaximum, base::DoubleToString(maximum)))); - } -} - -bool JSONSchemaValidator::ValidateType(const base::Value* instance, - const std::string& expected_type, - const std::string& path) { - std::string actual_type = GetJSONSchemaType(instance); - if (expected_type == actual_type || - (expected_type == schema::kNumber && actual_type == schema::kInteger)) { - return true; - } else if (expected_type == schema::kInteger && - actual_type == schema::kNumber) { - errors_.push_back(Error(path, kInvalidTypeIntegerNumber)); - return false; - } else { - errors_.push_back(Error(path, FormatErrorMessage( - kInvalidType, expected_type, actual_type))); - return false; - } -} - -bool JSONSchemaValidator::SchemaAllowsAnyAdditionalItems( - const base::DictionaryValue* schema, - const base::DictionaryValue** additional_properties_schema) { - // If the validator allows additional properties globally, and this schema - // doesn't override, then we can exit early. - schema->GetDictionary(schema::kAdditionalProperties, - additional_properties_schema); - - if (*additional_properties_schema) { - std::string additional_properties_type(schema::kAny); - CHECK((*additional_properties_schema)->GetString( - schema::kType, &additional_properties_type)); - return additional_properties_type == schema::kAny; - } else { - return default_allow_additional_properties_; - } -} diff --git a/chromium/components/json_schema/json_schema_validator.h b/chromium/components/json_schema/json_schema_validator.h deleted file mode 100644 index 4584a9da77a..00000000000 --- a/chromium/components/json_schema/json_schema_validator.h +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_H_ -#define COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" - -namespace base { -class DictionaryValue; -class ListValue; -class StringValue; -class Value; -} - -//============================================================================== -// This class implements a subset of JSON Schema. -// See: http://www.json.com/json-schema-proposal/ for more details. -// -// There is also an older JavaScript implementation of the same functionality in -// chrome/renderer/resources/json_schema.js. -// -// The following features of JSON Schema are not implemented: -// - requires -// - unique -// - disallow -// - union types (but replaced with 'choices') -// - number.maxDecimal -// - string.pattern -// -// The following properties are not applicable to the interface exposed by -// this class: -// - options -// - readonly -// - title -// - description -// - format -// - default -// - transient -// - hidden -// -// There are also these departures from the JSON Schema proposal: -// - null counts as 'unspecified' for optional values -// - added the 'choices' property, to allow specifying a list of possible types -// for a value -// - by default an "object" typed schema does not allow additional properties. -// if present, "additionalProperties" is to be a schema against which all -// additional properties will be validated. -//============================================================================== -class JSONSchemaValidator { - public: - // Details about a validation error. - struct Error { - Error(); - - explicit Error(const std::string& message); - - Error(const std::string& path, const std::string& message); - - // The path to the location of the error in the JSON structure. - std::string path; - - // An english message describing the error. - std::string message; - }; - - // Error messages. - static const char kUnknownTypeReference[]; - static const char kInvalidChoice[]; - static const char kInvalidEnum[]; - static const char kObjectPropertyIsRequired[]; - static const char kUnexpectedProperty[]; - static const char kArrayMinItems[]; - static const char kArrayMaxItems[]; - static const char kArrayItemRequired[]; - static const char kStringMinLength[]; - static const char kStringMaxLength[]; - static const char kStringPattern[]; - static const char kNumberMinimum[]; - static const char kNumberMaximum[]; - static const char kInvalidType[]; - static const char kInvalidTypeIntegerNumber[]; - - // Classifies a Value as one of the JSON schema primitive types. - static std::string GetJSONSchemaType(const base::Value* value); - - // Utility methods to format error messages. The first method can have one - // wildcard represented by '*', which is replaced with s1. The second method - // can have two, which are replaced by s1 and s2. - static std::string FormatErrorMessage(const std::string& format, - const std::string& s1); - static std::string FormatErrorMessage(const std::string& format, - const std::string& s1, - const std::string& s2); - - // Verifies if |schema| is a valid JSON v3 schema. When this validation passes - // then |schema| is valid JSON that can be parsed into a DictionaryValue, - // and that DictionaryValue can be used to build a JSONSchemaValidator. - // Returns the parsed DictionaryValue when |schema| validated, otherwise - // returns NULL. In that case, |error| contains an error description. - static scoped_ptr<base::DictionaryValue> IsValidSchema( - const std::string& schema, - std::string* error); - - // Creates a validator for the specified schema. - // - // NOTE: This constructor assumes that |schema| is well formed and valid. - // Errors will result in CHECK at runtime; this constructor should not be used - // with untrusted schemas. - explicit JSONSchemaValidator(base::DictionaryValue* schema); - - // Creates a validator for the specified schema and user-defined types. Each - // type must be a valid JSONSchema type description with an additional "id" - // field. Schema objects in |schema| can refer to these types with the "$ref" - // property. - // - // NOTE: This constructor assumes that |schema| and |types| are well-formed - // and valid. Errors will result in CHECK at runtime; this constructor should - // not be used with untrusted schemas. - JSONSchemaValidator(base::DictionaryValue* schema, base::ListValue* types); - - ~JSONSchemaValidator(); - - // Whether the validator allows additional items for objects and lists, beyond - // those defined by their schema, by default. - // - // This setting defaults to false: all items in an instance list or object - // must be defined by the corresponding schema. - // - // This setting can be overridden on individual object and list schemas by - // setting the "additionalProperties" field. - bool default_allow_additional_properties() const { - return default_allow_additional_properties_; - } - - void set_default_allow_additional_properties(bool val) { - default_allow_additional_properties_ = val; - } - - // Returns any errors from the last call to to Validate(). - const std::vector<Error>& errors() const { - return errors_; - } - - // Validates a JSON value. Returns true if the instance is valid, false - // otherwise. If false is returned any errors are available from the errors() - // getter. - bool Validate(const base::Value* instance); - - private: - typedef std::map<std::string, const base::DictionaryValue*> TypeMap; - - // Each of the below methods handle a subset of the validation process. The - // path paramater is the path to |instance| from the root of the instance tree - // and is used in error messages. - - // Validates any instance node against any schema node. This is called for - // every node in the instance tree, and it just decides which of the more - // detailed methods to call. - void Validate(const base::Value* instance, - const base::DictionaryValue* schema, - const std::string& path); - - // Validates a node against a list of possible schemas. If any one of the - // schemas match, the node is valid. - void ValidateChoices(const base::Value* instance, - const base::ListValue* choices, - const std::string& path); - - // Validates a node against a list of exact primitive values, eg 42, "foobar". - void ValidateEnum(const base::Value* instance, - const base::ListValue* choices, - const std::string& path); - - // Validates a JSON object against an object schema node. - void ValidateObject(const base::DictionaryValue* instance, - const base::DictionaryValue* schema, - const std::string& path); - - // Validates a JSON array against an array schema node. - void ValidateArray(const base::ListValue* instance, - const base::DictionaryValue* schema, - const std::string& path); - - // Validates a JSON array against an array schema node configured to be a - // tuple. In a tuple, there is one schema node for each item expected in the - // array. - void ValidateTuple(const base::ListValue* instance, - const base::DictionaryValue* schema, - const std::string& path); - - // Validate a JSON string against a string schema node. - void ValidateString(const base::Value* instance, - const base::DictionaryValue* schema, - const std::string& path); - - // Validate a JSON number against a number schema node. - void ValidateNumber(const base::Value* instance, - const base::DictionaryValue* schema, - const std::string& path); - - // Validates that the JSON node |instance| has |expected_type|. - bool ValidateType(const base::Value* instance, - const std::string& expected_type, - const std::string& path); - - // Returns true if |schema| will allow additional items of any type. - bool SchemaAllowsAnyAdditionalItems( - const base::DictionaryValue* schema, - const base::DictionaryValue** addition_items_schema); - - // The root schema node. - base::DictionaryValue* schema_root_; - - // Map of user-defined name to type. - TypeMap types_; - - // Whether we allow additional properties on objects by default. This can be - // overridden by the allow_additional_properties flag on an Object schema. - bool default_allow_additional_properties_; - - // Errors accumulated since the last call to Validate(). - std::vector<Error> errors_; - - - DISALLOW_COPY_AND_ASSIGN(JSONSchemaValidator); -}; - -#endif // COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_H_ diff --git a/chromium/components/json_schema/json_schema_validator_unittest.cc b/chromium/components/json_schema/json_schema_validator_unittest.cc deleted file mode 100644 index 4844ed1a888..00000000000 --- a/chromium/components/json_schema/json_schema_validator_unittest.cc +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/values.h" -#include "components/json_schema/json_schema_validator.h" -#include "components/json_schema/json_schema_validator_unittest_base.h" -#include "testing/gtest/include/gtest/gtest.h" - -class JSONSchemaValidatorCPPTest : public JSONSchemaValidatorTestBase { - public: - JSONSchemaValidatorCPPTest() - : JSONSchemaValidatorTestBase(JSONSchemaValidatorTestBase::CPP) { - } - - protected: - virtual void ExpectValid(const std::string& test_source, - base::Value* instance, - base::DictionaryValue* schema, - base::ListValue* types) OVERRIDE { - JSONSchemaValidator validator(schema, types); - if (validator.Validate(instance)) - return; - - for (size_t i = 0; i < validator.errors().size(); ++i) { - ADD_FAILURE() << test_source << ": " - << validator.errors()[i].path << ": " - << validator.errors()[i].message; - } - } - - virtual void ExpectNotValid( - const std::string& test_source, - base::Value* instance, base::DictionaryValue* schema, - base::ListValue* types, - const std::string& expected_error_path, - const std::string& expected_error_message) OVERRIDE { - JSONSchemaValidator validator(schema, types); - if (validator.Validate(instance)) { - ADD_FAILURE() << test_source; - return; - } - - ASSERT_EQ(1u, validator.errors().size()) << test_source; - EXPECT_EQ(expected_error_path, validator.errors()[0].path) << test_source; - EXPECT_EQ(expected_error_message, validator.errors()[0].message) - << test_source; - } -}; - -TEST_F(JSONSchemaValidatorCPPTest, Test) { - RunTests(); -} - -TEST(JSONSchemaValidator, IsValidSchema) { - std::string error; - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("\0", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("string", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("\"string\"", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("[]", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema("{}", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( - "{ \"type\": 123 }", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( - "{ \"type\": \"invalid\" }", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( - "{" - " \"type\": \"object\"," - " \"properties\": []" // Invalid properties type. - "}", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( - "{" - " \"type\": \"string\"," - " \"maxLength\": -1" // Must be >= 0. - "}", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( - "{" - " \"type\": \"string\"," - " \"enum\": [ {} ]," // "enum" must contain simple values. - "}", &error)); - EXPECT_FALSE(JSONSchemaValidator::IsValidSchema( - "{" - " \"type\": \"array\"," - " \"items\": [ 123 ]," // "items" must contain a schema or schemas. - "}", &error)); - EXPECT_TRUE(JSONSchemaValidator::IsValidSchema( - "{ \"type\": \"object\" }", &error)) << error; - EXPECT_TRUE(JSONSchemaValidator::IsValidSchema( - "{ \"type\": [\"object\", \"array\"] }", &error)) << error; - EXPECT_TRUE(JSONSchemaValidator::IsValidSchema( - "{" - " \"type\": [\"object\", \"array\"]," - " \"properties\": {" - " \"string-property\": {" - " \"type\": \"string\"," - " \"minLength\": 1," - " \"maxLength\": 100," - " \"title\": \"The String Policy\"," - " \"description\": \"This policy controls the String widget.\"" - " }," - " \"integer-property\": {" - " \"type\": \"number\"," - " \"minimum\": 1000.0," - " \"maximum\": 9999.0" - " }," - " \"enum-property\": {" - " \"type\": \"integer\"," - " \"enum\": [0, 1, 10, 100]" - " }," - " \"items-property\": {" - " \"type\": \"array\"," - " \"items\": {" - " \"type\": \"string\"" - " }" - " }," - " \"items-list-property\": {" - " \"type\": \"array\"," - " \"items\": [" - " { \"type\": \"string\" }," - " { \"type\": \"integer\" }" - " ]" - " }" - " }," - " \"additionalProperties\": {" - " \"type\": \"any\"" - " }" - "}", &error)) << error; -} diff --git a/chromium/components/json_schema/json_schema_validator_unittest_base.cc b/chromium/components/json_schema/json_schema_validator_unittest_base.cc deleted file mode 100644 index 2e936a2eb9a..00000000000 --- a/chromium/components/json_schema/json_schema_validator_unittest_base.cc +++ /dev/null @@ -1,730 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/json_schema/json_schema_validator_unittest_base.h" - -#include <cfloat> -#include <cmath> -#include <limits> - -#include "base/base_paths.h" -#include "base/file_util.h" -#include "base/json/json_file_value_serializer.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/path_service.h" -#include "base/strings/stringprintf.h" -#include "base/values.h" -#include "components/json_schema/json_schema_constants.h" -#include "components/json_schema/json_schema_validator.h" - -namespace schema = json_schema_constants; - -namespace { - -#define TEST_SOURCE base::StringPrintf("%s:%i", __FILE__, __LINE__) - -base::Value* LoadValue(const std::string& filename) { - base::FilePath path; - PathService::Get(base::DIR_SOURCE_ROOT, &path); - path = path.AppendASCII("components") - .AppendASCII("test") - .AppendASCII("data") - .AppendASCII("json_schema") - .AppendASCII(filename); - EXPECT_TRUE(base::PathExists(path)); - - std::string error_message; - JSONFileValueSerializer serializer(path); - base::Value* result = serializer.Deserialize(NULL, &error_message); - if (!result) - ADD_FAILURE() << "Could not parse JSON: " << error_message; - return result; -} - -base::Value* LoadValue(const std::string& filename, base::Value::Type type) { - scoped_ptr<base::Value> result(LoadValue(filename)); - if (!result.get()) - return NULL; - if (!result->IsType(type)) { - ADD_FAILURE() << "Expected type " << type << ", got: " << result->GetType(); - return NULL; - } - return result.release(); -} - -base::ListValue* LoadList(const std::string& filename) { - return static_cast<base::ListValue*>( - LoadValue(filename, base::Value::TYPE_LIST)); -} - -base::DictionaryValue* LoadDictionary(const std::string& filename) { - return static_cast<base::DictionaryValue*>( - LoadValue(filename, base::Value::TYPE_DICTIONARY)); -} - -} // namespace - - -JSONSchemaValidatorTestBase::JSONSchemaValidatorTestBase( - JSONSchemaValidatorTestBase::ValidatorType type) - : type_(type) { -} - -void JSONSchemaValidatorTestBase::RunTests() { - TestComplex(); - TestStringPattern(); - TestEnum(); - TestChoices(); - TestExtends(); - TestObject(); - TestTypeReference(); - TestArrayTuple(); - TestArrayNonTuple(); - TestString(); - TestNumber(); - TestTypeClassifier(); - TestTypes(); -} - -void JSONSchemaValidatorTestBase::TestComplex() { - scoped_ptr<base::DictionaryValue> schema( - LoadDictionary("complex_schema.json")); - scoped_ptr<base::ListValue> instance(LoadList("complex_instance.json")); - - ASSERT_TRUE(schema.get()); - ASSERT_TRUE(instance.get()); - - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Remove(instance->GetSize() - 1, NULL); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Append(new base::DictionaryValue()); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "1", - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kNumber, - schema::kObject)); - instance->Remove(instance->GetSize() - 1, NULL); - - base::DictionaryValue* item = NULL; - ASSERT_TRUE(instance->GetDictionary(0, &item)); - item->SetString("url", "xxxxxxxxxxx"); - - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, - "0.url", - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kStringMaxLength, "10")); -} - -void JSONSchemaValidatorTestBase::TestStringPattern() { - // Regex patterns not supported in CPP validator. - if (type_ == CPP) - return; - - scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); - schema->SetString(schema::kType, schema::kString); - schema->SetString(schema::kPattern, "foo+"); - - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("foo")).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("foooooo")).get(), - schema.get(), NULL); - ExpectNotValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("bar")).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kStringPattern, "foo+")); -} - -void JSONSchemaValidatorTestBase::TestEnum() { - scoped_ptr<base::DictionaryValue> schema(LoadDictionary("enum_schema.json")); - - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("foo")).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(false)).get(), - schema.get(), NULL); - - ExpectNotValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("42")).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::kInvalidEnum); - ExpectNotValid(TEST_SOURCE, - scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::kInvalidEnum); -} - -void JSONSchemaValidatorTestBase::TestChoices() { - scoped_ptr<base::DictionaryValue> schema( - LoadDictionary("choices_schema.json")); - - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), NULL); - - scoped_ptr<base::DictionaryValue> instance(new base::DictionaryValue()); - instance->SetString("foo", "bar"); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - ExpectNotValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("foo")).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::kInvalidChoice); - ExpectNotValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::ListValue()).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::kInvalidChoice); - - instance->SetInteger("foo", 42); - ExpectNotValid(TEST_SOURCE, - instance.get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::kInvalidChoice); -} - -void JSONSchemaValidatorTestBase::TestExtends() { - // TODO(aa): JS only -} - -void JSONSchemaValidatorTestBase::TestObject() { - scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); - schema->SetString(schema::kType, schema::kObject); - schema->SetString("properties.foo.type", schema::kString); - schema->SetString("properties.bar.type", schema::kInteger); - - scoped_ptr<base::DictionaryValue> instance(new base::DictionaryValue()); - instance->SetString("foo", "foo"); - instance->SetInteger("bar", 42); - - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - instance->SetBoolean("extra", true); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, - "extra", JSONSchemaValidator::kUnexpectedProperty); - - instance->Remove("extra", NULL); - instance->Remove("bar", NULL); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "bar", - JSONSchemaValidator::kObjectPropertyIsRequired); - - instance->SetString("bar", "42"); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "bar", - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kInteger, - schema::kString)); - - base::DictionaryValue* additional_properties = new base::DictionaryValue(); - additional_properties->SetString(schema::kType, schema::kAny); - schema->Set(schema::kAdditionalProperties, additional_properties); - - instance->SetInteger("bar", 42); - instance->SetBoolean("extra", true); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - instance->SetString("extra", "foo"); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - additional_properties->SetString(schema::kType, schema::kBoolean); - instance->SetBoolean("extra", true); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - instance->SetString("extra", "foo"); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, - "extra", JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kBoolean, - schema::kString)); - - base::DictionaryValue* properties = NULL; - base::DictionaryValue* bar_property = NULL; - ASSERT_TRUE(schema->GetDictionary(schema::kProperties, &properties)); - ASSERT_TRUE(properties->GetDictionary("bar", &bar_property)); - - bar_property->SetBoolean(schema::kOptional, true); - instance->Remove("extra", NULL); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Remove("bar", NULL); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Set("bar", base::Value::CreateNullValue()); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, - "bar", JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kInteger, - schema::kNull)); - instance->SetString("bar", "42"); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, - "bar", JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kInteger, - schema::kString)); -} - -void JSONSchemaValidatorTestBase::TestTypeReference() { - scoped_ptr<base::ListValue> types(LoadList("reference_types.json")); - ASSERT_TRUE(types.get()); - - scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); - schema->SetString(schema::kType, schema::kObject); - schema->SetString("properties.foo.type", schema::kString); - schema->SetString("properties.bar.$ref", "Max10Int"); - schema->SetString("properties.baz.$ref", "MinLengthString"); - - scoped_ptr<base::DictionaryValue> schema_inline(new base::DictionaryValue()); - schema_inline->SetString(schema::kType, schema::kObject); - schema_inline->SetString("properties.foo.type", schema::kString); - schema_inline->SetString("properties.bar.id", "NegativeInt"); - schema_inline->SetString("properties.bar.type", schema::kInteger); - schema_inline->SetInteger("properties.bar.maximum", 0); - schema_inline->SetString("properties.baz.$ref", "NegativeInt"); - - scoped_ptr<base::DictionaryValue> instance(new base::DictionaryValue()); - instance->SetString("foo", "foo"); - instance->SetInteger("bar", 4); - instance->SetString("baz", "ab"); - - scoped_ptr<base::DictionaryValue> instance_inline( - new base::DictionaryValue()); - instance_inline->SetString("foo", "foo"); - instance_inline->SetInteger("bar", -4); - instance_inline->SetInteger("baz", -2); - - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), types.get()); - ExpectValid(TEST_SOURCE, instance_inline.get(), schema_inline.get(), NULL); - - // Validation failure, but successful schema reference. - instance->SetString("baz", "a"); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), types.get(), - "baz", JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kStringMinLength, "2")); - - instance_inline->SetInteger("bar", 20); - ExpectNotValid(TEST_SOURCE, instance_inline.get(), schema_inline.get(), NULL, - "bar", JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kNumberMaximum, "0")); - - // Remove MinLengthString type. - types->Remove(types->GetSize() - 1, NULL); - instance->SetString("baz", "ab"); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), types.get(), - "bar", JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kUnknownTypeReference, - "Max10Int")); - - // Remove internal type "NegativeInt". - schema_inline->Remove("properties.bar", NULL); - instance_inline->Remove("bar", NULL); - ExpectNotValid(TEST_SOURCE, instance_inline.get(), schema_inline.get(), NULL, - "baz", JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kUnknownTypeReference, - "NegativeInt")); -} - -void JSONSchemaValidatorTestBase::TestArrayTuple() { - scoped_ptr<base::DictionaryValue> schema( - LoadDictionary("array_tuple_schema.json")); - ASSERT_TRUE(schema.get()); - - scoped_ptr<base::ListValue> instance(new base::ListValue()); - instance->Append(new base::StringValue("42")); - instance->Append(new base::FundamentalValue(42)); - - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - instance->Append(new base::StringValue("anything")); - ExpectNotValid(TEST_SOURCE, - instance.get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kArrayMaxItems, "2")); - - instance->Remove(1, NULL); - instance->Remove(1, NULL); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "1", - JSONSchemaValidator::kArrayItemRequired); - - instance->Set(0, new base::FundamentalValue(42)); - instance->Append(new base::FundamentalValue(42)); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "0", - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kString, - schema::kInteger)); - - base::DictionaryValue* additional_properties = new base::DictionaryValue(); - additional_properties->SetString(schema::kType, schema::kAny); - schema->Set(schema::kAdditionalProperties, additional_properties); - instance->Set(0, new base::StringValue("42")); - instance->Append(new base::StringValue("anything")); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Set(2, new base::ListValue()); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - additional_properties->SetString(schema::kType, schema::kBoolean); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "2", - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kBoolean, - schema::kArray)); - instance->Set(2, new base::FundamentalValue(false)); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - base::ListValue* items_schema = NULL; - base::DictionaryValue* item0_schema = NULL; - ASSERT_TRUE(schema->GetList(schema::kItems, &items_schema)); - ASSERT_TRUE(items_schema->GetDictionary(0, &item0_schema)); - item0_schema->SetBoolean(schema::kOptional, true); - instance->Remove(2, NULL); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - // TODO(aa): I think this is inconsistent with the handling of NULL+optional - // for objects. - instance->Set(0, base::Value::CreateNullValue()); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Set(0, new base::FundamentalValue(42)); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "0", - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kString, - schema::kInteger)); -} - -void JSONSchemaValidatorTestBase::TestArrayNonTuple() { - scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); - schema->SetString(schema::kType, schema::kArray); - schema->SetString("items.type", schema::kString); - schema->SetInteger(schema::kMinItems, 2); - schema->SetInteger(schema::kMaxItems, 3); - - scoped_ptr<base::ListValue> instance(new base::ListValue()); - instance->Append(new base::StringValue("x")); - instance->Append(new base::StringValue("x")); - - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - instance->Append(new base::StringValue("x")); - ExpectValid(TEST_SOURCE, instance.get(), schema.get(), NULL); - - instance->Append(new base::StringValue("x")); - ExpectNotValid(TEST_SOURCE, - instance.get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kArrayMaxItems, "3")); - instance->Remove(1, NULL); - instance->Remove(1, NULL); - instance->Remove(1, NULL); - ExpectNotValid(TEST_SOURCE, - instance.get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kArrayMinItems, "2")); - - instance->Remove(1, NULL); - instance->Append(new base::FundamentalValue(42)); - ExpectNotValid(TEST_SOURCE, instance.get(), schema.get(), NULL, "1", - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, - schema::kString, - schema::kInteger)); -} - -void JSONSchemaValidatorTestBase::TestString() { - scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); - schema->SetString(schema::kType, schema::kString); - schema->SetInteger(schema::kMinLength, 1); - schema->SetInteger(schema::kMaxLength, 10); - - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("x")).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>( - new base::StringValue("xxxxxxxxxx")).get(), - schema.get(), NULL); - - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue(std::string())).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kStringMinLength, "1")); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("xxxxxxxxxxx")).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kStringMaxLength, "10")); -} - -void JSONSchemaValidatorTestBase::TestNumber() { - scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); - schema->SetString(schema::kType, schema::kNumber); - schema->SetInteger(schema::kMinimum, 1); - schema->SetInteger(schema::kMaximum, 100); - schema->SetInteger("maxDecimal", 2); - - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(1)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(50)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(100)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(88.88)).get(), - schema.get(), NULL); - - ExpectNotValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(0.5)).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kNumberMinimum, "1")); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(100.1)).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kNumberMaximum, "100")); -} - -void JSONSchemaValidatorTestBase::TestTypeClassifier() { - EXPECT_EQ(std::string(schema::kBoolean), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>( - new base::FundamentalValue(true)).get())); - EXPECT_EQ(std::string(schema::kBoolean), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>( - new base::FundamentalValue(false)).get())); - - // It doesn't matter whether the C++ type is 'integer' or 'real'. If the - // number is integral and within the representable range of integers in - // double, it's classified as 'integer'. - EXPECT_EQ(std::string(schema::kInteger), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get())); - EXPECT_EQ(std::string(schema::kInteger), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>(new base::FundamentalValue(0)).get())); - EXPECT_EQ(std::string(schema::kInteger), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get())); - EXPECT_EQ(std::string(schema::kInteger), - JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( - new base::FundamentalValue(pow(2.0, DBL_MANT_DIG))).get())); - EXPECT_EQ(std::string(schema::kInteger), - JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( - new base::FundamentalValue(pow(-2.0, DBL_MANT_DIG))).get())); - - // "number" is only used for non-integral numbers, or numbers beyond what - // double can accurately represent. - EXPECT_EQ(std::string(schema::kNumber), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>( - new base::FundamentalValue(88.8)).get())); - EXPECT_EQ(std::string(schema::kNumber), - JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( - new base::FundamentalValue(pow(2.0, DBL_MANT_DIG) * 2)).get())); - EXPECT_EQ(std::string(schema::kNumber), - JSONSchemaValidator::GetJSONSchemaType(scoped_ptr<base::Value>( - new base::FundamentalValue( - pow(-2.0, DBL_MANT_DIG) * 2)).get())); - - EXPECT_EQ(std::string(schema::kString), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>(new base::StringValue("foo")).get())); - EXPECT_EQ(std::string(schema::kArray), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>(new base::ListValue()).get())); - EXPECT_EQ(std::string(schema::kObject), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>(new base::DictionaryValue()).get())); - EXPECT_EQ(std::string(schema::kNull), - JSONSchemaValidator::GetJSONSchemaType( - scoped_ptr<base::Value>(base::Value::CreateNullValue()).get())); -} - -void JSONSchemaValidatorTestBase::TestTypes() { - scoped_ptr<base::DictionaryValue> schema(new base::DictionaryValue()); - - // valid - schema->SetString(schema::kType, schema::kObject); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::DictionaryValue()).get(), - schema.get(), NULL); - - schema->SetString(schema::kType, schema::kArray); - ExpectValid(TEST_SOURCE, scoped_ptr<base::Value>(new base::ListValue()).get(), - schema.get(), NULL); - - schema->SetString(schema::kType, schema::kString); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("foobar")).get(), - schema.get(), NULL); - - schema->SetString(schema::kType, schema::kNumber); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(88.8)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(0)).get(), - schema.get(), NULL); - - schema->SetString(schema::kType, schema::kInteger); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(0)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>( - new base::FundamentalValue(pow(2.0, DBL_MANT_DIG))).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>( - new base::FundamentalValue(pow(-2.0, DBL_MANT_DIG))).get(), - schema.get(), NULL); - - schema->SetString(schema::kType, schema::kBoolean); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(false)).get(), - schema.get(), NULL); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(true)).get(), - schema.get(), NULL); - - schema->SetString(schema::kType, schema::kNull); - ExpectValid(TEST_SOURCE, - scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), - schema.get(), NULL); - - // not valid - schema->SetString(schema::kType, schema::kObject); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::ListValue()).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, schema::kObject, schema::kArray)); - - schema->SetString(schema::kType, schema::kObject); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(base::Value::CreateNullValue()).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, schema::kObject, schema::kNull)); - - schema->SetString(schema::kType, schema::kArray); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, schema::kArray, schema::kInteger)); - - schema->SetString(schema::kType, schema::kString); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(42)).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage(JSONSchemaValidator::kInvalidType, - schema::kString, - schema::kInteger)); - - schema->SetString(schema::kType, schema::kNumber); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::StringValue("42")).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, schema::kNumber, schema::kString)); - - schema->SetString(schema::kType, schema::kInteger); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(88.8)).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::kInvalidTypeIntegerNumber); - - schema->SetString(schema::kType, schema::kBoolean); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(1)).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage(JSONSchemaValidator::kInvalidType, - schema::kBoolean, - schema::kInteger)); - - schema->SetString(schema::kType, schema::kNull); - ExpectNotValid( - TEST_SOURCE, - scoped_ptr<base::Value>(new base::FundamentalValue(false)).get(), - schema.get(), - NULL, - std::string(), - JSONSchemaValidator::FormatErrorMessage( - JSONSchemaValidator::kInvalidType, schema::kNull, schema::kBoolean)); -} diff --git a/chromium/components/json_schema/json_schema_validator_unittest_base.h b/chromium/components/json_schema/json_schema_validator_unittest_base.h deleted file mode 100644 index 7b4854e21e8..00000000000 --- a/chromium/components/json_schema/json_schema_validator_unittest_base.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_UNITTEST_BASE_H_ -#define COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_UNITTEST_BASE_H_ - -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { -class DictionaryValue; -class ListValue; -class Value; -} - -// Base class for unit tests for JSONSchemaValidator. There is currently only -// one implementation, JSONSchemaValidatorCPPTest. -// -// TODO(aa): Refactor chrome/test/data/json_schema_test.js into -// JSONSchemaValidatorJSTest that inherits from this. -class JSONSchemaValidatorTestBase : public testing::Test { - public: - enum ValidatorType { - CPP = 1, - JS = 2 - }; - - explicit JSONSchemaValidatorTestBase(ValidatorType type); - - void RunTests(); - - protected: - virtual void ExpectValid(const std::string& test_source, - base::Value* instance, - base::DictionaryValue* schema, - base::ListValue* types) = 0; - - virtual void ExpectNotValid(const std::string& test_source, - base::Value* instance, - base::DictionaryValue* schema, - base::ListValue* types, - const std::string& expected_error_path, - const std::string& expected_error_message) = 0; - - private: - void TestComplex(); - void TestStringPattern(); - void TestEnum(); - void TestChoices(); - void TestExtends(); - void TestObject(); - void TestTypeReference(); - void TestArrayTuple(); - void TestArrayNonTuple(); - void TestString(); - void TestNumber(); - void TestTypeClassifier(); - void TestTypes(); - - ValidatorType type_; -}; - -#endif // COMPONENTS_JSON_SCHEMA_JSON_SCHEMA_VALIDATOR_UNITTEST_BASE_H_ diff --git a/chromium/components/nacl/common/nacl_cmd_line.cc b/chromium/components/nacl/common/nacl_cmd_line.cc index d9bbd6557f4..b21a671ae1d 100644 --- a/chromium/components/nacl/common/nacl_cmd_line.cc +++ b/chromium/components/nacl/common/nacl_cmd_line.cc @@ -18,6 +18,7 @@ void CopyNaClCommandLineArguments(CommandLine* cmd_line) { // TODO(gregoryd): check which flags of those below can be supported. static const char* const kSwitchNames[] = { switches::kNoSandbox, + switches::kTestNaClSandbox, switches::kDisableBreakpad, switches::kFullMemoryCrashReport, switches::kEnableLogging, diff --git a/chromium/components/nacl/common/nacl_switches.cc b/chromium/components/nacl/common/nacl_switches.cc index 0dfdc949857..b9db537b252 100644 --- a/chromium/components/nacl/common/nacl_switches.cc +++ b/chromium/components/nacl/common/nacl_switches.cc @@ -36,4 +36,7 @@ const char kNaClLoaderCmdPrefix[] = "nacl-loader-cmd-prefix"; // Causes the process to run as a NativeClient loader. const char kNaClLoaderProcess[] = "nacl-loader"; +// Runs the security test for the NaCl loader sandbox. +const char kTestNaClSandbox[] = "test-nacl-sandbox"; + } // namespace switches diff --git a/chromium/components/nacl/common/nacl_switches.h b/chromium/components/nacl/common/nacl_switches.h index 9bc1bcb4697..8b12206a21a 100644 --- a/chromium/components/nacl/common/nacl_switches.h +++ b/chromium/components/nacl/common/nacl_switches.h @@ -18,6 +18,7 @@ extern const char kNaClGdb[]; extern const char kNaClGdbScript[]; extern const char kNaClLoaderCmdPrefix[]; extern const char kNaClLoaderProcess[]; +extern const char kTestNaClSandbox[]; } // namespace switches diff --git a/chromium/components/nacl/loader/nacl_main.cc b/chromium/components/nacl/loader/nacl_main.cc index 15b6fd2dc8c..a9ec5c93c37 100644 --- a/chromium/components/nacl/loader/nacl_main.cc +++ b/chromium/components/nacl/loader/nacl_main.cc @@ -29,7 +29,10 @@ int NaClMain(const content::MainFunctionParams& parameters) { #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) NaClMainPlatformDelegate platform(parameters); + + platform.PlatformInitialize(); bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); + platform.InitSandboxTests(no_sandbox); #if defined(OS_POSIX) // The number of cores must be obtained before the invocation of @@ -40,14 +43,25 @@ int NaClMain(const content::MainFunctionParams& parameters) { if (!no_sandbox) { platform.EnableSandbox(); } - NaClListener listener; + bool sandbox_test_result = platform.RunSandboxTests(); + + if (sandbox_test_result) { + NaClListener listener; #if defined(OS_POSIX) - listener.set_number_of_cores(number_of_cores); + listener.set_number_of_cores(number_of_cores); #endif - - listener.Listen(); + listener.Listen(); + } else { + // This indirectly prevents the test-harness-success-cookie from being set, + // as a way of communicating test failure, because the nexe won't reply. + // TODO(jvoung): find a better way to indicate failure that doesn't + // require waiting for a timeout. + VLOG(1) << "Sandbox test failed: Not launching NaCl process"; + } #else NOTIMPLEMENTED() << " not implemented startup, plugin startup dialog etc."; #endif + + platform.PlatformUninitialize(); return 0; } diff --git a/chromium/components/nacl/loader/nacl_main_platform_delegate.h b/chromium/components/nacl/loader/nacl_main_platform_delegate.h index ca740b85bcd..191831cfefe 100644 --- a/chromium/components/nacl/loader/nacl_main_platform_delegate.h +++ b/chromium/components/nacl/loader/nacl_main_platform_delegate.h @@ -5,20 +5,38 @@ #ifndef CHROME_NACL_NACL_MAIN_PLATFORM_DELEGATE_H_ #define CHROME_NACL_NACL_MAIN_PLATFORM_DELEGATE_H_ -#include "base/basictypes.h" +#include "base/native_library.h" #include "content/public/common/main_function_params.h" +typedef bool (*RunNaClLoaderTests)(void); +const char kNaClLoaderTestCall[] = "RunNaClLoaderTests"; + class NaClMainPlatformDelegate { public: explicit NaClMainPlatformDelegate( const content::MainFunctionParams& parameters); ~NaClMainPlatformDelegate(); + // Called first thing and last thing in the process' lifecycle, i.e. before + // the sandbox is enabled. + void PlatformInitialize(); + void PlatformUninitialize(); + + // Gives us an opportunity to initialize state used for tests before enabling + // the sandbox. + void InitSandboxTests(bool no_sandbox); + // Initiate Lockdown. void EnableSandbox(); + // Runs the sandbox tests for the NaCl Loader, if tests supplied. + // Cannot run again, after this (resources freed). + // Returns false if the tests are supplied and fail. + bool RunSandboxTests(); + private: const content::MainFunctionParams& parameters_; + base::NativeLibrary sandbox_test_module_; DISALLOW_COPY_AND_ASSIGN(NaClMainPlatformDelegate); }; diff --git a/chromium/components/nacl/loader/nacl_main_platform_delegate_linux.cc b/chromium/components/nacl/loader/nacl_main_platform_delegate_linux.cc index cbe886bc006..e9d2f731787 100644 --- a/chromium/components/nacl/loader/nacl_main_platform_delegate_linux.cc +++ b/chromium/components/nacl/loader/nacl_main_platform_delegate_linux.cc @@ -4,14 +4,28 @@ #include "components/nacl/loader/nacl_main_platform_delegate.h" +#include "base/command_line.h" + NaClMainPlatformDelegate::NaClMainPlatformDelegate( const content::MainFunctionParams& parameters) - : parameters_(parameters) { + : parameters_(parameters), sandbox_test_module_(NULL) { } NaClMainPlatformDelegate::~NaClMainPlatformDelegate() { } +void NaClMainPlatformDelegate::PlatformInitialize() { +} + +void NaClMainPlatformDelegate::PlatformUninitialize() { +} + +void NaClMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { + // The sandbox is started in the zygote process: zygote_main_linux.cc + // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox + return; +} + void NaClMainPlatformDelegate::EnableSandbox() { // The setuid sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox @@ -29,3 +43,9 @@ void NaClMainPlatformDelegate::EnableSandbox() { // At best, NaCl will not work. At worst, enabling the seccomp sandbox // could create a hole in the NaCl sandbox. } + +bool NaClMainPlatformDelegate::RunSandboxTests() { + // The sandbox is started in the zygote process: zygote_main_linux.cc + // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox + return true; +} diff --git a/chromium/components/nacl/loader/nacl_main_platform_delegate_mac.mm b/chromium/components/nacl/loader/nacl_main_platform_delegate_mac.mm index 78fa5390454..67ddced4396 100644 --- a/chromium/components/nacl/loader/nacl_main_platform_delegate_mac.mm +++ b/chromium/components/nacl/loader/nacl_main_platform_delegate_mac.mm @@ -5,22 +5,78 @@ #include "components/nacl/loader/nacl_main_platform_delegate.h" #import <Cocoa/Cocoa.h> +#include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" +#include "base/native_library.h" #include "components/nacl/common/nacl_sandbox_type_mac.h" #include "components/nacl/common/nacl_switches.h" #include "content/public/common/sandbox_init.h" NaClMainPlatformDelegate::NaClMainPlatformDelegate( const content::MainFunctionParams& parameters) - : parameters_(parameters) { + : parameters_(parameters), sandbox_test_module_(NULL) { } NaClMainPlatformDelegate::~NaClMainPlatformDelegate() { } +// TODO(jvoung): see if this old comment (from renderer_main_platform...) +// is relevant to the nacl loader. +// TODO(mac-port): Any code needed to initialize a process for purposes of +// running a NaClLoader needs to also be reflected in chrome_main.cc for +// --single-process support. +void NaClMainPlatformDelegate::PlatformInitialize() { +} + +void NaClMainPlatformDelegate::PlatformUninitialize() { +} + +void NaClMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { + const CommandLine& command_line = parameters_.command_line; + + DVLOG(1) << "Started NaClLdr with "; + const std::vector<std::string>& argstrings = command_line.argv(); + for (std::vector<std::string>::const_iterator ii = argstrings.begin(); + ii != argstrings.end(); ++ii) + DVLOG(1) << *ii; + + // Be sure not to load the sandbox test DLL if the sandbox isn't on. + // Comment-out guard and recompile if you REALLY want to test w/out the SB. + // TODO(jvoung): allow testing without sandbox, but change expected ret vals. + if (!no_sandbox) { + base::FilePath test_dll_name = + command_line.GetSwitchValuePath(switches::kTestNaClSandbox); + if (!test_dll_name.empty()) { + sandbox_test_module_ = base::LoadNativeLibrary(test_dll_name, NULL); + CHECK(sandbox_test_module_); + } + } +} + void NaClMainPlatformDelegate::EnableSandbox() { CHECK(content::InitializeSandbox(NACL_SANDBOX_TYPE_NACL_LOADER, base::FilePath())) << "Error initializing sandbox for " << switches::kNaClLoaderProcess; } + +bool NaClMainPlatformDelegate::RunSandboxTests() { + // TODO(jvoung): Win and mac should share this identical code. + bool result = true; + if (sandbox_test_module_) { + RunNaClLoaderTests run_security_tests = + reinterpret_cast<RunNaClLoaderTests>( + base::GetFunctionPointerFromNativeLibrary(sandbox_test_module_, + kNaClLoaderTestCall)); + if (run_security_tests) { + DVLOG(1) << "Running NaCl Loader security tests"; + result = (*run_security_tests)(); + } else { + VLOG(1) << "Failed to get NaCl sandbox test function"; + result = false; + } + base::UnloadNativeLibrary(sandbox_test_module_); + sandbox_test_module_ = NULL; + } + return result; +} diff --git a/chromium/components/nacl/loader/nacl_main_platform_delegate_win.cc b/chromium/components/nacl/loader/nacl_main_platform_delegate_win.cc index f530961700f..e79fe17725c 100644 --- a/chromium/components/nacl/loader/nacl_main_platform_delegate_win.cc +++ b/chromium/components/nacl/loader/nacl_main_platform_delegate_win.cc @@ -4,17 +4,59 @@ #include "components/nacl/loader/nacl_main_platform_delegate.h" +#include "base/command_line.h" +#include "base/files/file_path.h" #include "base/logging.h" +#include "base/native_library.h" +#include "components/nacl/common/nacl_switches.h" #include "sandbox/win/src/sandbox.h" NaClMainPlatformDelegate::NaClMainPlatformDelegate( const content::MainFunctionParams& parameters) - : parameters_(parameters) { + : parameters_(parameters), sandbox_test_module_(NULL) { } NaClMainPlatformDelegate::~NaClMainPlatformDelegate() { } +void NaClMainPlatformDelegate::PlatformInitialize() { + // Be mindful of what resources you acquire here. They can be used by + // malicious code if the renderer gets compromised. +} + +void NaClMainPlatformDelegate::PlatformUninitialize() { +} + +void NaClMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { + const CommandLine& command_line = parameters_.command_line; + + DVLOG(1) << "Started NaClLdr with " << command_line.GetCommandLineString(); + + sandbox::TargetServices* target_services = + parameters_.sandbox_info->target_services; + + if (target_services && !no_sandbox) { + base::FilePath test_dll_name = + command_line.GetSwitchValuePath(switches::kTestNaClSandbox); + if (!test_dll_name.empty()) { + // At this point, hack on the suffix according to with bitness + // of your windows process. +#if defined(_WIN64) + DVLOG(1) << "Using 64-bit test dll\n"; + test_dll_name = test_dll_name.InsertBeforeExtension(L"64"); + test_dll_name = test_dll_name.ReplaceExtension(L"dll"); +#else + DVLOG(1) << "Using 32-bit test dll\n"; + test_dll_name = test_dll_name.ReplaceExtension(L"dll"); +#endif + DVLOG(1) << "Loading test lib " << test_dll_name.value() << "\n"; + sandbox_test_module_ = base::LoadNativeLibrary(test_dll_name, NULL); + CHECK(sandbox_test_module_); + VLOG(1) << "Testing NaCl sandbox\n"; + } + } +} + void NaClMainPlatformDelegate::EnableSandbox() { sandbox::TargetServices* target_services = parameters_.sandbox_info->target_services; @@ -29,3 +71,24 @@ void NaClMainPlatformDelegate::EnableSandbox() { // Turn the sandbox on. target_services->LowerToken(); } + +bool NaClMainPlatformDelegate::RunSandboxTests() { + // TODO(jvoung): Win and mac should share this code. + bool result = true; + if (sandbox_test_module_) { + RunNaClLoaderTests run_security_tests = + reinterpret_cast<RunNaClLoaderTests>( + base::GetFunctionPointerFromNativeLibrary(sandbox_test_module_, + kNaClLoaderTestCall)); + if (run_security_tests) { + DVLOG(1) << "Running NaCl Loader security tests"; + result = (*run_security_tests)(); + } else { + VLOG(1) << "Failed to get NaCl sandbox test function"; + result = false; + } + base::UnloadNativeLibrary(sandbox_test_module_); + sandbox_test_module_ = NULL; + } + return result; +} diff --git a/chromium/components/policy.gypi b/chromium/components/policy.gypi deleted file mode 100644 index 5295ba46e96..00000000000 --- a/chromium/components/policy.gypi +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'targets': [ - { - 'target_name': 'policy_component', - 'type': '<(component)', - 'dependencies': [ - '../base/base.gyp:base', - 'json_schema', - ], - 'defines': [ - 'POLICY_COMPONENT_IMPLEMENTATION', - ], - 'include_dirs': [ - '..', - ], - 'conditions': [ - ['configuration_policy==1', { - 'sources': [ - 'policy/core/common/policy_schema.cc', - 'policy/core/common/policy_schema.h', - 'policy/policy_export.h', - ], - }, { # configuration_policy==0 - # The target 'policy_component' always exists. Later it will include - # some stubs when configuration_policy==0. For now this stub file is - # compiled so that an output is produced, otherwise the shared build - # breaks on iOS. - # TODO(joaodasilva): remove this comment and the temporary stub after - # moving one of the real stubs. http://crbug.com/271392 - 'sources': [ - 'policy/stub_to_remove.cc', - ], - }], - ], - }, - ], -} diff --git a/chromium/components/policy/OWNERS b/chromium/components/policy/OWNERS deleted file mode 100644 index dbccb7c3a0c..00000000000 --- a/chromium/components/policy/OWNERS +++ /dev/null @@ -1,6 +0,0 @@ -mnissler@chromium.org -pastarmovj@chromium.org -joaodasilva@chromium.org -bartfab@chromium.org -atwilson@chromium.org -pneubeck@chromium.org diff --git a/chromium/components/policy/core/common/policy_schema.cc b/chromium/components/policy/core/common/policy_schema.cc deleted file mode 100644 index 8c3145ce43a..00000000000 --- a/chromium/components/policy/core/common/policy_schema.cc +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/policy/core/common/policy_schema.h" - -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/stl_util.h" -#include "components/json_schema/json_schema_constants.h" -#include "components/json_schema/json_schema_validator.h" - -namespace policy { - -namespace { - -const char kJSONSchemaVersion[] = "http://json-schema.org/draft-03/schema#"; - -// Describes the properties of a TYPE_DICTIONARY policy schema. -class DictionaryPolicySchema : public PolicySchema { - public: - static scoped_ptr<PolicySchema> Parse(const base::DictionaryValue& schema, - std::string* error); - - virtual ~DictionaryPolicySchema(); - - virtual const PolicySchemaMap* GetProperties() const OVERRIDE; - virtual const PolicySchema* GetSchemaForAdditionalProperties() const OVERRIDE; - - private: - DictionaryPolicySchema(); - - PolicySchemaMap properties_; - scoped_ptr<PolicySchema> additional_properties_; - - DISALLOW_COPY_AND_ASSIGN(DictionaryPolicySchema); -}; - -// Describes the items of a TYPE_LIST policy schema. -class ListPolicySchema : public PolicySchema { - public: - static scoped_ptr<PolicySchema> Parse(const base::DictionaryValue& schema, - std::string* error); - - virtual ~ListPolicySchema(); - - virtual const PolicySchema* GetSchemaForItems() const OVERRIDE; - - private: - ListPolicySchema(); - - scoped_ptr<PolicySchema> items_schema_; - - DISALLOW_COPY_AND_ASSIGN(ListPolicySchema); -}; - -bool SchemaTypeToValueType(const std::string& type_string, - base::Value::Type* type) { - // Note: "any" is not an accepted type. - static const struct { - const char* schema_type; - base::Value::Type value_type; - } kSchemaToValueTypeMap[] = { - { json_schema_constants::kArray, base::Value::TYPE_LIST }, - { json_schema_constants::kBoolean, base::Value::TYPE_BOOLEAN }, - { json_schema_constants::kInteger, base::Value::TYPE_INTEGER }, - { json_schema_constants::kNull, base::Value::TYPE_NULL }, - { json_schema_constants::kNumber, base::Value::TYPE_DOUBLE }, - { json_schema_constants::kObject, base::Value::TYPE_DICTIONARY }, - { json_schema_constants::kString, base::Value::TYPE_STRING }, - }; - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kSchemaToValueTypeMap); ++i) { - if (kSchemaToValueTypeMap[i].schema_type == type_string) { - *type = kSchemaToValueTypeMap[i].value_type; - return true; - } - } - return false; -} - -scoped_ptr<PolicySchema> ParseSchema(const base::DictionaryValue& schema, - std::string* error) { - std::string type_string; - if (!schema.GetString(json_schema_constants::kType, &type_string)) { - *error = "The schema type must be declared."; - return scoped_ptr<PolicySchema>(); - } - - base::Value::Type type = base::Value::TYPE_NULL; - if (!SchemaTypeToValueType(type_string, &type)) { - *error = "The \"any\" type can't be used."; - return scoped_ptr<PolicySchema>(); - } - - switch (type) { - case base::Value::TYPE_DICTIONARY: - return DictionaryPolicySchema::Parse(schema, error); - case base::Value::TYPE_LIST: - return ListPolicySchema::Parse(schema, error); - default: - return make_scoped_ptr(new PolicySchema(type)); - } -} - -DictionaryPolicySchema::DictionaryPolicySchema() - : PolicySchema(base::Value::TYPE_DICTIONARY) {} - -DictionaryPolicySchema::~DictionaryPolicySchema() { - STLDeleteValues(&properties_); -} - -const PolicySchemaMap* DictionaryPolicySchema::GetProperties() const { - return &properties_; -} - -const PolicySchema* - DictionaryPolicySchema::GetSchemaForAdditionalProperties() const { - return additional_properties_.get(); -} - -// static -scoped_ptr<PolicySchema> DictionaryPolicySchema::Parse( - const base::DictionaryValue& schema, - std::string* error) { - scoped_ptr<DictionaryPolicySchema> dict_schema(new DictionaryPolicySchema()); - - const base::DictionaryValue* dict = NULL; - const base::DictionaryValue* properties = NULL; - if (schema.GetDictionary(json_schema_constants::kProperties, &properties)) { - for (base::DictionaryValue::Iterator it(*properties); - !it.IsAtEnd(); it.Advance()) { - // This should have been verified by the JSONSchemaValidator. - CHECK(it.value().GetAsDictionary(&dict)); - scoped_ptr<PolicySchema> sub_schema = ParseSchema(*dict, error); - if (!sub_schema) - return scoped_ptr<PolicySchema>(); - dict_schema->properties_[it.key()] = sub_schema.release(); - } - } - - if (schema.GetDictionary(json_schema_constants::kAdditionalProperties, - &dict)) { - scoped_ptr<PolicySchema> sub_schema = ParseSchema(*dict, error); - if (!sub_schema) - return scoped_ptr<PolicySchema>(); - dict_schema->additional_properties_ = sub_schema.Pass(); - } - - return dict_schema.PassAs<PolicySchema>(); -} - -ListPolicySchema::ListPolicySchema() - : PolicySchema(base::Value::TYPE_LIST) {} - -ListPolicySchema::~ListPolicySchema() {} - -const PolicySchema* ListPolicySchema::GetSchemaForItems() const { - return items_schema_.get(); -} - -scoped_ptr<PolicySchema> ListPolicySchema::Parse( - const base::DictionaryValue& schema, - std::string* error) { - const base::DictionaryValue* dict = NULL; - if (!schema.GetDictionary(json_schema_constants::kItems, &dict)) { - *error = "Arrays must declare a single schema for their items."; - return scoped_ptr<PolicySchema>(); - } - scoped_ptr<PolicySchema> items_schema = ParseSchema(*dict, error); - if (!items_schema) - return scoped_ptr<PolicySchema>(); - - scoped_ptr<ListPolicySchema> list_schema(new ListPolicySchema()); - list_schema->items_schema_ = items_schema.Pass(); - return list_schema.PassAs<PolicySchema>(); -} - -} // namespace - -PolicySchema::PolicySchema(base::Value::Type type) - : type_(type) {} - -PolicySchema::~PolicySchema() {} - -const PolicySchemaMap* PolicySchema::GetProperties() const { - NOTREACHED(); - return NULL; -} - -const PolicySchema* PolicySchema::GetSchemaForAdditionalProperties() const { - NOTREACHED(); - return NULL; -} - -const PolicySchema* PolicySchema::GetSchemaForProperty( - const std::string& key) const { - const PolicySchemaMap* properties = GetProperties(); - PolicySchemaMap::const_iterator it = properties->find(key); - return it == properties->end() ? GetSchemaForAdditionalProperties() - : it->second; -} - -const PolicySchema* PolicySchema::GetSchemaForItems() const { - NOTREACHED(); - return NULL; -} - -// static -scoped_ptr<PolicySchema> PolicySchema::Parse(const std::string& content, - std::string* error) { - // Validate as a generic JSON schema. - scoped_ptr<base::DictionaryValue> dict = - JSONSchemaValidator::IsValidSchema(content, error); - if (!dict) - return scoped_ptr<PolicySchema>(); - - // Validate the schema version. - std::string string_value; - if (!dict->GetString(json_schema_constants::kSchema, &string_value) || - string_value != kJSONSchemaVersion) { - *error = "Must declare JSON Schema v3 version in \"$schema\"."; - return scoped_ptr<PolicySchema>(); - } - - // Validate the main type. - if (!dict->GetString(json_schema_constants::kType, &string_value) || - string_value != json_schema_constants::kObject) { - *error = - "The main schema must have a type attribute with \"object\" value."; - return scoped_ptr<PolicySchema>(); - } - - // Checks for invalid attributes at the top-level. - if (dict->HasKey(json_schema_constants::kAdditionalProperties) || - dict->HasKey(json_schema_constants::kPatternProperties)) { - *error = "\"additionalProperties\" and \"patternProperties\" are not " - "supported at the main schema."; - return scoped_ptr<PolicySchema>(); - } - - return ParseSchema(*dict, error); -} - -} // namespace policy diff --git a/chromium/components/policy/core/common/policy_schema.h b/chromium/components/policy/core/common/policy_schema.h deleted file mode 100644 index c48ee6fc2b9..00000000000 --- a/chromium/components/policy/core/common/policy_schema.h +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_POLICY_CORE_COMMON_POLICY_SCHEMA_H_ -#define COMPONENTS_POLICY_CORE_COMMON_POLICY_SCHEMA_H_ - -#include <map> -#include <string> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/values.h" -#include "components/policy/policy_export.h" - -namespace policy { - -class PolicySchema; -typedef std::map<std::string, PolicySchema*> PolicySchemaMap; - -// Maps known policy keys to their expected types, and recursively describes -// the known keys within dictionary or list types. -class POLICY_EXPORT PolicySchema { - public: - - // Parses |schema| as a JSON v3 schema, and additionally verifies that: - // - the version is JSON schema v3; - // - the top-level entry is of type "object"; - // - the top-level object doesn't contain "additionalProperties" nor - // "patternProperties"; - // - each "property" maps to a schema with one "type"; - // - the type "any" is not used. - // If all the checks pass then the parsed PolicySchema is returned; otherwise - // returns NULL. - static scoped_ptr<PolicySchema> Parse(const std::string& schema, - std::string* error); - - explicit PolicySchema(base::Value::Type type); - virtual ~PolicySchema(); - - // Returns the expected type for this policy. At the top-level PolicySchema - // this is always TYPE_DICTIONARY. - base::Value::Type type() const { return type_; } - - // It is invalid to call these methods when type() is not TYPE_DICTIONARY. - // - // GetProperties() returns a map of the known property names to their schemas; - // the map is never NULL. - // GetSchemaForAdditionalProperties() returns the schema that should be used - // for keys not found in the map, and may be NULL. - // GetSchemaForProperty() is a utility method that combines both, returning - // the mapped schema if found in GetProperties(), otherwise returning - // GetSchemaForAdditionalProperties(). - virtual const PolicySchemaMap* GetProperties() const; - virtual const PolicySchema* GetSchemaForAdditionalProperties() const; - const PolicySchema* GetSchemaForProperty(const std::string& key) const; - - // It is invalid to call this method when type() is not TYPE_LIST. - // Returns the type of the entries of this "array", which is never NULL. - virtual const PolicySchema* GetSchemaForItems() const; - - private: - const base::Value::Type type_; - - DISALLOW_COPY_AND_ASSIGN(PolicySchema); -}; - -} // namespace policy - -#endif // COMPONENTS_POLICY_CORE_COMMON_POLICY_SCHEMA_H_ diff --git a/chromium/components/policy/core/common/policy_schema_unittest.cc b/chromium/components/policy/core/common/policy_schema_unittest.cc deleted file mode 100644 index bfbdd652159..00000000000 --- a/chromium/components/policy/core/common/policy_schema_unittest.cc +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/policy/core/common/policy_schema.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace policy { - -namespace { - -#define SCHEMA_VERSION "\"$schema\":\"http://json-schema.org/draft-03/schema#\"" -#define OBJECT_TYPE "\"type\":\"object\"" - -bool ParseFails(const std::string& content) { - std::string error; - scoped_ptr<PolicySchema> schema = PolicySchema::Parse(content, &error); - EXPECT_TRUE(schema || !error.empty()); - return !schema; -} - -} // namespace - -TEST(PolicySchemaTest, MinimalSchema) { - EXPECT_FALSE(ParseFails( - "{" - SCHEMA_VERSION "," - OBJECT_TYPE - "}")); -} - -TEST(PolicySchemaTest, InvalidSchemas) { - EXPECT_TRUE(ParseFails("")); - EXPECT_TRUE(ParseFails("omg")); - EXPECT_TRUE(ParseFails("\"omg\"")); - EXPECT_TRUE(ParseFails("123")); - EXPECT_TRUE(ParseFails("[]")); - EXPECT_TRUE(ParseFails("null")); - EXPECT_TRUE(ParseFails("{}")); - EXPECT_TRUE(ParseFails("{" SCHEMA_VERSION "}")); - EXPECT_TRUE(ParseFails("{" OBJECT_TYPE "}")); - - EXPECT_TRUE(ParseFails( - "{" - SCHEMA_VERSION "," - OBJECT_TYPE "," - "\"additionalProperties\": { \"type\":\"object\" }" - "}")); - - EXPECT_TRUE(ParseFails( - "{" - SCHEMA_VERSION "," - OBJECT_TYPE "," - "\"patternProperties\": { \"a+b*\": { \"type\": \"object\" } }" - "}")); - - EXPECT_TRUE(ParseFails( - "{" - SCHEMA_VERSION "," - OBJECT_TYPE "," - "\"properties\": { \"Policy\": { \"type\": \"bogus\" } }" - "}")); - - EXPECT_TRUE(ParseFails( - "{" - SCHEMA_VERSION "," - OBJECT_TYPE "," - "\"properties\": { \"Policy\": { \"type\": [\"string\", \"number\"] } }" - "}")); - - EXPECT_TRUE(ParseFails( - "{" - SCHEMA_VERSION "," - OBJECT_TYPE "," - "\"properties\": { \"Policy\": { \"type\": \"any\" } }" - "}")); -} - -TEST(PolicySchemaTest, ValidSchema) { - std::string error; - scoped_ptr<PolicySchema> schema = PolicySchema::Parse( - "{" - SCHEMA_VERSION "," - OBJECT_TYPE "," - "\"properties\": {" - " \"Boolean\": { \"type\": \"boolean\" }," - " \"Integer\": { \"type\": \"integer\" }," - " \"Null\": { \"type\": \"null\" }," - " \"Number\": { \"type\": \"number\" }," - " \"String\": { \"type\": \"string\" }," - " \"Array\": {" - " \"type\": \"array\"," - " \"items\": { \"type\": \"string\" }" - " }," - " \"ArrayOfObjects\": {" - " \"type\": \"array\"," - " \"items\": {" - " \"type\": \"object\"," - " \"properties\": {" - " \"one\": { \"type\": \"string\" }," - " \"two\": { \"type\": \"integer\" }" - " }" - " }" - " }," - " \"ArrayOfArray\": {" - " \"type\": \"array\"," - " \"items\": {" - " \"type\": \"array\"," - " \"items\": { \"type\": \"string\" }" - " }" - " }," - " \"Object\": {" - " \"type\": \"object\"," - " \"properties\": {" - " \"one\": { \"type\": \"boolean\" }," - " \"two\": { \"type\": \"integer\" }" - " }," - " \"additionalProperties\": { \"type\": \"string\" }" - " }" - "}" - "}", &error); - ASSERT_TRUE(schema) << error; - - ASSERT_EQ(base::Value::TYPE_DICTIONARY, schema->type()); - EXPECT_FALSE(schema->GetSchemaForProperty("invalid")); - - const PolicySchema* sub = schema->GetSchemaForProperty("Boolean"); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_BOOLEAN, sub->type()); - - sub = schema->GetSchemaForProperty("Integer"); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_INTEGER, sub->type()); - - sub = schema->GetSchemaForProperty("Null"); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_NULL, sub->type()); - - sub = schema->GetSchemaForProperty("Number"); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_DOUBLE, sub->type()); - sub = schema->GetSchemaForProperty("String"); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_STRING, sub->type()); - - sub = schema->GetSchemaForProperty("Array"); - ASSERT_TRUE(sub); - ASSERT_EQ(base::Value::TYPE_LIST, sub->type()); - sub = sub->GetSchemaForItems(); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_STRING, sub->type()); - - sub = schema->GetSchemaForProperty("ArrayOfObjects"); - ASSERT_TRUE(sub); - ASSERT_EQ(base::Value::TYPE_LIST, sub->type()); - sub = sub->GetSchemaForItems(); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_DICTIONARY, sub->type()); - const PolicySchema* subsub = sub->GetSchemaForProperty("one"); - ASSERT_TRUE(subsub); - EXPECT_EQ(base::Value::TYPE_STRING, subsub->type()); - subsub = sub->GetSchemaForProperty("two"); - ASSERT_TRUE(subsub); - EXPECT_EQ(base::Value::TYPE_INTEGER, subsub->type()); - subsub = sub->GetSchemaForProperty("invalid"); - EXPECT_FALSE(subsub); - - sub = schema->GetSchemaForProperty("ArrayOfArray"); - ASSERT_TRUE(sub); - ASSERT_EQ(base::Value::TYPE_LIST, sub->type()); - sub = sub->GetSchemaForItems(); - ASSERT_TRUE(sub); - ASSERT_EQ(base::Value::TYPE_LIST, sub->type()); - sub = sub->GetSchemaForItems(); - ASSERT_TRUE(sub); - EXPECT_EQ(base::Value::TYPE_STRING, sub->type()); - - sub = schema->GetSchemaForProperty("Object"); - ASSERT_TRUE(sub); - ASSERT_EQ(base::Value::TYPE_DICTIONARY, sub->type()); - subsub = sub->GetSchemaForProperty("one"); - ASSERT_TRUE(subsub); - EXPECT_EQ(base::Value::TYPE_BOOLEAN, subsub->type()); - subsub = sub->GetSchemaForProperty("two"); - ASSERT_TRUE(subsub); - EXPECT_EQ(base::Value::TYPE_INTEGER, subsub->type()); - subsub = sub->GetSchemaForProperty("undeclared"); - ASSERT_TRUE(subsub); - EXPECT_EQ(base::Value::TYPE_STRING, subsub->type()); -} - -} // namespace policy diff --git a/chromium/components/policy/policy_export.h b/chromium/components/policy/policy_export.h deleted file mode 100644 index 47376acaa85..00000000000 --- a/chromium/components/policy/policy_export.h +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_POLICY_POLICY_EXPORT_H_ -#define COMPONENTS_POLICY_POLICY_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(POLICY_COMPONENT_IMPLEMENTATION) -#define POLICY_EXPORT __declspec(dllexport) -#else -#define POLICY_EXPORT __declspec(dllimport) -#endif // defined(BASE_PREFS_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(POLICY_COMPONENT_IMPLEMENTATION) -#define POLICY_EXPORT __attribute__((visibility("default"))) -#else -#define POLICY_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define POLICY_EXPORT -#endif - -#endif // COMPONENTS_POLICY_POLICY_EXPORT_H_ diff --git a/chromium/components/policy/stub_to_remove.cc b/chromium/components/policy/stub_to_remove.cc deleted file mode 100644 index 6e352ace9cd..00000000000 --- a/chromium/components/policy/stub_to_remove.cc +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO(joaodasilva): remove this file and update the comment on policy.gypi. -// http://crbug.com/271392 |