-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathconfig_impl.cc
More file actions
2230 lines (1994 loc) · 101 KB
/
config_impl.cc
File metadata and controls
2230 lines (1994 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "source/common/router/config_impl.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "envoy/config/common/matcher/v3/matcher.pb.h"
#include "envoy/config/common/matcher/v3/matcher.pb.validate.h"
#include "envoy/config/core/v3/base.pb.h"
#include "envoy/config/route/v3/route.pb.h"
#include "envoy/config/route/v3/route_components.pb.h"
#include "envoy/http/header_map.h"
#include "envoy/runtime/runtime.h"
#include "envoy/type/matcher/v3/http_inputs.pb.h"
#include "envoy/type/matcher/v3/http_inputs.pb.validate.h"
#include "envoy/type/matcher/v3/string.pb.h"
#include "envoy/type/v3/percent.pb.h"
#include "envoy/upstream/cluster_manager.h"
#include "envoy/upstream/upstream.h"
#include "source/common/common/assert.h"
#include "source/common/common/empty_string.h"
#include "source/common/common/fmt.h"
#include "source/common/common/hash.h"
#include "source/common/common/logger.h"
#include "source/common/common/regex.h"
#include "source/common/common/utility.h"
#include "source/common/config/metadata.h"
#include "source/common/config/utility.h"
#include "source/common/config/well_known_names.h"
#include "source/common/formatter/substitution_format_string.h"
#include "source/common/grpc/common.h"
#include "source/common/http/header_utility.h"
#include "source/common/http/headers.h"
#include "source/common/http/matching/data_impl.h"
#include "source/common/http/path_utility.h"
#include "source/common/http/utility.h"
#include "source/common/matcher/matcher.h"
#include "source/common/protobuf/protobuf.h"
#include "source/common/protobuf/utility.h"
#include "source/common/router/context_impl.h"
#include "source/common/router/header_cluster_specifier.h"
#include "source/common/router/matcher_visitor.h"
#include "source/common/router/weighted_cluster_specifier.h"
#include "source/common/runtime/runtime_features.h"
#include "source/common/tracing/custom_tag_impl.h"
#include "source/common/tracing/http_tracer_impl.h"
#include "source/extensions/early_data/default_early_data_policy.h"
#include "source/extensions/matching/network/common/inputs.h"
#include "source/extensions/path/match/uri_template/uri_template_match.h"
#include "source/extensions/path/rewrite/uri_template/uri_template_rewrite.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/strings/match.h"
#include "absl/types/optional.h"
namespace Envoy {
namespace Router {
class RouteCreator {
public:
static absl::StatusOr<RouteEntryImplBaseConstSharedPtr>
createAndValidateRoute(const envoy::config::route::v3::Route& route_config,
const CommonVirtualHostSharedPtr& vhost,
Server::Configuration::ServerFactoryContext& factory_context,
ProtobufMessage::ValidationVisitor& validator, bool validate_clusters) {
absl::Status creation_status = absl::OkStatus();
RouteEntryImplBaseConstSharedPtr route;
switch (route_config.match().path_specifier_case()) {
case envoy::config::route::v3::RouteMatch::PathSpecifierCase::kPrefix:
route = std::make_shared<PrefixRouteEntryImpl>(vhost, route_config, factory_context,
validator, creation_status);
break;
case envoy::config::route::v3::RouteMatch::PathSpecifierCase::kPath:
route = std::make_shared<PathRouteEntryImpl>(vhost, route_config, factory_context, validator,
creation_status);
break;
case envoy::config::route::v3::RouteMatch::PathSpecifierCase::kSafeRegex:
route = std::make_shared<RegexRouteEntryImpl>(vhost, route_config, factory_context, validator,
creation_status);
break;
case envoy::config::route::v3::RouteMatch::PathSpecifierCase::kConnectMatcher:
route = std::make_shared<ConnectRouteEntryImpl>(vhost, route_config, factory_context,
validator, creation_status);
break;
case envoy::config::route::v3::RouteMatch::PathSpecifierCase::kPathSeparatedPrefix:
route = std::make_shared<PathSeparatedPrefixRouteEntryImpl>(
vhost, route_config, factory_context, validator, creation_status);
break;
case envoy::config::route::v3::RouteMatch::PathSpecifierCase::kPathMatchPolicy:
route = std::make_shared<UriTemplateMatcherRouteEntryImpl>(
vhost, route_config, factory_context, validator, creation_status);
break;
case envoy::config::route::v3::RouteMatch::PathSpecifierCase::PATH_SPECIFIER_NOT_SET:
break; // return the error below.
}
if (!route) {
return absl::InvalidArgumentError("Invalid route config");
}
RETURN_IF_NOT_OK(creation_status);
if (validate_clusters) {
const Upstream::ClusterManager& cluster_manager = factory_context.clusterManager();
RETURN_IF_NOT_OK(route->validateClusters(cluster_manager));
for (const auto& shadow_policy : route->shadowPolicies()) {
if (!shadow_policy->cluster().empty()) {
ASSERT(shadow_policy->clusterHeader().get().empty());
// if (!validation_clusters->hasCluster(shadow_policy->cluster())) {
if (!cluster_manager.hasCluster(shadow_policy->cluster())) {
return absl::InvalidArgumentError(
fmt::format("route: unknown shadow cluster '{}'", shadow_policy->cluster()));
}
}
}
}
return route;
}
};
namespace {
constexpr uint32_t DEFAULT_MAX_DIRECT_RESPONSE_BODY_SIZE_BYTES = 4096;
// Returns an array of header parsers, sorted by specificity. The `specificity_ascend` parameter
// specifies whether the returned parsers will be sorted from least specific to most specific
// (global connection manager level header parser, virtual host level header parser and finally
// route-level parser.) or the reverse.
std::array<const HeaderParser*, 3>
getHeaderParsers(const HeaderParser* global_route_config_header_parser,
const HeaderParser* vhost_header_parser, const HeaderParser* route_header_parser,
bool specificity_ascend) {
if (specificity_ascend) {
// Sorted from least to most specific: global connection manager level headers, virtual host
// level headers and finally route-level headers.
return {global_route_config_header_parser, vhost_header_parser, route_header_parser};
} else {
// Sorted from most to least specific.
return {route_header_parser, vhost_header_parser, global_route_config_header_parser};
}
}
// If the implementation of a cluster specifier plugin is not provided in current Envoy and the
// plugin is set to optional, then this null plugin will be used as a placeholder.
class NullClusterSpecifierPlugin : public ClusterSpecifierPlugin {
public:
RouteConstSharedPtr route(RouteEntryAndRouteConstSharedPtr, const Http::RequestHeaderMap&,
const StreamInfo::StreamInfo&, uint64_t) const override {
return nullptr;
}
};
absl::StatusOr<ClusterSpecifierPluginSharedPtr>
getClusterSpecifierPluginByTheProto(const envoy::config::route::v3::ClusterSpecifierPlugin& plugin,
ProtobufMessage::ValidationVisitor& validator,
Server::Configuration::ServerFactoryContext& factory_context) {
auto* factory =
Envoy::Config::Utility::getFactory<ClusterSpecifierPluginFactoryConfig>(plugin.extension());
if (factory == nullptr) {
if (plugin.is_optional()) {
return std::make_shared<NullClusterSpecifierPlugin>();
}
return absl::InvalidArgumentError(
fmt::format("Didn't find a registered implementation for '{}' with type URL: '{}'",
plugin.extension().name(),
Envoy::Config::Utility::getFactoryType(plugin.extension().typed_config())));
}
ASSERT(factory != nullptr);
auto config =
Envoy::Config::Utility::translateToFactoryConfig(plugin.extension(), validator, *factory);
return factory->createClusterSpecifierPlugin(*config, factory_context);
}
::Envoy::Http::Utility::RedirectConfig
createRedirectConfig(const envoy::config::route::v3::Route& route, Regex::Engine& regex_engine) {
::Envoy::Http::Utility::RedirectConfig redirect_config{
route.redirect().scheme_redirect(),
route.redirect().host_redirect(),
route.redirect().port_redirect() ? ":" + std::to_string(route.redirect().port_redirect())
: "",
route.redirect().path_redirect(),
route.redirect().prefix_rewrite(),
route.redirect().has_regex_rewrite() ? route.redirect().regex_rewrite().substitution() : "",
route.redirect().has_regex_rewrite()
? THROW_OR_RETURN_VALUE(Regex::Utility::parseRegex(
route.redirect().regex_rewrite().pattern(), regex_engine),
Regex::CompiledMatcherPtr)
: nullptr,
route.redirect().path_redirect().find('?') != absl::string_view::npos,
route.redirect().https_redirect(),
route.redirect().strip_query()};
if (route.redirect().has_regex_rewrite()) {
ASSERT(redirect_config.prefix_rewrite_redirect_.empty());
}
return redirect_config;
}
std::string generateNewPath(absl::string_view origin_path, absl::string_view path_to_strip,
absl::string_view new_path_to_replace) {
ASSERT(path_to_strip.size() <= origin_path.size());
std::string result;
result.reserve(new_path_to_replace.size() + origin_path.size() - path_to_strip.size());
result.append(new_path_to_replace);
result.append(origin_path.substr(path_to_strip.size()));
return result;
}
std::string rewritePathByPrefixOrRegex(absl::string_view path, absl::string_view matched,
absl::string_view prefix_rewrite,
const Regex::CompiledMatcher* regex_rewrite,
absl::string_view regex_rewrite_substitution) {
if (!prefix_rewrite.empty()) {
ASSERT(absl::StartsWithIgnoreCase(path, matched));
return generateNewPath(path, matched, prefix_rewrite);
}
if (regex_rewrite != nullptr) {
absl::string_view path_only = Http::PathUtil::removeQueryAndFragment(path);
ASSERT(path_only.size() <= path.size());
const std::string new_path_only =
regex_rewrite->replaceAll(path_only, regex_rewrite_substitution);
// If regex rewrite fails then return nothing.
if (new_path_only.empty()) {
return {};
}
return generateNewPath(path, path_only, new_path_only);
}
return {};
}
} // namespace
const std::string& OriginalConnectPort::key() {
CONSTRUCT_ON_FIRST_USE(std::string, "envoy.router.original_connect_port");
}
std::string SslRedirector::newUri(const Http::RequestHeaderMap& headers) const {
return Http::Utility::createSslRedirectPath(headers);
}
HedgePolicyImpl::HedgePolicyImpl(const envoy::config::route::v3::HedgePolicy& hedge_policy)
: additional_request_chance_(hedge_policy.additional_request_chance()),
initial_requests_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(hedge_policy, initial_requests, 1)),
hedge_on_per_try_timeout_(hedge_policy.hedge_on_per_try_timeout()) {}
HedgePolicyImpl::HedgePolicyImpl() : initial_requests_(1), hedge_on_per_try_timeout_(false) {}
absl::StatusOr<std::unique_ptr<InternalRedirectPolicyImpl>> InternalRedirectPolicyImpl::create(
const envoy::config::route::v3::InternalRedirectPolicy& policy_config,
ProtobufMessage::ValidationVisitor& validator, absl::string_view current_route_name) {
absl::Status creation_status = absl::OkStatus();
auto ret = std::unique_ptr<InternalRedirectPolicyImpl>(new InternalRedirectPolicyImpl(
policy_config, validator, current_route_name, creation_status));
RETURN_IF_NOT_OK(creation_status);
return ret;
}
InternalRedirectPolicyImpl::InternalRedirectPolicyImpl(
const envoy::config::route::v3::InternalRedirectPolicy& policy_config,
ProtobufMessage::ValidationVisitor& validator, absl::string_view current_route_name,
absl::Status& creation_status)
: current_route_name_(current_route_name),
redirect_response_codes_(buildRedirectResponseCodes(policy_config)),
max_internal_redirects_(
PROTOBUF_GET_WRAPPED_OR_DEFAULT(policy_config, max_internal_redirects, 1)),
enabled_(true), allow_cross_scheme_redirect_(policy_config.allow_cross_scheme_redirect()) {
for (const auto& predicate : policy_config.predicates()) {
auto& factory =
Envoy::Config::Utility::getAndCheckFactory<InternalRedirectPredicateFactory>(predicate);
auto config = factory.createEmptyConfigProto();
SET_AND_RETURN_IF_NOT_OK(
Envoy::Config::Utility::translateOpaqueConfig(predicate.typed_config(), validator, *config),
creation_status);
predicate_factories_.emplace_back(&factory, std::move(config));
}
for (const auto& header : policy_config.response_headers_to_copy()) {
if (!Http::HeaderUtility::isModifiableHeader(header)) {
creation_status =
absl::InvalidArgumentError(":-prefixed headers or Hosts may not be specified here.");
return;
}
response_headers_to_copy_.emplace_back(header);
}
}
std::vector<InternalRedirectPredicateSharedPtr> InternalRedirectPolicyImpl::predicates() const {
std::vector<InternalRedirectPredicateSharedPtr> predicates;
predicates.reserve(predicate_factories_.size());
for (const auto& predicate_factory : predicate_factories_) {
predicates.emplace_back(predicate_factory.first->createInternalRedirectPredicate(
*predicate_factory.second, current_route_name_));
}
return predicates;
}
const std::vector<Http::LowerCaseString>&
InternalRedirectPolicyImpl::responseHeadersToCopy() const {
return response_headers_to_copy_;
}
absl::flat_hash_set<Http::Code> InternalRedirectPolicyImpl::buildRedirectResponseCodes(
const envoy::config::route::v3::InternalRedirectPolicy& policy_config) const {
if (policy_config.redirect_response_codes_size() == 0) {
return absl::flat_hash_set<Http::Code>{Http::Code::Found};
}
absl::flat_hash_set<Http::Code> ret;
std::for_each(policy_config.redirect_response_codes().begin(),
policy_config.redirect_response_codes().end(), [&ret](uint32_t response_code) {
const absl::flat_hash_set<uint32_t> valid_redirect_response_code = {301, 302, 303,
307, 308};
if (valid_redirect_response_code.contains(response_code)) {
ret.insert(static_cast<Http::Code>(response_code));
}
});
return ret;
}
absl::Status validateMirrorClusterSpecifier(
const envoy::config::route::v3::RouteAction::RequestMirrorPolicy& config) {
if (!config.cluster().empty() && !config.cluster_header().empty()) {
return absl::InvalidArgumentError(fmt::format("Only one of cluster '{}' or cluster_header '{}' "
"in request mirror policy can be specified",
config.cluster(), config.cluster_header()));
} else if (config.cluster().empty() && config.cluster_header().empty()) {
// For shadow policies with `cluster_header_`, we only verify that this field is not
// empty because the cluster name is not set yet at config time.
return absl::InvalidArgumentError(
"Exactly one of cluster or cluster_header in request mirror policy need to be specified");
}
return absl::OkStatus();
}
absl::StatusOr<std::shared_ptr<ShadowPolicyImpl>>
ShadowPolicyImpl::create(const RequestMirrorPolicy& config,
Server::Configuration::CommonFactoryContext& factory_context) {
absl::Status creation_status = absl::OkStatus();
auto ret = std::shared_ptr<ShadowPolicyImpl>(
new ShadowPolicyImpl(config, factory_context, creation_status));
RETURN_IF_NOT_OK(creation_status);
return ret;
}
ShadowPolicyImpl::ShadowPolicyImpl(const RequestMirrorPolicy& config,
Server::Configuration::CommonFactoryContext& factory_context,
absl::Status& creation_status)
: cluster_(config.cluster()), cluster_header_(config.cluster_header()),
disable_shadow_host_suffix_append_(config.disable_shadow_host_suffix_append()),
host_rewrite_literal_(config.host_rewrite_literal()),
auto_host_rewrite_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, auto_host_rewrite, false)) {
SET_AND_RETURN_IF_NOT_OK(validateMirrorClusterSpecifier(config), creation_status);
if (config.has_runtime_fraction()) {
runtime_key_ = config.runtime_fraction().runtime_key();
default_value_ = config.runtime_fraction().default_value();
} else {
// If there is no runtime fraction specified, the default is 100% sampled. By leaving
// runtime_key_ empty and forcing the default to 100% this will yield the expected behavior.
default_value_.set_numerator(100);
default_value_.set_denominator(envoy::type::v3::FractionalPercent::HUNDRED);
}
// If trace sampling is not explicitly configured in shadow_policy, we pass null optional to
// inherit the parent's sampling decision. This prevents oversampling when runtime sampling is
// disabled.
trace_sampled_ = config.has_trace_sampled() ? absl::optional<bool>(config.trace_sampled().value())
: absl::nullopt;
// Create HeaderMutations directly from HeaderMutation rules
if (!config.request_headers_mutations().empty()) {
auto mutations_or_error =
Http::HeaderMutations::create(config.request_headers_mutations(), factory_context);
SET_AND_RETURN_IF_NOT_OK(mutations_or_error.status(), creation_status);
request_headers_mutations_ = std::move(mutations_or_error.value());
}
}
const Http::HeaderEvaluator& ShadowPolicyImpl::headerEvaluator() const {
if (request_headers_mutations_) {
return *request_headers_mutations_;
}
return HeaderParser::defaultParser();
}
DecoratorImpl::DecoratorImpl(const envoy::config::route::v3::Decorator& decorator)
: operation_(decorator.operation()),
propagate_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(decorator, propagate, true)) {}
void DecoratorImpl::apply(Tracing::Span& span) const {
if (!operation_.empty()) {
span.setOperation(operation_);
}
}
const std::string& DecoratorImpl::getOperation() const { return operation_; }
bool DecoratorImpl::propagate() const { return propagate_; }
RouteTracingImpl::RouteTracingImpl(const envoy::config::route::v3::Tracing& tracing) {
if (!tracing.has_client_sampling()) {
client_sampling_.set_numerator(100);
client_sampling_.set_denominator(envoy::type::v3::FractionalPercent::HUNDRED);
} else {
client_sampling_ = tracing.client_sampling();
}
if (!tracing.has_random_sampling()) {
random_sampling_.set_numerator(100);
random_sampling_.set_denominator(envoy::type::v3::FractionalPercent::HUNDRED);
} else {
random_sampling_ = tracing.random_sampling();
}
if (!tracing.has_overall_sampling()) {
overall_sampling_.set_numerator(100);
overall_sampling_.set_denominator(envoy::type::v3::FractionalPercent::HUNDRED);
} else {
overall_sampling_ = tracing.overall_sampling();
}
for (const auto& tag : tracing.custom_tags()) {
custom_tags_.emplace(tag.tag(), Tracing::CustomTagUtility::createCustomTag(tag));
}
if (!tracing.operation().empty()) {
auto operation = Formatter::FormatterImpl::create(tracing.operation(), true);
THROW_IF_NOT_OK_REF(operation.status());
operation_ = std::move(operation.value());
}
if (!tracing.upstream_operation().empty()) {
auto operation = Formatter::FormatterImpl::create(tracing.upstream_operation(), true);
THROW_IF_NOT_OK_REF(operation.status());
upstream_operation_ = std::move(operation.value());
}
}
const envoy::type::v3::FractionalPercent& RouteTracingImpl::getClientSampling() const {
return client_sampling_;
}
const envoy::type::v3::FractionalPercent& RouteTracingImpl::getRandomSampling() const {
return random_sampling_;
}
const envoy::type::v3::FractionalPercent& RouteTracingImpl::getOverallSampling() const {
return overall_sampling_;
}
const Tracing::CustomTagMap& RouteTracingImpl::getCustomTags() const { return custom_tags_; }
uint64_t getRequestBodyBufferLimit(const CommonVirtualHostSharedPtr& vhost,
const envoy::config::route::v3::Route& route) {
// Route level request_body_buffer_limit takes precedence over all others.
if (route.has_request_body_buffer_limit()) {
return route.request_body_buffer_limit().value();
}
// Then virtual host level request_body_buffer_limit.
if (const auto v = vhost->requestBodyBufferLimit(); v.has_value()) {
return v.value();
}
// Then route level legacy per_request_buffer_limit_bytes.
if (route.has_per_request_buffer_limit_bytes()) {
return route.per_request_buffer_limit_bytes().value();
}
// Then virtual host level legacy per_request_buffer_limit_bytes.
if (const auto v = vhost->legacyRequestBodyBufferLimit(); v.has_value()) {
return v.value();
}
// Finally return max value to indicate no limit.
return std::numeric_limits<uint64_t>::max();
}
RouteEntryImplBase::RouteEntryImplBase(const CommonVirtualHostSharedPtr& vhost,
const envoy::config::route::v3::Route& route,
Server::Configuration::ServerFactoryContext& factory_context,
ProtobufMessage::ValidationVisitor& validator,
absl::Status& creation_status)
: path_matcher_(
THROW_OR_RETURN_VALUE(buildPathMatcher(route, validator), PathMatcherSharedPtr)),
prefix_rewrite_(route.route().prefix_rewrite()),
path_rewriter_(
THROW_OR_RETURN_VALUE(buildPathRewriter(route, validator), PathRewriterSharedPtr)),
host_rewrite_(route.route().host_rewrite_literal()),
host_rewrite_header_(route.route().host_rewrite_header()),
host_rewrite_path_regex_(
route.route().has_host_rewrite_path_regex()
? THROW_OR_RETURN_VALUE(
Regex::Utility::parseRegex(route.route().host_rewrite_path_regex().pattern(),
factory_context.regexEngine()),
Regex::CompiledMatcherPtr)
: nullptr),
host_rewrite_path_regex_substitution_(
route.route().has_host_rewrite_path_regex()
? route.route().host_rewrite_path_regex().substitution()
: ""),
vhost_(vhost), cluster_name_(route.route().cluster()),
timeout_(PROTOBUF_GET_MS_OR_DEFAULT(route.route(), timeout, DEFAULT_ROUTE_TIMEOUT_MS)),
optional_timeouts_(buildOptionalTimeouts(route.route())), loader_(factory_context.runtime()),
runtime_(loadRuntimeData(route.match())),
redirect_config_(route.has_redirect()
? std::make_unique<::Envoy::Http::Utility::RedirectConfig>(
createRedirectConfig(route, factory_context.regexEngine()))
: nullptr),
hedge_policy_(buildHedgePolicy(vhost->hedgePolicy(), route.route())),
internal_redirect_policy_(
THROW_OR_RETURN_VALUE(buildInternalRedirectPolicy(route.route(), validator, route.name()),
std::unique_ptr<InternalRedirectPolicyImpl>)),
config_headers_(
Http::HeaderUtility::buildHeaderDataVector(route.match().headers(), factory_context)),
dynamic_metadata_([&]() {
std::vector<Envoy::Matchers::MetadataMatcher> vec;
for (const auto& elt : route.match().dynamic_metadata()) {
vec.emplace_back(elt, factory_context);
}
return vec;
}()),
filter_state_([&]() {
std::vector<Envoy::Matchers::FilterStateMatcher> vec;
vec.reserve(route.match().filter_state().size());
for (const auto& elt : route.match().filter_state()) {
Envoy::Matchers::FilterStateMatcherPtr match = THROW_OR_RETURN_VALUE(
Envoy::Matchers::FilterStateMatcher::create(elt, factory_context),
Envoy::Matchers::FilterStateMatcherPtr);
vec.emplace_back(std::move(*match));
}
return vec;
}()),
opaque_config_(parseOpaqueConfig(route)), decorator_(parseDecorator(route)),
route_tracing_(parseRouteTracing(route)), route_name_(route.name()),
time_source_(factory_context.mainThreadDispatcher().timeSource()),
request_body_buffer_limit_(getRequestBodyBufferLimit(vhost, route)),
direct_response_code_(ConfigUtility::parseDirectResponseCode(route)),
cluster_not_found_response_code_(ConfigUtility::parseClusterNotFoundResponseCode(
route.route().cluster_not_found_response_code())),
priority_(ConfigUtility::parsePriority(route.route().priority())),
auto_host_rewrite_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(route.route(), auto_host_rewrite, false)),
append_xfh_(route.route().append_x_forwarded_host()),
using_new_timeouts_(route.route().has_max_stream_duration()),
match_grpc_(route.match().has_grpc()),
case_sensitive_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(route.match(), case_sensitive, true)) {
auto config_or_error =
PerFilterConfigs::create(route.typed_per_filter_config(), factory_context, validator);
SET_AND_RETURN_IF_NOT_OK(config_or_error.status(), creation_status);
per_filter_configs_ = std::move(config_or_error.value());
auto policy_or_error =
buildRetryPolicy(vhost->retryPolicy(), route.route(), validator, factory_context);
SET_AND_RETURN_IF_NOT_OK(policy_or_error.status(), creation_status);
retry_policy_ = policy_or_error.value() != nullptr ? std::move(policy_or_error.value())
: RetryPolicyImpl::DefaultRetryPolicy;
if (route.has_direct_response() && route.direct_response().has_body()) {
auto provider_or_error = Envoy::Config::DataSource::DataSourceProvider<std::string>::create(
route.direct_response().body(), factory_context.mainThreadDispatcher(),
factory_context.threadLocal(), factory_context.api(), true,
[](absl::string_view data) { return std::make_shared<std::string>(data); },
vhost_->globalRouteConfig().maxDirectResponseBodySizeBytes());
SET_AND_RETURN_IF_NOT_OK(provider_or_error.status(), creation_status);
direct_response_body_provider_ = std::move(provider_or_error.value());
}
if (route.direct_response().has_body_format()) {
Server::GenericFactoryContextImpl generic_context(factory_context,
factory_context.messageValidationVisitor());
auto formatter_or_error = Formatter::SubstitutionFormatStringUtils::fromProtoConfig(
route.direct_response().body_format(), generic_context);
SET_AND_RETURN_IF_NOT_OK(formatter_or_error.status(), creation_status);
direct_response_body_formatter_ = std::move(formatter_or_error.value());
// Capture the content_type from body_format, using the same defaulting logic as
// local_reply.cc BodyFormatter: explicit content_type > JSON format default > empty
// (text/plain).
const auto& body_format = route.direct_response().body_format();
if (!body_format.content_type().empty()) {
direct_response_content_type_ = body_format.content_type();
} else if (body_format.format_case() ==
envoy::config::core::v3::SubstitutionFormatString::FormatCase::kJsonFormat) {
direct_response_content_type_ = Http::Headers::get().ContentTypeValues.Json;
}
// else: leave empty; sendLocalReply will use its default "text/plain"
}
if (!route.request_headers_to_add().empty() || !route.request_headers_to_remove().empty()) {
auto parser_or_error =
HeaderParser::configure(route.request_headers_to_add(), route.request_headers_to_remove());
SET_AND_RETURN_IF_NOT_OK(parser_or_error.status(), creation_status);
request_headers_parser_ = std::move(parser_or_error.value());
}
if (!route.response_headers_to_add().empty() || !route.response_headers_to_remove().empty()) {
auto parser_or_error = HeaderParser::configure(route.response_headers_to_add(),
route.response_headers_to_remove());
SET_AND_RETURN_IF_NOT_OK(parser_or_error.status(), creation_status);
response_headers_parser_ = std::move(parser_or_error.value());
}
if (route.has_metadata()) {
metadata_ = std::make_unique<RouteMetadataPack>(route.metadata());
}
if (route.route().has_metadata_match()) {
const auto filter_it = route.route().metadata_match().filter_metadata().find(
Envoy::Config::MetadataFilters::get().ENVOY_LB);
if (filter_it != route.route().metadata_match().filter_metadata().end()) {
metadata_match_criteria_ = std::make_unique<MetadataMatchCriteriaImpl>(filter_it->second);
}
}
shadow_policies_.reserve(route.route().request_mirror_policies().size());
for (const auto& mirror_policy_config : route.route().request_mirror_policies()) {
auto policy_or_error = ShadowPolicyImpl::create(mirror_policy_config, factory_context);
SET_AND_RETURN_IF_NOT_OK(policy_or_error.status(), creation_status);
shadow_policies_.push_back(std::move(policy_or_error.value()));
}
// Inherit policies from the virtual host, which might be from the route config.
if (shadow_policies_.empty()) {
shadow_policies_ = vhost->shadowPolicies();
}
if (route.route().has_weighted_clusters()) {
cluster_specifier_plugin_ = std::make_shared<WeightedClusterSpecifierPlugin>(
route.route().weighted_clusters(), metadata_match_criteria_.get(), route_name_,
factory_context, creation_status);
RETURN_ONLY_IF_NOT_OK_REF(creation_status);
} else if (route.route().has_inline_cluster_specifier_plugin()) {
auto plugin_or_error = getClusterSpecifierPluginByTheProto(
route.route().inline_cluster_specifier_plugin(), validator, factory_context);
SET_AND_RETURN_IF_NOT_OK(plugin_or_error.status(), creation_status);
cluster_specifier_plugin_ = std::move(plugin_or_error.value());
} else if (route.route().has_cluster_specifier_plugin()) {
auto plugin_or_error = vhost_->globalRouteConfig().clusterSpecifierPlugin(
route.route().cluster_specifier_plugin());
SET_AND_RETURN_IF_NOT_OK(plugin_or_error.status(), creation_status);
cluster_specifier_plugin_ = std::move(plugin_or_error.value());
} else if (route.route().has_cluster_header()) {
cluster_specifier_plugin_ =
std::make_shared<HeaderClusterSpecifierPlugin>(route.route().cluster_header());
}
for (const auto& query_parameter : route.match().query_parameters()) {
config_query_parameters_.push_back(
std::make_unique<ConfigUtility::QueryParameterMatcher>(query_parameter, factory_context));
}
for (const auto& cookie_matcher : route.match().cookies()) {
config_cookies_.push_back(
std::make_unique<ConfigUtility::CookieMatcher>(cookie_matcher, factory_context));
}
if (!config_cookies_.empty()) {
config_cookie_names_.reserve(config_cookies_.size());
for (const auto& matcher : config_cookies_) {
config_cookie_names_.insert(matcher->name());
}
}
if (!route.route().hash_policy().empty()) {
hash_policy_ = THROW_OR_RETURN_VALUE(
Http::HashPolicyImpl::create(route.route().hash_policy(), factory_context.regexEngine()),
std::unique_ptr<Http::HashPolicyImpl>);
}
if (route.match().has_tls_context()) {
tls_context_match_criteria_ =
std::make_unique<TlsContextMatchCriteriaImpl>(route.match().tls_context());
}
if (!route.route().rate_limits().empty()) {
rate_limit_policy_ = std::make_unique<RateLimitPolicyImpl>(route.route().rate_limits(),
factory_context, creation_status);
if (!creation_status.ok()) {
return;
}
}
// Returns true if include_vh_rate_limits is explicitly set to true otherwise it defaults to false
// which is similar to VhRateLimitOptions::Override and will only use virtual host rate limits if
// the route is empty
include_vh_rate_limits_ =
PROTOBUF_GET_WRAPPED_OR_DEFAULT(route.route(), include_vh_rate_limits, false);
if (route.route().has_cors()) {
cors_policy_ = std::make_unique<CorsPolicyImpl>(route.route().cors(), factory_context);
}
for (const auto& upgrade_config : route.route().upgrade_configs()) {
const bool enabled = upgrade_config.has_enabled() ? upgrade_config.enabled().value() : true;
const bool success =
upgrade_map_
.emplace(std::make_pair(
Envoy::Http::LowerCaseString(upgrade_config.upgrade_type()).get(), enabled))
.second;
if (!success) {
creation_status = absl::InvalidArgumentError(
absl::StrCat("Duplicate upgrade ", upgrade_config.upgrade_type()));
return;
}
if (upgrade_config.has_connect_config()) {
if (absl::EqualsIgnoreCase(upgrade_config.upgrade_type(),
Http::Headers::get().MethodValues.Connect) ||
absl::EqualsIgnoreCase(upgrade_config.upgrade_type(),
Http::Headers::get().UpgradeValues.ConnectUdp)) {
connect_config_ = std::make_unique<ConnectConfig>(upgrade_config.connect_config());
} else {
creation_status = absl::InvalidArgumentError(absl::StrCat(
"Non-CONNECT upgrade type ", upgrade_config.upgrade_type(), " has ConnectConfig"));
return;
}
}
}
int num_rewrite_polices = 0;
if (path_rewriter_ != nullptr) {
++num_rewrite_polices;
}
if (!prefix_rewrite_.empty()) {
++num_rewrite_polices;
}
if (route.route().has_regex_rewrite()) {
++num_rewrite_polices;
}
if (!route.route().path_rewrite().empty()) {
++num_rewrite_polices;
}
if (num_rewrite_polices > 1) {
creation_status = absl::InvalidArgumentError(
"Specify only one of prefix_rewrite, regex_rewrite or path_rewrite_policy");
return;
}
if (!prefix_rewrite_.empty() && path_matcher_ != nullptr) {
creation_status =
absl::InvalidArgumentError("Cannot use prefix_rewrite with matcher extension");
return;
}
if (route.route().has_regex_rewrite()) {
auto rewrite_spec = route.route().regex_rewrite();
regex_rewrite_ = THROW_OR_RETURN_VALUE(
Regex::Utility::parseRegex(rewrite_spec.pattern(), factory_context.regexEngine()),
Regex::CompiledMatcherPtr);
regex_rewrite_substitution_ = rewrite_spec.substitution();
}
if (!route.route().path_rewrite().empty()) {
auto formatter_or = Envoy::Formatter::FormatterImpl::create(route.route().path_rewrite(), true);
if (!formatter_or.ok()) {
creation_status = absl::InvalidArgumentError(
absl::StrCat("Failed to create path rewrite formatter: ", formatter_or.status()));
return;
}
path_rewrite_formatter_ = std::move(formatter_or.value());
}
if (path_rewriter_ != nullptr) {
SET_AND_RETURN_IF_NOT_OK(path_rewriter_->isCompatiblePathMatcher(path_matcher_),
creation_status);
}
if (!route.route().host_rewrite().empty()) {
auto formatter_or =
Envoy::Formatter::FormatterImpl::create(route.route().host_rewrite(), false);
if (!formatter_or.ok()) {
creation_status = absl::InvalidArgumentError(
absl::StrCat("Failed to create host rewrite formatter: ", formatter_or.status()));
return;
}
host_rewrite_formatter_ = std::move(formatter_or.value());
}
if (redirect_config_ != nullptr && redirect_config_->path_redirect_has_query_ &&
redirect_config_->strip_query_) {
ENVOY_LOG(debug,
"`strip_query` is set to true, but `path_redirect` contains query string and it will "
"not be stripped: {}",
redirect_config_->path_redirect_);
}
if (!route.stat_prefix().empty()) {
route_stats_context_ = std::make_unique<RouteStatsContextImpl>(
factory_context.scope(), factory_context.routerContext().routeStatNames(),
vhost->statName(), route.stat_prefix());
}
if (route.route().has_early_data_policy()) {
auto& factory = Envoy::Config::Utility::getAndCheckFactory<EarlyDataPolicyFactory>(
route.route().early_data_policy());
auto message = Envoy::Config::Utility::translateToFactoryConfig(
route.route().early_data_policy(), validator, factory);
early_data_policy_ = factory.createEarlyDataPolicy(*message);
} else {
early_data_policy_ = std::make_unique<DefaultEarlyDataPolicy>(/*allow_safe_request*/ true);
}
}
bool RouteEntryImplBase::evaluateRuntimeMatch(const uint64_t random_value) const {
return runtime_ == nullptr
? true
: loader_.snapshot().featureEnabled(runtime_->fractional_runtime_key_,
runtime_->fractional_runtime_default_,
random_value);
}
absl::string_view
RouteEntryImplBase::sanitizePathBeforePathMatching(const absl::string_view path) const {
absl::string_view ret = path;
if (vhost_->globalRouteConfig().ignorePathParametersInPathMatching()) {
auto pos = ret.find_first_of(';');
if (pos != absl::string_view::npos) {
ret.remove_suffix(ret.length() - pos);
}
}
return ret;
}
bool RouteEntryImplBase::evaluateTlsContextMatch(const StreamInfo::StreamInfo& stream_info) const {
bool matches = true;
if (!tlsContextMatchCriteria()) {
return matches;
}
const TlsContextMatchCriteria& criteria = *tlsContextMatchCriteria();
if (criteria.presented().has_value()) {
const bool peer_presented =
stream_info.downstreamAddressProvider().sslConnection() &&
stream_info.downstreamAddressProvider().sslConnection()->peerCertificatePresented();
matches &= criteria.presented().value() == peer_presented;
}
if (criteria.validated().has_value()) {
const bool peer_validated =
stream_info.downstreamAddressProvider().sslConnection() &&
stream_info.downstreamAddressProvider().sslConnection()->peerCertificateValidated();
matches &= criteria.validated().value() == peer_validated;
}
return matches;
}
bool RouteEntryImplBase::isRedirect() const {
if (!isDirectResponse()) {
return false;
}
if (redirect_config_ == nullptr) {
return false;
}
return !redirect_config_->host_redirect_.empty() || !redirect_config_->path_redirect_.empty() ||
!redirect_config_->prefix_rewrite_redirect_.empty() ||
redirect_config_->regex_rewrite_redirect_ != nullptr;
}
bool RouteEntryImplBase::matchRoute(const Http::RequestHeaderMap& headers,
const StreamInfo::StreamInfo& stream_info,
uint64_t random_value) const {
bool matches = true;
matches &= evaluateRuntimeMatch(random_value);
if (!matches) {
// No need to waste further cycles calculating a route match.
return false;
}
if (match_grpc_) {
matches &= Grpc::Common::isGrpcRequestHeaders(headers);
if (!matches) {
return false;
}
}
matches &= Http::HeaderUtility::matchHeaders(headers, config_headers_);
if (!matches) {
return false;
}
if (!config_query_parameters_.empty()) {
auto query_parameters =
Http::Utility::QueryParamsMulti::parseQueryString(headers.getPathValue());
matches &= ConfigUtility::matchQueryParams(query_parameters, config_query_parameters_);
if (!matches) {
return false;
}
}
if (!config_cookies_.empty()) {
const auto cookies =
Http::Utility::parseCookies(headers, [this](absl::string_view key) -> bool {
return config_cookie_names_.find(key) != config_cookie_names_.end();
});
if (!ConfigUtility::matchCookies(cookies, config_cookies_)) {
return false;
}
}
matches &= evaluateTlsContextMatch(stream_info);
for (const auto& m : dynamic_metadata_) {
if (!matches) {
// No need to check anymore as all dynamic metadata matchers must match for a match to occur.
break;
}
matches &= m.match(stream_info.dynamicMetadata());
}
for (const auto& m : filter_state_) {
if (!matches) {
// No need to check anymore as all filter state matchers must match for a match to occur.
break;
}
matches &= m.match(stream_info.filterState());
}
return matches;
}
const std::string& RouteEntryImplBase::clusterName() const { return cluster_name_; }
void RouteEntryImplBase::finalizePathHeaderForRedirect(Http::RequestHeaderMap& headers,
absl::string_view matched_path,
bool keep_old_path) const {
if (redirect_config_ == nullptr) {
return;
}
const std::string new_path = rewritePathByPrefixOrRegex(
headers.getPathValue(), matched_path, redirect_config_->prefix_rewrite_redirect_,
redirect_config_->regex_rewrite_redirect_.get(),
redirect_config_->regex_rewrite_redirect_substitution_);
// Empty new_path means there is no rewrite or the rewrite fails. Then we do nothing.
if (!new_path.empty()) {
if (keep_old_path) {
headers.setEnvoyOriginalPath(headers.getPathValue());
}
headers.setPath(new_path);
}
}
void RouteEntryImplBase::finalizePathHeader(Http::RequestHeaderMap& headers,
const Formatter::Context& context,
const StreamInfo::StreamInfo& stream_info,
bool keep_old_path) const {
const std::string new_path = currentUrlPathAfterRewrite(headers, context, stream_info);
// Empty new_path means there is no rewrite or the rewrite fails. Then we do nothing.
if (!new_path.empty()) {
if (keep_old_path) {
headers.setEnvoyOriginalPath(headers.getPathValue());
}
headers.setPath(new_path);
}
}
void RouteEntryImplBase::finalizeHostHeader(Http::RequestHeaderMap& headers,
const Formatter::Context& context,
const StreamInfo::StreamInfo& stream_info,
bool keep_old_host) const {
absl::string_view hostname;
std::string buffer;
if (!host_rewrite_.empty()) {
hostname = host_rewrite_;
} else if (!host_rewrite_header_.get().empty()) {
if (const auto header = headers.get(host_rewrite_header_); !header.empty()) {
hostname = header[0]->value().getStringView();
}
} else if (host_rewrite_path_regex_) {
absl::string_view path = headers.getPathValue();
buffer = host_rewrite_path_regex_->replaceAll(Http::PathUtil::removeQueryAndFragment(path),
host_rewrite_path_regex_substitution_);
hostname = buffer;
} else if (host_rewrite_formatter_) {
buffer = host_rewrite_formatter_->format(context, stream_info);
hostname = buffer;
}
if (hostname.empty()) {
return;
}
Http::Utility::updateAuthority(headers, hostname, append_xfh_, keep_old_host);
}
void RouteEntryImplBase::finalizeRequestHeaders(Http::RequestHeaderMap& headers,
const Formatter::Context& context,
const StreamInfo::StreamInfo& stream_info,
bool keep_original_host_or_path) const {
// Apply header transformations configured via request_headers_to_add first.
// This is important because host/path rewriting may depend on headers added here.
for (const HeaderParser* header_parser : getRequestHeaderParsers(
/*specificity_ascend=*/vhost_->globalRouteConfig().mostSpecificHeaderMutationsWins())) {
// Later evaluated header parser wins.
header_parser->evaluateHeaders(headers, context, stream_info);
}
// Restore the port if this was a CONNECT request.
// Note this will restore the port for HTTP/2 CONNECT-upgrades as well as as HTTP/1.1 style
// CONNECT requests.
if (Http::HeaderUtility::getPortStart(headers.getHostValue()) == absl::string_view::npos) {
if (auto typed_state = stream_info.filterState().getDataReadOnly<OriginalConnectPort>(