forked from envoyproxy/envoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_integration.cc
1755 lines (1539 loc) · 77.1 KB
/
http_integration.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 "test/integration/http_integration.h"
#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/event/dispatcher.h"
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"
#include "envoy/extensions/transport_sockets/quic/v3/quic_transport.pb.h"
#include "envoy/http/header_map.h"
#include "envoy/network/address.h"
#include "envoy/registry/registry.h"
#include "source/common/api/api_impl.h"
#include "source/common/buffer/buffer_impl.h"
#include "source/common/common/fmt.h"
#include "source/common/common/thread_annotations.h"
#include "source/common/http/headers.h"
#include "source/common/network/socket_option_impl.h"
#include "source/common/network/utility.h"
#include "source/common/protobuf/utility.h"
#include "source/common/runtime/runtime_impl.h"
#include "source/common/upstream/upstream_impl.h"
#ifdef ENVOY_ENABLE_QUIC
#include "source/common/quic/client_connection_factory_impl.h"
#include "source/common/quic/quic_transport_socket_factory.h"
#endif
#include "source/extensions/transport_sockets/tls/context_config_impl.h"
#include "source/extensions/transport_sockets/tls/context_impl.h"
#include "source/extensions/transport_sockets/tls/ssl_socket.h"
#include "test/common/upstream/utility.h"
#include "test/integration/autonomous_upstream.h"
#include "test/integration/ssl_utility.h"
#include "test/integration/test_host_predicate_config.h"
#include "test/integration/utility.h"
#include "test/mocks/upstream/cluster_info.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 "base_integration_test.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace {
using testing::HasSubstr;
envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::CodecType
typeToCodecType(Http::CodecType type) {
switch (type) {
case Http::CodecType::HTTP1:
return envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
HTTP1;
case Http::CodecType::HTTP2:
return envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
HTTP2;
case Http::CodecType::HTTP3:
return envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
HTTP3;
default:
RELEASE_ASSERT(0, "");
}
}
} // namespace
IntegrationCodecClient::IntegrationCodecClient(
Event::Dispatcher& dispatcher, Random::RandomGenerator& random,
Network::ClientConnectionPtr&& conn, Upstream::HostDescriptionConstSharedPtr host_description,
Http::CodecType type)
: IntegrationCodecClient(dispatcher, random, std::move(conn), std::move(host_description), type,
true) {}
IntegrationCodecClient::IntegrationCodecClient(
Event::Dispatcher& dispatcher, Random::RandomGenerator& random,
Network::ClientConnectionPtr&& conn, Upstream::HostDescriptionConstSharedPtr host_description,
Http::CodecType type, bool wait_till_connected)
: CodecClientProd(type, std::move(conn), host_description, dispatcher, random, nullptr),
dispatcher_(dispatcher), callbacks_(*this, wait_till_connected), codec_callbacks_(*this),
codec_client_callbacks_(*this) {
connection_->addConnectionCallbacks(callbacks_);
setCodecConnectionCallbacks(codec_callbacks_);
setCodecClientCallbacks(codec_client_callbacks_);
if (wait_till_connected) {
dispatcher.run(Event::Dispatcher::RunType::Block);
}
}
void IntegrationCodecClient::flushWrite() {
connection_->dispatcher().run(Event::Dispatcher::RunType::NonBlock);
// NOTE: We should run blocking until all the body data is flushed.
}
IntegrationStreamDecoderPtr
IntegrationCodecClient::makeHeaderOnlyRequest(const Http::RequestHeaderMap& headers) {
auto response = std::make_unique<IntegrationStreamDecoder>(dispatcher_);
Http::RequestEncoder& encoder = newStream(*response);
encoder.getStream().addCallbacks(*response);
encoder.encodeHeaders(headers, true).IgnoreError();
flushWrite();
return response;
}
IntegrationStreamDecoderPtr
IntegrationCodecClient::makeRequestWithBody(const Http::RequestHeaderMap& headers,
uint64_t body_size, bool end_stream) {
return makeRequestWithBody(headers, std::string(body_size, 'a'), end_stream);
}
IntegrationStreamDecoderPtr
IntegrationCodecClient::makeRequestWithBody(const Http::RequestHeaderMap& headers,
const std::string& body, bool end_stream) {
auto response = std::make_unique<IntegrationStreamDecoder>(dispatcher_);
Http::RequestEncoder& encoder = newStream(*response);
encoder.getStream().addCallbacks(*response);
encoder.encodeHeaders(headers, false).IgnoreError();
Buffer::OwnedImpl data(body);
encoder.encodeData(data, end_stream);
flushWrite();
return response;
}
void IntegrationCodecClient::sendData(Http::RequestEncoder& encoder, absl::string_view data,
bool end_stream) {
Buffer::OwnedImpl buffer_data(data.data(), data.size());
encoder.encodeData(buffer_data, end_stream);
flushWrite();
}
void IntegrationCodecClient::sendData(Http::RequestEncoder& encoder, Buffer::Instance& data,
bool end_stream) {
encoder.encodeData(data, end_stream);
flushWrite();
}
void IntegrationCodecClient::sendData(Http::RequestEncoder& encoder, uint64_t size,
bool end_stream) {
Buffer::OwnedImpl data(std::string(size, 'a'));
sendData(encoder, data, end_stream);
}
void IntegrationCodecClient::sendTrailers(Http::RequestEncoder& encoder,
const Http::RequestTrailerMap& trailers) {
encoder.encodeTrailers(trailers);
flushWrite();
}
void IntegrationCodecClient::sendReset(Http::RequestEncoder& encoder) {
encoder.getStream().resetStream(Http::StreamResetReason::LocalReset);
flushWrite();
}
void IntegrationCodecClient::sendMetadata(Http::RequestEncoder& encoder,
Http::MetadataMap metadata_map) {
Http::MetadataMapPtr metadata_map_ptr = std::make_unique<Http::MetadataMap>(metadata_map);
Http::MetadataMapVector metadata_map_vector;
metadata_map_vector.push_back(std::move(metadata_map_ptr));
encoder.encodeMetadata(metadata_map_vector);
flushWrite();
}
std::pair<Http::RequestEncoder&, IntegrationStreamDecoderPtr>
IntegrationCodecClient::startRequest(const Http::RequestHeaderMap& headers,
bool header_only_request) {
auto response = std::make_unique<IntegrationStreamDecoder>(dispatcher_);
Http::RequestEncoder& encoder = newStream(*response);
encoder.getStream().addCallbacks(*response);
encoder.encodeHeaders(headers, /*end_stream=*/header_only_request).IgnoreError();
flushWrite();
return {encoder, std::move(response)};
}
AssertionResult IntegrationCodecClient::waitForDisconnect(std::chrono::milliseconds time_to_wait) {
if (disconnected_) {
return AssertionSuccess();
}
Event::TimerPtr wait_timer;
bool wait_timer_triggered = false;
if (time_to_wait.count()) {
wait_timer = connection_->dispatcher().createTimer([this, &wait_timer_triggered] {
connection_->dispatcher().exit();
wait_timer_triggered = true;
});
wait_timer->enableTimer(time_to_wait);
}
connection_->dispatcher().run(Event::Dispatcher::RunType::Block);
// Disable the timer if it was created. This call is harmless if the timer already triggered.
if (wait_timer) {
wait_timer->disableTimer();
}
if (wait_timer_triggered && !disconnected_) {
if (time_to_wait == TestUtility::DefaultTimeout) {
ADD_FAILURE() << "Please don't waitForDisconnect with a 5s timeout if failure is expected\n";
}
return AssertionFailure() << "Timed out waiting for disconnect";
}
EXPECT_TRUE(disconnected_);
return AssertionSuccess();
}
void IntegrationCodecClient::ConnectionCallbacks::onEvent(Network::ConnectionEvent event) {
parent_.last_connection_event_ = event;
if (event == Network::ConnectionEvent::Connected) {
parent_.connected_ = true;
if (block_till_connected_) {
parent_.connection_->dispatcher().exit();
}
} else if (event == Network::ConnectionEvent::RemoteClose) {
parent_.disconnected_ = true;
parent_.connection_->dispatcher().exit();
} else {
if (parent_.type() == Http::CodecType::HTTP3 && !parent_.connected_ && block_till_connected_) {
// Before handshake gets established, any connection failure should exit the loop. I.e. a QUIC
// connection may fail of INVALID_VERSION if both this client doesn't support any of the
// versions the server advertised before handshake established. In this case the connection is
// closed locally and this is in a blocking event loop.
parent_.connection_->dispatcher().exit();
}
parent_.disconnected_ = true;
}
}
Network::ClientConnectionPtr HttpIntegrationTest::makeClientConnectionWithOptions(
uint32_t port, const Network::ConnectionSocket::OptionsSharedPtr& options) {
if (downstream_protocol_ <= Http::CodecType::HTTP2) {
return BaseIntegrationTest::makeClientConnectionWithOptions(port, options);
}
#ifdef ENVOY_ENABLE_QUIC
// Setting socket options is not supported for HTTP3.
Network::Address::InstanceConstSharedPtr server_addr = Network::Utility::resolveUrl(
fmt::format("udp://{}:{}", Network::Test::getLoopbackAddressUrlString(version_), port));
Network::Address::InstanceConstSharedPtr local_addr =
Network::Test::getCanonicalLoopbackAddress(version_);
auto& quic_transport_socket_factory_ref =
dynamic_cast<Quic::QuicClientTransportSocketFactory&>(*quic_transport_socket_factory_);
return Quic::createQuicNetworkConnection(
*quic_connection_persistent_info_, quic_transport_socket_factory_ref.getCryptoConfig(),
quic::QuicServerId(
quic_transport_socket_factory_ref.clientContextConfig()->serverNameIndication(),
static_cast<uint16_t>(port)),
*dispatcher_, server_addr, local_addr, quic_stat_names_, {}, *stats_store_.rootScope(),
options, nullptr, connection_id_generator_);
#else
ASSERT(false, "running a QUIC integration test without compiling QUIC");
return nullptr;
#endif
}
IntegrationCodecClientPtr HttpIntegrationTest::makeHttpConnection(uint32_t port) {
return makeHttpConnection(makeClientConnection(port));
}
IntegrationCodecClientPtr HttpIntegrationTest::makeRawHttpConnection(
Network::ClientConnectionPtr&& conn,
absl::optional<envoy::config::core::v3::Http2ProtocolOptions> http2_options) {
std::shared_ptr<Upstream::MockClusterInfo> cluster{new NiceMock<Upstream::MockClusterInfo>()};
cluster->max_response_headers_count_ = 200;
if (!http2_options.has_value()) {
http2_options = Http2::Utility::initializeAndValidateOptions(
envoy::config::core::v3::Http2ProtocolOptions());
http2_options.value().set_allow_connect(true);
http2_options.value().set_allow_metadata(true);
#ifdef ENVOY_ENABLE_QUIC
} else {
cluster->http3_options_ = ConfigHelper::http2ToHttp3ProtocolOptions(
http2_options.value(), quic::kStreamReceiveWindowLimit);
cluster->http3_options_.set_allow_extended_connect(true);
#endif
}
cluster->http2_options_ = http2_options.value();
cluster->http1_settings_.enable_trailers_ = true;
Upstream::HostDescriptionConstSharedPtr host_description{Upstream::makeTestHostDescription(
cluster, fmt::format("tcp://{}:80", Network::Test::getLoopbackAddressUrlString(version_)),
timeSystem())};
// This call may fail in QUICHE because of INVALID_VERSION. QUIC connection doesn't support
// in-connection version negotiation.
auto codec = std::make_unique<IntegrationCodecClient>(*dispatcher_, random_, std::move(conn),
host_description, downstream_protocol_);
if (downstream_protocol_ == Http::CodecType::HTTP3 && codec->disconnected()) {
// Connection may get closed during version negotiation or handshake.
// TODO(#8479) QUIC connection doesn't support in-connection version negotiationPropagate
// INVALID_VERSION error to caller and let caller to use server advertised version list to
// create a new connection with mutually supported version and make client codec again.
ENVOY_LOG(error, "Fail to connect to server with error: {}",
codec->connection()->transportFailureReason());
}
return codec;
}
IntegrationCodecClientPtr
HttpIntegrationTest::makeHttpConnection(Network::ClientConnectionPtr&& conn) {
auto codec = makeRawHttpConnection(std::move(conn), absl::nullopt);
EXPECT_TRUE(codec->connected()) << codec->connection()->transportFailureReason();
return codec;
}
HttpIntegrationTest::HttpIntegrationTest(Http::CodecType downstream_protocol,
Network::Address::IpVersion version,
const std::string& config)
: HttpIntegrationTest::HttpIntegrationTest(
downstream_protocol,
[version](int) {
return Network::Utility::parseInternetAddress(
Network::Test::getLoopbackAddressString(version), 0);
},
version, config) {}
HttpIntegrationTest::HttpIntegrationTest(Http::CodecType downstream_protocol,
const InstanceConstSharedPtrFn& upstream_address_fn,
Network::Address::IpVersion version,
const std::string& config)
: BaseIntegrationTest(upstream_address_fn, version, config),
downstream_protocol_(downstream_protocol), quic_stat_names_(stats_store_.symbolTable()) {
// Legacy integration tests expect the default listener to be named "http" for
// lookupPort calls.
config_helper_.renameListener("http");
config_helper_.setClientCodec(typeToCodecType(downstream_protocol_));
}
void HttpIntegrationTest::useAccessLog(
absl::string_view format,
std::vector<envoy::config::core::v3::TypedExtensionConfig> formatters) {
access_log_name_ = TestEnvironment::temporaryPath(TestUtility::uniqueFilename());
ASSERT_TRUE(config_helper_.setAccessLog(access_log_name_, format, formatters));
}
HttpIntegrationTest::~HttpIntegrationTest() { cleanupUpstreamAndDownstream(); }
void HttpIntegrationTest::initialize() {
if (downstream_protocol_ != Http::CodecType::HTTP3) {
return BaseIntegrationTest::initialize();
}
#ifdef ENVOY_ENABLE_QUIC
// Needs to be instantiated before base class calls initialize() which starts a QUIC listener
// according to the config.
quic_transport_socket_factory_ = IntegrationUtil::createQuicUpstreamTransportSocketFactory(
*api_, stats_store_, context_manager_, san_to_match_);
// Needed to config QUIC transport socket factory, and needs to be added before base class calls
// initialize().
config_helper_.addQuicDownstreamTransportSocketConfig(enable_quic_early_data_);
BaseIntegrationTest::initialize();
registerTestServerPorts({"http"}, test_server_);
// Needs to outlive all QUIC connections.
auto cluster = std::make_shared<NiceMock<Upstream::MockClusterInfo>>();
auto quic_connection_persistent_info =
Quic::createPersistentQuicInfoForCluster(*dispatcher_, *cluster);
// Config IETF QUIC flow control window.
quic_connection_persistent_info->quic_config_
.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend(
Http3::Utility::OptionsLimits::DEFAULT_INITIAL_STREAM_WINDOW_SIZE);
// Config Google QUIC flow control window.
quic_connection_persistent_info->quic_config_.SetInitialStreamFlowControlWindowToSend(
Http3::Utility::OptionsLimits::DEFAULT_INITIAL_STREAM_WINDOW_SIZE);
quic_connection_persistent_info_ = std::move(quic_connection_persistent_info);
#else
ASSERT(false, "running a QUIC integration test without compiling QUIC");
#endif
}
void HttpIntegrationTest::setupHttp1ImplOverrides(Http1ParserImpl http1_implementation) {
switch (http1_implementation) {
case Http1ParserImpl::HttpParser:
config_helper_.addRuntimeOverride("envoy.reloadable_features.http1_use_balsa_parser", "false");
break;
case Http1ParserImpl::BalsaParser:
config_helper_.addRuntimeOverride("envoy.reloadable_features.http1_use_balsa_parser", "true");
break;
}
}
void HttpIntegrationTest::setupHttp2ImplOverrides(Http2Impl http2_implementation) {
switch (http2_implementation) {
case Http2Impl::Nghttp2:
config_helper_.addRuntimeOverride("envoy.reloadable_features.http2_use_oghttp2", "false");
break;
case Http2Impl::Oghttp2:
config_helper_.addRuntimeOverride("envoy.reloadable_features.http2_use_oghttp2", "true");
break;
}
}
void HttpIntegrationTest::setDownstreamProtocol(Http::CodecType downstream_protocol) {
downstream_protocol_ = downstream_protocol;
config_helper_.setClientCodec(typeToCodecType(downstream_protocol_));
}
ConfigHelper::HttpModifierFunction HttpIntegrationTest::setEnableDownstreamTrailersHttp1() {
return [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) { hcm.mutable_http_protocol_options()->set_enable_trailers(true); };
}
ConfigHelper::ConfigModifierFunction HttpIntegrationTest::setEnableUpstreamTrailersHttp1() {
return [&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
RELEASE_ASSERT(bootstrap.mutable_static_resources()->clusters_size() == 1, "");
if (fake_upstreams_[0]->httpType() == Http::CodecType::HTTP1) {
ConfigHelper::HttpProtocolOptions protocol_options;
protocol_options.mutable_explicit_http_config()
->mutable_http_protocol_options()
->set_enable_trailers(true);
ConfigHelper::setProtocolOptions(*bootstrap.mutable_static_resources()->mutable_clusters(0),
protocol_options);
}
};
}
ConfigHelper::HttpModifierFunction HttpIntegrationTest::configureProxyStatus() {
return [](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) {
auto* psc = hcm.mutable_proxy_status_config();
psc->set_set_recommended_response_code(false);
};
}
IntegrationStreamDecoderPtr HttpIntegrationTest::sendRequestAndWaitForResponse(
const Http::TestRequestHeaderMapImpl& request_headers, uint32_t request_body_size,
const Http::TestResponseHeaderMapImpl& response_headers, uint32_t response_body_size,
const std::vector<uint64_t>& upstream_indices, std::chrono::milliseconds timeout) {
ASSERT(codec_client_ != nullptr);
// Send the request to Envoy.
IntegrationStreamDecoderPtr response;
if (request_body_size) {
response = codec_client_->makeRequestWithBody(request_headers, request_body_size);
} else {
response = codec_client_->makeHeaderOnlyRequest(request_headers);
}
waitForNextUpstreamRequest(upstream_indices, timeout);
// Send response headers, and end_stream if there is no response body.
upstream_request_->encodeHeaders(response_headers, response_body_size == 0);
// Send any response data, with end_stream true.
if (response_body_size) {
upstream_request_->encodeData(response_body_size, true);
}
// Wait for the response to be read by the codec client.
RELEASE_ASSERT(response->waitForEndStream(timeout),
fmt::format("unexpected timeout after ", timeout.count(), " ms"));
return response;
}
IntegrationStreamDecoderPtr HttpIntegrationTest::sendRequestAndWaitForResponse(
const Http::TestRequestHeaderMapImpl& request_headers, uint32_t request_body_size,
const Http::TestResponseHeaderMapImpl& response_headers, uint32_t response_body_size,
uint64_t upstream_index, std::chrono::milliseconds timeout) {
return sendRequestAndWaitForResponse(request_headers, request_body_size, response_headers,
response_body_size, std::vector<uint64_t>{upstream_index},
timeout);
}
void HttpIntegrationTest::cleanupUpstreamAndDownstream() {
// Close the upstream connection first. If there's an outstanding request,
// closing the client may result in a FIN being sent upstream, and FakeConnectionBase::close
// will interpret that as an unexpected disconnect. The codec client is not
// subject to the same failure mode.
if (fake_upstream_connection_) {
AssertionResult result = fake_upstream_connection_->close();
RELEASE_ASSERT(result, result.message());
result = fake_upstream_connection_->waitForDisconnect();
RELEASE_ASSERT(result, result.message());
fake_upstream_connection_.reset();
}
if (codec_client_) {
codec_client_->close();
}
}
void HttpIntegrationTest::sendRequestAndVerifyResponse(
const Http::TestRequestHeaderMapImpl& request_headers, const int request_size,
const Http::TestResponseHeaderMapImpl& response_headers, const int response_size,
const int backend_idx,
absl::optional<const Http::TestResponseHeaderMapImpl> expected_response_headers) {
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = sendRequestAndWaitForResponse(request_headers, request_size, response_headers,
response_size, backend_idx);
verifyResponse(std::move(response), "200",
(expected_response_headers.has_value()) ? *expected_response_headers
: response_headers,
std::string(response_size, 'a'));
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(request_size, upstream_request_->bodyLength());
cleanupUpstreamAndDownstream();
}
void HttpIntegrationTest::verifyResponse(IntegrationStreamDecoderPtr response,
const std::string& response_code,
const Http::TestResponseHeaderMapImpl& expected_headers,
const std::string& expected_body) {
EXPECT_TRUE(response->complete());
EXPECT_EQ(response_code, response->headers().getStatusValue());
expected_headers.iterate([response_headers = &response->headers()](
const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
const auto entry =
response_headers->get(Http::LowerCaseString{std::string(header.key().getStringView())});
EXPECT_FALSE(entry.empty());
EXPECT_EQ(header.value().getStringView(), entry[0]->value().getStringView());
return Http::HeaderMap::Iterate::Continue;
});
EXPECT_EQ(response->body(), expected_body);
}
absl::optional<uint64_t> HttpIntegrationTest::waitForNextUpstreamConnection(
const std::vector<uint64_t>& upstream_indices,
std::chrono::milliseconds connection_wait_timeout,
FakeHttpConnectionPtr& fake_upstream_connection) {
AssertionResult result = AssertionFailure();
int upstream_index = 0;
Event::TestTimeSystem::RealTimeBound bound(connection_wait_timeout);
// Loop over the upstreams until the call times out or an upstream request is received.
while (!result) {
upstream_index = upstream_index % upstream_indices.size();
result = fake_upstreams_[upstream_indices[upstream_index]]->waitForHttpConnection(
*dispatcher_, fake_upstream_connection, std::chrono::milliseconds(5));
if (result) {
return upstream_index;
} else if (!bound.withinBound()) {
RELEASE_ASSERT(0, "Timed out waiting for new connection.");
break;
}
++upstream_index;
}
RELEASE_ASSERT(result, result.message());
return {};
}
absl::optional<uint64_t>
HttpIntegrationTest::waitForNextUpstreamRequest(const std::vector<uint64_t>& upstream_indices,
std::chrono::milliseconds connection_wait_timeout) {
absl::optional<uint64_t> upstream_with_request;
// If there is no upstream connection, wait for it to be established.
if (!fake_upstream_connection_) {
upstream_with_request = waitForNextUpstreamConnection(upstream_indices, connection_wait_timeout,
fake_upstream_connection_);
}
// Wait for the next stream on the upstream connection.
AssertionResult result =
fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_);
RELEASE_ASSERT(result, result.message());
// Wait for the stream to be completely received.
result = upstream_request_->waitForEndStream(*dispatcher_);
RELEASE_ASSERT(result, result.message());
return upstream_with_request;
}
void HttpIntegrationTest::waitForNextUpstreamRequest(
uint64_t upstream_index, std::chrono::milliseconds connection_wait_timeout) {
waitForNextUpstreamRequest(std::vector<uint64_t>({upstream_index}), connection_wait_timeout);
}
void HttpIntegrationTest::checkSimpleRequestSuccess(uint64_t expected_request_size,
uint64_t expected_response_size,
IntegrationStreamDecoder* response) {
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(expected_request_size, upstream_request_->bodyLength());
ASSERT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
EXPECT_EQ(expected_response_size, response->body().size());
}
void HttpIntegrationTest::testRouterRequestAndResponseWithBody(
uint64_t request_size, uint64_t response_size, bool big_header, bool set_content_length_header,
ConnectionCreationFunction* create_connection, std::chrono::milliseconds timeout) {
#ifdef ENVOY_CONFIG_COVERAGE
// Avoid excessive logging at UDP packet level, which causes log spamming, as well as worse
// contention: https://github.com/envoyproxy/envoy/issues/19595
ENVOY_LOG_MISC(warn, "manually lowering logs to error");
LogLevelSetter save_levels(spdlog::level::err);
#endif
initialize();
codec_client_ = makeHttpConnection(
create_connection ? ((*create_connection)()) : makeClientConnection((lookupPort("http"))));
if (set_content_length_header) {
default_request_headers_.setContentLength(request_size);
default_response_headers_.setContentLength(response_size);
}
if (big_header) {
default_request_headers_.addCopy("big", std::string(4096, 'a'));
}
auto response = sendRequestAndWaitForResponse(
default_request_headers_, request_size, default_response_headers_, response_size, 0, timeout);
checkSimpleRequestSuccess(request_size, response_size, response.get());
}
void HttpIntegrationTest::testGiantRequestAndResponse(uint64_t request_size, uint64_t response_size,
bool set_content_length_header,
std::chrono::milliseconds timeout) {
autonomous_upstream_ = true;
#ifdef ENVOY_CONFIG_COVERAGE
// Avoid excessive logging at UDP packet level, which causes log spamming, as well as worse
// contention: https://github.com/envoyproxy/envoy/issues/19595
ENVOY_LOG_MISC(warn, "manually lowering logs to error");
LogLevelSetter save_levels(spdlog::level::err);
#endif
initialize();
codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http")));
Http::TestRequestHeaderMapImpl request_headers{
{":method", "GET"},
{":path", "/test/long/url"},
{":authority", "sni.lyft.com"},
{":scheme", "http"},
{AutonomousStream::RESPONSE_SIZE_BYTES, std::to_string(response_size)},
{AutonomousStream::EXPECT_REQUEST_SIZE_BYTES, std::to_string(request_size)},
{AutonomousStream::NO_TRAILERS, "0"}};
auto response_headers =
std::make_unique<Http::TestResponseHeaderMapImpl>(default_response_headers_);
if (set_content_length_header) {
request_headers.setContentLength(request_size);
response_headers->setContentLength(response_size);
}
reinterpret_cast<AutonomousUpstream*>(fake_upstreams_.front().get())
->setResponseHeaders(std::move(response_headers));
auto response = codec_client_->makeRequestWithBody(request_headers, request_size);
// Wait for the response to be read by the codec client.
RELEASE_ASSERT(response->waitForEndStream(timeout), "unexpected timeout");
ASSERT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
EXPECT_EQ(response_size, response->body().size());
}
void HttpIntegrationTest::testRouterUpstreamProtocolError(const std::string& expected_code,
const std::string& expected_flag) {
useAccessLog("%RESPONSE_CODE% %RESPONSE_FLAGS%");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder = codec_client_->startRequest(Http::TestRequestHeaderMapImpl{
{":method", "GET"}, {":path", "/test/long/url"}, {":authority", "sni.lyft.com"}});
auto response = std::move(encoder_decoder.second);
FakeRawConnectionPtr fake_upstream_connection;
ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection));
std::string data;
ASSERT_TRUE(fake_upstream_connection->waitForData(
FakeRawConnection::waitForInexactMatch("\r\n\r\n"), &data));
ASSERT_TRUE(fake_upstream_connection->write("bad protocol data!"));
ASSERT_TRUE(fake_upstream_connection->waitForDisconnect());
ASSERT_TRUE(codec_client_->waitForDisconnect());
EXPECT_TRUE(response->complete());
EXPECT_EQ(expected_code, response->headers().getStatusValue());
std::string log = waitForAccessLog(access_log_name_);
EXPECT_THAT(log, HasSubstr(expected_code));
EXPECT_THAT(log, HasSubstr(expected_flag));
}
IntegrationStreamDecoderPtr
HttpIntegrationTest::makeHeaderOnlyRequest(ConnectionCreationFunction* create_connection,
int upstream_index, const std::string& path,
const std::string& authority) {
// This is called multiple times per test in ads_integration_test. Only call
// initialize() the first time.
if (!initialized()) {
initialize();
}
codec_client_ = makeHttpConnection(
create_connection ? ((*create_connection)()) : makeClientConnection((lookupPort("http"))));
if (!authority.empty()) {
default_request_headers_.setHost(authority);
}
default_request_headers_.setPath(path);
return sendRequestAndWaitForResponse(default_request_headers_, 0, default_response_headers_, 0,
upstream_index);
}
void HttpIntegrationTest::testRouterHeaderOnlyRequestAndResponse(
ConnectionCreationFunction* create_connection, int upstream_index, const std::string& path,
const std::string& authority) {
auto response = makeHeaderOnlyRequest(create_connection, upstream_index, path, authority);
checkSimpleRequestSuccess(0U, 0U, response.get());
}
// Change the default route to be restrictive, and send a request to an alternate route.
void HttpIntegrationTest::testRouterNotFound() {
config_helper_.setDefaultHostAndRoute("foo.com", "/found");
config_helper_.addConfigModifier(configureProxyStatus());
initialize();
BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest(
lookupPort("http"), "GET", "/notfound", "", downstream_protocol_, version_);
ASSERT_TRUE(response->complete());
EXPECT_EQ("404", response->headers().getStatusValue());
EXPECT_EQ(response->headers().getProxyStatusValue(),
"envoy; error=destination_not_found; details=\"route_not_found; NR\"");
}
// Change the default route to be restrictive, and send a POST to an alternate route.
void HttpIntegrationTest::testRouterNotFoundWithBody() {
config_helper_.setDefaultHostAndRoute("foo.com", "/found");
config_helper_.addConfigModifier(configureProxyStatus());
initialize();
BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest(
lookupPort("http"), "POST", "/notfound", "foo", downstream_protocol_, version_);
ASSERT_TRUE(response->complete());
EXPECT_EQ("404", response->headers().getStatusValue());
EXPECT_EQ(response->headers().getProxyStatusValue(),
"envoy; error=destination_not_found; details=\"route_not_found; NR\"");
}
// Make sure virtual cluster stats are charged to the appropriate virtual cluster.
void HttpIntegrationTest::testRouterVirtualClusters() {
const std::string matching_header = "x-use-test-vcluster";
config_helper_.addConfigModifier(
[matching_header](
envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) {
auto* route_config = hcm.mutable_route_config();
ASSERT_EQ(1, route_config->virtual_hosts_size());
auto* virtual_host = route_config->mutable_virtual_hosts(0);
{
auto* virtual_cluster = virtual_host->add_virtual_clusters();
virtual_cluster->set_name("test_vcluster");
auto* headers = virtual_cluster->add_headers();
headers->set_name(matching_header);
headers->set_present_match(true);
}
});
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
Http::TestRequestHeaderMapImpl request_headers{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "sni.lyft.com"},
{matching_header, "true"}};
auto response = sendRequestAndWaitForResponse(request_headers, 0, default_response_headers_, 0);
checkSimpleRequestSuccess(0, 0, response.get());
test_server_->waitForCounterEq("vhost.integration.vcluster.test_vcluster.upstream_rq_total", 1);
test_server_->waitForCounterEq("vhost.integration.vcluster.other.upstream_rq_total", 0);
auto response2 =
sendRequestAndWaitForResponse(default_request_headers_, 0, default_response_headers_, 0);
checkSimpleRequestSuccess(0, 0, response2.get());
test_server_->waitForCounterEq("vhost.integration.vcluster.test_vcluster.upstream_rq_total", 1);
test_server_->waitForCounterEq("vhost.integration.vcluster.other.upstream_rq_total", 1);
}
// Make sure route level stats are generated correctly.
void HttpIntegrationTest::testRouteStats() {
config_helper_.addConfigModifier(
[](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) {
auto* route_config = hcm.mutable_route_config();
ASSERT_EQ(1, route_config->virtual_hosts_size());
auto* virtual_host = route_config->mutable_virtual_hosts(0);
auto* route = virtual_host->mutable_routes(0);
route->set_stat_prefix("test_route");
});
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
Http::TestRequestHeaderMapImpl request_headers{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "sni.lyft.com"}};
auto response = sendRequestAndWaitForResponse(request_headers, 0, default_response_headers_, 0);
checkSimpleRequestSuccess(0, 0, response.get());
test_server_->waitForCounterEq("vhost.integration.route.test_route.upstream_rq_total", 1);
test_server_->waitForCounterEq("vhost.integration.route.test_route.upstream_rq_completed", 1);
}
void HttpIntegrationTest::testRouterUpstreamDisconnectBeforeRequestComplete() {
config_helper_.addConfigModifier(configureProxyStatus());
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder = codec_client_->startRequest(default_request_headers_);
auto response = std::move(encoder_decoder.second);
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_TRUE(upstream_request_->waitForHeadersComplete());
ASSERT_TRUE(fake_upstream_connection_->close());
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
ASSERT_TRUE(response->waitForEndStream());
if (downstream_protocol_ == Http::CodecType::HTTP1) {
ASSERT_TRUE(codec_client_->waitForDisconnect());
} else {
codec_client_->close();
}
EXPECT_FALSE(upstream_request_->complete());
EXPECT_EQ(0U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("503", response->headers().getStatusValue());
EXPECT_EQ(response->headers().getProxyStatusValue(),
"envoy; error=connection_terminated; "
"details=\"upstream_reset_before_response_started{connection_termination}; UC\"");
EXPECT_EQ("upstream connect error or disconnect/reset before headers. reset reason: connection "
"termination",
response->body());
}
void HttpIntegrationTest::testRouterUpstreamDisconnectBeforeResponseComplete(
ConnectionCreationFunction* create_connection) {
initialize();
codec_client_ = makeHttpConnection(
create_connection ? ((*create_connection)()) : makeClientConnection((lookupPort("http"))));
auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(default_response_headers_, false);
response->waitForHeaders();
ASSERT_TRUE(fake_upstream_connection_->close());
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
if (downstream_protocol_ == Http::CodecType::HTTP1) {
ASSERT_TRUE(codec_client_->waitForDisconnect());
} else {
ASSERT_TRUE(response->waitForReset());
codec_client_->close();
}
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(0U, upstream_request_->bodyLength());
EXPECT_FALSE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
EXPECT_EQ(0U, response->body().size());
}
void HttpIntegrationTest::testRouterDownstreamDisconnectBeforeRequestComplete(
ConnectionCreationFunction* create_connection) {
initialize();
codec_client_ = makeHttpConnection(
create_connection ? ((*create_connection)()) : makeClientConnection((lookupPort("http"))));
auto encoder_decoder = codec_client_->startRequest(default_request_headers_);
auto response = std::move(encoder_decoder.second);
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_TRUE(upstream_request_->waitForHeadersComplete());
codec_client_->close();
if (upstreamProtocol() == Http::CodecType::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());
}
EXPECT_FALSE(upstream_request_->complete());
EXPECT_EQ(0U, upstream_request_->bodyLength());
EXPECT_FALSE(response->complete());
}
void HttpIntegrationTest::testRouterDownstreamDisconnectBeforeResponseComplete(
ConnectionCreationFunction* create_connection) {
#if defined(__APPLE__) || defined(WIN32)
// Skip this test on OS/X + Windows: we can't detect the early close, and we
// won't clean up the upstream connection until it times out. See #4294.
if (downstream_protocol_ == Http::CodecType::HTTP1) {
return;
}
#endif
initialize();
codec_client_ = makeHttpConnection(
create_connection ? ((*create_connection)()) : makeClientConnection((lookupPort("http"))));
auto response = codec_client_->makeHeaderOnlyRequest(default_request_headers_);
waitForNextUpstreamRequest();
upstream_request_->encodeHeaders(default_response_headers_, false);
upstream_request_->encodeData(512, false);
response->waitForBodyData(512);
codec_client_->close();
if (upstreamProtocol() == Http::CodecType::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());
}
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(0U, upstream_request_->bodyLength());
EXPECT_FALSE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
EXPECT_EQ(512U, response->body().size());
}
void HttpIntegrationTest::testRouterUpstreamResponseBeforeRequestComplete() {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto encoder_decoder = codec_client_->startRequest(default_request_headers_);
auto response = std::move(encoder_decoder.second);
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_TRUE(upstream_request_->waitForHeadersComplete());
upstream_request_->encodeHeaders(default_response_headers_, false);
upstream_request_->encodeData(512, true);
ASSERT_TRUE(response->waitForEndStream());
if (upstreamProtocol() == Http::CodecType::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());
}
if (downstream_protocol_ == Http::CodecType::HTTP1) {
ASSERT_TRUE(codec_client_->waitForDisconnect());
} else {
codec_client_->close();
}
EXPECT_FALSE(upstream_request_->complete());
EXPECT_EQ(0U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
EXPECT_EQ(512U, response->body().size());
}
void HttpIntegrationTest::testRetry() {
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeRequestWithBody(
Http::TestRequestHeaderMapImpl{{":method", "POST"},
{":path", "/test/long/url"},
{":scheme", "http"},
{":authority", "sni.lyft.com"},
{"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() == Http::CodecType::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);
ASSERT_TRUE(response->waitForEndStream());
EXPECT_TRUE(upstream_request_->complete());
EXPECT_EQ(1024U, upstream_request_->bodyLength());
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
EXPECT_EQ(512U, response->body().size());
}
// Tests that the x-envoy-attempt-count header is properly set on the upstream request
// and updated after the request is retried.
void HttpIntegrationTest::testRetryAttemptCountHeader() {
auto host = config_helper_.createVirtualHost("sni.lyft.com", "/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", "sni.lyft.com"},
{"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().getEnvoyAttemptCountValue()).c_str()), 1);