forked from envoyproxy/envoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol_integration_test.cc
1824 lines (1567 loc) · 78.8 KB
/
protocol_integration_test.cc
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 <functional>
#include <list>
#include <memory>
#include <regex>
#include <string>
#include <vector>
#include "envoy/buffer/buffer.h"
#include "envoy/config/bootstrap/v3/bootstrap.pb.h"
#include "envoy/config/route/v3/route_components.pb.h"
#include "envoy/event/dispatcher.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "envoy/http/header_map.h"
#include "envoy/registry/registry.h"
#include "common/api/api_impl.h"
#include "common/buffer/buffer_impl.h"
#include "common/common/fmt.h"
#include "common/common/thread_annotations.h"
#include "common/http/headers.h"
#include "common/http/utility.h"
#include "common/network/utility.h"
#include "common/protobuf/utility.h"
#include "common/runtime/runtime_impl.h"
#include "common/upstream/upstream_impl.h"
#include "test/common/upstream/utility.h"
#include "test/integration/autonomous_upstream.h"
#include "test/integration/http_integration.h"
#include "test/integration/http_protocol_integration.h"
#include "test/integration/test_host_predicate_config.h"
#include "test/integration/utility.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/registry.h"
#include "absl/time/time.h"
#include "gtest/gtest.h"
using testing::HasSubstr;
using testing::Not;
namespace Envoy {
void setDoNotValidateRouteConfig(
envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) {
auto* route_config = hcm.mutable_route_config();
route_config->mutable_validate_clusters()->set_value(false);
};
// Tests for DownstreamProtocolIntegrationTest will be run with all protocols
// (H1/H2 downstream) but only H1 upstreams.
//
// This is useful for things which will likely not differ based on upstream
// behavior, for example "how does Envoy handle duplicate content lengths from
// downstream"?
class DownstreamProtocolIntegrationTest : public HttpProtocolIntegrationTest {
protected:
template <class T> void changeHeadersForStopAllTests(T& headers, bool set_buffer_limit) {
headers.addCopy("content_size", std::to_string(count_ * size_));
headers.addCopy("added_size", std::to_string(added_decoded_data_size_));
headers.addCopy("is_first_trigger", "value");
if (set_buffer_limit) {
headers.addCopy("buffer_limit", std::to_string(buffer_limit_));
}
}
void verifyUpStreamRequestAfterStopAllFilter() {
if (downstreamProtocol() == Http::CodecClient::Type::HTTP2) {
// decode-headers-return-stop-all-filter calls addDecodedData in decodeData and
// decodeTrailers. 2 decoded data were added.
EXPECT_EQ(count_ * size_ + added_decoded_data_size_ * 2, upstream_request_->bodyLength());
} else {
EXPECT_EQ(count_ * size_ + added_decoded_data_size_ * 1, upstream_request_->bodyLength());
}
EXPECT_EQ(true, upstream_request_->complete());
}
const int count_ = 70;
const int size_ = 1000;
const int added_decoded_data_size_ = 1;
const int buffer_limit_ = 100;
};
// Tests for ProtocolIntegrationTest will be run with the full mesh of H1/H2
// downstream and H1/H2 upstreams.
using ProtocolIntegrationTest = HttpProtocolIntegrationTest;
TEST_P(ProtocolIntegrationTest, TrailerSupportHttp1) {
config_helper_.addConfigModifier(setEnableDownstreamTrailersHttp1());
config_helper_.addConfigModifier(setEnableUpstreamTrailersHttp1());
testTrailers(10, 20, true, true);
}
TEST_P(ProtocolIntegrationTest, ShutdownWithActiveConnPoolConnections) {
auto response = makeHeaderOnlyRequest(nullptr, 0);
// Shut down the server with active connection pool connections.
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
test_server_.reset();
checkSimpleRequestSuccess(0U, 0U, response.get());
}
// Change the default route to be restrictive, and send a request to an alternate route.
TEST_P(ProtocolIntegrationTest, RouterNotFound) { testRouterNotFound(); }
TEST_P(ProtocolIntegrationTest, RouterVirtualClusters) { testRouterVirtualClusters(); }
// Change the default route to be restrictive, and send a POST to an alternate route.
TEST_P(DownstreamProtocolIntegrationTest, RouterNotFoundBodyNoBuffer) {
testRouterNotFoundWithBody();
}
// Add a route that uses unknown cluster (expect 404 Not Found).
TEST_P(DownstreamProtocolIntegrationTest, RouterClusterNotFound404) {
config_helper_.addConfigModifier(&setDoNotValidateRouteConfig);
auto host = config_helper_.createVirtualHost("foo.com", "/unknown", "unknown_cluster");
host.mutable_routes(0)->mutable_route()->set_cluster_not_found_response_code(
envoy::config::route::v3::RouteAction::NOT_FOUND);
config_helper_.addVirtualHost(host);
initialize();
BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest(
lookupPort("http"), "GET", "/unknown", "", downstream_protocol_, version_, "foo.com");
ASSERT_TRUE(response->complete());
EXPECT_EQ("404", response->headers().Status()->value().getStringView());
}
// Add a route that uses unknown cluster (expect 503 Service Unavailable).
TEST_P(DownstreamProtocolIntegrationTest, RouterClusterNotFound503) {
config_helper_.addConfigModifier(&setDoNotValidateRouteConfig);
auto host = config_helper_.createVirtualHost("foo.com", "/unknown", "unknown_cluster");
host.mutable_routes(0)->mutable_route()->set_cluster_not_found_response_code(
envoy::config::route::v3::RouteAction::SERVICE_UNAVAILABLE);
config_helper_.addVirtualHost(host);
initialize();
BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest(
lookupPort("http"), "GET", "/unknown", "", downstream_protocol_, version_, "foo.com");
ASSERT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().Status()->value().getStringView());
}
// Add a route which redirects HTTP to HTTPS, and verify Envoy sends a 301
TEST_P(ProtocolIntegrationTest, RouterRedirect) {
auto host = config_helper_.createVirtualHost("www.redirect.com", "/");
host.set_require_tls(envoy::config::route::v3::VirtualHost::ALL);
config_helper_.addVirtualHost(host);
initialize();
BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest(
lookupPort("http"), "GET", "/foo", "", downstream_protocol_, version_, "www.redirect.com");
ASSERT_TRUE(response->complete());
EXPECT_EQ("301", response->headers().Status()->value().getStringView());
EXPECT_EQ("https://www.redirect.com/foo",
response->headers().get(Http::Headers::get().Location)->value().getStringView());
}
// Add a health check filter and verify correct computation of health based on upstream status.
TEST_P(ProtocolIntegrationTest, ComputedHealthCheck) {
config_helper_.addFilter(R"EOF(
name: health_check
typed_config:
"@type": type.googleapis.com/envoy.config.filter.http.health_check.v2.HealthCheck
pass_through_mode: false
cluster_min_healthy_percentages:
example_cluster_name: { value: 75 }
)EOF");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{
{":method", "GET"}, {":path", "/healthcheck"}, {":scheme", "http"}, {":authority", "host"}});
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().Status()->value().getStringView());
}
// Add a health check filter and verify correct computation of health based on upstream status.
TEST_P(ProtocolIntegrationTest, ModifyBuffer) {
config_helper_.addFilter(R"EOF(
name: health_check
typed_config:
"@type": type.googleapis.com/envoy.config.filter.http.health_check.v2.HealthCheck
pass_through_mode: false
cluster_min_healthy_percentages:
example_cluster_name: { value: 75 }
)EOF");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{
{":method", "GET"}, {":path", "/healthcheck"}, {":scheme", "http"}, {":authority", "host"}});
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().Status()->value().getStringView());
}
TEST_P(ProtocolIntegrationTest, AddEncodedTrailers) {
config_helper_.addFilter(R"EOF(
name: add-trailers-filter
typed_config:
"@type": type.googleapis.com/google.protobuf.Empty
)EOF");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(default_request_headers_, 128);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);
upstream_request_->encodeData(128, true);
response->waitForEndStream();
if (upstreamProtocol() == FakeHttpConnection::Type::HTTP2) {
EXPECT_EQ("decode", upstream_request_->trailers()
->get(Http::LowerCaseString("grpc-message"))
->value()
.getStringView());
}
EXPECT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().Status()->value().getStringView());
if (downstream_protocol_ == Http::CodecClient::Type::HTTP2) {
EXPECT_EQ("encode", response->trailers()->GrpcMessage()->value().getStringView());
}
}
// Add a health check filter and verify correct behavior when draining.
TEST_P(ProtocolIntegrationTest, DrainClose) {
config_helper_.addFilter(ConfigHelper::defaultHealthCheckFilter());
initialize();
test_server_->drainManager().draining_ = true;
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_);
response->waitForEndStream();
codec_client_->waitForDisconnect();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
if (downstream_protocol_ == Http::CodecClient::Type::HTTP2) {
EXPECT_TRUE(codec_client_->sawGoAway());
}
test_server_->drainManager().draining_ = false;
}
// Regression test for https://github.com/envoyproxy/envoy/issues/9873
TEST_P(ProtocolIntegrationTest, ResponseWithHostHeader) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestRequestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"}});
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(
Http::TestResponseHeaderMapImpl{{":status", "200"}, {"host", "host"}}, true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_EQ("host",
response->headers().get(Http::LowerCaseString("host"))->value().getStringView());
}
// Regression test for https://github.com/envoyproxy/envoy/issues/10270
TEST_P(ProtocolIntegrationTest, LongHeaderValueWithSpaces) {
// Header with at least 20kb of spaces surrounded by non-whitespace characters to ensure that
// dispatching is split across 2 dispatch calls. This threshold comes from Envoy preferring 16KB
// reads, which the buffer rounds up to about 20KB when allocating slices in
// Buffer::OwnedImpl::reserve().
const std::string long_header_value_with_inner_lws = "v" + std::string(32 * 1024, ' ') + "v";
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestRequestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"longrequestvalue", long_header_value_with_inner_lws}});
waitForNextUpstreamRequest();
EXPECT_EQ(long_header_value_with_inner_lws, upstream_request_->headers()
.get(Http::LowerCaseString("longrequestvalue"))
->value()
.getStringView());
upstream_request_->encodeHeaders(
Http::TestResponseHeaderMapImpl{{":status", "200"},
{"host", "host"},
{"longresponsevalue", long_header_value_with_inner_lws}},
true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_EQ("host",
response->headers().get(Http::LowerCaseString("host"))->value().getStringView());
EXPECT_EQ(
long_header_value_with_inner_lws,
response->headers().get(Http::LowerCaseString("longresponsevalue"))->value().getStringView());
}
TEST_P(ProtocolIntegrationTest, Retry) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}},
1024);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);
if (fake_upstreams_[0]->httpType() == FakeHttpConnection::Type::HTTP1) {
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
} else {
ASSERT_TRUE(upstream_request_->waitForReset());
}
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(default_response_headers_, false);
upstream_request_->encodeData(512, true);
response->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(1024U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_EQ(512U, response->body().size());
}
TEST_P(ProtocolIntegrationTest, RetryStreaming) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}});
auto& encoder = encoder_decoder.first;
auto& response = encoder_decoder.second;
// Send some data, but not the entire body.
std::string data(1024, 'a');
Buffer::OwnedImpl send1(data);
encoder.encodeData(send1, false);
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
// Send back an upstream failure.
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);
if (fake_upstreams_[0]->httpType() == FakeHttpConnection::Type::HTTP1) {
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
} else {
ASSERT_TRUE(upstream_request_->waitForReset());
}
// Wait for a retry. Ensure all data, both before and after the retry, is received.
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
// Finish the request.
std::string data2(512, 'b');
Buffer::OwnedImpl send2(data2);
encoder.encodeData(send2, true);
std::string combined_request_data = data + data2;
ASSERT_TRUE(upstream_request_->waitForData(*dispatcher_, combined_request_data));
upstream_request_->encodeHeaders(default_response_headers_, false);
upstream_request_->encodeData(512, true);
response->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(combined_request_data.size(), upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_EQ(512U, response->body().size());
}
TEST_P(ProtocolIntegrationTest, RetryStreamingCancelDueToBufferOverflow) {
config_helper_.addConfigModifier(
[](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) {
auto* route = hcm.mutable_route_config()->mutable_virtual_hosts(0)->mutable_routes(0);
route->mutable_per_request_buffer_limit_bytes()->set_value(1024);
route->mutable_route()
->mutable_retry_policy()
->mutable_retry_back_off()
->mutable_base_interval()
->MergeFrom(
ProtobufUtil::TimeUtil::MillisecondsToDuration(100000000)); // Effectively infinity.
});
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}});
auto& encoder = encoder_decoder.first;
auto& response = encoder_decoder.second;
// Send some data, but less than the buffer limit, and not end-stream
std::string data(64, 'a');
Buffer::OwnedImpl send1(data);
encoder.encodeData(send1, false);
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
// Send back an upstream failure.
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);
if (fake_upstreams_[0]->httpType() == FakeHttpConnection::Type::HTTP1) {
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
} else {
ASSERT_TRUE(upstream_request_->waitForReset());
}
// Overflow the request buffer limit. Because the retry base interval is infinity, no
// request will be in progress. This will cause the request to be aborted and an error
// to be returned to the client.
std::string data2(2048, 'b');
Buffer::OwnedImpl send2(data2);
encoder.encodeData(send2, false);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("507", response->headers().Status()->value().getStringView());
test_server_->waitForCounterEq("cluster.cluster_0.retry_or_shadow_abandoned", 1);
}
// Tests that the x-envoy-attempt-count header is properly set on the upstream request and the
// downstream response, and updated after the request is retried.
TEST_P(DownstreamProtocolIntegrationTest, RetryAttemptCountHeader) {
auto host = config_helper_.createVirtualHost("host", "/test_retry");
host.set_include_request_attempt_count(true);
host.set_include_attempt_count_in_response(true);
config_helper_.addVirtualHost(host);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test_retry"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}},
1024);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);
EXPECT_EQ(
atoi(std::string(upstream_request_->headers().EnvoyAttemptCount()->value().getStringView())
.c_str()),
1);
if (fake_upstreams_[0]->httpType() == FakeHttpConnection::Type::HTTP1) {
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
} else {
ASSERT_TRUE(upstream_request_->waitForReset());
}
waitForNextUpstreamRequest();
EXPECT_EQ(
atoi(std::string(upstream_request_->headers().EnvoyAttemptCount()->value().getStringView())
.c_str()),
2);
upstream_request_->encodeHeaders(default_response_headers_, false);
upstream_request_->encodeData(512, true);
response->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(1024U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_EQ(512U, response->body().size());
EXPECT_EQ(
2,
atoi(std::string(response->headers().EnvoyAttemptCount()->value().getStringView()).c_str()));
}
// Verifies that a retry priority can be configured and affect the host selected during retries.
// The retry priority will always target P1, which would otherwise never be hit due to P0 being
// healthy.
TEST_P(DownstreamProtocolIntegrationTest, RetryPriority) {
const Upstream::HealthyLoad healthy_priority_load({0u, 100u});
const Upstream::DegradedLoad degraded_priority_load({0u, 100u});
NiceMock<Upstream::MockRetryPriority> retry_priority(healthy_priority_load,
degraded_priority_load);
Upstream::MockRetryPriorityFactory factory(retry_priority);
Registry::InjectFactory<Upstream::RetryPriorityFactory> inject_factory(factory);
// Add route with custom retry policy
auto host = config_helper_.createVirtualHost("host", "/test_retry");
host.set_include_request_attempt_count(true);
auto retry_policy = host.mutable_routes(0)->mutable_route()->mutable_retry_policy();
retry_policy->mutable_retry_priority()->set_name(factory.name());
config_helper_.addVirtualHost(host);
// We want to work with a cluster with two hosts.
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
auto* cluster = bootstrap.mutable_static_resources()->mutable_clusters(0);
auto* load_assignment = cluster->mutable_load_assignment();
load_assignment->clear_endpoints();
for (int i = 0; i < 2; ++i) {
auto locality = load_assignment->add_endpoints();
locality->set_priority(i);
locality->mutable_locality()->set_region("region");
locality->mutable_locality()->set_zone("zone");
locality->mutable_locality()->set_sub_zone("sub_zone" + std::to_string(i));
locality->add_lb_endpoints()->mutable_endpoint()->MergeFrom(
ConfigHelper::buildEndpoint(Network::Test::getLoopbackAddressString(version_)));
}
});
fake_upstreams_count_ = 2;
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test_retry"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}},
1024);
// Note how we're expecting each upstream request to hit the same upstream.
waitForNextUpstreamRequest(0);
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);
if (fake_upstreams_[0]->httpType() == FakeHttpConnection::Type::HTTP1) {
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
ASSERT_TRUE(fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
} else {
ASSERT_TRUE(upstream_request_->waitForReset());
}
waitForNextUpstreamRequest(1);
upstream_request_->encodeHeaders(default_response_headers_, false);
upstream_request_->encodeData(512, true);
response->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(1024U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_EQ(512U, response->body().size());
}
//
// Verifies that a retry host filter can be configured and affect the host selected during retries.
// The predicate will keep track of the first host attempted, and attempt to route all requests to
// the same host. With a total of two upstream hosts, this should result in us continuously sending
// requests to the same host.
TEST_P(DownstreamProtocolIntegrationTest, RetryHostPredicateFilter) {
TestHostPredicateFactory predicate_factory;
Registry::InjectFactory<Upstream::RetryHostPredicateFactory> inject_factory(predicate_factory);
// Add route with custom retry policy
auto host = config_helper_.createVirtualHost("host", "/test_retry");
host.set_include_request_attempt_count(true);
auto retry_policy = host.mutable_routes(0)->mutable_route()->mutable_retry_policy();
retry_policy->add_retry_host_predicate()->set_name(predicate_factory.name());
config_helper_.addVirtualHost(host);
// We want to work with a cluster with two hosts.
config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
bootstrap.mutable_static_resources()
->mutable_clusters(0)
->mutable_load_assignment()
->mutable_endpoints(0)
->add_lb_endpoints()
->mutable_endpoint()
->MergeFrom(ConfigHelper::buildEndpoint(Network::Test::getLoopbackAddressString(version_)));
});
fake_upstreams_count_ = 2;
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test_retry"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}},
1024);
// Note how we're expecting each upstream request to hit the same upstream.
auto upstream_idx = waitForNextUpstreamRequest({0, 1});
ASSERT_TRUE(upstream_idx.has_value());
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, false);
if (fake_upstreams_[*upstream_idx]->httpType() == FakeHttpConnection::Type::HTTP1) {
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
ASSERT_TRUE(fake_upstreams_[*upstream_idx]->waitForHttpConnection(*dispatcher_,
fake_upstream_connection_));
} else {
ASSERT_TRUE(upstream_request_->waitForReset());
}
waitForNextUpstreamRequest(*upstream_idx);
upstream_request_->encodeHeaders(default_response_headers_, false);
upstream_request_->encodeData(512, true);
response->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(1024U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_EQ(512U, response->body().size());
}
// Very similar set-up to testRetry but with a 16k request the request will not
// be buffered and the 503 will be returned to the user.
TEST_P(ProtocolIntegrationTest, RetryHittingBufferLimit) {
config_helper_.setBufferLimits(1024, 1024); // Set buffer limits upstream and downstream.
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}},
1024 * 65);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, true);
response->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(66560U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().Status()->value().getStringView());
}
// Very similar set-up to RetryHittingBufferLimits but using the route specific cap.
TEST_P(ProtocolIntegrationTest, RetryHittingRouteLimits) {
auto host = config_helper_.createVirtualHost("nobody.com", "/");
host.mutable_per_request_buffer_limit_bytes()->set_value(0);
config_helper_.addVirtualHost(host);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/"},
{":scheme", "http"},
{":authority", "nobody.com"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}},
1);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "503"}}, true);
response->waitForEndStream();
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(1U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().Status()->value().getStringView());
}
// Test hitting the decoder buffer filter with too many request bytes to buffer. Ensure the
// connection manager sends a 413.
TEST_P(DownstreamProtocolIntegrationTest, HittingDecoderFilterLimit) {
config_helper_.addFilter("{ name: encoder-decoder-buffer-filter, typed_config: { \"@type\": "
"type.googleapis.com/google.protobuf.Empty } }");
config_helper_.setBufferLimits(1024, 1024);
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
// Envoy will likely connect and proxy some unspecified amount of data before
// hitting the buffer limit and disconnecting. Ignore this if it happens.
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/dynamo/url"},
{":scheme", "http"},
{":authority", "host"},
{"x-forwarded-for", "10.0.0.1"},
{"x-envoy-retry-on", "5xx"}},
1024 * 65);
response->waitForEndStream();
// With HTTP/1 there's a possible race where if the connection backs up early,
// the 413-and-connection-close may be sent while the body is still being
// sent, resulting in a write error and the connection being closed before the
// response is read.
if (downstream_protocol_ == Http::CodecClient::Type::HTTP2) {
ASSERT_TRUE(response->complete());
}
if (response->complete()) {
EXPECT_EQ("413", response->headers().Status()->value().getStringView());
}
}
// Test hitting the encoder buffer filter with too many response bytes to buffer. Given the request
// headers are sent on early, the stream/connection will be reset.
TEST_P(ProtocolIntegrationTest, HittingEncoderFilterLimit) {
useAccessLog();
config_helper_.addFilter("{ name: encoder-decoder-buffer-filter, typed_config: { \"@type\": "
"type.googleapis.com/google.protobuf.Empty } }");
config_helper_.setBufferLimits(1024, 1024);
initialize();
// Send the request.
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder = codec_client_->startRequest(default_request_headers_);
auto downstream_request = &encoder_decoder.first;
auto response = std::move(encoder_decoder.second);
Buffer::OwnedImpl data("HTTP body content goes here");
codec_client_->sendData(*downstream_request, data, true);
waitForNextUpstreamRequest();
// Send the response headers.
upstream_request_->encodeHeaders(default_response_headers_, false);
// Now send an overly large response body. At some point, too much data will
// be buffered, the stream will be reset, and the connection will disconnect.
fake_upstreams_[0]->set_allow_unexpected_disconnects(true);
upstream_request_->encodeData(1024 * 65, false);
if (upstreamProtocol() == FakeHttpConnection::Type::HTTP1) {
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
} else {
ASSERT_TRUE(upstream_request_->waitForReset());
ASSERT_TRUE(fake_upstream_connection_->close());
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
}
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("500", response->headers().Status()->value().getStringView());
// Regression test https://github.com/envoyproxy/envoy/issues/9881 by making
// sure this path does standard HCM header transformations.
EXPECT_TRUE(response->headers().Date() != nullptr);
EXPECT_THAT(waitForAccessLog(access_log_name_), HasSubstr("500"));
test_server_->waitForCounterEq("http.config_test.downstream_rq_5xx", 1);
}
TEST_P(ProtocolIntegrationTest, EnvoyHandling100Continue) { testEnvoyHandling100Continue(); }
TEST_P(ProtocolIntegrationTest, EnvoyHandlingDuplicate100Continue) {
testEnvoyHandling100Continue(true);
}
TEST_P(ProtocolIntegrationTest, EnvoyProxyingEarly100Continue) {
testEnvoyProxying100Continue(true);
}
TEST_P(ProtocolIntegrationTest, EnvoyProxyingLate100Continue) {
testEnvoyProxying100Continue(false);
}
TEST_P(ProtocolIntegrationTest, TwoRequests) { testTwoRequests(); }
TEST_P(ProtocolIntegrationTest, TwoRequestsWithForcedBackup) { testTwoRequests(true); }
// Verify that headers with underscores in their names are dropped from client requests
// but remain in upstream responses.
TEST_P(ProtocolIntegrationTest, HeadersWithUnderscoresDropped) {
config_helper_.addConfigModifier(
[&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) -> void {
hcm.mutable_common_http_protocol_options()->set_headers_with_underscores_action(
envoy::config::core::v3::HttpProtocolOptions::DROP_HEADER);
});
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestRequestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"foo_bar", "baz"}});
waitForNextUpstreamRequest();
EXPECT_THAT(upstream_request_->headers(), Not(HeaderHasValueRef("foo_bar", "baz")));
upstream_request_->encodeHeaders(
Http::TestResponseHeaderMapImpl{{":status", "200"}, {"bar_baz", "fooz"}}, true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_THAT(response->headers(), HeaderHasValueRef("bar_baz", "fooz"));
}
// Verify that by default headers with underscores in their names remain in both requests and
// responses when allowed in configuration.
TEST_P(ProtocolIntegrationTest, HeadersWithUnderscoresRemainByDefault) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestRequestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"foo_bar", "baz"}});
waitForNextUpstreamRequest();
EXPECT_THAT(upstream_request_->headers(), HeaderHasValueRef("foo_bar", "baz"));
upstream_request_->encodeHeaders(
Http::TestResponseHeaderMapImpl{{":status", "200"}, {"bar_baz", "fooz"}}, true);
response->waitForEndStream();
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
EXPECT_THAT(response->headers(), HeaderHasValueRef("bar_baz", "fooz"));
}
// Verify that request with headers containing underscores is rejected when configured.
TEST_P(ProtocolIntegrationTest, HeadersWithUnderscoresCauseRequestRejectedByDefault) {
config_helper_.addConfigModifier(
[&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) -> void {
hcm.mutable_common_http_protocol_options()->set_headers_with_underscores_action(
envoy::config::core::v3::HttpProtocolOptions::REJECT_REQUEST);
});
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestRequestHeaderMapImpl{{":method", "GET"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"foo_bar", "baz"}});
if (downstream_protocol_ == Http::CodecClient::Type::HTTP1) {
codec_client_->waitForDisconnect();
ASSERT_TRUE(response->complete());
EXPECT_EQ("400", response->headers().Status()->value().getStringView());
} else {
response->waitForReset();
codec_client_->close();
ASSERT_TRUE(response->reset());
EXPECT_EQ(Http::StreamResetReason::RemoteReset, response->reset_reason());
}
}
TEST_P(DownstreamProtocolIntegrationTest, ValidZeroLengthContent) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
Http::TestRequestHeaderMapImpl request_headers{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"content-length", "0"}};
auto response = sendRequestAndWaitForResponse(request_headers, 0, default_response_headers_, 0);
ASSERT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
}
// Validate that lots of tiny cookies doesn't cause a DoS (single cookie header).
TEST_P(DownstreamProtocolIntegrationTest, LargeCookieParsingConcatenated) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
Http::TestRequestHeaderMapImpl request_headers{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"content-length", "0"}};
std::vector<std::string> cookie_pieces;
cookie_pieces.reserve(7000);
for (int i = 0; i < 7000; i++) {
cookie_pieces.push_back(fmt::sprintf("a%x=b", i));
}
request_headers.addCopy("cookie", absl::StrJoin(cookie_pieces, "; "));
auto response = sendRequestAndWaitForResponse(request_headers, 0, default_response_headers_, 0);
ASSERT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
}
// Validate that lots of tiny cookies doesn't cause a DoS (many cookie headers).
TEST_P(DownstreamProtocolIntegrationTest, LargeCookieParsingMany) {
// Set header count limit to 2010.
uint32_t max_count = 2010;
config_helper_.addConfigModifier(
[&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) -> void {
hcm.mutable_common_http_protocol_options()->mutable_max_headers_count()->set_value(
max_count);
});
max_request_headers_count_ = max_count;
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
Http::TestRequestHeaderMapImpl request_headers{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "host"},
{"content-length", "0"}};
for (int i = 0; i < 2000; i++) {
request_headers.addCopy("cookie", fmt::sprintf("a%x=b", i));
}
auto response = sendRequestAndWaitForResponse(request_headers, 0, default_response_headers_, 0);
ASSERT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().Status()->value().getStringView());
}
TEST_P(DownstreamProtocolIntegrationTest, InvalidContentLength) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":authority", "host"},
{"content-length", "-1"}});
auto response = std::move(encoder_decoder.second);
codec_client_->waitForDisconnect();
if (downstream_protocol_ == Http::CodecClient::Type::HTTP1) {
ASSERT_TRUE(response->complete());
EXPECT_EQ("400", response->headers().Status()->value().getStringView());
} else {
ASSERT_TRUE(response->reset());
EXPECT_EQ(Http::StreamResetReason::ConnectionTermination, response->reset_reason());
}
}
// TODO(PiotrSikora): move this HTTP/2 only variant to http2_integration_test.cc.
TEST_P(DownstreamProtocolIntegrationTest, InvalidContentLengthAllowed) {
config_helper_.addConfigModifier(
[](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) -> void {
hcm.mutable_http2_protocol_options()->set_stream_error_on_invalid_http_messaging(true);
});
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":authority", "host"},
{"content-length", "-1"}});
auto response = std::move(encoder_decoder.second);
if (downstream_protocol_ == Http::CodecClient::Type::HTTP1) {
codec_client_->waitForDisconnect();
} else {
response->waitForReset();
codec_client_->close();
}
if (downstream_protocol_ == Http::CodecClient::Type::HTTP1) {
ASSERT_TRUE(response->complete());
EXPECT_EQ("400", response->headers().Status()->value().getStringView());
} else {
ASSERT_TRUE(response->reset());
EXPECT_EQ(Http::StreamResetReason::RemoteReset, response->reset_reason());
}
}
TEST_P(DownstreamProtocolIntegrationTest, MultipleContentLengths) {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder =
codec_client_->startRequest(Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":authority", "host"},
{"content-length", "3,2"}});
auto response = std::move(encoder_decoder.second);
codec_client_->waitForDisconnect();