diff --git a/BUILD b/BUILD index 9c0f0ad4144..ad9364a4833 100644 --- a/BUILD +++ b/BUILD @@ -587,6 +587,7 @@ grpc_cc_library( ], external_deps = [ "absl/status", + "absl/status:statusor", "absl/synchronization", "absl/container:inlined_vector", "absl/strings", @@ -3117,7 +3118,6 @@ grpc_cc_library( deps = [ "channel_args", "config", - "error", "gpr_base", "grpc_service_config", "json", @@ -7000,13 +7000,12 @@ grpc_cc_library( ], external_deps = [ "absl/base:core_headers", + "absl/status", + "absl/status:statusor", "absl/strings", "absl/strings:str_format", ], - deps = [ - "error", - "gpr_base", - ], + deps = ["gpr_base"], ) grpc_cc_library( diff --git a/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc b/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc index af536a6ee0a..61f68edd521 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc +++ b/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc @@ -253,16 +253,19 @@ bool ValueInJsonArray(const Json::Array& array, const char* value) { std::string ChooseServiceConfig(char* service_config_choice_json, grpc_error_handle* error) { - Json json = Json::Parse(service_config_choice_json, error); - if (!GRPC_ERROR_IS_NONE(*error)) return ""; - if (json.type() != Json::Type::ARRAY) { + auto json = Json::Parse(service_config_choice_json); + if (!json.ok()) { + *error = absl_status_to_grpc_error(json.status()); + return ""; + } + if (json->type() != Json::Type::ARRAY) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Service Config Choices, error: should be of type array"); return ""; } const Json* service_config = nullptr; std::vector error_list; - for (const Json& choice : json.array_value()) { + for (const Json& choice : json->array_value()) { if (choice.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Service Config Choice, error: should be of type object")); diff --git a/src/core/ext/xds/xds_bootstrap.cc b/src/core/ext/xds/xds_bootstrap.cc index 0d969ddae09..85a7012fca0 100644 --- a/src/core/ext/xds/xds_bootstrap.cc +++ b/src/core/ext/xds/xds_bootstrap.cc @@ -24,6 +24,8 @@ #include #include "absl/memory/memory.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" @@ -179,16 +181,13 @@ bool XdsBootstrap::XdsServer::IgnoreResourceDeletion() const { std::unique_ptr XdsBootstrap::Create( absl::string_view json_string, grpc_error_handle* error) { - Json json = Json::Parse(json_string, error); - if (!GRPC_ERROR_IS_NONE(*error)) { - grpc_error_handle error_out = - GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Failed to parse bootstrap JSON string", error, 1); - GRPC_ERROR_UNREF(*error); - *error = error_out; + auto json = Json::Parse(json_string); + if (!json.ok()) { + *error = GRPC_ERROR_CREATE_FROM_CPP_STRING(absl::StrCat( + "Failed to parse bootstrap JSON string: ", json.status().ToString())); return nullptr; } - return absl::make_unique(std::move(json), error); + return absl::make_unique(std::move(*json), error); } XdsBootstrap::XdsBootstrap(Json json, grpc_error_handle* error) { diff --git a/src/core/ext/xds/xds_cluster_specifier_plugin.cc b/src/core/ext/xds/xds_cluster_specifier_plugin.cc index 0d6a61e50bc..2d033ade3d5 100644 --- a/src/core/ext/xds/xds_cluster_specifier_plugin.cc +++ b/src/core/ext/xds/xds_cluster_specifier_plugin.cc @@ -79,10 +79,9 @@ XdsRouteLookupClusterSpecifierPlugin::GenerateLoadBalancingPolicyConfig( upb_JsonEncode(plugin_config, msg_type, symtab, 0, reinterpret_cast(buf), json_size + 1, status.ptr()); Json::Object rls_policy; - grpc_error_handle error = GRPC_ERROR_NONE; - rls_policy["routeLookupConfig"] = - Json::Parse(reinterpret_cast(buf), &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto json = Json::Parse(reinterpret_cast(buf)); + GPR_ASSERT(json.ok()); + rls_policy["routeLookupConfig"] = std::move(*json); Json::Object cds_policy; cds_policy["cds_experimental"] = Json::Object(); Json::Array child_policy; diff --git a/src/core/ext/xds/xds_lb_policy_registry.cc b/src/core/ext/xds/xds_lb_policy_registry.cc index 1824530e268..52004d4700d 100644 --- a/src/core/ext/xds/xds_lb_policy_registry.cc +++ b/src/core/ext/xds/xds_lb_policy_registry.cc @@ -44,7 +44,6 @@ #include "src/core/ext/filters/client_channel/lb_policy_registry.h" #include "src/core/ext/xds/upb_utils.h" #include "src/core/ext/xds/xds_common_types.h" -#include "src/core/lib/iomgr/error.h" namespace grpc_core { @@ -166,18 +165,15 @@ absl::StatusOr ParseStructToJson(const XdsEncodingContext& context, void* buf = upb_Arena_Malloc(context.arena, json_size + 1); upb_JsonEncode(resource, msg_def, context.symtab, 0, reinterpret_cast(buf), json_size + 1, status.ptr()); - grpc_error_handle error = GRPC_ERROR_NONE; - auto json = Json::Parse(reinterpret_cast(buf), &error); - if (!GRPC_ERROR_IS_NONE(error)) { + auto json = Json::Parse(reinterpret_cast(buf)); + if (!json.ok()) { // This should not happen - auto ret_status = absl::InternalError( + return absl::InternalError( absl::StrCat("Error parsing JSON form of google::Protobuf::Struct " "produced by upb library: ", - grpc_error_std_string(error))); - GRPC_ERROR_UNREF(error); - return ret_status; + json.status().ToString())); } - return json; + return std::move(*json); } } // namespace diff --git a/src/core/lib/json/json.h b/src/core/lib/json/json.h index aaca601bb60..ffc6d50e464 100644 --- a/src/core/lib/json/json.h +++ b/src/core/lib/json/json.h @@ -1,20 +1,18 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ +// +// Copyright 2015 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// #ifndef GRPC_CORE_LIB_JSON_JSON_H #define GRPC_CORE_LIB_JSON_JSON_H @@ -26,10 +24,9 @@ #include #include +#include "absl/status/statusor.h" #include "absl/strings/string_view.h" -#include "src/core/lib/iomgr/error.h" - namespace grpc_core { // A JSON value, which can be any one of object, array, string, @@ -54,8 +51,8 @@ class Json { using Object = std::map; using Array = std::vector; - // Parses JSON string from json_str. On error, sets *error. - static Json Parse(absl::string_view json_str, grpc_error_handle* error); + // Parses JSON string from json_str. + static absl::StatusOr Parse(absl::string_view json_str); Json() = default; @@ -246,4 +243,4 @@ class Json { } // namespace grpc_core -#endif /* GRPC_CORE_LIB_JSON_JSON_H */ +#endif // GRPC_CORE_LIB_JSON_JSON_H diff --git a/src/core/lib/json/json_reader.cc b/src/core/lib/json/json_reader.cc index afa574dbbbf..b5bd2840c73 100644 --- a/src/core/lib/json/json_reader.cc +++ b/src/core/lib/json/json_reader.cc @@ -1,20 +1,18 @@ -/* - * - * Copyright 2015-2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ +// +// Copyright 2015-2016 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// #include @@ -28,13 +26,15 @@ #include #include "absl/base/attributes.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" +#include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include -#include "src/core/lib/iomgr/error.h" #include "src/core/lib/json/json.h" #define GRPC_JSON_MAX_DEPTH 255 @@ -46,7 +46,7 @@ namespace { class JsonReader { public: - static grpc_error_handle Parse(absl::string_view input, Json* output); + static absl::StatusOr Parse(absl::string_view input); private: enum class Status { @@ -125,7 +125,7 @@ class JsonReader { bool container_just_begun_ = false; uint16_t unicode_char_ = 0; uint16_t unicode_high_surrogate_ = 0; - std::vector errors_; + std::vector errors_; bool truncated_errors_ = false; uint8_t utf8_bytes_remaining_ = 0; uint8_t utf8_first_byte_ = 0; @@ -235,9 +235,8 @@ Json* JsonReader::CreateAndLinkValue() { if (errors_.size() == GRPC_JSON_MAX_ERRORS) { truncated_errors_ = true; } else { - errors_.push_back(GRPC_ERROR_CREATE_FROM_CPP_STRING( - absl::StrFormat("duplicate key \"%s\" at index %" PRIuPTR, key_, - CurrentIndex()))); + errors_.push_back(absl::StrFormat( + "duplicate key \"%s\" at index %" PRIuPTR, key_, CurrentIndex())); } } value = &(*parent->mutable_object())[std::move(key_)]; @@ -255,9 +254,9 @@ bool JsonReader::StartContainer(Json::Type type) { if (errors_.size() == GRPC_JSON_MAX_ERRORS) { truncated_errors_ = true; } else { - errors_.push_back(GRPC_ERROR_CREATE_FROM_CPP_STRING( + errors_.push_back( absl::StrFormat("exceeded max stack depth (%d) at index %" PRIuPTR, - GRPC_JSON_MAX_DEPTH, CurrentIndex()))); + GRPC_JSON_MAX_DEPTH, CurrentIndex())); } return false; } @@ -896,35 +895,32 @@ JsonReader::Status JsonReader::Run() { GPR_UNREACHABLE_CODE(return Status::GRPC_JSON_INTERNAL_ERROR); } -grpc_error_handle JsonReader::Parse(absl::string_view input, Json* output) { +absl::StatusOr JsonReader::Parse(absl::string_view input) { JsonReader reader(input); Status status = reader.Run(); if (reader.truncated_errors_) { - reader.errors_.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( + reader.errors_.push_back( "too many errors encountered during JSON parsing -- fix reported " - "errors and try again to see additional errors")); + "errors and try again to see additional errors"); } if (status == Status::GRPC_JSON_INTERNAL_ERROR) { - reader.errors_.push_back(GRPC_ERROR_CREATE_FROM_CPP_STRING(absl::StrCat( - "internal error in JSON parser at index ", reader.CurrentIndex()))); + reader.errors_.push_back(absl::StrCat( + "internal error in JSON parser at index ", reader.CurrentIndex())); } else if (status == Status::GRPC_JSON_PARSE_ERROR) { - reader.errors_.push_back(GRPC_ERROR_CREATE_FROM_CPP_STRING( - absl::StrCat("JSON parse error at index ", reader.CurrentIndex()))); + reader.errors_.push_back( + absl::StrCat("JSON parse error at index ", reader.CurrentIndex())); } if (!reader.errors_.empty()) { - return GRPC_ERROR_CREATE_FROM_VECTOR("JSON parsing failed", - &reader.errors_); + return absl::InvalidArgumentError(absl::StrCat( + "JSON parsing failed: [", absl::StrJoin(reader.errors_, "; "), "]")); } - *output = std::move(reader.root_value_); - return GRPC_ERROR_NONE; + return std::move(reader.root_value_); } } // namespace -Json Json::Parse(absl::string_view json_str, grpc_error_handle* error) { - Json value; - *error = JsonReader::Parse(json_str, &value); - return value; +absl::StatusOr Json::Parse(absl::string_view json_str) { + return JsonReader::Parse(json_str); } } // namespace grpc_core diff --git a/src/core/lib/security/authorization/rbac_translator.cc b/src/core/lib/security/authorization/rbac_translator.cc index 82736d9c267..6be855a3114 100644 --- a/src/core/lib/security/authorization/rbac_translator.cc +++ b/src/core/lib/security/authorization/rbac_translator.cc @@ -33,7 +33,6 @@ #include "absl/strings/strip.h" #include "src/core/lib/gpr/useful.h" -#include "src/core/lib/iomgr/error.h" #include "src/core/lib/json/json.h" #include "src/core/lib/matchers/matchers.h" @@ -329,21 +328,18 @@ absl::StatusOr ParseAllowRulesArray(const Json& json, absl::StatusOr GenerateRbacPolicies( absl::string_view authz_policy) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(authz_policy, &error); - if (!GRPC_ERROR_IS_NONE(error)) { - absl::Status status = absl::InvalidArgumentError( + auto json = Json::Parse(authz_policy); + if (!json.ok()) { + return absl::InvalidArgumentError( absl::StrCat("Failed to parse gRPC authorization policy. Error: ", - grpc_error_std_string(error))); - GRPC_ERROR_UNREF(error); - return status; + json.status().ToString())); } - if (json.type() != Json::Type::OBJECT) { + if (json->type() != Json::Type::OBJECT) { return absl::InvalidArgumentError( "SDK authorization policy is not an object."); } - auto it = json.mutable_object()->find("name"); - if (it == json.mutable_object()->end()) { + auto it = json->mutable_object()->find("name"); + if (it == json->mutable_object()->end()) { return absl::InvalidArgumentError("\"name\" field is not present."); } if (it->second.type() != Json::Type::STRING) { @@ -351,8 +347,8 @@ absl::StatusOr GenerateRbacPolicies( } absl::string_view name = it->second.string_value(); RbacPolicies rbac_policies; - it = json.mutable_object()->find("deny_rules"); - if (it != json.mutable_object()->end()) { + it = json->mutable_object()->find("deny_rules"); + if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::ARRAY) { return absl::InvalidArgumentError("\"deny_rules\" is not an array."); } @@ -366,8 +362,8 @@ absl::StatusOr GenerateRbacPolicies( } else { rbac_policies.deny_policy.action = Rbac::Action::kDeny; } - it = json.mutable_object()->find("allow_rules"); - if (it == json.mutable_object()->end()) { + it = json->mutable_object()->find("allow_rules"); + if (it == json->mutable_object()->end()) { return absl::InvalidArgumentError("\"allow_rules\" is not present."); } if (it->second.type() != Json::Type::ARRAY) { diff --git a/src/core/lib/security/credentials/external/aws_external_account_credentials.cc b/src/core/lib/security/credentials/external/aws_external_account_credentials.cc index aff56c99add..04c6a48467f 100644 --- a/src/core/lib/security/credentials/external/aws_external_account_credentials.cc +++ b/src/core/lib/security/credentials/external/aws_external_account_credentials.cc @@ -413,16 +413,23 @@ void AwsExternalAccountCredentials::OnRetrieveSigningKeysInternal( } absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); - Json json = Json::Parse(response_body, &error); - if (!GRPC_ERROR_IS_NONE(error) || json.type() != Json::Type::OBJECT) { + auto json = Json::Parse(response_body); + if (!json.ok()) { FinishRetrieveSubjectToken( - "", GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Invalid retrieve signing keys response.", &error, 1)); - GRPC_ERROR_UNREF(error); + "", GRPC_ERROR_CREATE_FROM_CPP_STRING( + absl::StrCat("Invalid retrieve signing keys response: ", + json.status().ToString()))); + return; + } + if (json->type() != Json::Type::OBJECT) { + FinishRetrieveSubjectToken("", + GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Invalid retrieve signing keys response: " + "JSON type is not object")); return; } - auto it = json.object_value().find("AccessKeyId"); - if (it != json.object_value().end() && + auto it = json->object_value().find("AccessKeyId"); + if (it != json->object_value().end() && it->second.type() == Json::Type::STRING) { access_key_id_ = it->second.string_value(); } else { @@ -431,8 +438,8 @@ void AwsExternalAccountCredentials::OnRetrieveSigningKeysInternal( "Missing or invalid AccessKeyId in %s.", response_body))); return; } - it = json.object_value().find("SecretAccessKey"); - if (it != json.object_value().end() && + it = json->object_value().find("SecretAccessKey"); + if (it != json->object_value().end() && it->second.type() == Json::Type::STRING) { secret_access_key_ = it->second.string_value(); } else { @@ -441,8 +448,8 @@ void AwsExternalAccountCredentials::OnRetrieveSigningKeysInternal( "Missing or invalid SecretAccessKey in %s.", response_body))); return; } - it = json.object_value().find("Token"); - if (it != json.object_value().end() && + it = json->object_value().find("Token"); + if (it != json->object_value().end() && it->second.type() == Json::Type::STRING) { token_ = it->second.string_value(); } else { diff --git a/src/core/lib/security/credentials/external/external_account_credentials.cc b/src/core/lib/security/credentials/external/external_account_credentials.cc index f3fdec6588d..8d227d5ac11 100644 --- a/src/core/lib/security/credentials/external/external_account_credentials.cc +++ b/src/core/lib/security/credentials/external/external_account_credentials.cc @@ -28,6 +28,7 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/match.h" +#include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" @@ -393,18 +394,21 @@ void ExternalAccountCredentials::OnExchangeTokenInternal( } void ExternalAccountCredentials::ImpersenateServiceAccount() { - grpc_error_handle error = GRPC_ERROR_NONE; absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); - Json json = Json::Parse(response_body, &error); - if (!GRPC_ERROR_IS_NONE(error) || json.type() != Json::Type::OBJECT) { - FinishTokenFetch(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Invalid token exchange response.", &error, 1)); - GRPC_ERROR_UNREF(error); + auto json = Json::Parse(response_body); + if (!json.ok()) { + FinishTokenFetch(GRPC_ERROR_CREATE_FROM_CPP_STRING(absl::StrCat( + "Invalid token exchange response: ", json.status().ToString()))); + return; + } + if (json->type() != Json::Type::OBJECT) { + FinishTokenFetch(GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Invalid token exchange response: JSON type is not object")); return; } - auto it = json.object_value().find("access_token"); - if (it == json.object_value().end() || + auto it = json->object_value().find("access_token"); + if (it == json->object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_CPP_STRING(absl::StrFormat( "Missing or invalid access_token in %s.", response_body))); @@ -470,23 +474,29 @@ void ExternalAccountCredentials::OnImpersenateServiceAccountInternal( } absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); - Json json = Json::Parse(response_body, &error); - if (!GRPC_ERROR_IS_NONE(error) || json.type() != Json::Type::OBJECT) { - FinishTokenFetch(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Invalid service account impersonation response.", &error, 1)); - GRPC_ERROR_UNREF(error); + auto json = Json::Parse(response_body); + if (!json.ok()) { + FinishTokenFetch(GRPC_ERROR_CREATE_FROM_CPP_STRING( + absl::StrCat("Invalid service account impersonation response: ", + json.status().ToString()))); return; } - auto it = json.object_value().find("accessToken"); - if (it == json.object_value().end() || + if (json->type() != Json::Type::OBJECT) { + FinishTokenFetch(GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Invalid service account impersonation response: " + "JSON type is not object")); + return; + } + auto it = json->object_value().find("accessToken"); + if (it == json->object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_CPP_STRING(absl::StrFormat( "Missing or invalid accessToken in %s.", response_body))); return; } std::string access_token = it->second.string_value(); - it = json.object_value().find("expireTime"); - if (it == json.object_value().end() || + it = json->object_value().find("expireTime"); + if (it == json->object_value().end() || it->second.type() != Json::Type::STRING) { FinishTokenFetch(GRPC_ERROR_CREATE_FROM_CPP_STRING(absl::StrFormat( "Missing or invalid expireTime in %s.", response_body))); @@ -538,18 +548,17 @@ void ExternalAccountCredentials::FinishTokenFetch(grpc_error_handle error) { grpc_call_credentials* grpc_external_account_credentials_create( const char* json_string, const char* scopes_string) { - grpc_error_handle error = GRPC_ERROR_NONE; - grpc_core::Json json = grpc_core::Json::Parse(json_string, &error); - if (!GRPC_ERROR_IS_NONE(error)) { + auto json = grpc_core::Json::Parse(json_string); + if (!json.ok()) { gpr_log(GPR_ERROR, "External account credentials creation failed. Error: %s.", - grpc_error_std_string(error).c_str()); - GRPC_ERROR_UNREF(error); + json.status().ToString().c_str()); return nullptr; } std::vector scopes = absl::StrSplit(scopes_string, ','); + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = grpc_core::ExternalAccountCredentials::Create( - json, std::move(scopes), &error) + *json, std::move(scopes), &error) .release(); if (!GRPC_ERROR_IS_NONE(error)) { gpr_log(GPR_ERROR, diff --git a/src/core/lib/security/credentials/external/file_external_account_credentials.cc b/src/core/lib/security/credentials/external/file_external_account_credentials.cc index 40eba0a84e8..5b893b02ef6 100644 --- a/src/core/lib/security/credentials/external/file_external_account_credentials.cc +++ b/src/core/lib/security/credentials/external/file_external_account_credentials.cc @@ -20,6 +20,7 @@ #include #include +#include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include @@ -114,17 +115,15 @@ void FileExternalAccountCredentials::RetrieveSubjectToken( } absl::string_view content = StringViewFromSlice(content_slice.slice); if (format_type_ == "json") { - Json content_json = Json::Parse(content, &error); - if (!GRPC_ERROR_IS_NONE(error) || - content_json.type() != Json::Type::OBJECT) { + auto content_json = Json::Parse(content); + if (!content_json.ok() || content_json->type() != Json::Type::OBJECT) { cb("", GRPC_ERROR_CREATE_FROM_STATIC_STRING( "The content of the file is not a valid json object.")); - GRPC_ERROR_UNREF(error); return; } auto content_it = - content_json.object_value().find(format_subject_token_field_name_); - if (content_it == content_json.object_value().end()) { + content_json->object_value().find(format_subject_token_field_name_); + if (content_it == content_json->object_value().end()) { cb("", GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Subject token field not present.")); return; diff --git a/src/core/lib/security/credentials/external/url_external_account_credentials.cc b/src/core/lib/security/credentials/external/url_external_account_credentials.cc index 986820f02ca..b352fa0df2d 100644 --- a/src/core/lib/security/credentials/external/url_external_account_credentials.cc +++ b/src/core/lib/security/credentials/external/url_external_account_credentials.cc @@ -202,18 +202,16 @@ void UrlExternalAccountCredentials::OnRetrieveSubjectTokenInternal( absl::string_view response_body(ctx_->response.body, ctx_->response.body_length); if (format_type_ == "json") { - grpc_error_handle error = GRPC_ERROR_NONE; - Json response_json = Json::Parse(response_body, &error); - if (!GRPC_ERROR_IS_NONE(error) || - response_json.type() != Json::Type::OBJECT) { + auto response_json = Json::Parse(response_body); + if (!response_json.ok() || response_json->type() != Json::Type::OBJECT) { FinishRetrieveSubjectToken( "", GRPC_ERROR_CREATE_FROM_STATIC_STRING( "The format of response is not a valid json object.")); return; } auto response_it = - response_json.object_value().find(format_subject_token_field_name_); - if (response_it == response_json.object_value().end()) { + response_json->object_value().find(format_subject_token_field_name_); + if (response_it == response_json->object_value().end()) { FinishRetrieveSubjectToken("", GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Subject token field not present.")); return; diff --git a/src/core/lib/security/credentials/google_default/google_default_credentials.cc b/src/core/lib/security/credentials/google_default/google_default_credentials.cc index 29f637cc80e..04f44ec8171 100644 --- a/src/core/lib/security/credentials/google_default/google_default_credentials.cc +++ b/src/core/lib/security/credentials/google_default/google_default_credentials.cc @@ -67,6 +67,7 @@ #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_refcount.h" #include "src/core/lib/surface/api_trace.h" +#include "src/core/lib/transport/error_utils.h" #include "src/core/lib/uri/uri_parser.h" using grpc_core::Json; @@ -313,8 +314,14 @@ static grpc_error_handle create_default_creds_from_path( } error = grpc_load_file(creds_path.c_str(), 0, &creds_data); if (!GRPC_ERROR_IS_NONE(error)) goto end; - json = Json::Parse(grpc_core::StringViewFromSlice(creds_data), &error); - if (!GRPC_ERROR_IS_NONE(error)) goto end; + { + auto json_or = Json::Parse(grpc_core::StringViewFromSlice(creds_data)); + if (!json_or.ok()) { + error = absl_status_to_grpc_error(json_or.status()); + goto end; + } + json = std::move(*json_or); + } if (json.type() != Json::Type::OBJECT) { error = grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to parse JSON"), diff --git a/src/core/lib/security/credentials/jwt/json_token.cc b/src/core/lib/security/credentials/jwt/json_token.cc index e6f5e4aa412..7bc52c7e4ea 100644 --- a/src/core/lib/security/credentials/jwt/json_token.cc +++ b/src/core/lib/security/credentials/jwt/json_token.cc @@ -25,12 +25,16 @@ #include #include +#include #include #include #include #include +#include "absl/status/status.h" +#include "absl/status/statusor.h" + #include #include #include @@ -125,9 +129,14 @@ end: grpc_auth_json_key grpc_auth_json_key_create_from_string( const char* json_string) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_string, &error); - GRPC_LOG_IF_ERROR("JSON key parsing", error); + Json json; + auto json_or = Json::Parse(json_string); + if (!json_or.ok()) { + gpr_log(GPR_ERROR, "JSON key parsing error: %s", + json_or.status().ToString().c_str()); + } else { + json = std::move(*json_or); + } return grpc_auth_json_key_create_from_json(json); } diff --git a/src/core/lib/security/credentials/jwt/jwt_credentials.cc b/src/core/lib/security/credentials/jwt/jwt_credentials.cc index b4ff3f23440..abea57c8b02 100644 --- a/src/core/lib/security/credentials/jwt/jwt_credentials.cc +++ b/src/core/lib/security/credentials/jwt/jwt_credentials.cc @@ -37,7 +37,6 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/iomgr/error.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/json/json.h" #include "src/core/lib/promise/poll.h" @@ -141,14 +140,12 @@ grpc_service_account_jwt_access_credentials_create_from_auth_json_key( } static char* redact_private_key(const char* json_key) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_key, &error); - if (!GRPC_ERROR_IS_NONE(error) || json.type() != Json::Type::OBJECT) { - GRPC_ERROR_UNREF(error); + auto json = Json::Parse(json_key); + if (!json.ok() || json->type() != Json::Type::OBJECT) { return gpr_strdup(""); } - (*json.mutable_object())["private_key"] = ""; - return gpr_strdup(json.Dump(/*indent=*/2).c_str()); + (*json->mutable_object())["private_key"] = ""; + return gpr_strdup(json->Dump(/*indent=*/2).c_str()); } grpc_call_credentials* grpc_service_account_jwt_access_credentials_create( diff --git a/src/core/lib/security/credentials/jwt/jwt_verifier.cc b/src/core/lib/security/credentials/jwt/jwt_verifier.cc index 6e91c7a83dd..587ab604fa8 100644 --- a/src/core/lib/security/credentials/jwt/jwt_verifier.cc +++ b/src/core/lib/security/credentials/jwt/jwt_verifier.cc @@ -38,6 +38,7 @@ #include #include +#include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" @@ -111,16 +112,14 @@ static Json parse_json_part_from_jwt(const char* str, size_t len) { return Json(); // JSON null } absl::string_view string = grpc_core::StringViewFromSlice(slice); - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(string, &error); - if (!GRPC_ERROR_IS_NONE(error)) { + auto json = Json::Parse(string); + grpc_slice_unref_internal(slice); + if (!json.ok()) { gpr_log(GPR_ERROR, "JSON parse error: %s", - grpc_error_std_string(error).c_str()); - GRPC_ERROR_UNREF(error); - json = Json(); // JSON null + json.status().ToString().c_str()); + return Json(); // JSON null } - grpc_slice_unref_internal(slice); - return json; + return std::move(*json); } static const char* validate_string_field(const Json& json, const char* key) { @@ -435,14 +434,13 @@ static Json json_from_http(const grpc_http_response* response) { response->status); return Json(); // JSON null } - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse( - absl::string_view(response->body, response->body_length), &error); - if (!GRPC_ERROR_IS_NONE(error)) { + auto json = + Json::Parse(absl::string_view(response->body, response->body_length)); + if (!json.ok()) { gpr_log(GPR_ERROR, "Invalid JSON found in response."); return Json(); // JSON null } - return json; + return std::move(*json); } static const Json* find_property_by_name(const Json& json, const char* name) { diff --git a/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc b/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc index 619766a4243..36e78d04acb 100644 --- a/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc +++ b/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc @@ -114,12 +114,13 @@ end: grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string( const char* json_string) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_string, &error); - if (!GRPC_ERROR_IS_NONE(error)) { + Json json; + auto json_or = Json::Parse(json_string); + if (!json_or.ok()) { gpr_log(GPR_ERROR, "JSON parsing failed: %s", - grpc_error_std_string(error).c_str()); - GRPC_ERROR_UNREF(error); + json_or.status().ToString().c_str()); + } else { + json = std::move(*json_or); } return grpc_auth_refresh_token_create_from_json(json); } @@ -158,7 +159,6 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response( grpc_core::Duration* token_lifetime) { char* null_terminated_body = nullptr; grpc_credentials_status status = GRPC_CREDENTIALS_OK; - Json json; if (response == nullptr) { gpr_log(GPR_ERROR, "Received NULL response."); @@ -184,38 +184,36 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response( const char* token_type = nullptr; const char* expires_in = nullptr; Json::Object::const_iterator it; - grpc_error_handle error = GRPC_ERROR_NONE; - json = Json::Parse(null_terminated_body, &error); - if (!GRPC_ERROR_IS_NONE(error)) { + auto json = Json::Parse(null_terminated_body); + if (!json.ok()) { gpr_log(GPR_ERROR, "Could not parse JSON from %s: %s", - null_terminated_body, grpc_error_std_string(error).c_str()); - GRPC_ERROR_UNREF(error); + null_terminated_body, json.status().ToString().c_str()); status = GRPC_CREDENTIALS_ERROR; goto end; } - if (json.type() != Json::Type::OBJECT) { + if (json->type() != Json::Type::OBJECT) { gpr_log(GPR_ERROR, "Response should be a JSON object"); status = GRPC_CREDENTIALS_ERROR; goto end; } - it = json.object_value().find("access_token"); - if (it == json.object_value().end() || + it = json->object_value().find("access_token"); + if (it == json->object_value().end() || it->second.type() != Json::Type::STRING) { gpr_log(GPR_ERROR, "Missing or invalid access_token in JSON."); status = GRPC_CREDENTIALS_ERROR; goto end; } access_token = it->second.string_value().c_str(); - it = json.object_value().find("token_type"); - if (it == json.object_value().end() || + it = json->object_value().find("token_type"); + if (it == json->object_value().end() || it->second.type() != Json::Type::STRING) { gpr_log(GPR_ERROR, "Missing or invalid token_type in JSON."); status = GRPC_CREDENTIALS_ERROR; goto end; } token_type = it->second.string_value().c_str(); - it = json.object_value().find("expires_in"); - if (it == json.object_value().end() || + it = json->object_value().find("expires_in"); + if (it == json->object_value().end() || it->second.type() != Json::Type::NUMBER) { gpr_log(GPR_ERROR, "Missing or invalid expires_in in JSON."); status = GRPC_CREDENTIALS_ERROR; diff --git a/src/core/lib/service_config/service_config_impl.cc b/src/core/lib/service_config/service_config_impl.cc index 29fc2f332be..3ea676a0483 100644 --- a/src/core/lib/service_config/service_config_impl.cc +++ b/src/core/lib/service_config/service_config_impl.cc @@ -25,6 +25,8 @@ #include #include "absl/memory/memory.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" @@ -32,7 +34,6 @@ #include "src/core/lib/config/core_configuration.h" #include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/iomgr/error.h" #include "src/core/lib/json/json.h" #include "src/core/lib/service_config/service_config_parser.h" #include "src/core/lib/slice/slice_internal.h" @@ -42,17 +43,11 @@ namespace grpc_core { absl::StatusOr> ServiceConfigImpl::Create( const ChannelArgs& args, absl::string_view json_string) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_string, &error); - if (!GRPC_ERROR_IS_NONE(error)) { - absl::Status status = - absl::InvalidArgumentError(grpc_error_std_string(error)); - GRPC_ERROR_UNREF(error); - return status; - } + auto json = Json::Parse(json_string); + if (!json.ok()) return json.status(); absl::Status status; auto service_config = MakeRefCounted( - args, std::string(json_string), std::move(json), &status); + args, std::string(json_string), std::move(*json), &status); if (!status.ok()) return status; return service_config; } diff --git a/src/cpp/client/secure_credentials.cc b/src/cpp/client/secure_credentials.cc index 4db969b6b8f..daf3eaae08e 100644 --- a/src/cpp/client/secure_credentials.cc +++ b/src/cpp/client/secure_credentials.cc @@ -24,6 +24,8 @@ #include #include +#include "absl/status/status.h" +#include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include @@ -166,31 +168,30 @@ grpc::Status StsCredentialsOptionsFromJson(const std::string& json_string, "options cannot be nullptr."); } ClearStsCredentialsOptions(options); - grpc_error_handle error = GRPC_ERROR_NONE; - grpc_core::Json json = grpc_core::Json::Parse(json_string.c_str(), &error); - if (!GRPC_ERROR_IS_NONE(error) || - json.type() != grpc_core::Json::Type::OBJECT) { - GRPC_ERROR_UNREF(error); - return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Invalid json."); + auto json = grpc_core::Json::Parse(json_string.c_str()); + if (!json.ok() || json->type() != grpc_core::Json::Type::OBJECT) { + return grpc::Status( + grpc::StatusCode::INVALID_ARGUMENT, + absl::StrCat("Invalid json: ", json.status().ToString())); } // Required fields. const char* value = grpc_json_get_string_property( - json, "token_exchange_service_uri", nullptr); + *json, "token_exchange_service_uri", nullptr); if (value == nullptr) { ClearStsCredentialsOptions(options); return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "token_exchange_service_uri must be specified."); } options->token_exchange_service_uri.assign(value); - value = grpc_json_get_string_property(json, "subject_token_path", nullptr); + value = grpc_json_get_string_property(*json, "subject_token_path", nullptr); if (value == nullptr) { ClearStsCredentialsOptions(options); return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "subject_token_path must be specified."); } options->subject_token_path.assign(value); - value = grpc_json_get_string_property(json, "subject_token_type", nullptr); + value = grpc_json_get_string_property(*json, "subject_token_type", nullptr); if (value == nullptr) { ClearStsCredentialsOptions(options); return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, @@ -199,17 +200,17 @@ grpc::Status StsCredentialsOptionsFromJson(const std::string& json_string, options->subject_token_type.assign(value); // Optional fields. - value = grpc_json_get_string_property(json, "resource", nullptr); + value = grpc_json_get_string_property(*json, "resource", nullptr); if (value != nullptr) options->resource.assign(value); - value = grpc_json_get_string_property(json, "audience", nullptr); + value = grpc_json_get_string_property(*json, "audience", nullptr); if (value != nullptr) options->audience.assign(value); - value = grpc_json_get_string_property(json, "scope", nullptr); + value = grpc_json_get_string_property(*json, "scope", nullptr); if (value != nullptr) options->scope.assign(value); - value = grpc_json_get_string_property(json, "requested_token_type", nullptr); + value = grpc_json_get_string_property(*json, "requested_token_type", nullptr); if (value != nullptr) options->requested_token_type.assign(value); - value = grpc_json_get_string_property(json, "actor_token_path", nullptr); + value = grpc_json_get_string_property(*json, "actor_token_path", nullptr); if (value != nullptr) options->actor_token_path.assign(value); - value = grpc_json_get_string_property(json, "actor_token_type", nullptr); + value = grpc_json_get_string_property(*json, "actor_token_type", nullptr); if (value != nullptr) options->actor_token_type.assign(value); return grpc::Status(); diff --git a/test/core/channel/channelz_test.cc b/test/core/channel/channelz_test.cc index b3471777793..4e465f6840c 100644 --- a/test/core/channel/channelz_test.cc +++ b/test/core/channel/channelz_test.cc @@ -103,15 +103,14 @@ void ValidateGetTopChannels(size_t expected_channels) { std::string json_str = ChannelzRegistry::GetTopChannels(0); grpc::testing::ValidateGetTopChannelsResponseProtoJsonTranslation( json_str.c_str()); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); // This check will naturally have to change when we support pagination. // tracked: https://github.com/grpc/grpc/issues/16019. - ValidateJsonArraySize((*parsed_json.mutable_object())["channel"], + ValidateJsonArraySize((*parsed_json->mutable_object())["channel"], expected_channels); - ValidateJsonEnd(parsed_json, true); + ValidateJsonEnd(*parsed_json, true); // Also check that the core API formats this correctly. char* core_api_json_str = grpc_channelz_get_top_channels(0); grpc::testing::ValidateGetTopChannelsResponseProtoJsonTranslation( @@ -123,15 +122,14 @@ void ValidateGetServers(size_t expected_servers) { std::string json_str = ChannelzRegistry::GetServers(0); grpc::testing::ValidateGetServersResponseProtoJsonTranslation( json_str.c_str()); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); // This check will naturally have to change when we support pagination. // tracked: https://github.com/grpc/grpc/issues/16019. - ValidateJsonArraySize((*parsed_json.mutable_object())["server"], + ValidateJsonArraySize((*parsed_json->mutable_object())["server"], expected_servers); - ValidateJsonEnd(parsed_json, true); + ValidateJsonEnd(*parsed_json, true); // Also check that the core API formats this correctly. char* core_api_json_str = grpc_channelz_get_servers(0); grpc::testing::ValidateGetServersResponseProtoJsonTranslation( @@ -206,11 +204,10 @@ void ValidateChildInteger(const Json::Object& object, const std::string& key, void ValidateCounters(const std::string& json_str, const ValidateChannelDataArgs& args) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(json.type(), Json::Type::OBJECT); - Json::Object* object = json.mutable_object(); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); + ASSERT_EQ(json->type(), Json::Type::OBJECT); + Json::Object* object = json->mutable_object(); Json& data = (*object)["data"]; ASSERT_EQ(data.type(), Json::Type::OBJECT); ValidateChildInteger(data.object_value(), "callsStarted", args.calls_started); @@ -359,23 +356,21 @@ TEST_F(ChannelzRegistryBasedTest, GetTopChannelsPagination) { std::string json_str = ChannelzRegistry::GetTopChannels(0); grpc::testing::ValidateGetTopChannelsResponseProtoJsonTranslation( json_str.c_str()); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); // 100 is the pagination limit. - ValidateJsonArraySize((*parsed_json.mutable_object())["channel"], 100); - ValidateJsonEnd(parsed_json, false); + ValidateJsonArraySize((*parsed_json->mutable_object())["channel"], 100); + ValidateJsonEnd(*parsed_json, false); // Now we get the rest. json_str = ChannelzRegistry::GetTopChannels(101); grpc::testing::ValidateGetTopChannelsResponseProtoJsonTranslation( json_str.c_str()); - error = GRPC_ERROR_NONE; - parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); - ValidateJsonArraySize((*parsed_json.mutable_object())["channel"], 50); - ValidateJsonEnd(parsed_json, true); + parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); + ValidateJsonArraySize((*parsed_json->mutable_object())["channel"], 50); + ValidateJsonEnd(*parsed_json, true); } TEST_F(ChannelzRegistryBasedTest, GetTopChannelsUuidCheck) { @@ -384,11 +379,10 @@ TEST_F(ChannelzRegistryBasedTest, GetTopChannelsUuidCheck) { ChannelFixture channels[kNumChannels]; (void)channels; // suppress unused variable error std::string json_str = ChannelzRegistry::GetTopChannels(0); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); - Json& array = (*parsed_json.mutable_object())["channel"]; + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); + Json& array = (*parsed_json->mutable_object())["channel"]; ValidateJsonArraySize(array, kNumChannels); std::vector uuids = GetUuidListFromArray(array.array_value()); for (int i = 0; i < kNumChannels; ++i) { @@ -404,11 +398,10 @@ TEST_F(ChannelzRegistryBasedTest, GetTopChannelsMiddleUuidCheck) { (void)channels; // suppress unused variable error // Only query for the end of the channels. std::string json_str = ChannelzRegistry::GetTopChannels(kMidQuery); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); - Json& array = (*parsed_json.mutable_object())["channel"]; + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); + Json& array = (*parsed_json->mutable_object())["channel"]; ValidateJsonArraySize(array, kNumChannels - kMidQuery + 1); std::vector uuids = GetUuidListFromArray(array.array_value()); for (size_t i = 0; i < uuids.size(); ++i) { @@ -426,11 +419,10 @@ TEST_F(ChannelzRegistryBasedTest, GetTopChannelsNoHitUuid) { (void)channels; // suppress unused variable error // Query in the middle of the server channels. std::string json_str = ChannelzRegistry::GetTopChannels(45); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); - Json& array = (*parsed_json.mutable_object())["channel"]; + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); + Json& array = (*parsed_json->mutable_object())["channel"]; ValidateJsonArraySize(array, 10); std::vector uuids = GetUuidListFromArray(array.array_value()); for (size_t i = 0; i < uuids.size(); ++i) { @@ -447,21 +439,19 @@ TEST_F(ChannelzRegistryBasedTest, GetTopChannelsMoreGaps) { ChannelFixture channel_with_uuid5; // Current state of list: [1, NULL, 3, NULL, 5] std::string json_str = ChannelzRegistry::GetTopChannels(2); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); - Json array = (*parsed_json.mutable_object())["channel"]; + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); + Json array = (*parsed_json->mutable_object())["channel"]; ValidateJsonArraySize(array, 2); std::vector uuids = GetUuidListFromArray(array.array_value()); EXPECT_EQ(static_cast(3), uuids[0]); EXPECT_EQ(static_cast(5), uuids[1]); json_str = ChannelzRegistry::GetTopChannels(4); - error = GRPC_ERROR_NONE; - parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); - array = (*parsed_json.mutable_object())["channel"]; + parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); + array = (*parsed_json->mutable_object())["channel"]; ValidateJsonArraySize(array, 1); uuids = GetUuidListFromArray(array.array_value()); EXPECT_EQ(static_cast(5), uuids[0]); @@ -480,11 +470,10 @@ TEST_F(ChannelzRegistryBasedTest, GetTopChannelsUuidAfterCompaction) { } } std::string json_str = ChannelzRegistry::GetTopChannels(0); - grpc_error_handle error = GRPC_ERROR_NONE; - Json parsed_json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), Json::Type::OBJECT); - Json& array = (*parsed_json.mutable_object())["channel"]; + auto parsed_json = Json::Parse(json_str); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), Json::Type::OBJECT); + Json& array = (*parsed_json->mutable_object())["channel"]; ValidateJsonArraySize(array, kLoopIterations); std::vector uuids = GetUuidListFromArray(array.array_value()); for (int i = 0; i < kLoopIterations; ++i) { diff --git a/test/core/client_channel/service_config_test.cc b/test/core/client_channel/service_config_test.cc index d51153376e7..d764d5c80a9 100644 --- a/test/core/client_channel/service_config_test.cc +++ b/test/core/client_channel/service_config_test.cc @@ -742,13 +742,9 @@ TEST_F(ClientChannelParserTest, InvalidHealthCheckMultipleEntries) { "}"; auto service_config = ServiceConfigImpl::Create(ChannelArgs(), test_json); EXPECT_EQ(service_config.status().code(), absl::StatusCode::kInvalidArgument); - // TODO(roth): When we convert the JSON API to return absl::Status - // instead of grpc_error, change this expectation to be a fixed string - // equality match. - EXPECT_THAT(std::string(service_config.status().message()), - ::testing::ContainsRegex( - "JSON parsing failed" CHILD_ERROR_TAG - "duplicate key \"healthCheckConfig\" at index 104")); + EXPECT_EQ(service_config.status().message(), + "JSON parsing failed: [" + "duplicate key \"healthCheckConfig\" at index 104]"); } // diff --git a/test/core/json/fuzzer.cc b/test/core/json/fuzzer.cc index f6a9c7a997a..47b43c71c6e 100644 --- a/test/core/json/fuzzer.cc +++ b/test/core/json/fuzzer.cc @@ -29,15 +29,13 @@ bool squelch = true; bool leak_check = true; extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - grpc_error_handle error = GRPC_ERROR_NONE; auto json = grpc_core::Json::Parse( - absl::string_view(reinterpret_cast(data), size), &error); - if (GRPC_ERROR_IS_NONE(error)) { - auto text2 = json.Dump(); - auto json2 = grpc_core::Json::Parse(text2, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); - GPR_ASSERT(json == json2); + absl::string_view(reinterpret_cast(data), size)); + if (json.ok()) { + auto text2 = json->Dump(); + auto json2 = grpc_core::Json::Parse(text2); + GPR_ASSERT(json2.ok()); + GPR_ASSERT(*json == *json2); } - GRPC_ERROR_UNREF(error); return 0; } diff --git a/test/core/json/json_test.cc b/test/core/json/json_test.cc index 9be8d40aca1..fd78a3e9fd4 100644 --- a/test/core/json/json_test.cc +++ b/test/core/json/json_test.cc @@ -1,20 +1,18 @@ -/* - * - * Copyright 2015-2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ +// +// Copyright 2015-2016 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// #include "src/core/lib/json/json.h" @@ -77,11 +75,10 @@ void ValidateValue(const Json& actual, const Json& expected) { void RunSuccessTest(const char* input, const Json& expected, const char* expected_output) { gpr_log(GPR_INFO, "parsing string \"%s\" - should succeed", input); - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(input, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ValidateValue(json, expected); - std::string output = json.Dump(); + auto json = Json::Parse(input); + ASSERT_TRUE(json.ok()) << json.status(); + ValidateValue(*json, expected); + std::string output = json->Dump(); EXPECT_EQ(output, expected_output); } @@ -101,10 +98,9 @@ TEST(Json, Utf16) { MATCHER(ContainsInvalidUtf8, absl::StrCat(negation ? "Contains" : "Does not contain", " invalid UTF-8 characters.")) { - grpc_error_handle error = GRPC_ERROR_NONE; - const Json json = Json::Parse(arg, &error); - return (error.code() == absl::StatusCode::kUnknown) && - (absl::StrContains(error.message(), "JSON parsing failed")); + auto json = Json::Parse(arg); + return json.status().code() == absl::StatusCode::kInvalidArgument && + absl::StrContains(json.status().message(), "JSON parsing failed"); } TEST(Json, Utf8) { @@ -197,11 +193,8 @@ TEST(Json, Keywords) { void RunParseFailureTest(const char* input) { gpr_log(GPR_INFO, "parsing string \"%s\" - should fail", input); - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(input, &error); - gpr_log(GPR_INFO, "error: %s", grpc_error_std_string(error).c_str()); - EXPECT_NE(error, GRPC_ERROR_NONE); - GRPC_ERROR_UNREF(error); + auto json = Json::Parse(input); + EXPECT_FALSE(json.ok()); } TEST(Json, InvalidInput) { diff --git a/test/core/security/credentials_test.cc b/test/core/security/credentials_test.cc index abf6722ea9e..0427ec10b44 100644 --- a/test/core/security/credentials_test.cc +++ b/test/core/security/credentials_test.cc @@ -2620,11 +2620,9 @@ TEST(CredentialsTest, TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatText) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_url_external_account_creds_options_credential_source_format_text, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + valid_url_external_account_creds_options_credential_source_format_text); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2632,12 +2630,13 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatText) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2658,11 +2657,9 @@ TEST(CredentialsTest, std::map emd = { {"authorization", "Bearer token_exchange_access_token"}}; ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_url_external_account_creds_options_credential_source_with_qurey_params_format_text, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + valid_url_external_account_creds_options_credential_source_with_qurey_params_format_text); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2670,12 +2667,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2693,11 +2691,9 @@ TEST(CredentialsTest, TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatJson) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_url_external_account_creds_options_credential_source_format_json, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + valid_url_external_account_creds_options_credential_source_format_json); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2705,12 +2701,13 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatJson) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2728,10 +2725,9 @@ TEST(CredentialsTest, TestUrlExternalAccountCredsSuccessFormatJson) { TEST(CredentialsTest, TestUrlExternalAccountCredsFailureInvalidCredentialSourceUrl) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - invalid_url_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(invalid_url_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2739,12 +2735,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = UrlExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds == nullptr); std::string actual_error; @@ -2756,14 +2753,11 @@ TEST(CredentialsTest, TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatText) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; char* subject_token_path = write_tmp_jwt_file("test_subject_token"); - Json credential_source = Json::Parse( - absl::StrFormat( - "{\"file\":\"%s\"}", - absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}})), - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse(absl::StrFormat( + "{\"file\":\"%s\"}", + absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}}))); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2771,12 +2765,13 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatText) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2796,22 +2791,19 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatText) { TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatJson) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; char* subject_token_path = write_tmp_jwt_file("{\"access_token\":\"test_subject_token\"}"); - Json credential_source = Json::Parse( - absl::StrFormat( - "{\n" - "\"file\":\"%s\",\n" - "\"format\":\n" - "{\n" - "\"type\":\"json\",\n" - "\"subject_token_field_name\":\"access_token\"\n" - "}\n" - "}", - absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}})), - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse(absl::StrFormat( + "{\n" + "\"file\":\"%s\",\n" + "\"format\":\n" + "{\n" + "\"type\":\"json\",\n" + "\"subject_token_field_name\":\"access_token\"\n" + "}\n" + "}", + absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}}))); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2819,12 +2811,13 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatJson) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2844,10 +2837,8 @@ TEST(CredentialsTest, TestFileExternalAccountCredsSuccessFormatJson) { TEST(CredentialsTest, TestFileExternalAccountCredsFailureFileNotFound) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = - Json::Parse("{\"file\":\"non_exisiting_file\"}", &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse("{\"file\":\"non_exisiting_file\"}"); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2855,12 +2846,13 @@ TEST(CredentialsTest, TestFileExternalAccountCredsFailureFileNotFound) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2881,21 +2873,18 @@ TEST(CredentialsTest, TestFileExternalAccountCredsFailureFileNotFound) { TEST(CredentialsTest, TestFileExternalAccountCredsFailureInvalidJsonContent) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; char* subject_token_path = write_tmp_jwt_file("not_a_valid_json_file"); - Json credential_source = Json::Parse( - absl::StrFormat( - "{\n" - "\"file\":\"%s\",\n" - "\"format\":\n" - "{\n" - "\"type\":\"json\",\n" - "\"subject_token_field_name\":\"access_token\"\n" - "}\n" - "}", - absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}})), - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse(absl::StrFormat( + "{\n" + "\"file\":\"%s\",\n" + "\"format\":\n" + "{\n" + "\"type\":\"json\",\n" + "\"subject_token_field_name\":\"access_token\"\n" + "}\n" + "}", + absl::StrReplaceAll(subject_token_path, {{"\\", "\\\\"}}))); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2903,12 +2892,13 @@ TEST(CredentialsTest, TestFileExternalAccountCredsFailureInvalidJsonContent) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = FileExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2931,10 +2921,9 @@ TEST(CredentialsTest, TestFileExternalAccountCredsFailureInvalidJsonContent) { TEST(CredentialsTest, TestAwsExternalAccountCredsSuccess) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2942,12 +2931,13 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccess) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -2965,11 +2955,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccess) { TEST(CredentialsTest, TestAwsImdsv2ExternalAccountCredsSuccess) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_imdsv2_external_account_creds_options_credential_source, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + valid_aws_imdsv2_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -2977,12 +2965,13 @@ TEST(CredentialsTest, TestAwsImdsv2ExternalAccountCredsSuccess) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3002,10 +2991,9 @@ TEST(CredentialsTest, TestAwsImdsv2ExternalAccountCredsSuccess) { TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysUrl) { ExecCtx exec_ctx; gpr_setenv("AWS_REGION", "test_regionz"); - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3013,12 +3001,13 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysUrl) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3039,10 +3028,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathDefaultRegionEnvKeysUrl) { ExecCtx exec_ctx; gpr_setenv("AWS_DEFAULT_REGION", "test_regionz"); - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3050,12 +3038,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3078,10 +3067,9 @@ TEST(CredentialsTest, // Make sure that AWS_REGION gets used over AWS_DEFAULT_REGION gpr_setenv("AWS_REGION", "test_regionz"); gpr_setenv("AWS_DEFAULT_REGION", "ERROR_REGION"); - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3089,12 +3077,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3117,10 +3106,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionUrlKeysEnv) { gpr_setenv("AWS_ACCESS_KEY_ID", "test_access_key_id"); gpr_setenv("AWS_SECRET_ACCESS_KEY", "test_secret_access_key"); gpr_setenv("AWS_SESSION_TOKEN", "test_token"); - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3128,12 +3116,13 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionUrlKeysEnv) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3158,10 +3147,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysEnv) { gpr_setenv("AWS_ACCESS_KEY_ID", "test_access_key_id"); gpr_setenv("AWS_SECRET_ACCESS_KEY", "test_secret_access_key"); gpr_setenv("AWS_SESSION_TOKEN", "test_token"); - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3169,12 +3157,13 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsSuccessPathRegionEnvKeysEnv) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3203,10 +3192,9 @@ TEST(CredentialsTest, gpr_setenv("AWS_ACCESS_KEY_ID", "test_access_key_id"); gpr_setenv("AWS_SECRET_ACCESS_KEY", "test_secret_access_key"); gpr_setenv("AWS_SESSION_TOKEN", "test_token"); - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3214,12 +3202,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3248,10 +3237,9 @@ TEST(CredentialsTest, gpr_setenv("AWS_ACCESS_KEY_ID", "test_access_key_id"); gpr_setenv("AWS_SECRET_ACCESS_KEY", "test_secret_access_key"); gpr_setenv("AWS_SESSION_TOKEN", "test_token"); - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - valid_aws_external_account_creds_options_credential_source, &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = + Json::Parse(valid_aws_external_account_creds_options_credential_source); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3259,12 +3247,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3287,11 +3276,9 @@ TEST(CredentialsTest, TEST(CredentialsTest, TestAwsExternalAccountCredsFailureUnmatchedEnvironmentId) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - invalid_aws_external_account_creds_options_credential_source_unmatched_environment_id, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + invalid_aws_external_account_creds_options_credential_source_unmatched_environment_id); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3299,12 +3286,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds == nullptr); std::string expected_error = "environment_id does not match."; @@ -3317,11 +3305,9 @@ TEST(CredentialsTest, TEST(CredentialsTest, TestAwsExternalAccountCredsFailureInvalidRegionUrl) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - invalid_aws_external_account_creds_options_credential_source_invalid_region_url, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + invalid_aws_external_account_creds_options_credential_source_invalid_region_url); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3329,12 +3315,13 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureInvalidRegionUrl) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3357,11 +3344,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureInvalidRegionUrl) { TEST(CredentialsTest, TestAwsExternalAccountCredsFailureInvalidUrl) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - invalid_aws_external_account_creds_options_credential_source_invalid_url, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + invalid_aws_external_account_creds_options_credential_source_invalid_url); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3369,12 +3354,13 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureInvalidUrl) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3396,11 +3382,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureInvalidUrl) { TEST(CredentialsTest, TestAwsExternalAccountCredsFailureMissingRoleName) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - invalid_aws_external_account_creds_options_credential_source_missing_role_name, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + invalid_aws_external_account_creds_options_credential_source_missing_role_name); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3408,12 +3392,13 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureMissingRoleName) { "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); @@ -3437,11 +3422,9 @@ TEST(CredentialsTest, TestAwsExternalAccountCredsFailureMissingRoleName) { TEST(CredentialsTest, TestAwsExternalAccountCredsFailureInvalidRegionalCredVerificationUrl) { ExecCtx exec_ctx; - grpc_error_handle error = GRPC_ERROR_NONE; - Json credential_source = Json::Parse( - invalid_aws_external_account_creds_options_credential_source_invalid_regional_cred_verification_url, - &error); - GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); + auto credential_source = Json::Parse( + invalid_aws_external_account_creds_options_credential_source_invalid_regional_cred_verification_url); + GPR_ASSERT(credential_source.ok()); ExternalAccountCredentials::Options options = { "external_account", // type; "audience", // audience; @@ -3449,12 +3432,13 @@ TEST(CredentialsTest, "", // service_account_impersonation_url; "https://foo.com:5555/token", // token_url; "https://foo.com:5555/token_info", // token_info_url; - credential_source, // credential_source; + *credential_source, // credential_source; "quota_project_id", // quota_project_id; "client_id", // client_id; "client_secret", // client_secret; "", // workforce_pool_user_project; }; + grpc_error_handle error = GRPC_ERROR_NONE; auto creds = AwsExternalAccountCredentials::Create(options, {}, &error); GPR_ASSERT(creds != nullptr); GPR_ASSERT(GRPC_ERROR_IS_NONE(error)); diff --git a/test/core/security/json_token_test.cc b/test/core/security/json_token_test.cc index 014b4008ccb..8aa405407bc 100644 --- a/test/core/security/json_token_test.cc +++ b/test/core/security/json_token_test.cc @@ -217,16 +217,15 @@ static Json parse_json_part_from_jwt(const char* str, size_t len) { grpc_slice slice = grpc_base64_decode(b64, 1); gpr_free(b64); EXPECT_FALSE(GRPC_SLICE_IS_EMPTY(slice)); - grpc_error_handle error = GRPC_ERROR_NONE; absl::string_view string = grpc_core::StringViewFromSlice(slice); - Json json = Json::Parse(string, &error); - if (!GRPC_ERROR_IS_NONE(error)) { + auto json = Json::Parse(string); + grpc_slice_unref(slice); + if (!json.ok()) { gpr_log(GPR_ERROR, "JSON parse error: %s", - grpc_error_std_string(error).c_str()); - GRPC_ERROR_UNREF(error); + json.status().ToString().c_str()); + return Json(); } - grpc_slice_unref(slice); - return json; + return std::move(*json); } static void check_jwt_header(const Json& header) { diff --git a/test/core/security/jwt_verifier_test.cc b/test/core/security/jwt_verifier_test.cc index 3d1960462b8..db4f7f64645 100644 --- a/test/core/security/jwt_verifier_test.cc +++ b/test/core/security/jwt_verifier_test.cc @@ -208,18 +208,13 @@ TEST(JwtVerifierTest, JwtIssuerEmailDomain) { TEST(JwtVerifierTest, ClaimsSuccess) { grpc_jwt_claims* claims; - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(claims_without_time_constraint, &error); - if (!GRPC_ERROR_IS_NONE(error)) { - gpr_log(GPR_ERROR, "JSON parse error: %s", - grpc_error_std_string(error).c_str()); - } - ASSERT_TRUE(GRPC_ERROR_IS_NONE(error)); - ASSERT_EQ(json.type(), Json::Type::OBJECT); + auto json = Json::Parse(claims_without_time_constraint); + ASSERT_TRUE(json.ok()) << json.status(); + ASSERT_EQ(json->type(), Json::Type::OBJECT); grpc_core::ExecCtx exec_ctx; - claims = grpc_jwt_claims_from_json(json); + claims = grpc_jwt_claims_from_json(*json); ASSERT_NE(claims, nullptr); - ASSERT_EQ(*grpc_jwt_claims_json(claims), json); + ASSERT_EQ(*grpc_jwt_claims_json(claims), *json); ASSERT_STREQ(grpc_jwt_claims_audience(claims), "https://foo.com"); ASSERT_STREQ(grpc_jwt_claims_issuer(claims), "blah.foo.com"); ASSERT_STREQ(grpc_jwt_claims_subject(claims), "juju@blah.foo.com"); @@ -231,21 +226,16 @@ TEST(JwtVerifierTest, ClaimsSuccess) { TEST(JwtVerifierTest, ExpiredClaimsFailure) { grpc_jwt_claims* claims; - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(expired_claims, &error); - if (!GRPC_ERROR_IS_NONE(error)) { - gpr_log(GPR_ERROR, "JSON parse error: %s", - grpc_error_std_string(error).c_str()); - } - ASSERT_TRUE(GRPC_ERROR_IS_NONE(error)); - ASSERT_EQ(json.type(), Json::Type::OBJECT); + auto json = Json::Parse(expired_claims); + ASSERT_TRUE(json.ok()) << json.status(); + ASSERT_EQ(json->type(), Json::Type::OBJECT); gpr_timespec exp_iat = {100, 0, GPR_CLOCK_REALTIME}; gpr_timespec exp_exp = {120, 0, GPR_CLOCK_REALTIME}; gpr_timespec exp_nbf = {60, 0, GPR_CLOCK_REALTIME}; grpc_core::ExecCtx exec_ctx; - claims = grpc_jwt_claims_from_json(json); + claims = grpc_jwt_claims_from_json(*json); ASSERT_NE(claims, nullptr); - ASSERT_EQ(*grpc_jwt_claims_json(claims), json); + ASSERT_EQ(*grpc_jwt_claims_json(claims), *json); ASSERT_STREQ(grpc_jwt_claims_audience(claims), "https://foo.com"); ASSERT_STREQ(grpc_jwt_claims_issuer(claims), "blah.foo.com"); ASSERT_STREQ(grpc_jwt_claims_subject(claims), "juju@blah.foo.com"); @@ -253,37 +243,26 @@ TEST(JwtVerifierTest, ExpiredClaimsFailure) { ASSERT_EQ(gpr_time_cmp(grpc_jwt_claims_issued_at(claims), exp_iat), 0); ASSERT_EQ(gpr_time_cmp(grpc_jwt_claims_expires_at(claims), exp_exp), 0); ASSERT_EQ(gpr_time_cmp(grpc_jwt_claims_not_before(claims), exp_nbf), 0); - ASSERT_EQ(grpc_jwt_claims_check(claims, "https://foo.com"), GRPC_JWT_VERIFIER_TIME_CONSTRAINT_FAILURE); grpc_jwt_claims_destroy(claims); } TEST(JwtVerifierTest, InvalidClaimsFailure) { - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(invalid_claims, &error); - if (!GRPC_ERROR_IS_NONE(error)) { - gpr_log(GPR_ERROR, "JSON parse error: %s", - grpc_error_std_string(error).c_str()); - } - ASSERT_TRUE(GRPC_ERROR_IS_NONE(error)); - ASSERT_EQ(json.type(), Json::Type::OBJECT); + auto json = Json::Parse(invalid_claims); + ASSERT_TRUE(json.ok()) << json.status(); + ASSERT_EQ(json->type(), Json::Type::OBJECT); grpc_core::ExecCtx exec_ctx; - ASSERT_EQ(grpc_jwt_claims_from_json(json), nullptr); + ASSERT_EQ(grpc_jwt_claims_from_json(*json), nullptr); } TEST(JwtVerifierTest, BadAudienceClaimsFailure) { grpc_jwt_claims* claims; - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(claims_without_time_constraint, &error); - if (!GRPC_ERROR_IS_NONE(error)) { - gpr_log(GPR_ERROR, "JSON parse error: %s", - grpc_error_std_string(error).c_str()); - } - ASSERT_TRUE(GRPC_ERROR_IS_NONE(error)); - ASSERT_EQ(json.type(), Json::Type::OBJECT); + auto json = Json::Parse(claims_without_time_constraint); + ASSERT_TRUE(json.ok()) << json.status(); + ASSERT_EQ(json->type(), Json::Type::OBJECT); grpc_core::ExecCtx exec_ctx; - claims = grpc_jwt_claims_from_json(json); + claims = grpc_jwt_claims_from_json(*json); ASSERT_NE(claims, nullptr); ASSERT_EQ(grpc_jwt_claims_check(claims, "https://bar.com"), GRPC_JWT_VERIFIER_BAD_AUDIENCE); @@ -292,16 +271,11 @@ TEST(JwtVerifierTest, BadAudienceClaimsFailure) { TEST(JwtVerifierTest, BadSubjectClaimsFailure) { grpc_jwt_claims* claims; - grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(claims_with_bad_subject, &error); - if (!GRPC_ERROR_IS_NONE(error)) { - gpr_log(GPR_ERROR, "JSON parse error: %s", - grpc_error_std_string(error).c_str()); - } - ASSERT_TRUE(GRPC_ERROR_IS_NONE(error)); - ASSERT_EQ(json.type(), Json::Type::OBJECT); + auto json = Json::Parse(claims_with_bad_subject); + ASSERT_TRUE(json.ok()) << json.status(); + ASSERT_EQ(json->type(), Json::Type::OBJECT); grpc_core::ExecCtx exec_ctx; - claims = grpc_jwt_claims_from_json(json); + claims = grpc_jwt_claims_from_json(*json); ASSERT_NE(claims, nullptr); ASSERT_EQ(grpc_jwt_claims_check(claims, "https://foo.com"), GRPC_JWT_VERIFIER_BAD_SUBJECT); diff --git a/test/core/xds/file_watcher_certificate_provider_factory_test.cc b/test/core/xds/file_watcher_certificate_provider_factory_test.cc index fc9735fa44d..d1613073cbd 100644 --- a/test/core/xds/file_watcher_certificate_provider_factory_test.cc +++ b/test/core/xds/file_watcher_certificate_provider_factory_test.cc @@ -45,11 +45,11 @@ TEST(FileWatcherConfigTest, Basic) { " \"refresh_interval\": \"%ds\"" "}", kIdentityCertFile, kPrivateKeyFile, kRootCertFile, kRefreshInterval); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(config->identity_cert_file(), kIdentityCertFile); EXPECT_EQ(config->private_key_file(), kPrivateKeyFile); @@ -65,11 +65,11 @@ TEST(FileWatcherConfigTest, DefaultRefreshInterval) { " \"ca_certificate_file\": \"%s\"" "}", kIdentityCertFile, kPrivateKeyFile, kRootCertFile); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(config->identity_cert_file(), kIdentityCertFile); EXPECT_EQ(config->private_key_file(), kPrivateKeyFile); @@ -83,11 +83,11 @@ TEST(FileWatcherConfigTest, OnlyRootCertificatesFileProvided) { " \"ca_certificate_file\": \"%s\"" "}", kRootCertFile); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_TRUE(config->identity_cert_file().empty()); EXPECT_TRUE(config->private_key_file().empty()); @@ -102,11 +102,11 @@ TEST(FileWatcherConfigTest, OnlyIdenityCertificatesAndPrivateKeyProvided) { " \"private_key_file\": \"%s\"" "}", kIdentityCertFile, kPrivateKeyFile); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(config->identity_cert_file(), kIdentityCertFile); EXPECT_EQ(config->private_key_file(), kPrivateKeyFile); @@ -122,11 +122,11 @@ TEST(FileWatcherConfigTest, WrongTypes) { " \"ca_certificate_file\": 123," " \"refresh_interval\": 123" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "field:certificate_file error:type should be STRING.*" @@ -144,11 +144,11 @@ TEST(FileWatcherConfigTest, IdentityCertProvidedButPrivateKeyMissing) { " \"certificate_file\": \"%s\"" "}", kIdentityCertFile); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "fields \"certificate_file\" and \"private_key_file\" must " @@ -162,11 +162,11 @@ TEST(FileWatcherConfigTest, PrivateKeyProvidedButIdentityCertMissing) { " \"private_key_file\": \"%s\"" "}", kPrivateKeyFile); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "fields \"certificate_file\" and \"private_key_file\" must " @@ -176,11 +176,11 @@ TEST(FileWatcherConfigTest, PrivateKeyProvidedButIdentityCertMissing) { TEST(FileWatcherConfigTest, EmptyJsonObject) { std::string json_str = absl::StrFormat("{}"); + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - FileWatcherCertificateProviderFactory::Config::Parse(json, &error); + FileWatcherCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex("At least one of \"certificate_file\" and " diff --git a/test/core/xds/google_mesh_ca_certificate_provider_factory_test.cc b/test/core/xds/google_mesh_ca_certificate_provider_factory_test.cc index afd15d22538..e40507c8a96 100644 --- a/test/core/xds/google_mesh_ca_certificate_provider_factory_test.cc +++ b/test/core/xds/google_mesh_ca_certificate_provider_factory_test.cc @@ -69,11 +69,11 @@ TEST(GoogleMeshCaConfigTest, Basic) { "\"https://container.googleapis.com/v1/project/test-project1/locations/" "test-zone2/clusters/test-cluster3\"" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(config->endpoint(), "newmeshca.googleapis.com"); EXPECT_EQ(config->sts_config().token_exchange_service_uri, @@ -122,11 +122,11 @@ TEST(GoogleMeshCaConfigTest, Defaults) { "\"https://container.googleapis.com/v1/project/test-project1/locations/" "test-zone2/clusters/test-cluster3\"" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(config->endpoint(), "meshca.googleapis.com"); EXPECT_EQ(config->sts_config().token_exchange_service_uri, @@ -174,11 +174,11 @@ TEST(GoogleMeshCaConfigTest, WrongExpectedValues) { "\"https://container.googleapis.com/v1/project/test-project1/locations/" "test-zone2/clusters/test-cluster3\"" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex("field:api_type error:Only GRPC is supported.*" @@ -217,11 +217,11 @@ TEST(GoogleMeshCaConfigTest, WrongTypes) { " \"key_size\": \"1024A\"," " \"location\": 123" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex( @@ -261,11 +261,11 @@ TEST(GoogleMeshCaConfigTest, GrpcServicesNotAnArray) { "\"https://container.googleapis.com/v1/project/test-project1/locations/" "test-zone2/clusters/test-cluster3\"" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex( @@ -286,11 +286,11 @@ TEST(GoogleMeshCaConfigTest, GoogleGrpcNotAnObject) { "\"https://container.googleapis.com/v1/project/test-project1/locations/" "test-zone2/clusters/test-cluster3\"" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex("field:server.*field:grpc_services.*field:" @@ -313,11 +313,11 @@ TEST(GoogleMeshCaConfigTest, CallCredentialsNotAnArray) { "\"https://container.googleapis.com/v1/project/test-project1/locations/" "test-zone2/clusters/test-cluster3\"" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "field:server.*field:grpc_services.*field:google_grpc.*" @@ -342,11 +342,11 @@ TEST(GoogleMeshCaConfigTest, StsServiceNotAnObject) { "\"https://container.googleapis.com/v1/project/test-project1/locations/" "test-zone2/clusters/test-cluster3\"" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); auto config = - GoogleMeshCaCertificateProviderFactory::Config::Parse(json, &error); + GoogleMeshCaCertificateProviderFactory::Config::Parse(*json, &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex( diff --git a/test/core/xds/xds_bootstrap_test.cc b/test/core/xds/xds_bootstrap_test.cc index 4b79ad8f458..2637d540630 100644 --- a/test/core/xds/xds_bootstrap_test.cc +++ b/test/core/xds/xds_bootstrap_test.cc @@ -117,10 +117,10 @@ TEST(XdsBootstrapTest, Basic) { " \"server_listener_resource_name_template\": \"example/resource\"," " \"ignore\": {}" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(bootstrap.server().server_uri, "fake:///lb"); EXPECT_EQ(bootstrap.server().channel_creds_type, "fake"); @@ -183,10 +183,10 @@ TEST(XdsBootstrapTest, ValidWithoutNode) { " }" " ]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(bootstrap.server().server_uri, "fake:///lb"); EXPECT_EQ(bootstrap.server().channel_creds_type, "fake"); @@ -203,10 +203,10 @@ TEST(XdsBootstrapTest, InsecureCreds) { " }" " ]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(bootstrap.server().server_uri, "fake:///lb"); EXPECT_EQ(bootstrap.server().channel_creds_type, "insecure"); @@ -239,10 +239,10 @@ TEST(XdsBootstrapTest, GoogleDefaultCreds) { " }" " ]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); EXPECT_EQ(bootstrap.server().server_uri, "fake:///lb"); EXPECT_EQ(bootstrap.server().channel_creds_type, "google_default"); @@ -258,10 +258,10 @@ TEST(XdsBootstrapTest, MissingChannelCreds) { " }" " ]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex("field:channel_creds error:does not exist.")); @@ -278,10 +278,10 @@ TEST(XdsBootstrapTest, NoKnownChannelCreds) { " }" " ]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "no known creds type found in \"channel_creds\"")); @@ -289,10 +289,10 @@ TEST(XdsBootstrapTest, NoKnownChannelCreds) { } TEST(XdsBootstrapTest, MissingXdsServers) { + auto json = Json::Parse("{}"); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse("{}", &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex("\"xds_servers\" field not present")); GRPC_ERROR_UNREF(error); @@ -306,10 +306,10 @@ TEST(XdsBootstrapTest, TopFieldsWrongTypes) { " \"server_listener_resource_name_template\":1," " \"certificate_providers\":1" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex("\"xds_servers\" field is not an array.*" "\"node\" field is not an object.*" @@ -326,10 +326,10 @@ TEST(XdsBootstrapTest, XdsServerMissingServerUri) { "{" " \"xds_servers\":[{}]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex("errors parsing \"xds_servers\" array.*" @@ -349,10 +349,10 @@ TEST(XdsBootstrapTest, XdsServerUriAndCredsWrongTypes) { " }" " ]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "errors parsing \"xds_servers\" array.*" @@ -378,10 +378,10 @@ TEST(XdsBootstrapTest, ChannelCredsFieldsWrongTypes) { " }" " ]" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex("errors parsing \"xds_servers\" array.*" @@ -404,10 +404,10 @@ TEST(XdsBootstrapTest, NodeFieldsWrongTypes) { " \"metadata\":0" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex("errors parsing \"node\" object.*" "\"id\" field is not a string.*" @@ -428,10 +428,10 @@ TEST(XdsBootstrapTest, LocalityFieldsWrongType) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex("errors parsing \"node\" object.*" "errors parsing \"locality\" object.*" @@ -454,10 +454,10 @@ TEST(XdsBootstrapTest, CertificateProvidersElementWrongType) { " \"plugin\":1" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "errors parsing \"certificate_providers\" object.*" @@ -480,10 +480,10 @@ TEST(XdsBootstrapTest, CertificateProvidersPluginNameWrongType) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "errors parsing \"certificate_providers\" object.*" @@ -507,10 +507,10 @@ TEST(XdsBootstrapTest, CertificateProvidersUnrecognizedPluginName) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "errors parsing \"certificate_providers\" object.*" @@ -548,10 +548,10 @@ TEST(XdsBootstrapTest, AuthorityXdsServerInvalidResourceTemplate) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "errors parsing \"authorities\".*" @@ -580,10 +580,10 @@ TEST(XdsBootstrapTest, AuthorityXdsServerMissingServerUri) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT( grpc_error_std_string(error), ::testing::ContainsRegex("errors parsing \"authorities\".*" @@ -663,10 +663,10 @@ TEST(XdsBootstrapTest, CertificateProvidersFakePluginParsingError) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); EXPECT_THAT(grpc_error_std_string(error), ::testing::ContainsRegex( "errors parsing \"certificate_providers\" object.*" @@ -693,10 +693,10 @@ TEST(XdsBootstrapTest, CertificateProvidersFakePluginParsingSuccess) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); ASSERT_TRUE(GRPC_ERROR_IS_NONE(error)) << grpc_error_std_string(error); const CertificateProviderStore::PluginDefinition& fake_plugin = bootstrap.certificate_providers().at("fake_plugin"); @@ -723,10 +723,10 @@ TEST(XdsBootstrapTest, CertificateProvidersFakePluginEmptyConfig) { " }" " }" "}"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - XdsBootstrap bootstrap(std::move(json), &error); + XdsBootstrap bootstrap(std::move(*json), &error); ASSERT_TRUE(GRPC_ERROR_IS_NONE(error)) << grpc_error_std_string(error); const CertificateProviderStore::PluginDefinition& fake_plugin = bootstrap.certificate_providers().at("fake_plugin"); @@ -751,11 +751,11 @@ TEST(XdsBootstrapTest, XdsServerToJsonAndParse) { " ]," " \"ignore\": 0" " }"; + auto json = Json::Parse(json_str); + ASSERT_TRUE(json.ok()) << json.status(); grpc_error_handle error = GRPC_ERROR_NONE; - Json json = Json::Parse(json_str, &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); XdsBootstrap::XdsServer xds_server = - XdsBootstrap::XdsServer::Parse(json, &error); + XdsBootstrap::XdsServer::Parse(*json, &error); ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); Json::Object output = xds_server.ToJson(); XdsBootstrap::XdsServer output_xds_server = diff --git a/test/core/xds/xds_lb_policy_registry_test.cc b/test/core/xds/xds_lb_policy_registry_test.cc index 38ecedbe62c..50fc25759b8 100644 --- a/test/core/xds/xds_lb_policy_registry_test.cc +++ b/test/core/xds/xds_lb_policy_registry_test.cc @@ -133,11 +133,10 @@ TEST(XdsLbPolicyRegistryTest, RingHashRingSizeDefaults) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse("{" "\"ring_hash_experimental\": {" - "}}", - &error)); + "}}") + .value()); } TEST(XdsLbPolicyRegistryTest, RingHashRingSizeCustom) { @@ -152,13 +151,12 @@ TEST(XdsLbPolicyRegistryTest, RingHashRingSizeCustom) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse("{" "\"ring_hash_experimental\": {" " \"minRingSize\": 1234," " \"maxRingSize\": 4567" - "}}", - &error)); + "}}") + .value()); } TEST(XdsLbPolicyRegistryTest, RoundRobin) { @@ -169,11 +167,10 @@ TEST(XdsLbPolicyRegistryTest, RoundRobin) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse("{" "\"round_robin\": {}" - "}", - &error)); + "}") + .value()); } TEST(XdsLbPolicyRegistryTest, WrrLocality) { @@ -190,14 +187,13 @@ TEST(XdsLbPolicyRegistryTest, WrrLocality) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse("{" "\"xds_wrr_locality_experimental\": {" " \"child_policy\": [{" " \"round_robin\": {}" " }]" - "}}", - &error)); + "}}") + .value()); } TEST(XdsLbPolicyRegistryTest, WrrLocalityMissingEndpointPickingPolicy) { @@ -256,14 +252,13 @@ TEST(XdsLbPolicyRegistryTest, WrrLocalityUnsupportedTypeSkipped) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse("{" "\"xds_wrr_locality_experimental\": {" " \"child_policy\": [{" " \"round_robin\": {}" " }]" - "}}", - &error)); + "}}") + .value()); } class CustomLbPolicyFactory : public LoadBalancingPolicyFactory { @@ -292,10 +287,7 @@ TEST(XdsLbPolicyRegistryTest, CustomLbPolicy) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; - EXPECT_EQ((*result)[0], Json::Parse("{" - "\"test.CustomLb\": null}", - &error)); + EXPECT_EQ((*result)[0], Json::Parse("{\"test.CustomLb\": null}").value()); } TEST(XdsLbPolicyRegistryTest, CustomLbPolicyUdpaTyped) { @@ -308,10 +300,7 @@ TEST(XdsLbPolicyRegistryTest, CustomLbPolicyUdpaTyped) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; - EXPECT_EQ((*result)[0], Json::Parse("{" - "\"test.CustomLb\": null}", - &error)); + EXPECT_EQ((*result)[0], Json::Parse("{\"test.CustomLb\": null}").value()); } TEST(XdsLbPolicyRegistryTest, UnsupportedCustomTypeError) { @@ -408,7 +397,6 @@ TEST(XdsLbPolicyRegistryTest, CustomLbPolicyJsonConversion) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse( R"json({ "test.CustomLb":{ @@ -420,8 +408,8 @@ TEST(XdsLbPolicyRegistryTest, CustomLbPolicyJsonConversion) { }, "list": [null, 234] } - })json", - &error)); + })json") + .value()); } TEST(XdsLbPolicyRegistryTest, CustomLbPolicyListError) { @@ -458,11 +446,10 @@ TEST(XdsLbPolicyRegistryTest, UnsupportedBuiltInTypeSkipped) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse("{" "\"round_robin\": {}" - "}", - &error)); + "}") + .value()); } TEST(XdsLbPolicyRegistryTest, UnsupportedCustomTypeSkipped) { @@ -481,11 +468,10 @@ TEST(XdsLbPolicyRegistryTest, UnsupportedCustomTypeSkipped) { auto result = ConvertXdsPolicy(policy); EXPECT_TRUE(result.ok()); EXPECT_EQ(result->size(), 1); - grpc_error_handle error = GRPC_ERROR_NONE; EXPECT_EQ((*result)[0], Json::Parse("{" "\"round_robin\": {}" - "}", - &error)); + "}") + .value()); } // Build a recurse load balancing policy that goes beyond the max allowable diff --git a/test/cpp/util/channel_trace_proto_helper.cc b/test/cpp/util/channel_trace_proto_helper.cc index 770c9b00cb8..9ab8a2b6e93 100644 --- a/test/cpp/util/channel_trace_proto_helper.cc +++ b/test/cpp/util/channel_trace_proto_helper.cc @@ -59,15 +59,10 @@ void VaidateProtoJsonTranslation(const std::string& json_str) { EXPECT_TRUE(s.ok()); // Parse JSON and re-dump to string, to make sure formatting is the // same as what would be generated by our JSON library. - grpc_error_handle error = GRPC_ERROR_NONE; - grpc_core::Json parsed_json = - grpc_core::Json::Parse(proto_json_str.c_str(), &error); - ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_std_string(error); - ASSERT_EQ(parsed_json.type(), grpc_core::Json::Type::OBJECT); - proto_json_str = parsed_json.Dump(); - // uncomment these to compare the json strings. - // gpr_log(GPR_ERROR, "tracer json: %s", json_str.c_str()); - // gpr_log(GPR_ERROR, "proto json: %s", proto_json_str.c_str()); + auto parsed_json = grpc_core::Json::Parse(proto_json_str.c_str()); + ASSERT_TRUE(parsed_json.ok()) << parsed_json.status(); + ASSERT_EQ(parsed_json->type(), grpc_core::Json::Type::OBJECT); + proto_json_str = parsed_json->Dump(); EXPECT_EQ(json_str, proto_json_str); }