diff --git a/include/envoy/server/BUILD b/include/envoy/server/BUILD index 2dbd768aab91..591868dde496 100644 --- a/include/envoy/server/BUILD +++ b/include/envoy/server/BUILD @@ -234,6 +234,7 @@ envoy_cc_library( ":resource_monitor_interface", "//include/envoy/api:api_interface", "//include/envoy/event:dispatcher_interface", + "//include/envoy/protobuf:message_validator_interface", ], ) diff --git a/include/envoy/server/filter_config.h b/include/envoy/server/filter_config.h index 8cd1b4058353..4864d5bf9da6 100644 --- a/include/envoy/server/filter_config.h +++ b/include/envoy/server/filter_config.h @@ -269,11 +269,14 @@ class ProtocolOptionsFactory { * implementation is unable to produce a factory with the provided parameters, it should throw an * EnvoyException. * @param config supplies the protobuf configuration for the filter + * @param validation_visitor message validation visitor instance. * @return Upstream::ProtocolOptionsConfigConstSharedPtr the protocol options */ virtual Upstream::ProtocolOptionsConfigConstSharedPtr - createProtocolOptionsConfig(const Protobuf::Message& config) { + createProtocolOptionsConfig(const Protobuf::Message& config, + ProtobufMessage::ValidationVisitor& validation_visitor) { UNREFERENCED_PARAMETER(config); + UNREFERENCED_PARAMETER(validation_visitor); return nullptr; } diff --git a/include/envoy/server/resource_monitor_config.h b/include/envoy/server/resource_monitor_config.h index aef576b8e4bf..db7cc786a11e 100644 --- a/include/envoy/server/resource_monitor_config.h +++ b/include/envoy/server/resource_monitor_config.h @@ -3,6 +3,7 @@ #include "envoy/api/api.h" #include "envoy/common/pure.h" #include "envoy/event/dispatcher.h" +#include "envoy/protobuf/message_validator.h" #include "envoy/server/resource_monitor.h" #include "common/protobuf/protobuf.h" @@ -25,6 +26,12 @@ class ResourceMonitorFactoryContext { * @return reference to the Api object */ virtual Api::Api& api() PURE; + + /** + * @return ProtobufMessage::ValidationVisitor& validation visitor for filter configuration + * messages. + */ + virtual ProtobufMessage::ValidationVisitor& messageValidationVisitor() PURE; }; /** diff --git a/include/envoy/upstream/retry.h b/include/envoy/upstream/retry.h index dd518eb13ea5..82928f661f39 100644 --- a/include/envoy/upstream/retry.h +++ b/include/envoy/upstream/retry.h @@ -79,8 +79,10 @@ class RetryPriorityFactory { public: virtual ~RetryPriorityFactory() = default; - virtual RetryPrioritySharedPtr createRetryPriority(const Protobuf::Message& config, - uint32_t retry_count) PURE; + virtual RetryPrioritySharedPtr + createRetryPriority(const Protobuf::Message& config, + ProtobufMessage::ValidationVisitor& validation_visitor, + uint32_t retry_count) PURE; virtual std::string name() const PURE; diff --git a/source/common/access_log/access_log_impl.cc b/source/common/access_log/access_log_impl.cc index f59c96d1b66e..498c3e18176d 100644 --- a/source/common/access_log/access_log_impl.cc +++ b/source/common/access_log/access_log_impl.cc @@ -53,7 +53,8 @@ bool ComparisonFilter::compareAgainstValue(uint64_t lhs) { FilterPtr FilterFactory::fromProto(const envoy::config::filter::accesslog::v2::AccessLogFilter& config, - Runtime::Loader& runtime, Runtime::RandomGenerator& random) { + Runtime::Loader& runtime, Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor) { switch (config.filter_specifier_case()) { case envoy::config::filter::accesslog::v2::AccessLogFilter::kStatusCodeFilter: return FilterPtr{new StatusCodeFilter(config.status_code_filter(), runtime)}; @@ -66,19 +67,19 @@ FilterFactory::fromProto(const envoy::config::filter::accesslog::v2::AccessLogFi case envoy::config::filter::accesslog::v2::AccessLogFilter::kRuntimeFilter: return FilterPtr{new RuntimeFilter(config.runtime_filter(), runtime, random)}; case envoy::config::filter::accesslog::v2::AccessLogFilter::kAndFilter: - return FilterPtr{new AndFilter(config.and_filter(), runtime, random)}; + return FilterPtr{new AndFilter(config.and_filter(), runtime, random, validation_visitor)}; case envoy::config::filter::accesslog::v2::AccessLogFilter::kOrFilter: - return FilterPtr{new OrFilter(config.or_filter(), runtime, random)}; + return FilterPtr{new OrFilter(config.or_filter(), runtime, random, validation_visitor)}; case envoy::config::filter::accesslog::v2::AccessLogFilter::kHeaderFilter: return FilterPtr{new HeaderFilter(config.header_filter())}; case envoy::config::filter::accesslog::v2::AccessLogFilter::kResponseFlagFilter: - MessageUtil::validate(config); + MessageUtil::validate(config, validation_visitor); return FilterPtr{new ResponseFlagFilter(config.response_flag_filter())}; case envoy::config::filter::accesslog::v2::AccessLogFilter::kGrpcStatusFilter: - MessageUtil::validate(config); + MessageUtil::validate(config, validation_visitor); return FilterPtr{new GrpcStatusFilter(config.grpc_status_filter())}; case envoy::config::filter::accesslog::v2::AccessLogFilter::kExtensionFilter: - MessageUtil::validate(config); + MessageUtil::validate(config, validation_visitor); { auto& factory = Config::Utility::getAndCheckFactory( config.extension_filter().name()); @@ -140,19 +141,22 @@ bool RuntimeFilter::evaluate(const StreamInfo::StreamInfo&, const Http::HeaderMa OperatorFilter::OperatorFilter(const Protobuf::RepeatedPtrField< envoy::config::filter::accesslog::v2::AccessLogFilter>& configs, - Runtime::Loader& runtime, Runtime::RandomGenerator& random) { + Runtime::Loader& runtime, Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor) { for (const auto& config : configs) { - filters_.emplace_back(FilterFactory::fromProto(config, runtime, random)); + filters_.emplace_back(FilterFactory::fromProto(config, runtime, random, validation_visitor)); } } OrFilter::OrFilter(const envoy::config::filter::accesslog::v2::OrFilter& config, - Runtime::Loader& runtime, Runtime::RandomGenerator& random) - : OperatorFilter(config.filters(), runtime, random) {} + Runtime::Loader& runtime, Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor) + : OperatorFilter(config.filters(), runtime, random, validation_visitor) {} AndFilter::AndFilter(const envoy::config::filter::accesslog::v2::AndFilter& config, - Runtime::Loader& runtime, Runtime::RandomGenerator& random) - : OperatorFilter(config.filters(), runtime, random) {} + Runtime::Loader& runtime, Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor) + : OperatorFilter(config.filters(), runtime, random, validation_visitor) {} bool OrFilter::evaluate(const StreamInfo::StreamInfo& info, const Http::HeaderMap& request_headers, const Http::HeaderMap& response_headers, @@ -268,7 +272,8 @@ AccessLogFactory::fromProto(const envoy::config::filter::accesslog::v2::AccessLo Server::Configuration::FactoryContext& context) { FilterPtr filter; if (config.has_filter()) { - filter = FilterFactory::fromProto(config.filter(), context.runtime(), context.random()); + filter = FilterFactory::fromProto(config.filter(), context.runtime(), context.random(), + context.messageValidationVisitor()); } auto& factory = diff --git a/source/common/access_log/access_log_impl.h b/source/common/access_log/access_log_impl.h index 899e81a2902e..7e3aa51b3329 100644 --- a/source/common/access_log/access_log_impl.h +++ b/source/common/access_log/access_log_impl.h @@ -28,7 +28,8 @@ class FilterFactory { * Read a filter definition from proto and instantiate a concrete filter class. */ static FilterPtr fromProto(const envoy::config::filter::accesslog::v2::AccessLogFilter& config, - Runtime::Loader& runtime, Runtime::RandomGenerator& random); + Runtime::Loader& runtime, Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor); }; /** @@ -82,7 +83,8 @@ class OperatorFilter : public Filter { public: OperatorFilter(const Protobuf::RepeatedPtrField< envoy::config::filter::accesslog::v2::AccessLogFilter>& configs, - Runtime::Loader& runtime, Runtime::RandomGenerator& random); + Runtime::Loader& runtime, Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor); protected: std::vector filters_; @@ -94,7 +96,8 @@ class OperatorFilter : public Filter { class AndFilter : public OperatorFilter { public: AndFilter(const envoy::config::filter::accesslog::v2::AndFilter& config, Runtime::Loader& runtime, - Runtime::RandomGenerator& random); + Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor); // AccessLog::Filter bool evaluate(const StreamInfo::StreamInfo& info, const Http::HeaderMap& request_headers, @@ -108,7 +111,8 @@ class AndFilter : public OperatorFilter { class OrFilter : public OperatorFilter { public: OrFilter(const envoy::config::filter::accesslog::v2::OrFilter& config, Runtime::Loader& runtime, - Runtime::RandomGenerator& random); + Runtime::RandomGenerator& random, + ProtobufMessage::ValidationVisitor& validation_visitor); // AccessLog::Filter bool evaluate(const StreamInfo::StreamInfo& info, const Http::HeaderMap& request_headers, diff --git a/source/common/protobuf/utility.h b/source/common/protobuf/utility.h index 2f2aff2a3f6e..d0451893d479 100644 --- a/source/common/protobuf/utility.h +++ b/source/common/protobuf/utility.h @@ -235,9 +235,12 @@ class MessageUtil { * @param message message to validate. * @throw ProtoValidationException if the message does not satisfy its type constraints. */ - template static void validate(const MessageType& message) { + template + static void validate(const MessageType& message, + ProtobufMessage::ValidationVisitor& validation_visitor) { // Log warnings or throw errors if deprecated fields are in use. checkForDeprecation(message); + checkUnknownFields(message, validation_visitor); std::string err; if (!Validate(message, &err)) { @@ -249,14 +252,14 @@ class MessageUtil { static void loadFromFileAndValidate(const std::string& path, MessageType& message, ProtobufMessage::ValidationVisitor& validation_visitor) { loadFromFile(path, message, validation_visitor); - validate(message); + validate(message, validation_visitor); } template static void loadFromYamlAndValidate(const std::string& yaml, MessageType& message, ProtobufMessage::ValidationVisitor& validation_visitor) { loadFromYaml(yaml, message, validation_visitor); - validate(message); + validate(message, validation_visitor); } /** @@ -268,9 +271,11 @@ class MessageUtil { * @throw ProtoValidationException if the message does not satisfy its type constraints. */ template - static const MessageType& downcastAndValidate(const Protobuf::Message& config) { + static const MessageType& + downcastAndValidate(const Protobuf::Message& config, + ProtobufMessage::ValidationVisitor& validation_visitor) { const auto& typed_config = dynamic_cast(config); - validate(typed_config); + validate(typed_config, validation_visitor); return typed_config; } @@ -282,13 +287,11 @@ class MessageUtil { * @return MessageType the typed message inside the Any. */ template - static inline MessageType anyConvert(const ProtobufWkt::Any& message, - ProtobufMessage::ValidationVisitor& validation_visitor) { + static inline MessageType anyConvert(const ProtobufWkt::Any& message) { MessageType typed_message; if (!message.UnpackTo(&typed_message)) { throw EnvoyException("Unable to unpack " + message.DebugString()); } - checkUnknownFields(typed_message, validation_visitor); return typed_message; }; diff --git a/source/common/router/config_impl.cc b/source/common/router/config_impl.cc index a589af954269..408689e95d80 100644 --- a/source/common/router/config_impl.cc +++ b/source/common/router/config_impl.cc @@ -66,7 +66,8 @@ HedgePolicyImpl::HedgePolicyImpl() : initial_requests_(1), additional_request_chance_({}), hedge_on_per_try_timeout_(false) {} RetryPolicyImpl::RetryPolicyImpl(const envoy::api::v2::route::RetryPolicy& retry_policy, - ProtobufMessage::ValidationVisitor& validation_visitor) { + ProtobufMessage::ValidationVisitor& validation_visitor) + : validation_visitor_(&validation_visitor) { per_try_timeout_ = std::chrono::milliseconds(PROTOBUF_GET_MS_OR_DEFAULT(retry_policy, per_try_timeout, 0)); num_retries_ = PROTOBUF_GET_WRAPPED_OR_DEFAULT(retry_policy, num_retries, 1); @@ -141,7 +142,8 @@ Upstream::RetryPrioritySharedPtr RetryPolicyImpl::retryPriority() const { auto& factory = Envoy::Config::Utility::getAndCheckFactory( retry_priority_config_.first); - return factory.createRetryPriority(*retry_priority_config_.second, num_retries_); + return factory.createRetryPriority(*retry_priority_config_.second, *validation_visitor_, + num_retries_); } CorsPolicyImpl::CorsPolicyImpl(const envoy::api::v2::route::CorsPolicy& config, diff --git a/source/common/router/config_impl.h b/source/common/router/config_impl.h index 22ed8ae088a6..202ffe6bea6d 100644 --- a/source/common/router/config_impl.h +++ b/source/common/router/config_impl.h @@ -258,6 +258,7 @@ class RetryPolicyImpl : public RetryPolicy { std::vector retriable_status_codes_; absl::optional base_interval_; absl::optional max_interval_; + ProtobufMessage::ValidationVisitor* validation_visitor_{}; }; /** diff --git a/source/common/router/rds_impl.cc b/source/common/router/rds_impl.cc index d94910325cdb..b95554601aef 100644 --- a/source/common/router/rds_impl.cc +++ b/source/common/router/rds_impl.cc @@ -92,9 +92,8 @@ void RdsRouteConfigSubscription::onConfigUpdate( if (!validateUpdateSize(resources.size())) { return; } - auto route_config = MessageUtil::anyConvert( - resources[0], validation_visitor_); - MessageUtil::validate(route_config); + auto route_config = MessageUtil::anyConvert(resources[0]); + MessageUtil::validate(route_config, validation_visitor_); if (route_config.name() != route_config_name_) { throw EnvoyException(fmt::format("Unexpected RDS configuration (expecting {}): {}", route_config_name_, route_config.name())); diff --git a/source/common/router/rds_impl.h b/source/common/router/rds_impl.h index 2e8bbc61a5b4..21acac47cfa7 100644 --- a/source/common/router/rds_impl.h +++ b/source/common/router/rds_impl.h @@ -118,9 +118,7 @@ class RdsRouteConfigSubscription : Envoy::Config::SubscriptionCallbacks, void onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason reason, const EnvoyException* e) override; std::string resourceName(const ProtobufWkt::Any& resource) override { - return MessageUtil::anyConvert(resource, - validation_visitor_) - .name(); + return MessageUtil::anyConvert(resource).name(); } RdsRouteConfigSubscription( diff --git a/source/common/router/route_config_update_receiver_impl.cc b/source/common/router/route_config_update_receiver_impl.cc index ecaa5dbb20e8..81931e482c90 100644 --- a/source/common/router/route_config_update_receiver_impl.cc +++ b/source/common/router/route_config_update_receiver_impl.cc @@ -60,9 +60,8 @@ void RouteConfigUpdateReceiverImpl::updateVhosts( const Protobuf::RepeatedPtrField& added_resources) { for (const auto& resource : added_resources) { envoy::api::v2::route::VirtualHost vhost = - MessageUtil::anyConvert(resource.resource(), - validation_visitor_); - MessageUtil::validate(vhost); + MessageUtil::anyConvert(resource.resource()); + MessageUtil::validate(vhost, validation_visitor_); auto found = vhosts.find(vhost.name()); if (found != vhosts.end()) { vhosts.erase(found); diff --git a/source/common/router/scoped_rds.cc b/source/common/router/scoped_rds.cc index e30ea4296b7c..26ef93327284 100644 --- a/source/common/router/scoped_rds.cc +++ b/source/common/router/scoped_rds.cc @@ -105,8 +105,8 @@ void ScopedRdsConfigSubscription::onConfigUpdate( const std::string& version_info) { std::vector scoped_routes; for (const auto& resource_any : resources) { - scoped_routes.emplace_back(MessageUtil::anyConvert( - resource_any, validation_visitor_)); + scoped_routes.emplace_back( + MessageUtil::anyConvert(resource_any)); } std::unordered_set resource_names; @@ -117,7 +117,7 @@ void ScopedRdsConfigSubscription::onConfigUpdate( } } for (const auto& scoped_route : scoped_routes) { - MessageUtil::validate(scoped_route); + MessageUtil::validate(scoped_route, validation_visitor_); } // TODO(AndresGuedez): refactor such that it can be shared with other delta APIs (e.g., CDS). diff --git a/source/common/router/scoped_rds.h b/source/common/router/scoped_rds.h index 4fd6c72c3ff8..3d006b6a7039 100644 --- a/source/common/router/scoped_rds.h +++ b/source/common/router/scoped_rds.h @@ -115,9 +115,7 @@ class ScopedRdsConfigSubscription : public Envoy::Config::DeltaConfigSubscriptio ConfigSubscriptionCommonBase::onConfigUpdateFailed(); } std::string resourceName(const ProtobufWkt::Any& resource) override { - return MessageUtil::anyConvert(resource, - validation_visitor_) - .name(); + return MessageUtil::anyConvert(resource).name(); } const std::string name_; diff --git a/source/common/router/vhds.cc b/source/common/router/vhds.cc index f48449f67897..6cd05ed015f0 100644 --- a/source/common/router/vhds.cc +++ b/source/common/router/vhds.cc @@ -28,8 +28,7 @@ VhdsSubscription::VhdsSubscription(RouteConfigUpdatePtr& config_update_info, scope_(factory_context.scope().createScope(stat_prefix + "vhds." + config_update_info_->routeConfigName() + ".")), stats_({ALL_VHDS_STATS(POOL_COUNTER(*scope_))}), - route_config_providers_(route_config_providers), - validation_visitor_(factory_context.messageValidationVisitor()) { + route_config_providers_(route_config_providers) { const auto& config_source = config_update_info_->routeConfiguration() .vhds() .config_source() diff --git a/source/common/router/vhds.h b/source/common/router/vhds.h index 0959bc6eca2a..a2d3cb6beb81 100644 --- a/source/common/router/vhds.h +++ b/source/common/router/vhds.h @@ -59,9 +59,7 @@ class VhdsSubscription : Envoy::Config::SubscriptionCallbacks, void onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason reason, const EnvoyException* e) override; std::string resourceName(const ProtobufWkt::Any& resource) override { - return MessageUtil::anyConvert(resource, - validation_visitor_) - .name(); + return MessageUtil::anyConvert(resource).name(); } RouteConfigUpdatePtr& config_update_info_; @@ -70,7 +68,6 @@ class VhdsSubscription : Envoy::Config::SubscriptionCallbacks, Stats::ScopePtr scope_; VhdsStats stats_; std::unordered_set& route_config_providers_; - ProtobufMessage::ValidationVisitor& validation_visitor_; }; using VhdsSubscriptionPtr = std::unique_ptr; diff --git a/source/common/runtime/runtime_impl.cc b/source/common/runtime/runtime_impl.cc index 3e86fcba3329..b668b9aa7187 100644 --- a/source/common/runtime/runtime_impl.cc +++ b/source/common/runtime/runtime_impl.cc @@ -517,9 +517,8 @@ RtdsSubscription::RtdsSubscription( void RtdsSubscription::onConfigUpdate(const Protobuf::RepeatedPtrField& resources, const std::string&) { validateUpdateSize(resources.size()); - auto runtime = MessageUtil::anyConvert( - resources[0], validation_visitor_); - MessageUtil::validate(runtime); + auto runtime = MessageUtil::anyConvert(resources[0]); + MessageUtil::validate(runtime, validation_visitor_); if (runtime.name() != resource_name_) { throw EnvoyException( fmt::format("Unexpected RTDS runtime (expecting {}): {}", resource_name_, runtime.name())); diff --git a/source/common/runtime/runtime_impl.h b/source/common/runtime/runtime_impl.h index 06be894c5aec..7832fe970c87 100644 --- a/source/common/runtime/runtime_impl.h +++ b/source/common/runtime/runtime_impl.h @@ -209,9 +209,7 @@ struct RtdsSubscription : Config::SubscriptionCallbacks, Logger::Loggable(resource, - validation_visitor_) - .name(); + return MessageUtil::anyConvert(resource).name(); } void start(); diff --git a/source/common/secret/sds_api.cc b/source/common/secret/sds_api.cc index 1aa00bb8c75b..7d695040dfa9 100644 --- a/source/common/secret/sds_api.cc +++ b/source/common/secret/sds_api.cc @@ -30,9 +30,8 @@ SdsApi::SdsApi(envoy::api::v2::core::ConfigSource sds_config, absl::string_view void SdsApi::onConfigUpdate(const Protobuf::RepeatedPtrField& resources, const std::string& version_info) { validateUpdateSize(resources.size()); - auto secret = - MessageUtil::anyConvert(resources[0], validation_visitor_); - MessageUtil::validate(secret); + auto secret = MessageUtil::anyConvert(resources[0]); + MessageUtil::validate(secret, validation_visitor_); if (secret.name() != sds_config_name_) { throw EnvoyException( diff --git a/source/common/secret/sds_api.h b/source/common/secret/sds_api.h index d6b9235157fa..762de28c96b4 100644 --- a/source/common/secret/sds_api.h +++ b/source/common/secret/sds_api.h @@ -59,8 +59,7 @@ class SdsApi : public Config::SubscriptionCallbacks { void onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason reason, const EnvoyException* e) override; std::string resourceName(const ProtobufWkt::Any& resource) override { - return MessageUtil::anyConvert(resource, validation_visitor_) - .name(); + return MessageUtil::anyConvert(resource).name(); } private: diff --git a/source/common/upstream/cds_api_impl.cc b/source/common/upstream/cds_api_impl.cc index 2d0271f56e58..3ec334cf9b52 100644 --- a/source/common/upstream/cds_api_impl.cc +++ b/source/common/upstream/cds_api_impl.cc @@ -35,8 +35,7 @@ void CdsApiImpl::onConfigUpdate(const Protobuf::RepeatedPtrField clusters; for (const auto& cluster_blob : resources) { - clusters.push_back( - MessageUtil::anyConvert(cluster_blob, validation_visitor_)); + clusters.push_back(MessageUtil::anyConvert(cluster_blob)); clusters_to_remove.erase(clusters.back().name()); } Protobuf::RepeatedPtrField to_remove_repeated; @@ -66,9 +65,8 @@ void CdsApiImpl::onConfigUpdate( for (const auto& resource : added_resources) { envoy::api::v2::Cluster cluster; try { - cluster = MessageUtil::anyConvert(resource.resource(), - validation_visitor_); - MessageUtil::validate(cluster); + cluster = MessageUtil::anyConvert(resource.resource()); + MessageUtil::validate(cluster, validation_visitor_); if (!cluster_names.insert(cluster.name()).second) { // NOTE: at this point, the first of these duplicates has already been successfully applied. throw EnvoyException(fmt::format("duplicate cluster {} found", cluster.name())); diff --git a/source/common/upstream/cds_api_impl.h b/source/common/upstream/cds_api_impl.h index 2825213f3153..b17d4bbc9989 100644 --- a/source/common/upstream/cds_api_impl.h +++ b/source/common/upstream/cds_api_impl.h @@ -43,7 +43,7 @@ class CdsApiImpl : public CdsApi, void onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason reason, const EnvoyException* e) override; std::string resourceName(const ProtobufWkt::Any& resource) override { - return MessageUtil::anyConvert(resource, validation_visitor_).name(); + return MessageUtil::anyConvert(resource).name(); } CdsApiImpl(const envoy::api::v2::core::ConfigSource& cds_config, ClusterManager& cm, diff --git a/source/common/upstream/cluster_factory_impl.h b/source/common/upstream/cluster_factory_impl.h index ae709eb094c2..4b3f536dd3c5 100644 --- a/source/common/upstream/cluster_factory_impl.h +++ b/source/common/upstream/cluster_factory_impl.h @@ -178,7 +178,8 @@ template class ConfigurableClusterFactoryBase : public Clust cluster.cluster_type().typed_config(), ProtobufWkt::Struct::default_instance(), socket_factory_context.messageValidationVisitor(), *config); return createClusterWithConfig(cluster, - MessageUtil::downcastAndValidate(*config), + MessageUtil::downcastAndValidate( + *config, context.messageValidationVisitor()), context, socket_factory_context, std::move(stats_scope)); } diff --git a/source/common/upstream/eds.cc b/source/common/upstream/eds.cc index 7205d5aec7d2..3d795c9a207b 100644 --- a/source/common/upstream/eds.cc +++ b/source/common/upstream/eds.cc @@ -101,9 +101,9 @@ void EdsClusterImpl::onConfigUpdate(const Protobuf::RepeatedPtrField( - resources[0], validation_visitor_); - MessageUtil::validate(cluster_load_assignment); + auto cluster_load_assignment = + MessageUtil::anyConvert(resources[0]); + MessageUtil::validate(cluster_load_assignment, validation_visitor_); if (cluster_load_assignment.cluster_name() != cluster_name_) { throw EnvoyException(fmt::format("Unexpected EDS cluster (expecting {}): {}", cluster_name_, cluster_load_assignment.cluster_name())); diff --git a/source/common/upstream/eds.h b/source/common/upstream/eds.h index c7b3ffaba024..0df5f4c84473 100644 --- a/source/common/upstream/eds.h +++ b/source/common/upstream/eds.h @@ -38,9 +38,7 @@ class EdsClusterImpl : public BaseDynamicClusterImpl, Config::SubscriptionCallba void onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason reason, const EnvoyException* e) override; std::string resourceName(const ProtobufWkt::Any& resource) override { - return MessageUtil::anyConvert(resource, - validation_visitor_) - .cluster_name(); + return MessageUtil::anyConvert(resource).cluster_name(); } using LocalityWeightsMap = diff --git a/source/common/upstream/upstream_impl.cc b/source/common/upstream/upstream_impl.cc index f44e01f5a5de..8443868f68f0 100644 --- a/source/common/upstream/upstream_impl.cc +++ b/source/common/upstream/upstream_impl.cc @@ -140,7 +140,7 @@ createProtocolOptionsConfig(const std::string& name, const ProtobufWkt::Any& typ Envoy::Config::Utility::translateOpaqueConfig(typed_config, config, validation_visitor, *proto_config); - return factory->createProtocolOptionsConfig(*proto_config); + return factory->createProtocolOptionsConfig(*proto_config, validation_visitor); } std::map diff --git a/source/extensions/access_loggers/file/config.cc b/source/extensions/access_loggers/file/config.cc index d04f3965a008..fcf432a861bc 100644 --- a/source/extensions/access_loggers/file/config.cc +++ b/source/extensions/access_loggers/file/config.cc @@ -24,7 +24,8 @@ FileAccessLogFactory::createAccessLogInstance(const Protobuf::Message& config, AccessLog::FilterPtr&& filter, Server::Configuration::FactoryContext& context) { const auto& fal_config = - MessageUtil::downcastAndValidate(config); + MessageUtil::downcastAndValidate( + config, context.messageValidationVisitor()); AccessLog::FormatterPtr formatter; if (fal_config.access_log_format_case() == envoy::config::accesslog::v2::FileAccessLog::kFormat || diff --git a/source/extensions/access_loggers/grpc/http_config.cc b/source/extensions/access_loggers/grpc/http_config.cc index 2e3f19e87927..1047beaa579a 100644 --- a/source/extensions/access_loggers/grpc/http_config.cc +++ b/source/extensions/access_loggers/grpc/http_config.cc @@ -29,7 +29,8 @@ HttpGrpcAccessLogFactory::createAccessLogInstance(const Protobuf::Message& confi validateProtoDescriptors(); const auto& proto_config = MessageUtil::downcastAndValidate< - const envoy::config::accesslog::v2::HttpGrpcAccessLogConfig&>(config); + const envoy::config::accesslog::v2::HttpGrpcAccessLogConfig&>( + config, context.messageValidationVisitor()); std::shared_ptr grpc_access_logger_cache = context.singletonManager().getTyped( SINGLETON_MANAGER_REGISTERED_NAME(grpc_access_logger_cache), [&context] { diff --git a/source/extensions/filters/http/common/factory_base.h b/source/extensions/filters/http/common/factory_base.h index 8e3a9669173b..73c91d4d1be8 100644 --- a/source/extensions/filters/http/common/factory_base.h +++ b/source/extensions/filters/http/common/factory_base.h @@ -25,8 +25,9 @@ class FactoryBase : public Server::Configuration::NamedHttpFilterConfigFactory { createFilterFactoryFromProto(const Protobuf::Message& proto_config, const std::string& stats_prefix, Server::Configuration::FactoryContext& context) override { - return createFilterFactoryFromProtoTyped( - MessageUtil::downcastAndValidate(proto_config), stats_prefix, context); + return createFilterFactoryFromProtoTyped(MessageUtil::downcastAndValidate( + proto_config, context.messageValidationVisitor()), + stats_prefix, context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { @@ -41,7 +42,9 @@ class FactoryBase : public Server::Configuration::NamedHttpFilterConfigFactory { createRouteSpecificFilterConfig(const Protobuf::Message& proto_config, Server::Configuration::FactoryContext& context) override { return createRouteSpecificFilterConfigTyped( - MessageUtil::downcastAndValidate(proto_config), context); + MessageUtil::downcastAndValidate( + proto_config, context.messageValidationVisitor()), + context); } std::string name() override { return name_; } diff --git a/source/extensions/filters/listener/original_src/original_src_config_factory.cc b/source/extensions/filters/listener/original_src/original_src_config_factory.cc index aa1efc58b6e2..14a1a7384bfe 100644 --- a/source/extensions/filters/listener/original_src/original_src_config_factory.cc +++ b/source/extensions/filters/listener/original_src/original_src_config_factory.cc @@ -14,9 +14,10 @@ namespace ListenerFilters { namespace OriginalSrc { Network::ListenerFilterFactoryCb OriginalSrcConfigFactory::createFilterFactoryFromProto( - const Protobuf::Message& message, Server::Configuration::ListenerFactoryContext&) { + const Protobuf::Message& message, Server::Configuration::ListenerFactoryContext& context) { auto proto_config = MessageUtil::downcastAndValidate< - const envoy::config::filter::listener::original_src::v2alpha1::OriginalSrc&>(message); + const envoy::config::filter::listener::original_src::v2alpha1::OriginalSrc&>( + message, context.messageValidationVisitor()); Config config(proto_config); return [config](Network::ListenerFilterManager& filter_manager) -> void { filter_manager.addAcceptFilter(std::make_unique(config)); diff --git a/source/extensions/filters/network/common/factory_base.h b/source/extensions/filters/network/common/factory_base.h index 0c241878d2e8..8b3bf610b83a 100644 --- a/source/extensions/filters/network/common/factory_base.h +++ b/source/extensions/filters/network/common/factory_base.h @@ -25,8 +25,9 @@ class FactoryBase : public Server::Configuration::NamedNetworkFilterConfigFactor Network::FilterFactoryCb createFilterFactoryFromProto(const Protobuf::Message& proto_config, Server::Configuration::FactoryContext& context) override { - return createFilterFactoryFromProtoTyped( - MessageUtil::downcastAndValidate(proto_config), context); + return createFilterFactoryFromProtoTyped(MessageUtil::downcastAndValidate( + proto_config, context.messageValidationVisitor()), + context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { @@ -38,9 +39,10 @@ class FactoryBase : public Server::Configuration::NamedNetworkFilterConfigFactor } Upstream::ProtocolOptionsConfigConstSharedPtr - createProtocolOptionsConfig(const Protobuf::Message& proto_config) override { - return createProtocolOptionsTyped( - MessageUtil::downcastAndValidate(proto_config)); + createProtocolOptionsConfig(const Protobuf::Message& proto_config, + ProtobufMessage::ValidationVisitor& validation_visitor) override { + return createProtocolOptionsTyped(MessageUtil::downcastAndValidate( + proto_config, validation_visitor)); } std::string name() override { return name_; } diff --git a/source/extensions/filters/network/dubbo_proxy/filters/factory_base.h b/source/extensions/filters/network/dubbo_proxy/filters/factory_base.h index 1319a846170b..021d99b52e2f 100644 --- a/source/extensions/filters/network/dubbo_proxy/filters/factory_base.h +++ b/source/extensions/filters/network/dubbo_proxy/filters/factory_base.h @@ -21,8 +21,9 @@ template class FactoryBase : public NamedDubboFilterConfigFa createFilterFactoryFromProto(const Protobuf::Message& proto_config, const std::string& stats_prefix, Server::Configuration::FactoryContext& context) override { - return createFilterFactoryFromProtoTyped( - MessageUtil::downcastAndValidate(proto_config), stats_prefix, context); + return createFilterFactoryFromProtoTyped(MessageUtil::downcastAndValidate( + proto_config, context.messageValidationVisitor()), + stats_prefix, context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { diff --git a/source/extensions/filters/network/thrift_proxy/filters/factory_base.h b/source/extensions/filters/network/thrift_proxy/filters/factory_base.h index bf2bb292f043..159328b73a94 100644 --- a/source/extensions/filters/network/thrift_proxy/filters/factory_base.h +++ b/source/extensions/filters/network/thrift_proxy/filters/factory_base.h @@ -16,8 +16,9 @@ template class FactoryBase : public NamedThriftFilterConfigF createFilterFactoryFromProto(const Protobuf::Message& proto_config, const std::string& stats_prefix, Server::Configuration::FactoryContext& context) override { - return createFilterFactoryFromProtoTyped( - MessageUtil::downcastAndValidate(proto_config), stats_prefix, context); + return createFilterFactoryFromProtoTyped(MessageUtil::downcastAndValidate( + proto_config, context.messageValidationVisitor()), + stats_prefix, context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { diff --git a/source/extensions/grpc_credentials/aws_iam/config.cc b/source/extensions/grpc_credentials/aws_iam/config.cc index 3128a9608434..d2b423f744d7 100644 --- a/source/extensions/grpc_credentials/aws_iam/config.cc +++ b/source/extensions/grpc_credentials/aws_iam/config.cc @@ -34,12 +34,15 @@ std::shared_ptr AwsIamGrpcCredentialsFactory::getChann case envoy::api::v2::core::GrpcService::GoogleGrpc::CallCredentials::kFromPlugin: { if (credential.from_plugin().name() == GrpcCredentialsNames::get().AwsIam) { AwsIamGrpcCredentialsFactory credentials_factory; + // We don't deal with validation failures here at runtime today, see + // https://github.com/envoyproxy/envoy/issues/8010. const Envoy::ProtobufTypes::MessagePtr config_message = Envoy::Config::Utility::translateToFactoryConfig( credential.from_plugin(), ProtobufMessage::getNullValidationVisitor(), credentials_factory); const auto& config = Envoy::MessageUtil::downcastAndValidate< - const envoy::config::grpc_credential::v2alpha::AwsIamConfig&>(*config_message); + const envoy::config::grpc_credential::v2alpha::AwsIamConfig&>( + *config_message, ProtobufMessage::getNullValidationVisitor()); auto credentials_provider = std::make_shared( api, HttpFilters::Common::Aws::Utility::metadataFetcher); diff --git a/source/extensions/grpc_credentials/file_based_metadata/config.cc b/source/extensions/grpc_credentials/file_based_metadata/config.cc index e40c4549f101..03eabb5e9094 100644 --- a/source/extensions/grpc_credentials/file_based_metadata/config.cc +++ b/source/extensions/grpc_credentials/file_based_metadata/config.cc @@ -28,16 +28,15 @@ FileBasedMetadataGrpcCredentialsFactory::getChannelCredentials( case envoy::api::v2::core::GrpcService::GoogleGrpc::CallCredentials::kFromPlugin: { if (credential.from_plugin().name() == GrpcCredentialsNames::get().FileBasedMetadata) { FileBasedMetadataGrpcCredentialsFactory file_based_metadata_credentials_factory; - // TODO(htuch): This should probably follow the standard metadata validation pattern, but - // needs error handling, since this happens at runtime, not config time, and we need to - // catch any validation exceptions. + // We don't deal with validation failures here at runtime today, see + // https://github.com/envoyproxy/envoy/issues/8010. const Envoy::ProtobufTypes::MessagePtr file_based_metadata_config_message = Envoy::Config::Utility::translateToFactoryConfig( credential.from_plugin(), ProtobufMessage::getNullValidationVisitor(), file_based_metadata_credentials_factory); const auto& file_based_metadata_config = Envoy::MessageUtil::downcastAndValidate< const envoy::config::grpc_credential::v2alpha::FileBasedMetadataConfig&>( - *file_based_metadata_config_message); + *file_based_metadata_config_message, ProtobufMessage::getNullValidationVisitor()); std::shared_ptr new_call_creds = grpc::MetadataCredentialsFromPlugin( std::make_unique(file_based_metadata_config, api)); if (call_creds == nullptr) { diff --git a/source/extensions/health_checkers/redis/utility.h b/source/extensions/health_checkers/redis/utility.h index df868f85a3e8..b05a1856f273 100644 --- a/source/extensions/health_checkers/redis/utility.h +++ b/source/extensions/health_checkers/redis/utility.h @@ -21,7 +21,7 @@ getRedisHealthCheckConfig(const envoy::api::v2::core::HealthCheck& health_check_ MessageUtil::jsonConvert(health_check_config.custom_health_check().config(), validation_visitor, *config); return MessageUtil::downcastAndValidate( - *config); + *config, validation_visitor); } } // namespace diff --git a/source/extensions/resource_monitors/common/factory_base.h b/source/extensions/resource_monitors/common/factory_base.h index 124367132ddc..65350bc6950c 100644 --- a/source/extensions/resource_monitors/common/factory_base.h +++ b/source/extensions/resource_monitors/common/factory_base.h @@ -15,8 +15,9 @@ class FactoryBase : public Server::Configuration::ResourceMonitorFactory { Server::ResourceMonitorPtr createResourceMonitor(const Protobuf::Message& config, Server::Configuration::ResourceMonitorFactoryContext& context) override { - return createResourceMonitorFromProtoTyped( - MessageUtil::downcastAndValidate(config), context); + return createResourceMonitorFromProtoTyped(MessageUtil::downcastAndValidate( + config, context.messageValidationVisitor()), + context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { diff --git a/source/extensions/retry/priority/previous_priorities/config.cc b/source/extensions/retry/priority/previous_priorities/config.cc index 5eaf923967db..d528442359f7 100644 --- a/source/extensions/retry/priority/previous_priorities/config.cc +++ b/source/extensions/retry/priority/previous_priorities/config.cc @@ -9,12 +9,14 @@ namespace Extensions { namespace Retry { namespace Priority { -Upstream::RetryPrioritySharedPtr -PreviousPrioritiesRetryPriorityFactory::createRetryPriority(const Protobuf::Message& config, - uint32_t max_retries) { +Upstream::RetryPrioritySharedPtr PreviousPrioritiesRetryPriorityFactory::createRetryPriority( + const Protobuf::Message& config, ProtobufMessage::ValidationVisitor& validation_visitor, + + uint32_t max_retries) { return std::make_shared( MessageUtil::downcastAndValidate< - const envoy::config::retry::previous_priorities::PreviousPrioritiesConfig&>(config) + const envoy::config::retry::previous_priorities::PreviousPrioritiesConfig&>( + config, validation_visitor) .update_frequency(), max_retries); } diff --git a/source/extensions/retry/priority/previous_priorities/config.h b/source/extensions/retry/priority/previous_priorities/config.h index b98555235299..8fe761b3fe69 100644 --- a/source/extensions/retry/priority/previous_priorities/config.h +++ b/source/extensions/retry/priority/previous_priorities/config.h @@ -15,8 +15,10 @@ namespace Priority { class PreviousPrioritiesRetryPriorityFactory : public Upstream::RetryPriorityFactory { public: - Upstream::RetryPrioritySharedPtr createRetryPriority(const Protobuf::Message& config, - uint32_t max_retries) override; + Upstream::RetryPrioritySharedPtr + createRetryPriority(const Protobuf::Message& config, + ProtobufMessage::ValidationVisitor& validation_visitor, + uint32_t max_retries) override; std::string name() const override { return RetryPriorityValues::get().PreviousPrioritiesRetryPriority; diff --git a/source/extensions/stat_sinks/dog_statsd/config.cc b/source/extensions/stat_sinks/dog_statsd/config.cc index 9902d3534451..6b7ce0182bb5 100644 --- a/source/extensions/stat_sinks/dog_statsd/config.cc +++ b/source/extensions/stat_sinks/dog_statsd/config.cc @@ -19,7 +19,8 @@ namespace DogStatsd { Stats::SinkPtr DogStatsdSinkFactory::createStatsSink(const Protobuf::Message& config, Server::Instance& server) { const auto& sink_config = - MessageUtil::downcastAndValidate(config); + MessageUtil::downcastAndValidate( + config, server.messageValidationContext().staticValidationVisitor()); Network::Address::InstanceConstSharedPtr address = Network::Address::resolveProtoAddress(sink_config.address()); ENVOY_LOG(debug, "dog_statsd UDP ip address: {}", address->asString()); diff --git a/source/extensions/stat_sinks/hystrix/config.cc b/source/extensions/stat_sinks/hystrix/config.cc index 3034efad99ae..a9fc2d697d60 100644 --- a/source/extensions/stat_sinks/hystrix/config.cc +++ b/source/extensions/stat_sinks/hystrix/config.cc @@ -19,7 +19,8 @@ namespace Hystrix { Stats::SinkPtr HystrixSinkFactory::createStatsSink(const Protobuf::Message& config, Server::Instance& server) { const auto& hystrix_sink = - MessageUtil::downcastAndValidate(config); + MessageUtil::downcastAndValidate( + config, server.messageValidationContext().staticValidationVisitor()); return std::make_unique(server, hystrix_sink.num_buckets()); } diff --git a/source/extensions/stat_sinks/metrics_service/config.cc b/source/extensions/stat_sinks/metrics_service/config.cc index 78bad7587992..80e74ea9925f 100644 --- a/source/extensions/stat_sinks/metrics_service/config.cc +++ b/source/extensions/stat_sinks/metrics_service/config.cc @@ -23,7 +23,7 @@ Stats::SinkPtr MetricsServiceSinkFactory::createStatsSink(const Protobuf::Messag const auto& sink_config = MessageUtil::downcastAndValidate( - config); + config, server.messageValidationContext().staticValidationVisitor()); const auto& grpc_service = sink_config.grpc_service(); ENVOY_LOG(debug, "Metrics Service gRPC service configuration: {}", grpc_service.DebugString()); diff --git a/source/extensions/stat_sinks/statsd/config.cc b/source/extensions/stat_sinks/statsd/config.cc index 6fe112882ae7..f7e352e30bd4 100644 --- a/source/extensions/stat_sinks/statsd/config.cc +++ b/source/extensions/stat_sinks/statsd/config.cc @@ -20,7 +20,8 @@ Stats::SinkPtr StatsdSinkFactory::createStatsSink(const Protobuf::Message& confi Server::Instance& server) { const auto& statsd_sink = - MessageUtil::downcastAndValidate(config); + MessageUtil::downcastAndValidate( + config, server.messageValidationContext().staticValidationVisitor()); switch (statsd_sink.statsd_specifier_case()) { case envoy::config::metrics::v2::StatsdSink::kAddress: { Network::Address::InstanceConstSharedPtr address = diff --git a/source/extensions/tracers/common/factory_base.h b/source/extensions/tracers/common/factory_base.h index 6b57de7b3c35..b32975a74e9f 100644 --- a/source/extensions/tracers/common/factory_base.h +++ b/source/extensions/tracers/common/factory_base.h @@ -17,8 +17,10 @@ template class FactoryBase : public Server::Configuration::T // Server::Configuration::TracerFactory Tracing::HttpTracerPtr createHttpTracer(const Protobuf::Message& config, Server::Instance& server) override { - return createHttpTracerTyped(MessageUtil::downcastAndValidate(config), - server); + return createHttpTracerTyped( + MessageUtil::downcastAndValidate( + config, server.messageValidationContext().staticValidationVisitor()), + server); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { diff --git a/source/extensions/transport_sockets/alts/config.cc b/source/extensions/transport_sockets/alts/config.cc index a85bb9d7fa85..712f69282078 100644 --- a/source/extensions/transport_sockets/alts/config.cc +++ b/source/extensions/transport_sockets/alts/config.cc @@ -79,7 +79,7 @@ Network::TransportSocketFactoryPtr createTransportSocketFactoryHelper( [] { return std::make_shared(); }); auto config = MessageUtil::downcastAndValidate( - message); + message, factory_ctxt.messageValidationVisitor()); HandshakeValidator validator = createHandshakeValidator(config); const std::string& handshaker_service = config.handshaker_service(); diff --git a/source/extensions/transport_sockets/tap/config.cc b/source/extensions/transport_sockets/tap/config.cc index c376fe7cec8a..fb04ed511b26 100644 --- a/source/extensions/transport_sockets/tap/config.cc +++ b/source/extensions/transport_sockets/tap/config.cc @@ -36,7 +36,7 @@ Network::TransportSocketFactoryPtr UpstreamTapSocketConfigFactory::createTranspo Server::Configuration::TransportSocketFactoryContext& context) { const auto& outer_config = MessageUtil::downcastAndValidate( - message); + message, context.messageValidationVisitor()); auto& inner_config_factory = Config::Utility::getAndCheckFactory< Server::Configuration::UpstreamTransportSocketConfigFactory>( outer_config.transport_socket().name()); @@ -55,7 +55,7 @@ Network::TransportSocketFactoryPtr DownstreamTapSocketConfigFactory::createTrans const std::vector& server_names) { const auto& outer_config = MessageUtil::downcastAndValidate( - message); + message, context.messageValidationVisitor()); auto& inner_config_factory = Config::Utility::getAndCheckFactory< Server::Configuration::DownstreamTransportSocketConfigFactory>( outer_config.transport_socket().name()); diff --git a/source/extensions/transport_sockets/tls/config.cc b/source/extensions/transport_sockets/tls/config.cc index 15854a3698bb..4d04b0f2c3b3 100644 --- a/source/extensions/transport_sockets/tls/config.cc +++ b/source/extensions/transport_sockets/tls/config.cc @@ -17,7 +17,8 @@ Network::TransportSocketFactoryPtr UpstreamSslSocketFactory::createTransportSock const Protobuf::Message& message, Server::Configuration::TransportSocketFactoryContext& context) { auto client_config = std::make_unique( - MessageUtil::downcastAndValidate(message), + MessageUtil::downcastAndValidate( + message, context.messageValidationVisitor()), context); return std::make_unique( std::move(client_config), context.sslContextManager(), context.statsScope()); @@ -34,7 +35,8 @@ Network::TransportSocketFactoryPtr DownstreamSslSocketFactory::createTransportSo const Protobuf::Message& message, Server::Configuration::TransportSocketFactoryContext& context, const std::vector& server_names) { auto server_config = std::make_unique( - MessageUtil::downcastAndValidate(message), + MessageUtil::downcastAndValidate( + message, context.messageValidationVisitor()), context); return std::make_unique( std::move(server_config), context.sslContextManager(), context.statsScope(), server_names); diff --git a/source/server/lds_api.cc b/source/server/lds_api.cc index 581abba24b71..957603de82f1 100644 --- a/source/server/lds_api.cc +++ b/source/server/lds_api.cc @@ -49,9 +49,8 @@ void LdsApiImpl::onConfigUpdate( for (const auto& resource : added_resources) { envoy::api::v2::Listener listener; try { - listener = MessageUtil::anyConvert(resource.resource(), - validation_visitor_); - MessageUtil::validate(listener); + listener = MessageUtil::anyConvert(resource.resource()); + MessageUtil::validate(listener, validation_visitor_); if (!listener_names.insert(listener.name()).second) { // NOTE: at this point, the first of these duplicates has already been successfully applied. throw EnvoyException(fmt::format("duplicate listener {} found", listener.name())); @@ -91,8 +90,7 @@ void LdsApiImpl::onConfigUpdate(const Protobuf::RepeatedPtrField(listener_blob, validation_visitor_) - .name(); + MessageUtil::anyConvert(listener_blob).name(); to_add->set_name(listener_name); to_add->set_version(version_info); to_add->mutable_resource()->MergeFrom(listener_blob); diff --git a/source/server/lds_api.h b/source/server/lds_api.h index 199bd8413243..24ca66cfe73f 100644 --- a/source/server/lds_api.h +++ b/source/server/lds_api.h @@ -39,7 +39,7 @@ class LdsApiImpl : public LdsApi, void onConfigUpdateFailed(Envoy::Config::ConfigUpdateFailureReason reason, const EnvoyException* e) override; std::string resourceName(const ProtobufWkt::Any& resource) override { - return MessageUtil::anyConvert(resource, validation_visitor_).name(); + return MessageUtil::anyConvert(resource).name(); } std::unique_ptr subscription_; diff --git a/source/server/overload_manager_impl.cc b/source/server/overload_manager_impl.cc index 6eaad4b82c9b..7795802b6c76 100644 --- a/source/server/overload_manager_impl.cc +++ b/source/server/overload_manager_impl.cc @@ -93,7 +93,7 @@ OverloadManagerImpl::OverloadManagerImpl( : started_(false), dispatcher_(dispatcher), tls_(slot_allocator.allocateSlot()), refresh_interval_( std::chrono::milliseconds(PROTOBUF_GET_MS_OR_DEFAULT(config, refresh_interval, 1000))) { - Configuration::ResourceMonitorFactoryContextImpl context(dispatcher, api); + Configuration::ResourceMonitorFactoryContextImpl context(dispatcher, api, validation_visitor); for (const auto& resource : config.resource_monitors()) { const auto& name = resource.name(); ENVOY_LOG(debug, "Adding resource monitor for {}", name); diff --git a/source/server/resource_monitor_config_impl.h b/source/server/resource_monitor_config_impl.h index bab2f6c3a64f..e565f6fd78ad 100644 --- a/source/server/resource_monitor_config_impl.h +++ b/source/server/resource_monitor_config_impl.h @@ -8,16 +8,22 @@ namespace Configuration { class ResourceMonitorFactoryContextImpl : public ResourceMonitorFactoryContext { public: - ResourceMonitorFactoryContextImpl(Event::Dispatcher& dispatcher, Api::Api& api) - : dispatcher_(dispatcher), api_(api) {} + ResourceMonitorFactoryContextImpl(Event::Dispatcher& dispatcher, Api::Api& api, + ProtobufMessage::ValidationVisitor& validation_visitor) + : dispatcher_(dispatcher), api_(api), validation_visitor_(validation_visitor) {} Event::Dispatcher& dispatcher() override { return dispatcher_; } Api::Api& api() override { return api_; } + ProtobufMessage::ValidationVisitor& messageValidationVisitor() override { + return validation_visitor_; + } + private: Event::Dispatcher& dispatcher_; Api::Api& api_; + ProtobufMessage::ValidationVisitor& validation_visitor_; }; } // namespace Configuration diff --git a/source/server/server.cc b/source/server/server.cc index 6e8cd16af655..4994d53ccdf8 100644 --- a/source/server/server.cc +++ b/source/server/server.cc @@ -231,7 +231,7 @@ InstanceUtil::BootstrapVersion InstanceUtil::loadBootstrapConfig( if (config_proto.ByteSize() != 0) { bootstrap.MergeFrom(config_proto); } - MessageUtil::validate(bootstrap); + MessageUtil::validate(bootstrap, validation_visitor); return BootstrapVersion::V2; } diff --git a/test/common/access_log/access_log_impl_test.cc b/test/common/access_log/access_log_impl_test.cc index fe29b7839499..02677fc783ed 100644 --- a/test/common/access_log/access_log_impl_test.cc +++ b/test/common/access_log/access_log_impl_test.cc @@ -1143,7 +1143,7 @@ class TestHeaderFilterFactory : public ExtensionFilterFactory { auto factory_config = Config::Utility::translateToFactoryConfig( config, Envoy::ProtobufMessage::getNullValidationVisitor(), *this); const auto& header_config = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *factory_config); return std::make_unique(header_config); } diff --git a/test/common/http/codec_impl_fuzz_test.cc b/test/common/http/codec_impl_fuzz_test.cc index 28cb56d0e592..f411565fa465 100644 --- a/test/common/http/codec_impl_fuzz_test.cc +++ b/test/common/http/codec_impl_fuzz_test.cc @@ -506,7 +506,7 @@ void codecFuzz(const test::common::http::CodecImplFuzzTestCase& input, HttpVersi DEFINE_PROTO_FUZZER(const test::common::http::CodecImplFuzzTestCase& input) { try { // Validate input early. - MessageUtil::validate(input); + TestUtility::validate(input); codecFuzz(input, HttpVersion::Http1); codecFuzz(input, HttpVersion::Http2); } catch (const EnvoyException& e) { diff --git a/test/common/protobuf/utility_test.cc b/test/common/protobuf/utility_test.cc index 9d437982a0e0..050fc0485e02 100644 --- a/test/common/protobuf/utility_test.cc +++ b/test/common/protobuf/utility_test.cc @@ -123,15 +123,28 @@ TEST_F(ProtobufUtilityTest, RepeatedPtrUtilDebugString) { EXPECT_EQ("[value: 10\n, value: 20\n]", RepeatedPtrUtil::debugString(repeated)); } -TEST_F(ProtobufUtilityTest, DowncastAndValidate) { +// Validated exception thrown when downcastAndValidate observes a PGV failures. +TEST_F(ProtobufUtilityTest, DowncastAndValidateFailedValidation) { envoy::config::bootstrap::v2::Bootstrap bootstrap; bootstrap.mutable_static_resources()->add_clusters(); - EXPECT_THROW(MessageUtil::validate(bootstrap), ProtoValidationException); + EXPECT_THROW(TestUtility::validate(bootstrap), ProtoValidationException); EXPECT_THROW( - MessageUtil::downcastAndValidate(bootstrap), + TestUtility::downcastAndValidate(bootstrap), ProtoValidationException); } +// Validated exception thrown when downcastAndValidate observes a unknown field. +TEST_F(ProtobufUtilityTest, DowncastAndValidateUnknownFields) { + envoy::config::bootstrap::v2::Bootstrap bootstrap; + bootstrap.GetReflection()->MutableUnknownFields(&bootstrap)->AddVarint(1, 0); + EXPECT_THROW_WITH_MESSAGE(TestUtility::validate(bootstrap), EnvoyException, + "Protobuf message (type envoy.config.bootstrap.v2.Bootstrap with " + "unknown field set {1}) has unknown fields"); + EXPECT_THROW_WITH_MESSAGE(TestUtility::validate(bootstrap), EnvoyException, + "Protobuf message (type envoy.config.bootstrap.v2.Bootstrap with " + "unknown field set {1}) has unknown fields"); +} + TEST_F(ProtobufUtilityTest, LoadBinaryProtoFromFile) { envoy::config::bootstrap::v2::Bootstrap bootstrap; bootstrap.mutable_cluster_manager() @@ -342,17 +355,6 @@ TEST_F(ProtobufUtilityTest, AnyConvertWrongType) { EnvoyException, "Unable to unpack .*"); } -TEST_F(ProtobufUtilityTest, AnyConvertWrongFields) { - const ProtobufWkt::Struct obj = MessageUtil::keyValueStruct("test_key", "test_value"); - ProtobufWkt::Any source_any; - source_any.PackFrom(obj); - source_any.set_type_url("type.google.com/google.protobuf.Timestamp"); - EXPECT_THROW_WITH_MESSAGE(TestUtility::anyConvert(source_any), - EnvoyException, - "Protobuf message (type google.protobuf.Timestamp with unknown " - "field set {1}) has unknown fields"); -} - TEST_F(ProtobufUtilityTest, JsonConvertSuccess) { envoy::config::bootstrap::v2::Bootstrap source; source.set_flags_path("foo"); diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index 6b7c5743dc90..ca9073d4b712 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -89,7 +89,7 @@ Http::TestHeaderMapImpl genHeaders(const std::string& host, const std::string& p envoy::api::v2::RouteConfiguration parseRouteConfigurationFromV2Yaml(const std::string& yaml) { envoy::api::v2::RouteConfiguration route_config; TestUtility::loadFromYaml(yaml, route_config); - MessageUtil::validate(route_config); + TestUtility::validate(route_config); return route_config; } diff --git a/test/common/router/header_formatter_test.cc b/test/common/router/header_formatter_test.cc index 3ab5ead740d7..e6c7c6aa7f45 100644 --- a/test/common/router/header_formatter_test.cc +++ b/test/common/router/header_formatter_test.cc @@ -505,7 +505,7 @@ TEST_F(StreamInfoHeaderFormatterTest, ValidateLimitsOnUserDefinedHeaders) { header->mutable_header()->set_key("header_name"); header->mutable_header()->set_value(long_string); header->mutable_append()->set_value(true); - EXPECT_THROW_WITH_REGEX(MessageUtil::validate(route), ProtoValidationException, + EXPECT_THROW_WITH_REGEX(TestUtility::validate(route), ProtoValidationException, "Proto constraint validation failed.*"); } { @@ -516,7 +516,7 @@ TEST_F(StreamInfoHeaderFormatterTest, ValidateLimitsOnUserDefinedHeaders) { header->mutable_header()->set_key("header_name"); header->mutable_header()->set_value("value"); } - EXPECT_THROW_WITH_REGEX(MessageUtil::validate(route), ProtoValidationException, + EXPECT_THROW_WITH_REGEX(TestUtility::validate(route), ProtoValidationException, "Proto constraint validation failed.*"); } } diff --git a/test/common/router/header_parser_fuzz_test.cc b/test/common/router/header_parser_fuzz_test.cc index 451aae702c4e..cb62744f52d1 100644 --- a/test/common/router/header_parser_fuzz_test.cc +++ b/test/common/router/header_parser_fuzz_test.cc @@ -11,7 +11,7 @@ namespace { DEFINE_PROTO_FUZZER(const test::common::router::TestCase& input) { try { - MessageUtil::validate(input); + TestUtility::validate(input); auto headers_to_add = replaceInvalidHeaders(input.headers_to_add()); Protobuf::RepeatedPtrField headers_to_remove; for (const auto& s : input.headers_to_remove()) { diff --git a/test/common/router/rds_impl_test.cc b/test/common/router/rds_impl_test.cc index 1046b5827be0..fb74aa9694f7 100644 --- a/test/common/router/rds_impl_test.cc +++ b/test/common/router/rds_impl_test.cc @@ -295,7 +295,7 @@ envoy::api::v2::RouteConfiguration parseRouteConfigurationFromV2Yaml(const std:: TEST_F(RouteConfigProviderManagerImplTest, ConfigDump) { auto message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["routes"](); const auto& route_config_dump = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); // No routes at all, no last_updated timestamp @@ -325,7 +325,7 @@ name: foo parseRouteConfigurationFromV2Yaml(config_yaml), factory_context_); message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["routes"](); const auto& route_config_dump2 = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); TestUtility::loadFromYaml(R"EOF( static_route_configs: @@ -368,7 +368,7 @@ name: foo rds_callbacks_->onConfigUpdate(response1.resources(), response1.version_info()); message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["routes"](); const auto& route_config_dump3 = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); TestUtility::loadFromYaml(R"EOF( static_route_configs: @@ -497,7 +497,7 @@ TEST_F(RouteConfigProviderManagerImplTest, onConfigUpdateWrongSize) { TEST_F(RouteConfigProviderManagerImplTest, ConfigDumpAfterConfigRejected) { auto message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["routes"](); const auto& route_config_dump = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); // No routes at all, no last_updated timestamp @@ -549,7 +549,7 @@ version_info: '1' message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["routes"](); const auto& route_config_dump3 = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); TestUtility::loadFromYaml(R"EOF( static_route_configs: diff --git a/test/common/router/route_fuzz_test.cc b/test/common/router/route_fuzz_test.cc index 865c30f3f8aa..b2cecf913b83 100644 --- a/test/common/router/route_fuzz_test.cc +++ b/test/common/router/route_fuzz_test.cc @@ -72,7 +72,7 @@ DEFINE_PROTO_FUZZER(const test::common::router::RouteTestCase& input) { try { NiceMock stream_info; NiceMock factory_context; - MessageUtil::validate(input.config()); + TestUtility::validate(input.config()); ConfigImpl config(cleanRouteConfig(input.config()), factory_context, true); Http::TestHeaderMapImpl headers = Fuzz::fromHeaders(input.headers()); // It's a precondition of routing that {:authority, :path, x-forwarded-proto} headers exists, diff --git a/test/common/router/router_ratelimit_test.cc b/test/common/router/router_ratelimit_test.cc index f49f4e943de9..207a82a2829f 100644 --- a/test/common/router/router_ratelimit_test.cc +++ b/test/common/router/router_ratelimit_test.cc @@ -31,7 +31,7 @@ namespace { envoy::api::v2::route::RateLimit parseRateLimitFromV2Yaml(const std::string& yaml_string) { envoy::api::v2::route::RateLimit rate_limit; TestUtility::loadFromYaml(yaml_string, rate_limit); - MessageUtil::validate(rate_limit); + TestUtility::validate(rate_limit); return rate_limit; } diff --git a/test/common/router/scoped_rds_test.cc b/test/common/router/scoped_rds_test.cc index 30d3a671ed0a..0bc871f232b8 100644 --- a/test/common/router/scoped_rds_test.cc +++ b/test/common/router/scoped_rds_test.cc @@ -191,7 +191,7 @@ TEST_F(ScopedRoutesConfigProviderManagerTest, ConfigDump) { auto message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["route_scopes"](); const auto& scoped_routes_config_dump = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); // No routes at all, no last_updated timestamp @@ -237,7 +237,7 @@ stat_prefix: foo factory_context_, "foo.", *config_provider_manager_); message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["route_scopes"](); const auto& scoped_routes_config_dump2 = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); TestUtility::loadFromYaml(R"EOF( inline_scoped_route_configs: @@ -310,7 +310,7 @@ route_configuration_name: dynamic-foo-route-config expected_config_dump); message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["route_scopes"](); const auto& scoped_routes_config_dump3 = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); EXPECT_EQ(expected_config_dump.DebugString(), scoped_routes_config_dump3.DebugString()); @@ -342,7 +342,7 @@ route_configuration_name: dynamic-foo-route-config expected_config_dump); message_ptr = factory_context_.admin_.config_tracker_.config_tracker_callbacks_["route_scopes"](); const auto& scoped_routes_config_dump4 = - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( *message_ptr); EXPECT_EQ(expected_config_dump.DebugString(), scoped_routes_config_dump4.DebugString()); } diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index 7c8d7cfb5701..c21134ee2deb 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -4070,7 +4070,7 @@ TEST(HealthCheckProto, Validation) { service_name: locations path: /healthcheck )EOF"; - EXPECT_THROW_WITH_REGEX(MessageUtil::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, + EXPECT_THROW_WITH_REGEX(TestUtility::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, "Proto constraint validation failed.*value must be greater than.*"); } { @@ -4082,7 +4082,7 @@ TEST(HealthCheckProto, Validation) { service_name: locations path: /healthcheck )EOF"; - EXPECT_THROW_WITH_REGEX(MessageUtil::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, + EXPECT_THROW_WITH_REGEX(TestUtility::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, "Proto constraint validation failed.*value must be greater than.*"); } { @@ -4094,7 +4094,7 @@ TEST(HealthCheckProto, Validation) { service_name: locations path: /healthcheck )EOF"; - EXPECT_THROW_WITH_REGEX(MessageUtil::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, + EXPECT_THROW_WITH_REGEX(TestUtility::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, "Proto constraint validation failed.*value must be greater than.*"); } { @@ -4106,7 +4106,7 @@ TEST(HealthCheckProto, Validation) { service_name: locations path: /healthcheck )EOF"; - EXPECT_THROW_WITH_REGEX(MessageUtil::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, + EXPECT_THROW_WITH_REGEX(TestUtility::validate(parseHealthCheckFromV2Yaml(yaml)), EnvoyException, "Proto constraint validation failed.*value must be greater than.*"); } } diff --git a/test/common/upstream/upstream_impl_test.cc b/test/common/upstream/upstream_impl_test.cc index f55f2884097a..a3cb1bdd6408 100644 --- a/test/common/upstream/upstream_impl_test.cc +++ b/test/common/upstream/upstream_impl_test.cc @@ -2094,7 +2094,8 @@ class TestNetworkFilterConfigFactory return parent_.createEmptyProtocolOptionsProto(); } Upstream::ProtocolOptionsConfigConstSharedPtr - createProtocolOptionsConfig(const Protobuf::Message& msg) override { + createProtocolOptionsConfig(const Protobuf::Message& msg, + ProtobufMessage::ValidationVisitor&) override { return parent_.createProtocolOptionsConfig(msg); } std::string name() override { CONSTRUCT_ON_FIRST_USE(std::string, "envoy.test.filter"); } @@ -2130,7 +2131,8 @@ class TestHttpFilterConfigFactory : public Server::Configuration::NamedHttpFilte return parent_.createEmptyProtocolOptionsProto(); } Upstream::ProtocolOptionsConfigConstSharedPtr - createProtocolOptionsConfig(const Protobuf::Message& msg) override { + createProtocolOptionsConfig(const Protobuf::Message& msg, + ProtobufMessage::ValidationVisitor&) override { return parent_.createProtocolOptionsConfig(msg); } std::string name() override { CONSTRUCT_ON_FIRST_USE(std::string, "envoy.test.filter"); } diff --git a/test/extensions/clusters/redis/redis_cluster_test.cc b/test/extensions/clusters/redis/redis_cluster_test.cc index a3190debb640..cb305b289c48 100644 --- a/test/extensions/clusters/redis/redis_cluster_test.cc +++ b/test/extensions/clusters/redis/redis_cluster_test.cc @@ -101,7 +101,7 @@ class RedisClusterTest : public testing::Test, cluster_callback_ = std::make_shared>(); cluster_.reset(new RedisCluster( cluster_config, - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( config), *this, cm, runtime_, *api_, dns_resolver_, factory_context, std::move(scope), false, cluster_callback_)); diff --git a/test/extensions/filters/http/ext_authz/config_test.cc b/test/extensions/filters/http/ext_authz/config_test.cc index 52942c6a7d6e..29e4a1097de4 100644 --- a/test/extensions/filters/http/ext_authz/config_test.cc +++ b/test/extensions/filters/http/ext_authz/config_test.cc @@ -31,6 +31,7 @@ TEST(HttpExtAuthzConfigTest, CorrectProtoGrpc) { TestUtility::loadFromYaml(yaml, *proto_config); testing::StrictMock context; + EXPECT_CALL(context, messageValidationVisitor()).Times(1); EXPECT_CALL(context, localInfo()).Times(1); EXPECT_CALL(context, clusterManager()).Times(1); EXPECT_CALL(context, runtime()).Times(1); @@ -85,6 +86,7 @@ TEST(HttpExtAuthzConfigTest, CorrectProtoHttp) { ProtobufTypes::MessagePtr proto_config = factory.createEmptyConfigProto(); TestUtility::loadFromYaml(yaml, *proto_config); testing::StrictMock context; + EXPECT_CALL(context, messageValidationVisitor()).Times(1); EXPECT_CALL(context, localInfo()).Times(1); EXPECT_CALL(context, clusterManager()).Times(1); EXPECT_CALL(context, runtime()).Times(1); diff --git a/test/extensions/filters/http/ext_authz/ext_authz_test.cc b/test/extensions/filters/http/ext_authz/ext_authz_test.cc index 3586d9d9b550..9207f2e9c6c7 100644 --- a/test/extensions/filters/http/ext_authz/ext_authz_test.cc +++ b/test/extensions/filters/http/ext_authz/ext_authz_test.cc @@ -306,7 +306,7 @@ TEST_F(HttpFilterTest, BadConfig) { envoy::config::filter::http::ext_authz::v2::ExtAuthz proto_config{}; TestUtility::loadFromYaml(filter_config, proto_config); EXPECT_THROW( - MessageUtil::downcastAndValidate( + TestUtility::downcastAndValidate( proto_config), ProtoValidationException); } diff --git a/test/extensions/filters/http/original_src/original_src_config_factory_test.cc b/test/extensions/filters/http/original_src/original_src_config_factory_test.cc index e581bfbd59a4..ea164cacc971 100644 --- a/test/extensions/filters/http/original_src/original_src_config_factory_test.cc +++ b/test/extensions/filters/http/original_src/original_src_config_factory_test.cc @@ -11,6 +11,7 @@ #include "gtest/gtest.h" using testing::Invoke; +using testing::NiceMock; namespace Envoy { namespace Extensions { @@ -27,7 +28,7 @@ TEST(OriginalSrcHttpConfigFactoryTest, TestCreateFactory) { ProtobufTypes::MessagePtr proto_config = factory.createEmptyConfigProto(); TestUtility::loadFromYaml(yaml, *proto_config); - Server::Configuration::MockFactoryContext context; + NiceMock context; Http::FilterFactoryCb cb = factory.createFilterFactoryFromProto(*proto_config, "", context); diff --git a/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc b/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc index 08ec55111ae2..25f758e9e6b2 100644 --- a/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc +++ b/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc @@ -11,6 +11,7 @@ #include "gtest/gtest.h" using testing::Invoke; +using testing::NiceMock; namespace Envoy { namespace Extensions { @@ -28,7 +29,7 @@ TEST(OriginalSrcConfigFactoryTest, TestCreateFactory) { ProtobufTypes::MessagePtr proto_config = factory.createEmptyConfigProto(); TestUtility::loadFromYaml(yaml, *proto_config); - Server::Configuration::MockListenerFactoryContext context; + NiceMock context; Network::ListenerFilterFactoryCb cb = factory.createFilterFactoryFromProto(*proto_config, context); diff --git a/test/extensions/filters/network/dubbo_proxy/conn_manager_test.cc b/test/extensions/filters/network/dubbo_proxy/conn_manager_test.cc index 2b0429d2da77..bd9de61eeb2a 100644 --- a/test/extensions/filters/network/dubbo_proxy/conn_manager_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/conn_manager_test.cc @@ -134,7 +134,7 @@ class ConnectionManagerTest : public testing::Test { if (!yaml.empty()) { TestUtility::loadFromYaml(yaml, proto_config_); - MessageUtil::validate(proto_config_); + TestUtility::validate(proto_config_); } proto_config_.set_stat_prefix("test"); diff --git a/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc b/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc index 623c6f657cd1..ad648d51fdc4 100644 --- a/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc @@ -24,7 +24,7 @@ envoy::config::filter::network::dubbo_proxy::v2alpha1::RouteConfiguration parseRouteConfigurationFromV2Yaml(const std::string& yaml) { envoy::config::filter::network::dubbo_proxy::v2alpha1::RouteConfiguration route_config; TestUtility::loadFromYaml(yaml, route_config); - MessageUtil::validate(route_config); + TestUtility::validate(route_config); return route_config; } @@ -32,7 +32,7 @@ envoy::config::filter::network::dubbo_proxy::v2alpha1::DubboProxy parseDubboProxyFromV2Yaml(const std::string& yaml) { envoy::config::filter::network::dubbo_proxy::v2alpha1::DubboProxy config; TestUtility::loadFromYaml(yaml, config); - MessageUtil::validate(config); + TestUtility::validate(config); return config; } diff --git a/test/extensions/filters/network/ext_authz/ext_authz_test.cc b/test/extensions/filters/network/ext_authz/ext_authz_test.cc index 8a344ed162f5..a9d86928e3ed 100644 --- a/test/extensions/filters/network/ext_authz/ext_authz_test.cc +++ b/test/extensions/filters/network/ext_authz/ext_authz_test.cc @@ -95,7 +95,7 @@ TEST_F(ExtAuthzFilterTest, BadExtAuthzConfig) { envoy::config::filter::network::ext_authz::v2::ExtAuthz proto_config{}; TestUtility::loadFromJson(json_string, proto_config); - EXPECT_THROW(MessageUtil::downcastAndValidate< + EXPECT_THROW(TestUtility::downcastAndValidate< const envoy::config::filter::network::ext_authz::v2::ExtAuthz&>(proto_config), ProtoValidationException); } diff --git a/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc b/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc index a8e76e040a2c..0e19ef9e943c 100644 --- a/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc +++ b/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc @@ -91,7 +91,7 @@ class ThriftConnectionManagerTest : public testing::Test { proto_config_.set_stat_prefix("test"); } else { TestUtility::loadFromYaml(yaml, proto_config_); - MessageUtil::validate(proto_config_); + TestUtility::validate(proto_config_); } proto_config_.set_stat_prefix("test"); diff --git a/test/extensions/filters/network/thrift_proxy/mocks.cc b/test/extensions/filters/network/thrift_proxy/mocks.cc index 3f591919a4fc..ae130a3c42c6 100644 --- a/test/extensions/filters/network/thrift_proxy/mocks.cc +++ b/test/extensions/filters/network/thrift_proxy/mocks.cc @@ -12,7 +12,8 @@ using testing::ReturnRef; namespace Envoy { // Provide a specialization for ProtobufWkt::Struct (for MockFilterConfigFactory) -template <> void MessageUtil::validate(const ProtobufWkt::Struct&) {} +template <> +void MessageUtil::validate(const ProtobufWkt::Struct&, ProtobufMessage::ValidationVisitor&) {} namespace Extensions { namespace NetworkFilters { diff --git a/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc b/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc index 794cc084e012..d29c89833022 100644 --- a/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc +++ b/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc @@ -22,7 +22,7 @@ envoy::config::filter::network::thrift_proxy::v2alpha1::RouteConfiguration parseRouteConfigurationFromV2Yaml(const std::string& yaml) { envoy::config::filter::network::thrift_proxy::v2alpha1::RouteConfiguration route_config; TestUtility::loadFromYaml(yaml, route_config); - MessageUtil::validate(route_config); + TestUtility::validate(route_config); return route_config; } diff --git a/test/extensions/resource_monitors/fixed_heap/config_test.cc b/test/extensions/resource_monitors/fixed_heap/config_test.cc index 64f8d6eae058..1c91ae642dd9 100644 --- a/test/extensions/resource_monitors/fixed_heap/config_test.cc +++ b/test/extensions/resource_monitors/fixed_heap/config_test.cc @@ -25,7 +25,8 @@ TEST(FixedHeapMonitorFactoryTest, CreateMonitor) { config.set_max_heap_size_bytes(std::numeric_limits::max()); Event::MockDispatcher dispatcher; Api::ApiPtr api = Api::createApiForTest(); - Server::Configuration::ResourceMonitorFactoryContextImpl context(dispatcher, *api); + Server::Configuration::ResourceMonitorFactoryContextImpl context( + dispatcher, *api, ProtobufMessage::getStrictValidationVisitor()); auto monitor = factory->createResourceMonitor(config, context); EXPECT_NE(monitor, nullptr); } diff --git a/test/extensions/resource_monitors/injected_resource/config_test.cc b/test/extensions/resource_monitors/injected_resource/config_test.cc index 8e1ce2266ac8..00862c91bf1e 100644 --- a/test/extensions/resource_monitors/injected_resource/config_test.cc +++ b/test/extensions/resource_monitors/injected_resource/config_test.cc @@ -28,7 +28,8 @@ TEST(InjectedResourceMonitorFactoryTest, CreateMonitor) { config.set_filename(TestEnvironment::temporaryPath("injected_resource")); Api::ApiPtr api = Api::createApiForTest(); Event::DispatcherPtr dispatcher(api->allocateDispatcher()); - Server::Configuration::ResourceMonitorFactoryContextImpl context(*dispatcher, *api); + Server::Configuration::ResourceMonitorFactoryContextImpl context( + *dispatcher, *api, ProtobufMessage::getStrictValidationVisitor()); Server::ResourceMonitorPtr monitor = factory->createResourceMonitor(config, context); EXPECT_NE(monitor, nullptr); } diff --git a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc index b017c90f0c74..a6ac6f290e31 100644 --- a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc +++ b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc @@ -61,7 +61,8 @@ class InjectedResourceMonitorTest : public testing::Test { std::unique_ptr createMonitor() { envoy::config::resource_monitor::injected_resource::v2alpha::InjectedResourceConfig config; config.set_filename(resource_filename_); - Server::Configuration::ResourceMonitorFactoryContextImpl context(*dispatcher_, *api_); + Server::Configuration::ResourceMonitorFactoryContextImpl context( + *dispatcher_, *api_, ProtobufMessage::getStrictValidationVisitor()); return std::make_unique(config, context); } diff --git a/test/extensions/retry/priority/previous_priorities/config_test.cc b/test/extensions/retry/priority/previous_priorities/config_test.cc index 9b2df9346020..47f425dfee60 100644 --- a/test/extensions/retry/priority/previous_priorities/config_test.cc +++ b/test/extensions/retry/priority/previous_priorities/config_test.cc @@ -31,7 +31,8 @@ class RetryPriorityTest : public testing::Test { // by that method is compatible with the downcast in createRetryPriority. auto empty = factory->createEmptyConfigProto(); empty->MergeFrom(config); - retry_priority_ = factory->createRetryPriority(*empty, 3); + retry_priority_ = + factory->createRetryPriority(*empty, ProtobufMessage::getStrictValidationVisitor(), 3); original_priority_load_ = Upstream::HealthyAndDegradedLoad{original_healthy_priority_load, original_degraded_priority_load}; } diff --git a/test/extensions/transport_sockets/alts/config_test.cc b/test/extensions/transport_sockets/alts/config_test.cc index 34fcd34ae645..68c602ea50fd 100644 --- a/test/extensions/transport_sockets/alts/config_test.cc +++ b/test/extensions/transport_sockets/alts/config_test.cc @@ -23,7 +23,7 @@ namespace Alts { namespace { TEST(UpstreamAltsConfigTest, CreateSocketFactory) { - MockTransportSocketFactoryContext factory_context; + NiceMock factory_context; Singleton::ManagerImpl singleton_manager{Thread::threadFactoryForTest()}; EXPECT_CALL(factory_context, singletonManager()).WillRepeatedly(ReturnRef(singleton_manager)); UpstreamAltsTransportSocketConfigFactory factory; @@ -43,7 +43,7 @@ TEST(UpstreamAltsConfigTest, CreateSocketFactory) { } TEST(DownstreamAltsConfigTest, CreateSocketFactory) { - MockTransportSocketFactoryContext factory_context; + NiceMock factory_context; Singleton::ManagerImpl singleton_manager{Thread::threadFactoryForTest()}; EXPECT_CALL(factory_context, singletonManager()).WillRepeatedly(ReturnRef(singleton_manager)); DownstreamAltsTransportSocketConfigFactory factory; diff --git a/test/extensions/transport_sockets/tls/context_impl_test.cc b/test/extensions/transport_sockets/tls/context_impl_test.cc index ef82b26fff43..92b78d793cd8 100644 --- a/test/extensions/transport_sockets/tls/context_impl_test.cc +++ b/test/extensions/transport_sockets/tls/context_impl_test.cc @@ -1074,7 +1074,7 @@ TEST_F(ServerContextConfigImplTest, MultiSdsConfig) { tls_context.mutable_common_tls_context()->add_tls_certificate_sds_secret_configs(); tls_context.mutable_common_tls_context()->add_tls_certificate_sds_secret_configs(); EXPECT_THROW_WITH_REGEX( - MessageUtil::validate(tls_context), + TestUtility::validate(tls_context), EnvoyException, "Proto constraint validation failed"); } diff --git a/test/mocks/upstream/mocks.h b/test/mocks/upstream/mocks.h index f194bffceca0..1b7f0b07b237 100644 --- a/test/mocks/upstream/mocks.h +++ b/test/mocks/upstream/mocks.h @@ -142,7 +142,9 @@ class MockRetryPriorityFactory : public RetryPriorityFactory { public: MockRetryPriorityFactory(const MockRetryPriority& retry_priority) : retry_priority_(retry_priority) {} - RetryPrioritySharedPtr createRetryPriority(const Protobuf::Message&, uint32_t) override { + RetryPrioritySharedPtr createRetryPriority(const Protobuf::Message&, + ProtobufMessage::ValidationVisitor&, + uint32_t) override { return std::make_shared>(retry_priority_); } diff --git a/test/test_common/utility.h b/test/test_common/utility.h index 7e33eeff7d1e..3da54288da7f 100644 --- a/test/test_common/utility.h +++ b/test/test_common/utility.h @@ -499,8 +499,7 @@ class TestUtility { template static inline MessageType anyConvert(const ProtobufWkt::Any& message) { - return MessageUtil::anyConvert(message, - ProtobufMessage::getStrictValidationVisitor()); + return MessageUtil::anyConvert(message); } template @@ -515,6 +514,16 @@ class TestUtility { ProtobufMessage::getStrictValidationVisitor()); } + template static void validate(const MessageType& message) { + return MessageUtil::validate(message, ProtobufMessage::getStrictValidationVisitor()); + } + + template + static const MessageType& downcastAndValidate(const Protobuf::Message& config) { + return MessageUtil::downcastAndValidate( + config, ProtobufMessage::getStrictValidationVisitor()); + } + static void jsonConvert(const Protobuf::Message& source, Protobuf::Message& dest) { // Explicit round-tripping to support conversions inside tests between arbitrary messages as a // convenience. diff --git a/test/tools/router_check/router.cc b/test/tools/router_check/router.cc index c75053792f6a..6922d26cea2f 100644 --- a/test/tools/router_check/router.cc +++ b/test/tools/router_check/router.cc @@ -165,7 +165,7 @@ bool RouterCheckTool::compareEntries(const std::string& expected_routes) { auto api = Api::createApiForTest(*stats); const std::string contents = api->fileSystem().fileReadToEnd(expected_routes); TestUtility::loadFromFile(expected_routes, validation_config, *api); - MessageUtil::validate(validation_config); + TestUtility::validate(validation_config); bool no_failures = true; for (const envoy::RouterCheckToolSchema::ValidationItem& check_config : diff --git a/test/tools/schema_validator/validator.cc b/test/tools/schema_validator/validator.cc index 80b2a4137061..fee3cde141e7 100644 --- a/test/tools/schema_validator/validator.cc +++ b/test/tools/schema_validator/validator.cc @@ -59,13 +59,13 @@ void Validator::validate(const std::string& config_path, Schema::Type schema_typ case Schema::Type::DiscoveryResponse: { envoy::api::v2::DiscoveryResponse discovery_response_config; TestUtility::loadFromFile(config_path, discovery_response_config, *api_); - MessageUtil::validate(discovery_response_config); + TestUtility::validate(discovery_response_config); break; } case Schema::Type::Route: { envoy::api::v2::RouteConfiguration route_config; TestUtility::loadFromFile(config_path, route_config, *api_); - MessageUtil::validate(route_config); + TestUtility::validate(route_config); break; } default: