1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <cstddef>
6 #include <cstdint>
7 #include <list>
8 #include <memory>
9 #include <ostream>
10 #include <string>
11 #include <utility>
12 #include <vector>
13
14 #include "absl/strings/str_cat.h"
15 #include "absl/strings/string_view.h"
16 #include "absl/time/clock.h"
17 #include "absl/time/time.h"
18 #include "absl/types/span.h"
19 #include "quiche/quic/core/crypto/null_encrypter.h"
20 #include "quiche/quic/core/crypto/quic_client_session_cache.h"
21 #include "quiche/quic/core/frames/quic_blocked_frame.h"
22 #include "quiche/quic/core/http/http_constants.h"
23 #include "quiche/quic/core/http/quic_spdy_client_stream.h"
24 #include "quiche/quic/core/http/quic_spdy_session.h"
25 #include "quiche/quic/core/http/web_transport_http3.h"
26 #include "quiche/quic/core/io/quic_default_event_loop.h"
27 #include "quiche/quic/core/io/quic_event_loop.h"
28 #include "quiche/quic/core/quic_connection.h"
29 #include "quiche/quic/core/quic_constants.h"
30 #include "quiche/quic/core/quic_data_writer.h"
31 #include "quiche/quic/core/quic_default_clock.h"
32 #include "quiche/quic/core/quic_error_codes.h"
33 #include "quiche/quic/core/quic_framer.h"
34 #include "quiche/quic/core/quic_packet_creator.h"
35 #include "quiche/quic/core/quic_packet_writer.h"
36 #include "quiche/quic/core/quic_packet_writer_wrapper.h"
37 #include "quiche/quic/core/quic_packets.h"
38 #include "quiche/quic/core/quic_session.h"
39 #include "quiche/quic/core/quic_types.h"
40 #include "quiche/quic/core/quic_utils.h"
41 #include "quiche/quic/platform/api/quic_expect_bug.h"
42 #include "quiche/quic/platform/api/quic_flags.h"
43 #include "quiche/quic/platform/api/quic_logging.h"
44 #include "quiche/quic/platform/api/quic_socket_address.h"
45 #include "quiche/quic/platform/api/quic_test.h"
46 #include "quiche/quic/platform/api/quic_test_loopback.h"
47 #include "quiche/quic/test_tools/bad_packet_writer.h"
48 #include "quiche/quic/test_tools/crypto_test_utils.h"
49 #include "quiche/quic/test_tools/packet_dropping_test_writer.h"
50 #include "quiche/quic/test_tools/packet_reordering_writer.h"
51 #include "quiche/quic/test_tools/qpack/qpack_encoder_peer.h"
52 #include "quiche/quic/test_tools/qpack/qpack_test_utils.h"
53 #include "quiche/quic/test_tools/quic_client_session_cache_peer.h"
54 #include "quiche/quic/test_tools/quic_config_peer.h"
55 #include "quiche/quic/test_tools/quic_connection_peer.h"
56 #include "quiche/quic/test_tools/quic_dispatcher_peer.h"
57 #include "quiche/quic/test_tools/quic_flow_controller_peer.h"
58 #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h"
59 #include "quiche/quic/test_tools/quic_server_peer.h"
60 #include "quiche/quic/test_tools/quic_session_peer.h"
61 #include "quiche/quic/test_tools/quic_spdy_session_peer.h"
62 #include "quiche/quic/test_tools/quic_spdy_stream_peer.h"
63 #include "quiche/quic/test_tools/quic_stream_id_manager_peer.h"
64 #include "quiche/quic/test_tools/quic_stream_peer.h"
65 #include "quiche/quic/test_tools/quic_stream_sequencer_peer.h"
66 #include "quiche/quic/test_tools/quic_test_backend.h"
67 #include "quiche/quic/test_tools/quic_test_client.h"
68 #include "quiche/quic/test_tools/quic_test_server.h"
69 #include "quiche/quic/test_tools/quic_test_utils.h"
70 #include "quiche/quic/test_tools/server_thread.h"
71 #include "quiche/quic/test_tools/web_transport_test_tools.h"
72 #include "quiche/quic/tools/quic_backend_response.h"
73 #include "quiche/quic/tools/quic_memory_cache_backend.h"
74 #include "quiche/quic/tools/quic_server.h"
75 #include "quiche/quic/tools/quic_simple_client_stream.h"
76 #include "quiche/quic/tools/quic_simple_server_stream.h"
77 #include "quiche/common/platform/api/quiche_test.h"
78 #include "quiche/common/quiche_stream.h"
79 #include "quiche/common/test_tools/quiche_test_utils.h"
80 #include "quiche/spdy/core/http2_header_block.h"
81
82 using spdy::Http2HeaderBlock;
83 using spdy::kV3LowestPriority;
84 using spdy::SpdyFramer;
85 using spdy::SpdySerializedFrame;
86 using spdy::SpdySettingsIR;
87 using ::testing::_;
88 using ::testing::Assign;
89 using ::testing::Invoke;
90 using ::testing::NiceMock;
91 using ::testing::UnorderedElementsAreArray;
92
93 namespace quic {
94 namespace test {
95 namespace {
96
97 const char kFooResponseBody[] = "Artichoke hearts make me happy.";
98 const char kBarResponseBody[] = "Palm hearts are pretty delicious, also.";
99 const char kTestUserAgentId[] = "quic/core/http/end_to_end_test.cc";
100 const float kSessionToStreamRatio = 1.5;
101 const int kLongConnectionIdLength = 16;
102
103 // Run all tests with the cross products of all versions.
104 struct TestParams {
TestParamsquic::test::__anon761fe56d0111::TestParams105 TestParams(const ParsedQuicVersion& version, QuicTag congestion_control_tag,
106 QuicEventLoopFactory* event_loop,
107 int override_server_connection_id_length)
108 : version(version),
109 congestion_control_tag(congestion_control_tag),
110 event_loop(event_loop),
111 override_server_connection_id_length(
112 override_server_connection_id_length) {}
113
operator <<(std::ostream & os,const TestParams & p)114 friend std::ostream& operator<<(std::ostream& os, const TestParams& p) {
115 os << "{ version: " << ParsedQuicVersionToString(p.version);
116 os << " congestion_control_tag: "
117 << QuicTagToString(p.congestion_control_tag)
118 << " event loop: " << p.event_loop->GetName()
119 << " connection ID length: " << p.override_server_connection_id_length
120 << " }";
121 return os;
122 }
123
124 ParsedQuicVersion version;
125 QuicTag congestion_control_tag;
126 QuicEventLoopFactory* event_loop;
127 int override_server_connection_id_length;
128 };
129
130 // Used by ::testing::PrintToStringParamName().
PrintToString(const TestParams & p)131 std::string PrintToString(const TestParams& p) {
132 std::string rv = absl::StrCat(
133 ParsedQuicVersionToString(p.version), "_",
134 QuicTagToString(p.congestion_control_tag), "_", p.event_loop->GetName(),
135 "_",
136 std::to_string((p.override_server_connection_id_length == -1)
137 ? static_cast<int>(kQuicDefaultConnectionIdLength)
138 : p.override_server_connection_id_length));
139 return EscapeTestParamName(rv);
140 }
141
142 // Constructs various test permutations.
GetTestParams()143 std::vector<TestParams> GetTestParams() {
144 std::vector<TestParams> params;
145 std::vector<int> connection_id_lengths{-1, kLongConnectionIdLength};
146 for (auto connection_id_length : connection_id_lengths) {
147 for (const QuicTag congestion_control_tag : {kTBBR, kQBIC, kB2ON}) {
148 if (!GetQuicReloadableFlag(quic_allow_client_enabled_bbr_v2) &&
149 congestion_control_tag == kB2ON) {
150 continue;
151 }
152 for (const ParsedQuicVersion& version : CurrentSupportedVersions()) {
153 // TODO(b/232269029): Q050 should be able to handle 0-RTT when the
154 // initial connection ID is > 8 bytes, but it cannot. This is an
155 // invasive fix that has no impact as long as gQUIC clients always use
156 // 8B server connection IDs. If this bug is fixed, we can change
157 // 'UsesTls' to 'AllowsVariableLengthConnectionIds()' below to test
158 // qQUIC as well.
159 if (connection_id_length == -1 || version.UsesTls()) {
160 params.push_back(TestParams(version, congestion_control_tag,
161 GetDefaultEventLoop(),
162 connection_id_length));
163 }
164 } // End of outer version loop.
165 } // End of congestion_control_tag loop.
166 } // End of connection_id_length loop.
167
168 // Only run every event loop implementation for one fixed configuration.
169 for (QuicEventLoopFactory* event_loop : GetAllSupportedEventLoops()) {
170 if (event_loop == GetDefaultEventLoop()) {
171 continue;
172 }
173 params.push_back(
174 TestParams(ParsedQuicVersion::RFCv1(), kTBBR, event_loop, -1));
175 }
176
177 return params;
178 }
179
WriteHeadersOnStream(QuicSpdyStream * stream)180 void WriteHeadersOnStream(QuicSpdyStream* stream) {
181 // Since QuicSpdyStream uses QuicHeaderList::empty() to detect too large
182 // headers, it also fails when receiving empty headers.
183 Http2HeaderBlock headers;
184 headers[":authority"] = "test.example.com:443";
185 headers[":path"] = "/path";
186 headers[":method"] = "GET";
187 headers[":scheme"] = "https";
188 stream->WriteHeaders(std::move(headers), /* fin = */ false, nullptr);
189 }
190
191 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
192 public:
ServerDelegate(QuicDispatcher * dispatcher)193 explicit ServerDelegate(QuicDispatcher* dispatcher)
194 : dispatcher_(dispatcher) {}
195 ~ServerDelegate() override = default;
OnCanWrite()196 void OnCanWrite() override { dispatcher_->OnCanWrite(); }
197
198 private:
199 QuicDispatcher* dispatcher_;
200 };
201
202 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
203 public:
ClientDelegate(QuicDefaultClient * client)204 explicit ClientDelegate(QuicDefaultClient* client) : client_(client) {}
205 ~ClientDelegate() override = default;
OnCanWrite()206 void OnCanWrite() override {
207 client_->default_network_helper()->OnSocketEvent(
208 nullptr, client_->GetLatestFD(), kSocketEventWritable);
209 }
210
211 private:
212 QuicDefaultClient* client_;
213 };
214
215 class EndToEndTest : public QuicTestWithParam<TestParams> {
216 protected:
EndToEndTest()217 EndToEndTest()
218 : initialized_(false),
219 connect_to_server_on_initialize_(true),
220 server_address_(QuicSocketAddress(TestLoopback(), 0)),
221 server_hostname_("test.example.com"),
222 fd_(kQuicInvalidSocketFd),
223 client_writer_(nullptr),
224 server_writer_(nullptr),
225 version_(GetParam().version),
226 client_supported_versions_({version_}),
227 server_supported_versions_(CurrentSupportedVersions()),
228 chlo_multiplier_(0),
229 stream_factory_(nullptr),
230 override_server_connection_id_length_(
231 GetParam().override_server_connection_id_length),
232 expected_server_connection_id_length_(kQuicDefaultConnectionIdLength) {
233 QUIC_LOG(INFO) << "Using Configuration: " << GetParam();
234
235 // Use different flow control windows for client/server.
236 client_config_.SetInitialStreamFlowControlWindowToSend(
237 2 * kInitialStreamFlowControlWindowForTest);
238 client_config_.SetInitialSessionFlowControlWindowToSend(
239 2 * kInitialSessionFlowControlWindowForTest);
240 server_config_.SetInitialStreamFlowControlWindowToSend(
241 3 * kInitialStreamFlowControlWindowForTest);
242 server_config_.SetInitialSessionFlowControlWindowToSend(
243 3 * kInitialSessionFlowControlWindowForTest);
244
245 // The default idle timeouts can be too strict when running on a busy
246 // machine.
247 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(30);
248 client_config_.set_max_time_before_crypto_handshake(timeout);
249 client_config_.set_max_idle_time_before_crypto_handshake(timeout);
250 server_config_.set_max_time_before_crypto_handshake(timeout);
251 server_config_.set_max_idle_time_before_crypto_handshake(timeout);
252
253 AddToCache("/foo", 200, kFooResponseBody);
254 AddToCache("/bar", 200, kBarResponseBody);
255 // Enable fixes for bugs found in tests and prod.
256 }
257
CreateClientWithWriter()258 virtual void CreateClientWithWriter() {
259 client_.reset(CreateQuicClient(client_writer_));
260 }
261
CreateQuicClient(QuicPacketWriterWrapper * writer)262 QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
263 QuicTestClient* client = new QuicTestClient(
264 server_address_, server_hostname_, client_config_,
265 client_supported_versions_,
266 crypto_test_utils::ProofVerifierForTesting(),
267 std::make_unique<QuicClientSessionCache>(),
268 GetParam().event_loop->Create(QuicDefaultClock::Get()));
269 client->SetUserAgentID(kTestUserAgentId);
270 client->UseWriter(writer);
271 if (!pre_shared_key_client_.empty()) {
272 client->client()->SetPreSharedKey(pre_shared_key_client_);
273 }
274 if (override_server_connection_id_length_ >= 0) {
275 client->UseConnectionIdLength(override_server_connection_id_length_);
276 }
277 if (override_client_connection_id_length_ >= 0) {
278 client->UseClientConnectionIdLength(
279 override_client_connection_id_length_);
280 }
281 client->client()->set_connection_debug_visitor(connection_debug_visitor_);
282 client->client()->set_enable_web_transport(enable_web_transport_);
283 client->Connect();
284 return client;
285 }
286
set_smaller_flow_control_receive_window()287 void set_smaller_flow_control_receive_window() {
288 const uint32_t kClientIFCW = 64 * 1024;
289 const uint32_t kServerIFCW = 1024 * 1024;
290 set_client_initial_stream_flow_control_receive_window(kClientIFCW);
291 set_client_initial_session_flow_control_receive_window(
292 kSessionToStreamRatio * kClientIFCW);
293 set_server_initial_stream_flow_control_receive_window(kServerIFCW);
294 set_server_initial_session_flow_control_receive_window(
295 kSessionToStreamRatio * kServerIFCW);
296 }
297
set_client_initial_stream_flow_control_receive_window(uint32_t window)298 void set_client_initial_stream_flow_control_receive_window(uint32_t window) {
299 ASSERT_TRUE(client_ == nullptr);
300 QUIC_DLOG(INFO) << "Setting client initial stream flow control window: "
301 << window;
302 client_config_.SetInitialStreamFlowControlWindowToSend(window);
303 }
304
set_client_initial_session_flow_control_receive_window(uint32_t window)305 void set_client_initial_session_flow_control_receive_window(uint32_t window) {
306 ASSERT_TRUE(client_ == nullptr);
307 QUIC_DLOG(INFO) << "Setting client initial session flow control window: "
308 << window;
309 client_config_.SetInitialSessionFlowControlWindowToSend(window);
310 }
311
set_client_initial_max_stream_data_incoming_bidirectional(uint32_t window)312 void set_client_initial_max_stream_data_incoming_bidirectional(
313 uint32_t window) {
314 ASSERT_TRUE(client_ == nullptr);
315 QUIC_DLOG(INFO)
316 << "Setting client initial max stream data incoming bidirectional: "
317 << window;
318 client_config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend(
319 window);
320 }
321
set_server_initial_max_stream_data_outgoing_bidirectional(uint32_t window)322 void set_server_initial_max_stream_data_outgoing_bidirectional(
323 uint32_t window) {
324 ASSERT_TRUE(client_ == nullptr);
325 QUIC_DLOG(INFO)
326 << "Setting server initial max stream data outgoing bidirectional: "
327 << window;
328 server_config_.SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend(
329 window);
330 }
331
set_server_initial_stream_flow_control_receive_window(uint32_t window)332 void set_server_initial_stream_flow_control_receive_window(uint32_t window) {
333 ASSERT_TRUE(server_thread_ == nullptr);
334 QUIC_DLOG(INFO) << "Setting server initial stream flow control window: "
335 << window;
336 server_config_.SetInitialStreamFlowControlWindowToSend(window);
337 }
338
set_server_initial_session_flow_control_receive_window(uint32_t window)339 void set_server_initial_session_flow_control_receive_window(uint32_t window) {
340 ASSERT_TRUE(server_thread_ == nullptr);
341 QUIC_DLOG(INFO) << "Setting server initial session flow control window: "
342 << window;
343 server_config_.SetInitialSessionFlowControlWindowToSend(window);
344 }
345
GetSentPacketManagerFromFirstServerSession()346 const QuicSentPacketManager* GetSentPacketManagerFromFirstServerSession() {
347 QuicConnection* server_connection = GetServerConnection();
348 if (server_connection == nullptr) {
349 ADD_FAILURE() << "Missing server connection";
350 return nullptr;
351 }
352 return &server_connection->sent_packet_manager();
353 }
354
GetSentPacketManagerFromClientSession()355 const QuicSentPacketManager* GetSentPacketManagerFromClientSession() {
356 QuicConnection* client_connection = GetClientConnection();
357 if (client_connection == nullptr) {
358 ADD_FAILURE() << "Missing client connection";
359 return nullptr;
360 }
361 return &client_connection->sent_packet_manager();
362 }
363
GetClientSession()364 QuicSpdyClientSession* GetClientSession() {
365 if (!client_) {
366 ADD_FAILURE() << "Missing QuicTestClient";
367 return nullptr;
368 }
369 if (client_->client() == nullptr) {
370 ADD_FAILURE() << "Missing MockableQuicClient";
371 return nullptr;
372 }
373 return client_->client()->client_session();
374 }
375
GetClientConnection()376 QuicConnection* GetClientConnection() {
377 QuicSpdyClientSession* client_session = GetClientSession();
378 if (client_session == nullptr) {
379 ADD_FAILURE() << "Missing client session";
380 return nullptr;
381 }
382 return client_session->connection();
383 }
384
GetServerConnection()385 QuicConnection* GetServerConnection() {
386 QuicSpdySession* server_session = GetServerSession();
387 if (server_session == nullptr) {
388 ADD_FAILURE() << "Missing server session";
389 return nullptr;
390 }
391 return server_session->connection();
392 }
393
GetServerSession()394 QuicSpdySession* GetServerSession() {
395 if (!server_thread_) {
396 ADD_FAILURE() << "Missing server thread";
397 return nullptr;
398 }
399 QuicServer* quic_server = server_thread_->server();
400 if (quic_server == nullptr) {
401 ADD_FAILURE() << "Missing server";
402 return nullptr;
403 }
404 QuicDispatcher* dispatcher = QuicServerPeer::GetDispatcher(quic_server);
405 if (dispatcher == nullptr) {
406 ADD_FAILURE() << "Missing dispatcher";
407 return nullptr;
408 }
409 if (dispatcher->NumSessions() == 0) {
410 ADD_FAILURE() << "Empty dispatcher session map";
411 return nullptr;
412 }
413 EXPECT_EQ(1u, dispatcher->NumSessions());
414 return static_cast<QuicSpdySession*>(
415 QuicDispatcherPeer::GetFirstSessionIfAny(dispatcher));
416 }
417
Initialize()418 bool Initialize() {
419 if (enable_web_transport_) {
420 memory_cache_backend_.set_enable_webtransport(true);
421 }
422
423 QuicTagVector copt;
424 server_config_.SetConnectionOptionsToSend(copt);
425 copt = client_extra_copts_;
426
427 // TODO(nimia): Consider setting the congestion control algorithm for the
428 // client as well according to the test parameter.
429 copt.push_back(GetParam().congestion_control_tag);
430 copt.push_back(k2PTO);
431 if (version_.HasIetfQuicFrames()) {
432 copt.push_back(kILD0);
433 }
434 copt.push_back(kPLE1);
435 client_config_.SetConnectionOptionsToSend(copt);
436
437 // Start the server first, because CreateQuicClient() attempts
438 // to connect to the server.
439 StartServer();
440
441 if (use_preferred_address_) {
442 SetQuicReloadableFlag(quic_use_received_client_addresses_cache, true);
443 // At this point, the server has an ephemeral port to listen on. Restart
444 // the server with the preferred address.
445 StopServer();
446 // server_address_ now contains the random listening port.
447 server_preferred_address_ =
448 QuicSocketAddress(TestLoopback(2), server_address_.port());
449 if (server_preferred_address_ == server_address_) {
450 ADD_FAILURE() << "Preferred address and server address are the same "
451 << server_address_;
452 return false;
453 }
454 // Send server preferred address and let server listen on Any.
455 if (server_preferred_address_.host().IsIPv4()) {
456 server_listening_address_ =
457 QuicSocketAddress(QuicIpAddress::Any4(), server_address_.port());
458 server_config_.SetIPv4AlternateServerAddressToSend(
459 server_preferred_address_);
460 } else {
461 server_listening_address_ =
462 QuicSocketAddress(QuicIpAddress::Any6(), server_address_.port());
463 server_config_.SetIPv6AlternateServerAddressToSend(
464 server_preferred_address_);
465 }
466 // Server restarts.
467 server_writer_ = new PacketDroppingTestWriter();
468 StartServer();
469
470 if (!GetQuicFlag(quic_always_support_server_preferred_address)) {
471 client_config_.SetConnectionOptionsToSend(QuicTagVector{kSPAD});
472 }
473 }
474
475 if (!connect_to_server_on_initialize_) {
476 initialized_ = true;
477 return true;
478 }
479
480 CreateClientWithWriter();
481 if (!client_) {
482 ADD_FAILURE() << "Missing QuicTestClient";
483 return false;
484 }
485 MockableQuicClient* client = client_->client();
486 if (client == nullptr) {
487 ADD_FAILURE() << "Missing MockableQuicClient";
488 return false;
489 }
490 if (client_writer_ != nullptr) {
491 QuicConnection* client_connection = GetClientConnection();
492 if (client_connection == nullptr) {
493 ADD_FAILURE() << "Missing client connection";
494 return false;
495 }
496 client_writer_->Initialize(
497 QuicConnectionPeer::GetHelper(client_connection),
498 QuicConnectionPeer::GetAlarmFactory(client_connection),
499 std::make_unique<ClientDelegate>(client));
500 }
501 initialized_ = true;
502 return client->connected();
503 }
504
SetUp()505 void SetUp() override {
506 // The ownership of these gets transferred to the QuicPacketWriterWrapper
507 // when Initialize() is executed.
508 client_writer_ = new PacketDroppingTestWriter();
509 server_writer_ = new PacketDroppingTestWriter();
510 }
511
TearDown()512 void TearDown() override {
513 EXPECT_TRUE(initialized_) << "You must call Initialize() in every test "
514 << "case. Otherwise, your test will leak memory.";
515 QuicConnection* client_connection = GetClientConnection();
516 if (client_connection != nullptr) {
517 client_connection->set_debug_visitor(nullptr);
518 } else {
519 ADD_FAILURE() << "Missing client connection";
520 }
521 StopServer(/*will_restart=*/false);
522 if (fd_ != kQuicInvalidSocketFd) {
523 // Every test should follow StopServer(true) with StartServer(), so we
524 // should never get here.
525 QuicUdpSocketApi socket_api;
526 socket_api.Destroy(fd_);
527 fd_ = kQuicInvalidSocketFd;
528 }
529 }
530
StartServer()531 void StartServer() {
532 if (fd_ != kQuicInvalidSocketFd) {
533 // We previously called StopServer to reserve the ephemeral port. Close
534 // the socket so that it's available below.
535 QuicUdpSocketApi socket_api;
536 socket_api.Destroy(fd_);
537 fd_ = kQuicInvalidSocketFd;
538 }
539 auto test_server = std::make_unique<QuicTestServer>(
540 crypto_test_utils::ProofSourceForTesting(), server_config_,
541 server_supported_versions_, &memory_cache_backend_,
542 expected_server_connection_id_length_);
543 test_server->SetEventLoopFactory(GetParam().event_loop);
544 const QuicSocketAddress server_listening_address =
545 server_listening_address_.has_value() ? *server_listening_address_
546 : server_address_;
547 server_thread_ = std::make_unique<ServerThread>(std::move(test_server),
548 server_listening_address);
549 if (chlo_multiplier_ != 0) {
550 server_thread_->server()->SetChloMultiplier(chlo_multiplier_);
551 }
552 if (!pre_shared_key_server_.empty()) {
553 server_thread_->server()->SetPreSharedKey(pre_shared_key_server_);
554 }
555 server_thread_->Initialize();
556 server_address_ =
557 QuicSocketAddress(server_address_.host(), server_thread_->GetPort());
558 QuicDispatcher* dispatcher =
559 QuicServerPeer::GetDispatcher(server_thread_->server());
560 ASSERT_TRUE(dispatcher != nullptr);
561 QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
562
563 server_writer_->Initialize(QuicDispatcherPeer::GetHelper(dispatcher),
564 QuicDispatcherPeer::GetAlarmFactory(dispatcher),
565 std::make_unique<ServerDelegate>(dispatcher));
566 if (stream_factory_ != nullptr) {
567 static_cast<QuicTestServer*>(server_thread_->server())
568 ->SetSpdyStreamFactory(stream_factory_);
569 }
570
571 server_thread_->Start();
572 }
573
StopServer(bool will_restart=true)574 void StopServer(bool will_restart = true) {
575 if (server_thread_) {
576 server_thread_->Quit();
577 server_thread_->Join();
578 }
579 if (will_restart) {
580 // server_address_ now contains the random listening port. Since many
581 // tests will attempt to re-bind the socket, claim it so that the kernel
582 // doesn't give away the ephemeral port.
583 QuicUdpSocketApi socket_api;
584 fd_ = socket_api.Create(
585 server_address_.host().AddressFamilyToInt(),
586 /*receive_buffer_size =*/kDefaultSocketReceiveBuffer,
587 /*send_buffer_size =*/kDefaultSocketReceiveBuffer);
588 if (fd_ == kQuicInvalidSocketFd) {
589 QUIC_LOG(ERROR) << "CreateSocket() failed: " << strerror(errno);
590 return;
591 }
592 int rc = socket_api.Bind(fd_, server_address_);
593 if (rc < 0) {
594 QUIC_LOG(ERROR) << "Bind failed: " << strerror(errno);
595 return;
596 }
597 }
598 }
599
AddToCache(absl::string_view path,int response_code,absl::string_view body)600 void AddToCache(absl::string_view path, int response_code,
601 absl::string_view body) {
602 memory_cache_backend_.AddSimpleResponse(server_hostname_, path,
603 response_code, body);
604 }
605
SetPacketLossPercentage(int32_t loss)606 void SetPacketLossPercentage(int32_t loss) {
607 client_writer_->set_fake_packet_loss_percentage(loss);
608 server_writer_->set_fake_packet_loss_percentage(loss);
609 }
610
SetPacketSendDelay(QuicTime::Delta delay)611 void SetPacketSendDelay(QuicTime::Delta delay) {
612 client_writer_->set_fake_packet_delay(delay);
613 server_writer_->set_fake_packet_delay(delay);
614 }
615
SetReorderPercentage(int32_t reorder)616 void SetReorderPercentage(int32_t reorder) {
617 client_writer_->set_fake_reorder_percentage(reorder);
618 server_writer_->set_fake_reorder_percentage(reorder);
619 }
620
621 // Verifies that the client and server connections were both free of packets
622 // being discarded, based on connection stats.
623 // Calls server_thread_ Pause() and Resume(), which may only be called once
624 // per test.
VerifyCleanConnection(bool had_packet_loss)625 void VerifyCleanConnection(bool had_packet_loss) {
626 QuicConnection* client_connection = GetClientConnection();
627 if (client_connection == nullptr) {
628 ADD_FAILURE() << "Missing client connection";
629 return;
630 }
631 QuicConnectionStats client_stats = client_connection->GetStats();
632 // TODO(ianswett): Determine why this becomes even more flaky with BBR
633 // enabled. b/62141144
634 if (!had_packet_loss && !GetQuicReloadableFlag(quic_default_to_bbr)) {
635 EXPECT_EQ(0u, client_stats.packets_lost);
636 }
637 EXPECT_EQ(0u, client_stats.packets_discarded);
638 // When client starts with an unsupported version, the version negotiation
639 // packet sent by server for the old connection (respond for the connection
640 // close packet) will be dropped by the client.
641 if (!ServerSendsVersionNegotiation()) {
642 EXPECT_EQ(0u, client_stats.packets_dropped);
643 }
644 if (!version_.UsesTls()) {
645 // Only enforce this for QUIC crypto because accounting of number of
646 // packets received, processed gets complicated with packets coalescing
647 // and key dropping. For example, a received undecryptable coalesced
648 // packet can be processed later and each sub-packet increases
649 // packets_processed.
650 EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
651 }
652
653 if (!server_thread_) {
654 ADD_FAILURE() << "Missing server thread";
655 return;
656 }
657 server_thread_->Pause();
658 QuicSpdySession* server_session = GetServerSession();
659 if (server_session != nullptr) {
660 QuicConnection* server_connection = server_session->connection();
661 if (server_connection != nullptr) {
662 QuicConnectionStats server_stats = server_connection->GetStats();
663 if (!had_packet_loss) {
664 EXPECT_EQ(0u, server_stats.packets_lost);
665 }
666 EXPECT_EQ(0u, server_stats.packets_discarded);
667 } else {
668 ADD_FAILURE() << "Missing server connection";
669 }
670 } else {
671 ADD_FAILURE() << "Missing server session";
672 }
673 // TODO(ianswett): Restore the check for packets_dropped equals 0.
674 // The expect for packets received is equal to packets processed fails
675 // due to version negotiation packets.
676 server_thread_->Resume();
677 }
678
679 // Returns true when client starts with an unsupported version, and client
680 // closes connection when version negotiation is received.
ServerSendsVersionNegotiation()681 bool ServerSendsVersionNegotiation() {
682 return client_supported_versions_[0] != version_;
683 }
684
SupportsIetfQuicWithTls(ParsedQuicVersion version)685 bool SupportsIetfQuicWithTls(ParsedQuicVersion version) {
686 return version.handshake_protocol == PROTOCOL_TLS1_3;
687 }
688
ExpectFlowControlsSynced(QuicSession * client,QuicSession * server)689 static void ExpectFlowControlsSynced(QuicSession* client,
690 QuicSession* server) {
691 EXPECT_EQ(
692 QuicFlowControllerPeer::SendWindowSize(client->flow_controller()),
693 QuicFlowControllerPeer::ReceiveWindowSize(server->flow_controller()));
694 EXPECT_EQ(
695 QuicFlowControllerPeer::ReceiveWindowSize(client->flow_controller()),
696 QuicFlowControllerPeer::SendWindowSize(server->flow_controller()));
697 }
698
ExpectFlowControlsSynced(QuicStream * client,QuicStream * server)699 static void ExpectFlowControlsSynced(QuicStream* client, QuicStream* server) {
700 EXPECT_EQ(QuicStreamPeer::SendWindowSize(client),
701 QuicStreamPeer::ReceiveWindowSize(server));
702 EXPECT_EQ(QuicStreamPeer::ReceiveWindowSize(client),
703 QuicStreamPeer::SendWindowSize(server));
704 }
705
706 // Must be called before Initialize to have effect.
SetSpdyStreamFactory(QuicTestServer::StreamFactory * factory)707 void SetSpdyStreamFactory(QuicTestServer::StreamFactory* factory) {
708 stream_factory_ = factory;
709 }
710
GetNthClientInitiatedBidirectionalId(int n)711 QuicStreamId GetNthClientInitiatedBidirectionalId(int n) {
712 return GetNthClientInitiatedBidirectionalStreamId(
713 version_.transport_version, n);
714 }
715
GetNthServerInitiatedBidirectionalId(int n)716 QuicStreamId GetNthServerInitiatedBidirectionalId(int n) {
717 return GetNthServerInitiatedBidirectionalStreamId(
718 version_.transport_version, n);
719 }
720
CheckResponseHeaders(QuicTestClient * client,const std::string & expected_status)721 bool CheckResponseHeaders(QuicTestClient* client,
722 const std::string& expected_status) {
723 const spdy::Http2HeaderBlock* response_headers = client->response_headers();
724 auto it = response_headers->find(":status");
725 if (it == response_headers->end()) {
726 ADD_FAILURE() << "Did not find :status header in response";
727 return false;
728 }
729 if (it->second != expected_status) {
730 ADD_FAILURE() << "Got bad :status response: \"" << it->second << "\"";
731 return false;
732 }
733 return true;
734 }
735
CheckResponseHeaders(QuicTestClient * client)736 bool CheckResponseHeaders(QuicTestClient* client) {
737 return CheckResponseHeaders(client, "200");
738 }
739
CheckResponseHeaders(const std::string & expected_status)740 bool CheckResponseHeaders(const std::string& expected_status) {
741 return CheckResponseHeaders(client_.get(), expected_status);
742 }
743
CheckResponseHeaders()744 bool CheckResponseHeaders() { return CheckResponseHeaders(client_.get()); }
745
CheckResponse(QuicTestClient * client,const std::string & received_response,const std::string & expected_response)746 bool CheckResponse(QuicTestClient* client,
747 const std::string& received_response,
748 const std::string& expected_response) {
749 EXPECT_THAT(client_->stream_error(), IsQuicStreamNoError());
750 EXPECT_THAT(client_->connection_error(), IsQuicNoError());
751
752 if (received_response.empty() && !expected_response.empty()) {
753 ADD_FAILURE() << "Failed to get any response for request";
754 return false;
755 }
756 if (received_response != expected_response) {
757 ADD_FAILURE() << "Got wrong response: \"" << received_response << "\"";
758 return false;
759 }
760 return CheckResponseHeaders(client);
761 }
762
SendSynchronousRequestAndCheckResponse(QuicTestClient * client,const std::string & request,const std::string & expected_response)763 bool SendSynchronousRequestAndCheckResponse(
764 QuicTestClient* client, const std::string& request,
765 const std::string& expected_response) {
766 std::string received_response = client->SendSynchronousRequest(request);
767 return CheckResponse(client, received_response, expected_response);
768 }
769
SendSynchronousRequestAndCheckResponse(const std::string & request,const std::string & expected_response)770 bool SendSynchronousRequestAndCheckResponse(
771 const std::string& request, const std::string& expected_response) {
772 return SendSynchronousRequestAndCheckResponse(client_.get(), request,
773 expected_response);
774 }
775
SendSynchronousFooRequestAndCheckResponse(QuicTestClient * client)776 bool SendSynchronousFooRequestAndCheckResponse(QuicTestClient* client) {
777 return SendSynchronousRequestAndCheckResponse(client, "/foo",
778 kFooResponseBody);
779 }
780
SendSynchronousFooRequestAndCheckResponse()781 bool SendSynchronousFooRequestAndCheckResponse() {
782 return SendSynchronousFooRequestAndCheckResponse(client_.get());
783 }
784
SendSynchronousBarRequestAndCheckResponse()785 bool SendSynchronousBarRequestAndCheckResponse() {
786 std::string received_response = client_->SendSynchronousRequest("/bar");
787 return CheckResponse(client_.get(), received_response, kBarResponseBody);
788 }
789
WaitForFooResponseAndCheckIt(QuicTestClient * client)790 bool WaitForFooResponseAndCheckIt(QuicTestClient* client) {
791 client->WaitForResponse();
792 std::string received_response = client->response_body();
793 return CheckResponse(client_.get(), received_response, kFooResponseBody);
794 }
795
WaitForFooResponseAndCheckIt()796 bool WaitForFooResponseAndCheckIt() {
797 return WaitForFooResponseAndCheckIt(client_.get());
798 }
799
CreateWebTransportSession(const std::string & path,bool wait_for_server_response,QuicSpdyStream ** connect_stream_out=nullptr)800 WebTransportHttp3* CreateWebTransportSession(
801 const std::string& path, bool wait_for_server_response,
802 QuicSpdyStream** connect_stream_out = nullptr) {
803 // Wait until we receive the settings from the server indicating
804 // WebTransport support.
805 client_->WaitUntil(
806 2000, [this]() { return GetClientSession()->SupportsWebTransport(); });
807 if (!GetClientSession()->SupportsWebTransport()) {
808 return nullptr;
809 }
810
811 spdy::Http2HeaderBlock headers;
812 headers[":scheme"] = "https";
813 headers[":authority"] = "localhost";
814 headers[":path"] = path;
815 headers[":method"] = "CONNECT";
816 headers[":protocol"] = "webtransport";
817
818 client_->SendMessage(headers, "", /*fin=*/false);
819 QuicSpdyStream* stream = client_->latest_created_stream();
820 if (stream->web_transport() == nullptr) {
821 return nullptr;
822 }
823 WebTransportSessionId id = client_->latest_created_stream()->id();
824 QuicSpdySession* client_session = GetClientSession();
825 if (client_session->GetWebTransportSession(id) == nullptr) {
826 return nullptr;
827 }
828 WebTransportHttp3* session = client_session->GetWebTransportSession(id);
829 if (wait_for_server_response) {
830 client_->WaitUntil(-1,
831 [stream]() { return stream->headers_decompressed(); });
832 EXPECT_TRUE(session->ready());
833 }
834 if (connect_stream_out != nullptr) {
835 *connect_stream_out = stream;
836 }
837 return session;
838 }
839
SetupWebTransportVisitor(WebTransportHttp3 * session)840 NiceMock<MockWebTransportSessionVisitor>& SetupWebTransportVisitor(
841 WebTransportHttp3* session) {
842 auto visitor_owned =
843 std::make_unique<NiceMock<MockWebTransportSessionVisitor>>();
844 NiceMock<MockWebTransportSessionVisitor>& visitor = *visitor_owned;
845 session->SetVisitor(std::move(visitor_owned));
846 return visitor;
847 }
848
ReadDataFromWebTransportStreamUntilFin(WebTransportStream * stream,MockWebTransportStreamVisitor * visitor=nullptr)849 std::string ReadDataFromWebTransportStreamUntilFin(
850 WebTransportStream* stream,
851 MockWebTransportStreamVisitor* visitor = nullptr) {
852 QuicStreamId id = stream->GetStreamId();
853 std::string buffer;
854
855 // Try reading data if immediately available.
856 WebTransportStream::ReadResult result = stream->Read(&buffer);
857 if (result.fin) {
858 return buffer;
859 }
860
861 while (true) {
862 bool can_read = false;
863 if (visitor == nullptr) {
864 auto visitor_owned = std::make_unique<MockWebTransportStreamVisitor>();
865 visitor = visitor_owned.get();
866 stream->SetVisitor(std::move(visitor_owned));
867 }
868 EXPECT_CALL(*visitor, OnCanRead())
869 .WillRepeatedly(Assign(&can_read, true));
870 client_->WaitUntil(5000 /*ms*/, [&can_read]() { return can_read; });
871 if (!can_read) {
872 ADD_FAILURE() << "Waiting for readable data on stream " << id
873 << " timed out";
874 return buffer;
875 }
876 if (GetClientSession()->GetOrCreateSpdyDataStream(id) == nullptr) {
877 ADD_FAILURE() << "Stream " << id
878 << " was deleted while waiting for incoming data";
879 return buffer;
880 }
881
882 result = stream->Read(&buffer);
883 if (result.fin) {
884 return buffer;
885 }
886 if (result.bytes_read == 0) {
887 ADD_FAILURE() << "No progress made while reading from stream "
888 << stream->GetStreamId();
889 return buffer;
890 }
891 }
892 }
893
ReadAllIncomingWebTransportUnidirectionalStreams(WebTransportSession * session)894 void ReadAllIncomingWebTransportUnidirectionalStreams(
895 WebTransportSession* session) {
896 while (true) {
897 WebTransportStream* received_stream =
898 session->AcceptIncomingUnidirectionalStream();
899 if (received_stream == nullptr) {
900 break;
901 }
902 received_webtransport_unidirectional_streams_.push_back(
903 ReadDataFromWebTransportStreamUntilFin(received_stream));
904 }
905 }
906
WaitForNewConnectionIds()907 void WaitForNewConnectionIds() {
908 // Wait until a new server CID is available for another migration.
909 const auto* client_connection = GetClientConnection();
910 while (!QuicConnectionPeer::HasUnusedPeerIssuedConnectionId(
911 client_connection) ||
912 (!client_connection->client_connection_id().IsEmpty() &&
913 !QuicConnectionPeer::HasSelfIssuedConnectionIdToConsume(
914 client_connection))) {
915 client_->client()->WaitForEvents();
916 }
917 }
918
919 quiche::test::ScopedEnvironmentForThreads environment_;
920 bool initialized_;
921 // If true, the Initialize() function will create |client_| and starts to
922 // connect to the server.
923 // Default is true.
924 bool connect_to_server_on_initialize_;
925 QuicSocketAddress server_address_;
926 std::optional<QuicSocketAddress> server_listening_address_;
927 std::string server_hostname_;
928 QuicTestBackend memory_cache_backend_;
929 std::unique_ptr<ServerThread> server_thread_;
930 // This socket keeps the ephemeral port reserved so that the kernel doesn't
931 // give it away while the server is shut down.
932 QuicUdpSocketFd fd_;
933 std::unique_ptr<QuicTestClient> client_;
934 QuicConnectionDebugVisitor* connection_debug_visitor_ = nullptr;
935 PacketDroppingTestWriter* client_writer_;
936 PacketDroppingTestWriter* server_writer_;
937 QuicConfig client_config_;
938 QuicConfig server_config_;
939 ParsedQuicVersion version_;
940 ParsedQuicVersionVector client_supported_versions_;
941 ParsedQuicVersionVector server_supported_versions_;
942 QuicTagVector client_extra_copts_;
943 size_t chlo_multiplier_;
944 QuicTestServer::StreamFactory* stream_factory_;
945 std::string pre_shared_key_client_;
946 std::string pre_shared_key_server_;
947 int override_server_connection_id_length_;
948 int override_client_connection_id_length_ = -1;
949 uint8_t expected_server_connection_id_length_;
950 bool enable_web_transport_ = false;
951 std::vector<std::string> received_webtransport_unidirectional_streams_;
952 bool use_preferred_address_ = false;
953 QuicSocketAddress server_preferred_address_;
954 QuicPacketWriterParams packet_writer_params_;
955 };
956
957 // Run all end to end tests with all supported versions.
958 INSTANTIATE_TEST_SUITE_P(EndToEndTests, EndToEndTest,
959 ::testing::ValuesIn(GetTestParams()),
960 ::testing::PrintToStringParamName());
961
TEST_P(EndToEndTest,HandshakeSuccessful)962 TEST_P(EndToEndTest, HandshakeSuccessful) {
963 ASSERT_TRUE(Initialize());
964 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
965 ASSERT_TRUE(server_thread_);
966 server_thread_->WaitForCryptoHandshakeConfirmed();
967 QuicSpdyClientSession* client_session = GetClientSession();
968 ASSERT_TRUE(client_session);
969 QuicCryptoStream* client_crypto_stream =
970 QuicSessionPeer::GetMutableCryptoStream(client_session);
971 ASSERT_TRUE(client_crypto_stream);
972 QuicStreamSequencer* client_sequencer =
973 QuicStreamPeer::sequencer(client_crypto_stream);
974 ASSERT_TRUE(client_sequencer);
975 EXPECT_FALSE(
976 QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(client_sequencer));
977
978 // We've had bugs in the past where the connections could end up on the wrong
979 // version. This was never diagnosed but could have been due to in-connection
980 // version negotiation back when that existed. At this point in time, our test
981 // setup ensures that connections here always use |version_|, but we add this
982 // sanity check out of paranoia to catch a regression of this type.
983 QuicConnection* client_connection = GetClientConnection();
984 ASSERT_TRUE(client_connection);
985 EXPECT_EQ(client_connection->version(), version_);
986
987 server_thread_->Pause();
988 QuicSpdySession* server_session = GetServerSession();
989 QuicConnection* server_connection = nullptr;
990 QuicCryptoStream* server_crypto_stream = nullptr;
991 QuicStreamSequencer* server_sequencer = nullptr;
992 if (server_session != nullptr) {
993 server_connection = server_session->connection();
994 server_crypto_stream =
995 QuicSessionPeer::GetMutableCryptoStream(server_session);
996 } else {
997 ADD_FAILURE() << "Missing server session";
998 }
999 if (server_crypto_stream != nullptr) {
1000 server_sequencer = QuicStreamPeer::sequencer(server_crypto_stream);
1001 } else {
1002 ADD_FAILURE() << "Missing server crypto stream";
1003 }
1004 if (server_sequencer != nullptr) {
1005 EXPECT_FALSE(
1006 QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(server_sequencer));
1007 } else {
1008 ADD_FAILURE() << "Missing server sequencer";
1009 }
1010 if (server_connection != nullptr) {
1011 EXPECT_EQ(server_connection->version(), version_);
1012 } else {
1013 ADD_FAILURE() << "Missing server connection";
1014 }
1015 server_thread_->Resume();
1016 }
1017
TEST_P(EndToEndTest,ExportKeyingMaterial)1018 TEST_P(EndToEndTest, ExportKeyingMaterial) {
1019 ASSERT_TRUE(Initialize());
1020 if (!version_.UsesTls()) {
1021 return;
1022 }
1023 const char* kExportLabel = "label";
1024 const int kExportLen = 30;
1025 std::string client_keying_material_export, server_keying_material_export;
1026
1027 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1028 ASSERT_TRUE(server_thread_);
1029 server_thread_->WaitForCryptoHandshakeConfirmed();
1030
1031 server_thread_->Pause();
1032 QuicSpdySession* server_session = GetServerSession();
1033 QuicCryptoStream* server_crypto_stream = nullptr;
1034 if (server_session != nullptr) {
1035 server_crypto_stream =
1036 QuicSessionPeer::GetMutableCryptoStream(server_session);
1037 } else {
1038 ADD_FAILURE() << "Missing server session";
1039 }
1040 if (server_crypto_stream != nullptr) {
1041 ASSERT_TRUE(server_crypto_stream->ExportKeyingMaterial(
1042 kExportLabel, /*context=*/"", kExportLen,
1043 &server_keying_material_export));
1044
1045 } else {
1046 ADD_FAILURE() << "Missing server crypto stream";
1047 }
1048 server_thread_->Resume();
1049
1050 QuicSpdyClientSession* client_session = GetClientSession();
1051 ASSERT_TRUE(client_session);
1052 QuicCryptoStream* client_crypto_stream =
1053 QuicSessionPeer::GetMutableCryptoStream(client_session);
1054 ASSERT_TRUE(client_crypto_stream);
1055 ASSERT_TRUE(client_crypto_stream->ExportKeyingMaterial(
1056 kExportLabel, /*context=*/"", kExportLen,
1057 &client_keying_material_export));
1058 ASSERT_EQ(client_keying_material_export.size(),
1059 static_cast<size_t>(kExportLen));
1060 EXPECT_EQ(client_keying_material_export, server_keying_material_export);
1061 }
1062
TEST_P(EndToEndTest,SimpleRequestResponse)1063 TEST_P(EndToEndTest, SimpleRequestResponse) {
1064 ASSERT_TRUE(Initialize());
1065
1066 SendSynchronousFooRequestAndCheckResponse();
1067 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1068 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1069 if (version_.UsesHttp3()) {
1070 QuicSpdyClientSession* client_session = GetClientSession();
1071 ASSERT_TRUE(client_session);
1072 EXPECT_TRUE(QuicSpdySessionPeer::GetSendControlStream(client_session));
1073 EXPECT_TRUE(QuicSpdySessionPeer::GetReceiveControlStream(client_session));
1074 server_thread_->Pause();
1075 QuicSpdySession* server_session = GetServerSession();
1076 if (server_session != nullptr) {
1077 EXPECT_TRUE(QuicSpdySessionPeer::GetSendControlStream(server_session));
1078 EXPECT_TRUE(QuicSpdySessionPeer::GetReceiveControlStream(server_session));
1079 } else {
1080 ADD_FAILURE() << "Missing server session";
1081 }
1082 server_thread_->Resume();
1083 }
1084 QuicConnectionStats client_stats = GetClientConnection()->GetStats();
1085 EXPECT_TRUE(client_stats.handshake_completion_time.IsInitialized());
1086 }
1087
TEST_P(EndToEndTest,HandshakeConfirmed)1088 TEST_P(EndToEndTest, HandshakeConfirmed) {
1089 ASSERT_TRUE(Initialize());
1090 if (!version_.UsesTls()) {
1091 return;
1092 }
1093 SendSynchronousFooRequestAndCheckResponse();
1094 // Verify handshake state.
1095 QuicSpdyClientSession* client_session = GetClientSession();
1096 ASSERT_TRUE(client_session);
1097 EXPECT_EQ(HANDSHAKE_CONFIRMED, client_session->GetHandshakeState());
1098 server_thread_->Pause();
1099 QuicSpdySession* server_session = GetServerSession();
1100 if (server_session != nullptr) {
1101 EXPECT_EQ(HANDSHAKE_CONFIRMED, server_session->GetHandshakeState());
1102 } else {
1103 ADD_FAILURE() << "Missing server session";
1104 }
1105 server_thread_->Resume();
1106 client_->Disconnect();
1107 }
1108
TEST_P(EndToEndTest,SendAndReceiveCoalescedPackets)1109 TEST_P(EndToEndTest, SendAndReceiveCoalescedPackets) {
1110 ASSERT_TRUE(Initialize());
1111 if (!version_.CanSendCoalescedPackets()) {
1112 return;
1113 }
1114 SendSynchronousFooRequestAndCheckResponse();
1115 // Verify client successfully processes coalesced packets.
1116 QuicConnection* client_connection = GetClientConnection();
1117 ASSERT_TRUE(client_connection);
1118 QuicConnectionStats client_stats = client_connection->GetStats();
1119 EXPECT_LT(0u, client_stats.num_coalesced_packets_received);
1120 EXPECT_EQ(client_stats.num_coalesced_packets_processed,
1121 client_stats.num_coalesced_packets_received);
1122 // TODO(fayang): verify server successfully processes coalesced packets.
1123 }
1124
1125 // Simple transaction, but set a non-default ack delay at the client
1126 // and ensure it gets to the server.
TEST_P(EndToEndTest,SimpleRequestResponseWithAckDelayChange)1127 TEST_P(EndToEndTest, SimpleRequestResponseWithAckDelayChange) {
1128 // Force the ACK delay to be something other than the default.
1129 constexpr uint32_t kClientMaxAckDelay = kDefaultDelayedAckTimeMs + 100u;
1130 client_config_.SetMaxAckDelayToSendMs(kClientMaxAckDelay);
1131 ASSERT_TRUE(Initialize());
1132
1133 SendSynchronousFooRequestAndCheckResponse();
1134 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1135 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1136
1137 server_thread_->Pause();
1138 const QuicSentPacketManager* server_sent_packet_manager =
1139 GetSentPacketManagerFromFirstServerSession();
1140 if (server_sent_packet_manager != nullptr) {
1141 EXPECT_EQ(
1142 kClientMaxAckDelay,
1143 server_sent_packet_manager->peer_max_ack_delay().ToMilliseconds());
1144 } else {
1145 ADD_FAILURE() << "Missing server sent packet manager";
1146 }
1147 server_thread_->Resume();
1148 }
1149
1150 // Simple transaction, but set a non-default ack exponent at the client
1151 // and ensure it gets to the server.
TEST_P(EndToEndTest,SimpleRequestResponseWithAckExponentChange)1152 TEST_P(EndToEndTest, SimpleRequestResponseWithAckExponentChange) {
1153 const uint32_t kClientAckDelayExponent = 19;
1154 EXPECT_NE(kClientAckDelayExponent, kDefaultAckDelayExponent);
1155 // Force the ACK exponent to be something other than the default.
1156 // Note that it is sent only with QUIC+TLS.
1157 client_config_.SetAckDelayExponentToSend(kClientAckDelayExponent);
1158 ASSERT_TRUE(Initialize());
1159
1160 SendSynchronousFooRequestAndCheckResponse();
1161
1162 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1163 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1164 server_thread_->Pause();
1165 QuicConnection* server_connection = GetServerConnection();
1166 if (server_connection != nullptr) {
1167 if (version_.UsesTls()) {
1168 // Should be only sent with QUIC+TLS.
1169 EXPECT_EQ(kClientAckDelayExponent,
1170 server_connection->framer().peer_ack_delay_exponent());
1171 } else {
1172 // No change for QUIC_CRYPTO.
1173 EXPECT_EQ(kDefaultAckDelayExponent,
1174 server_connection->framer().peer_ack_delay_exponent());
1175 }
1176 // No change, regardless of version.
1177 EXPECT_EQ(kDefaultAckDelayExponent,
1178 server_connection->framer().local_ack_delay_exponent());
1179 } else {
1180 ADD_FAILURE() << "Missing server connection";
1181 }
1182 server_thread_->Resume();
1183 }
1184
TEST_P(EndToEndTest,SimpleRequestResponseForcedVersionNegotiation)1185 TEST_P(EndToEndTest, SimpleRequestResponseForcedVersionNegotiation) {
1186 client_supported_versions_.insert(client_supported_versions_.begin(),
1187 QuicVersionReservedForNegotiation());
1188 NiceMock<MockQuicConnectionDebugVisitor> visitor;
1189 connection_debug_visitor_ = &visitor;
1190 EXPECT_CALL(visitor, OnVersionNegotiationPacket(_)).Times(1);
1191 ASSERT_TRUE(Initialize());
1192 ASSERT_TRUE(ServerSendsVersionNegotiation());
1193
1194 SendSynchronousFooRequestAndCheckResponse();
1195
1196 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1197 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1198 }
1199
TEST_P(EndToEndTest,ForcedVersionNegotiation)1200 TEST_P(EndToEndTest, ForcedVersionNegotiation) {
1201 client_supported_versions_.insert(client_supported_versions_.begin(),
1202 QuicVersionReservedForNegotiation());
1203 ASSERT_TRUE(Initialize());
1204 ASSERT_TRUE(ServerSendsVersionNegotiation());
1205
1206 SendSynchronousFooRequestAndCheckResponse();
1207 }
1208
TEST_P(EndToEndTest,SimpleRequestResponseZeroConnectionID)1209 TEST_P(EndToEndTest, SimpleRequestResponseZeroConnectionID) {
1210 if (!version_.AllowsVariableLengthConnectionIds() ||
1211 override_server_connection_id_length_ > -1) {
1212 ASSERT_TRUE(Initialize());
1213 return;
1214 }
1215 override_server_connection_id_length_ = 0;
1216 expected_server_connection_id_length_ = 0;
1217 ASSERT_TRUE(Initialize());
1218
1219 SendSynchronousFooRequestAndCheckResponse();
1220 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1221 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1222 QuicConnection* client_connection = GetClientConnection();
1223 ASSERT_TRUE(client_connection);
1224 EXPECT_EQ(client_connection->connection_id(),
1225 QuicUtils::CreateZeroConnectionId(version_.transport_version));
1226 }
1227
TEST_P(EndToEndTest,ZeroConnectionID)1228 TEST_P(EndToEndTest, ZeroConnectionID) {
1229 if (!version_.AllowsVariableLengthConnectionIds() ||
1230 override_server_connection_id_length_ > -1) {
1231 ASSERT_TRUE(Initialize());
1232 return;
1233 }
1234 override_server_connection_id_length_ = 0;
1235 expected_server_connection_id_length_ = 0;
1236 ASSERT_TRUE(Initialize());
1237
1238 SendSynchronousFooRequestAndCheckResponse();
1239 QuicConnection* client_connection = GetClientConnection();
1240 ASSERT_TRUE(client_connection);
1241 EXPECT_EQ(client_connection->connection_id(),
1242 QuicUtils::CreateZeroConnectionId(version_.transport_version));
1243 }
1244
TEST_P(EndToEndTest,BadConnectionIdLength)1245 TEST_P(EndToEndTest, BadConnectionIdLength) {
1246 if (!version_.AllowsVariableLengthConnectionIds() ||
1247 override_server_connection_id_length_ > -1) {
1248 ASSERT_TRUE(Initialize());
1249 return;
1250 }
1251 override_server_connection_id_length_ = 9;
1252 ASSERT_TRUE(Initialize());
1253 SendSynchronousFooRequestAndCheckResponse();
1254 EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
1255 ->client_session()
1256 ->connection()
1257 ->connection_id()
1258 .length());
1259 }
1260
TEST_P(EndToEndTest,ClientConnectionId)1261 TEST_P(EndToEndTest, ClientConnectionId) {
1262 if (!version_.SupportsClientConnectionIds()) {
1263 ASSERT_TRUE(Initialize());
1264 return;
1265 }
1266 override_client_connection_id_length_ = kQuicDefaultConnectionIdLength;
1267 ASSERT_TRUE(Initialize());
1268 SendSynchronousFooRequestAndCheckResponse();
1269 EXPECT_EQ(override_client_connection_id_length_, client_->client()
1270 ->client_session()
1271 ->connection()
1272 ->client_connection_id()
1273 .length());
1274 }
1275
TEST_P(EndToEndTest,ForcedVersionNegotiationAndClientConnectionId)1276 TEST_P(EndToEndTest, ForcedVersionNegotiationAndClientConnectionId) {
1277 if (!version_.SupportsClientConnectionIds()) {
1278 ASSERT_TRUE(Initialize());
1279 return;
1280 }
1281 client_supported_versions_.insert(client_supported_versions_.begin(),
1282 QuicVersionReservedForNegotiation());
1283 override_client_connection_id_length_ = kQuicDefaultConnectionIdLength;
1284 ASSERT_TRUE(Initialize());
1285 ASSERT_TRUE(ServerSendsVersionNegotiation());
1286 SendSynchronousFooRequestAndCheckResponse();
1287 EXPECT_EQ(override_client_connection_id_length_, client_->client()
1288 ->client_session()
1289 ->connection()
1290 ->client_connection_id()
1291 .length());
1292 }
1293
TEST_P(EndToEndTest,ForcedVersionNegotiationAndBadConnectionIdLength)1294 TEST_P(EndToEndTest, ForcedVersionNegotiationAndBadConnectionIdLength) {
1295 if (!version_.AllowsVariableLengthConnectionIds() ||
1296 override_server_connection_id_length_ > -1) {
1297 ASSERT_TRUE(Initialize());
1298 return;
1299 }
1300 client_supported_versions_.insert(client_supported_versions_.begin(),
1301 QuicVersionReservedForNegotiation());
1302 override_server_connection_id_length_ = 9;
1303 ASSERT_TRUE(Initialize());
1304 ASSERT_TRUE(ServerSendsVersionNegotiation());
1305 SendSynchronousFooRequestAndCheckResponse();
1306 EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
1307 ->client_session()
1308 ->connection()
1309 ->connection_id()
1310 .length());
1311 }
1312
1313 // Forced Version Negotiation with a client connection ID and a long
1314 // connection ID.
TEST_P(EndToEndTest,ForcedVersNegoAndClientCIDAndLongCID)1315 TEST_P(EndToEndTest, ForcedVersNegoAndClientCIDAndLongCID) {
1316 if (!version_.SupportsClientConnectionIds() ||
1317 !version_.AllowsVariableLengthConnectionIds() ||
1318 override_server_connection_id_length_ != kLongConnectionIdLength) {
1319 ASSERT_TRUE(Initialize());
1320 return;
1321 }
1322 client_supported_versions_.insert(client_supported_versions_.begin(),
1323 QuicVersionReservedForNegotiation());
1324 override_client_connection_id_length_ = 18;
1325 ASSERT_TRUE(Initialize());
1326 ASSERT_TRUE(ServerSendsVersionNegotiation());
1327 SendSynchronousFooRequestAndCheckResponse();
1328 EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
1329 ->client_session()
1330 ->connection()
1331 ->connection_id()
1332 .length());
1333 EXPECT_EQ(override_client_connection_id_length_, client_->client()
1334 ->client_session()
1335 ->connection()
1336 ->client_connection_id()
1337 .length());
1338 }
1339
TEST_P(EndToEndTest,MixGoodAndBadConnectionIdLengths)1340 TEST_P(EndToEndTest, MixGoodAndBadConnectionIdLengths) {
1341 if (!version_.AllowsVariableLengthConnectionIds() ||
1342 override_server_connection_id_length_ > -1) {
1343 ASSERT_TRUE(Initialize());
1344 return;
1345 }
1346
1347 // Start client_ which will use a bad connection ID length.
1348 override_server_connection_id_length_ = 9;
1349 ASSERT_TRUE(Initialize());
1350 override_server_connection_id_length_ = -1;
1351
1352 // Start client2 which will use a good connection ID length.
1353 std::unique_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
1354 Http2HeaderBlock headers;
1355 headers[":method"] = "POST";
1356 headers[":path"] = "/foo";
1357 headers[":scheme"] = "https";
1358 headers[":authority"] = server_hostname_;
1359 headers["content-length"] = "3";
1360 client2->SendMessage(headers, "", /*fin=*/false);
1361 client2->SendData("eep", true);
1362
1363 SendSynchronousFooRequestAndCheckResponse();
1364 EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
1365 ->client_session()
1366 ->connection()
1367 ->connection_id()
1368 .length());
1369
1370 WaitForFooResponseAndCheckIt(client2.get());
1371 EXPECT_EQ(kQuicDefaultConnectionIdLength, client2->client()
1372 ->client_session()
1373 ->connection()
1374 ->connection_id()
1375 .length());
1376 }
1377
TEST_P(EndToEndTest,SimpleRequestResponseWithLargeReject)1378 TEST_P(EndToEndTest, SimpleRequestResponseWithLargeReject) {
1379 chlo_multiplier_ = 1;
1380 ASSERT_TRUE(Initialize());
1381
1382 SendSynchronousFooRequestAndCheckResponse();
1383 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1384 if (version_.UsesTls()) {
1385 // REJ messages are a QUIC crypto feature, so TLS always returns false.
1386 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1387 } else {
1388 EXPECT_TRUE(client_->client()->ReceivedInchoateReject());
1389 }
1390 }
1391
TEST_P(EndToEndTest,SimpleRequestResponsev6)1392 TEST_P(EndToEndTest, SimpleRequestResponsev6) {
1393 server_address_ =
1394 QuicSocketAddress(QuicIpAddress::Loopback6(), server_address_.port());
1395 ASSERT_TRUE(Initialize());
1396
1397 SendSynchronousFooRequestAndCheckResponse();
1398 }
1399
TEST_P(EndToEndTest,ClientDoesNotAllowServerDataOnServerInitiatedBidirectionalStreams)1400 TEST_P(EndToEndTest,
1401 ClientDoesNotAllowServerDataOnServerInitiatedBidirectionalStreams) {
1402 set_client_initial_max_stream_data_incoming_bidirectional(0);
1403 ASSERT_TRUE(Initialize());
1404 SendSynchronousFooRequestAndCheckResponse();
1405 }
1406
TEST_P(EndToEndTest,ServerDoesNotAllowClientDataOnServerInitiatedBidirectionalStreams)1407 TEST_P(EndToEndTest,
1408 ServerDoesNotAllowClientDataOnServerInitiatedBidirectionalStreams) {
1409 set_server_initial_max_stream_data_outgoing_bidirectional(0);
1410 ASSERT_TRUE(Initialize());
1411 SendSynchronousFooRequestAndCheckResponse();
1412 }
1413
TEST_P(EndToEndTest,BothEndpointsDisallowDataOnServerInitiatedBidirectionalStreams)1414 TEST_P(EndToEndTest,
1415 BothEndpointsDisallowDataOnServerInitiatedBidirectionalStreams) {
1416 set_client_initial_max_stream_data_incoming_bidirectional(0);
1417 set_server_initial_max_stream_data_outgoing_bidirectional(0);
1418 ASSERT_TRUE(Initialize());
1419 SendSynchronousFooRequestAndCheckResponse();
1420 }
1421
1422 // Regression test for a bug where we would always fail to decrypt the first
1423 // initial packet. Undecryptable packets can be seen after the handshake
1424 // is complete due to dropping the initial keys at that point, so we only test
1425 // for undecryptable packets before then.
TEST_P(EndToEndTest,NoUndecryptablePacketsBeforeHandshakeComplete)1426 TEST_P(EndToEndTest, NoUndecryptablePacketsBeforeHandshakeComplete) {
1427 ASSERT_TRUE(Initialize());
1428
1429 SendSynchronousFooRequestAndCheckResponse();
1430
1431 QuicConnection* client_connection = GetClientConnection();
1432 ASSERT_TRUE(client_connection);
1433 QuicConnectionStats client_stats = client_connection->GetStats();
1434 EXPECT_EQ(
1435 0u,
1436 client_stats.undecryptable_packets_received_before_handshake_complete);
1437
1438 server_thread_->Pause();
1439 QuicConnection* server_connection = GetServerConnection();
1440 if (server_connection != nullptr) {
1441 QuicConnectionStats server_stats = server_connection->GetStats();
1442 EXPECT_EQ(
1443 0u,
1444 server_stats.undecryptable_packets_received_before_handshake_complete);
1445 } else {
1446 ADD_FAILURE() << "Missing server connection";
1447 }
1448 server_thread_->Resume();
1449 }
1450
TEST_P(EndToEndTest,SeparateFinPacket)1451 TEST_P(EndToEndTest, SeparateFinPacket) {
1452 ASSERT_TRUE(Initialize());
1453
1454 // Send a request in two parts: the request and then an empty packet with FIN.
1455 Http2HeaderBlock headers;
1456 headers[":method"] = "POST";
1457 headers[":path"] = "/foo";
1458 headers[":scheme"] = "https";
1459 headers[":authority"] = server_hostname_;
1460 client_->SendMessage(headers, "", /*fin=*/false);
1461 client_->SendData("", true);
1462 WaitForFooResponseAndCheckIt();
1463
1464 // Now do the same thing but with a content length.
1465 headers["content-length"] = "3";
1466 client_->SendMessage(headers, "", /*fin=*/false);
1467 client_->SendData("foo", true);
1468 WaitForFooResponseAndCheckIt();
1469 }
1470
TEST_P(EndToEndTest,MultipleRequestResponse)1471 TEST_P(EndToEndTest, MultipleRequestResponse) {
1472 ASSERT_TRUE(Initialize());
1473
1474 SendSynchronousFooRequestAndCheckResponse();
1475 SendSynchronousBarRequestAndCheckResponse();
1476 }
1477
TEST_P(EndToEndTest,MultipleRequestResponseZeroConnectionID)1478 TEST_P(EndToEndTest, MultipleRequestResponseZeroConnectionID) {
1479 if (!version_.AllowsVariableLengthConnectionIds() ||
1480 override_server_connection_id_length_ > -1) {
1481 ASSERT_TRUE(Initialize());
1482 return;
1483 }
1484 override_server_connection_id_length_ = 0;
1485 expected_server_connection_id_length_ = 0;
1486 ASSERT_TRUE(Initialize());
1487
1488 SendSynchronousFooRequestAndCheckResponse();
1489 SendSynchronousBarRequestAndCheckResponse();
1490 }
1491
TEST_P(EndToEndTest,MultipleStreams)1492 TEST_P(EndToEndTest, MultipleStreams) {
1493 // Verifies quic_test_client can track responses of all active streams.
1494 ASSERT_TRUE(Initialize());
1495
1496 const int kNumRequests = 10;
1497
1498 Http2HeaderBlock headers;
1499 headers[":method"] = "POST";
1500 headers[":path"] = "/foo";
1501 headers[":scheme"] = "https";
1502 headers[":authority"] = server_hostname_;
1503 headers["content-length"] = "3";
1504
1505 for (int i = 0; i < kNumRequests; ++i) {
1506 client_->SendMessage(headers, "bar", /*fin=*/true);
1507 }
1508
1509 while (kNumRequests > client_->num_responses()) {
1510 client_->ClearPerRequestState();
1511 ASSERT_TRUE(WaitForFooResponseAndCheckIt());
1512 }
1513 }
1514
TEST_P(EndToEndTest,MultipleClients)1515 TEST_P(EndToEndTest, MultipleClients) {
1516 ASSERT_TRUE(Initialize());
1517 std::unique_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
1518
1519 Http2HeaderBlock headers;
1520 headers[":method"] = "POST";
1521 headers[":path"] = "/foo";
1522 headers[":scheme"] = "https";
1523 headers[":authority"] = server_hostname_;
1524 headers["content-length"] = "3";
1525
1526 client_->SendMessage(headers, "", /*fin=*/false);
1527 client2->SendMessage(headers, "", /*fin=*/false);
1528
1529 client_->SendData("bar", true);
1530 WaitForFooResponseAndCheckIt();
1531
1532 client2->SendData("eep", true);
1533 WaitForFooResponseAndCheckIt(client2.get());
1534 }
1535
TEST_P(EndToEndTest,RequestOverMultiplePackets)1536 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
1537 // Send a large enough request to guarantee fragmentation.
1538 std::string huge_request =
1539 "/some/path?query=" + std::string(kMaxOutgoingPacketSize, '.');
1540 AddToCache(huge_request, 200, kBarResponseBody);
1541
1542 ASSERT_TRUE(Initialize());
1543
1544 SendSynchronousRequestAndCheckResponse(huge_request, kBarResponseBody);
1545 }
1546
TEST_P(EndToEndTest,MultiplePacketsRandomOrder)1547 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
1548 // Send a large enough request to guarantee fragmentation.
1549 std::string huge_request =
1550 "/some/path?query=" + std::string(kMaxOutgoingPacketSize, '.');
1551 AddToCache(huge_request, 200, kBarResponseBody);
1552
1553 ASSERT_TRUE(Initialize());
1554 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
1555 SetReorderPercentage(50);
1556
1557 SendSynchronousRequestAndCheckResponse(huge_request, kBarResponseBody);
1558 }
1559
TEST_P(EndToEndTest,PostMissingBytes)1560 TEST_P(EndToEndTest, PostMissingBytes) {
1561 ASSERT_TRUE(Initialize());
1562
1563 // Add a content length header with no body.
1564 Http2HeaderBlock headers;
1565 headers[":method"] = "POST";
1566 headers[":path"] = "/foo";
1567 headers[":scheme"] = "https";
1568 headers[":authority"] = server_hostname_;
1569 headers["content-length"] = "3";
1570
1571 // This should be detected as stream fin without complete request,
1572 // triggering an error response.
1573 client_->SendCustomSynchronousRequest(headers, "");
1574 EXPECT_EQ(QuicSimpleServerStream::kErrorResponseBody,
1575 client_->response_body());
1576 CheckResponseHeaders("500");
1577 }
1578
TEST_P(EndToEndTest,LargePostNoPacketLoss)1579 TEST_P(EndToEndTest, LargePostNoPacketLoss) {
1580 ASSERT_TRUE(Initialize());
1581
1582 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1583
1584 // 1 MB body.
1585 std::string body(1024 * 1024, 'a');
1586 Http2HeaderBlock headers;
1587 headers[":method"] = "POST";
1588 headers[":path"] = "/foo";
1589 headers[":scheme"] = "https";
1590 headers[":authority"] = server_hostname_;
1591
1592 EXPECT_EQ(kFooResponseBody,
1593 client_->SendCustomSynchronousRequest(headers, body));
1594 // TODO(ianswett): There should not be packet loss in this test, but on some
1595 // platforms the receive buffer overflows.
1596 VerifyCleanConnection(true);
1597 }
1598
1599 // Marked as slow since this adds a real-clock one second of delay.
TEST_P(EndToEndTest,QUICHE_SLOW_TEST (LargePostNoPacketLoss1sRTT))1600 TEST_P(EndToEndTest, QUICHE_SLOW_TEST(LargePostNoPacketLoss1sRTT)) {
1601 ASSERT_TRUE(Initialize());
1602 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
1603
1604 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1605
1606 // 100 KB body.
1607 std::string body(100 * 1024, 'a');
1608 Http2HeaderBlock headers;
1609 headers[":method"] = "POST";
1610 headers[":path"] = "/foo";
1611 headers[":scheme"] = "https";
1612 headers[":authority"] = server_hostname_;
1613
1614 EXPECT_EQ(kFooResponseBody,
1615 client_->SendCustomSynchronousRequest(headers, body));
1616 VerifyCleanConnection(false);
1617 }
1618
TEST_P(EndToEndTest,LargePostWithPacketLoss)1619 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
1620 // Connect with lower fake packet loss than we'd like to test.
1621 // Until b/10126687 is fixed, losing handshake packets is pretty
1622 // brutal.
1623 // Disable blackhole detection as this test is testing loss recovery.
1624 client_extra_copts_.push_back(kNBHD);
1625 SetPacketLossPercentage(5);
1626 ASSERT_TRUE(Initialize());
1627 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1628 SetPacketLossPercentage(30);
1629
1630 // 10 KB body.
1631 std::string body(1024 * 10, 'a');
1632 Http2HeaderBlock headers;
1633 headers[":method"] = "POST";
1634 headers[":path"] = "/foo";
1635 headers[":scheme"] = "https";
1636 headers[":authority"] = server_hostname_;
1637
1638 EXPECT_EQ(kFooResponseBody,
1639 client_->SendCustomSynchronousRequest(headers, body));
1640 if (override_server_connection_id_length_ == -1) {
1641 // If the client sends a longer connection ID, we can end up with dropped
1642 // packets. The packets_dropped counter increments whenever a packet arrives
1643 // with a new server connection ID that is not INITIAL, RETRY, or 1-RTT.
1644 // With packet losses, we could easily lose a server INITIAL and have the
1645 // first observed server packet be HANDSHAKE.
1646 VerifyCleanConnection(true);
1647 }
1648 }
1649
1650 // Regression test for b/80090281.
TEST_P(EndToEndTest,LargePostWithPacketLossAndAlwaysBundleWindowUpdates)1651 TEST_P(EndToEndTest, LargePostWithPacketLossAndAlwaysBundleWindowUpdates) {
1652 // Disable blackhole detection as this test is testing loss recovery.
1653 client_extra_copts_.push_back(kNBHD);
1654 ASSERT_TRUE(Initialize());
1655 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1656 server_thread_->WaitForCryptoHandshakeConfirmed();
1657
1658 // Normally server only bundles a retransmittable frame once every other
1659 // kMaxConsecutiveNonRetransmittablePackets ack-only packets. Setting the max
1660 // to 0 to reliably reproduce b/80090281.
1661 server_thread_->Schedule([this]() {
1662 QuicConnection* server_connection = GetServerConnection();
1663 if (server_connection != nullptr) {
1664 QuicConnectionPeer::
1665 SetMaxConsecutiveNumPacketsWithNoRetransmittableFrames(
1666 server_connection, 0);
1667 } else {
1668 ADD_FAILURE() << "Missing server connection";
1669 }
1670 });
1671
1672 SetPacketLossPercentage(30);
1673
1674 // 10 KB body.
1675 std::string body(1024 * 10, 'a');
1676 Http2HeaderBlock headers;
1677 headers[":method"] = "POST";
1678 headers[":path"] = "/foo";
1679 headers[":scheme"] = "https";
1680 headers[":authority"] = server_hostname_;
1681
1682 EXPECT_EQ(kFooResponseBody,
1683 client_->SendCustomSynchronousRequest(headers, body));
1684 VerifyCleanConnection(true);
1685 }
1686
TEST_P(EndToEndTest,LargePostWithPacketLossAndBlockedSocket)1687 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
1688 // Connect with lower fake packet loss than we'd like to test. Until
1689 // b/10126687 is fixed, losing handshake packets is pretty brutal.
1690 // Disable blackhole detection as this test is testing loss recovery.
1691 client_extra_copts_.push_back(kNBHD);
1692 SetPacketLossPercentage(5);
1693 ASSERT_TRUE(Initialize());
1694 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1695 SetPacketLossPercentage(10);
1696 client_writer_->set_fake_blocked_socket_percentage(10);
1697
1698 // 10 KB body.
1699 std::string body(1024 * 10, 'a');
1700 Http2HeaderBlock headers;
1701 headers[":method"] = "POST";
1702 headers[":path"] = "/foo";
1703 headers[":scheme"] = "https";
1704 headers[":authority"] = server_hostname_;
1705
1706 EXPECT_EQ(kFooResponseBody,
1707 client_->SendCustomSynchronousRequest(headers, body));
1708 }
1709
TEST_P(EndToEndTest,LargePostNoPacketLossWithDelayAndReordering)1710 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
1711 ASSERT_TRUE(Initialize());
1712 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1713 // Both of these must be called when the writer is not actively used.
1714 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
1715 SetReorderPercentage(30);
1716
1717 // 1 MB body.
1718 std::string body(1024 * 1024, 'a');
1719 Http2HeaderBlock headers;
1720 headers[":method"] = "POST";
1721 headers[":path"] = "/foo";
1722 headers[":scheme"] = "https";
1723 headers[":authority"] = server_hostname_;
1724
1725 EXPECT_EQ(kFooResponseBody,
1726 client_->SendCustomSynchronousRequest(headers, body));
1727 }
1728
1729 // TODO(b/214587920): make this test not rely on timeouts.
TEST_P(EndToEndTest,QUICHE_SLOW_TEST (AddressToken))1730 TEST_P(EndToEndTest, QUICHE_SLOW_TEST(AddressToken)) {
1731 client_config_.set_max_time_before_crypto_handshake(
1732 QuicTime::Delta::FromSeconds(3));
1733 client_config_.set_max_idle_time_before_crypto_handshake(
1734 QuicTime::Delta::FromSeconds(1));
1735
1736 client_extra_copts_.push_back(kTRTT);
1737 ASSERT_TRUE(Initialize());
1738 if (!version_.HasIetfQuicFrames()) {
1739 return;
1740 }
1741
1742 SendSynchronousFooRequestAndCheckResponse();
1743 QuicSpdyClientSession* client_session = GetClientSession();
1744 ASSERT_TRUE(client_session);
1745 EXPECT_FALSE(client_session->EarlyDataAccepted());
1746 EXPECT_FALSE(client_session->ReceivedInchoateReject());
1747 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1748 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1749
1750 client_->Disconnect();
1751
1752 // The 0-RTT handshake should succeed.
1753 client_->Connect();
1754 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1755 ASSERT_TRUE(client_->client()->connected());
1756 SendSynchronousFooRequestAndCheckResponse();
1757
1758 client_session = GetClientSession();
1759 ASSERT_TRUE(client_session);
1760 EXPECT_TRUE(client_session->EarlyDataAccepted());
1761 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1762
1763 server_thread_->Pause();
1764 QuicSpdySession* server_session = GetServerSession();
1765 QuicConnection* server_connection = GetServerConnection();
1766 if (server_session != nullptr && server_connection != nullptr) {
1767 // Verify address is validated via validating token received in INITIAL
1768 // packet.
1769 EXPECT_FALSE(
1770 server_connection->GetStats().address_validated_via_decrypting_packet);
1771 EXPECT_TRUE(server_connection->GetStats().address_validated_via_token);
1772
1773 // Verify the server received a cached min_rtt from the token and used it as
1774 // the initial rtt.
1775 const CachedNetworkParameters* server_received_network_params =
1776 static_cast<const QuicCryptoServerStreamBase*>(
1777 server_session->GetCryptoStream())
1778 ->PreviousCachedNetworkParams();
1779
1780 ASSERT_NE(server_received_network_params, nullptr);
1781 // QuicSentPacketManager::SetInitialRtt clamps the initial_rtt to between
1782 // [min_initial_rtt, max_initial_rtt].
1783 const QuicTime::Delta min_initial_rtt =
1784 QuicTime::Delta::FromMicroseconds(kMinTrustedInitialRoundTripTimeUs);
1785 const QuicTime::Delta max_initial_rtt =
1786 QuicTime::Delta::FromMicroseconds(kMaxInitialRoundTripTimeUs);
1787 const QuicTime::Delta expected_initial_rtt =
1788 std::max(min_initial_rtt,
1789 std::min(max_initial_rtt,
1790 QuicTime::Delta::FromMilliseconds(
1791 server_received_network_params->min_rtt_ms())));
1792 EXPECT_EQ(
1793 server_connection->sent_packet_manager().GetRttStats()->initial_rtt(),
1794 expected_initial_rtt);
1795 } else {
1796 ADD_FAILURE() << "Missing server connection";
1797 }
1798
1799 server_thread_->Resume();
1800
1801 client_->Disconnect();
1802
1803 // Regression test for b/206087883.
1804 // Mock server crash.
1805 StopServer();
1806
1807 // The handshake fails due to idle timeout.
1808 client_->Connect();
1809 ASSERT_FALSE(client_->client()->WaitForOneRttKeysAvailable());
1810 client_->WaitForWriteToFlush();
1811 client_->WaitForResponse();
1812 ASSERT_FALSE(client_->client()->connected());
1813 EXPECT_THAT(client_->connection_error(), IsError(QUIC_NETWORK_IDLE_TIMEOUT));
1814
1815 // Server restarts.
1816 server_writer_ = new PacketDroppingTestWriter();
1817 StartServer();
1818
1819 // Client re-connect.
1820 client_->Connect();
1821 ASSERT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1822 client_->WaitForWriteToFlush();
1823 client_->WaitForResponse();
1824 ASSERT_TRUE(client_->client()->connected());
1825 client_session = GetClientSession();
1826 ASSERT_TRUE(client_session);
1827 EXPECT_FALSE(client_session->EarlyDataAccepted());
1828 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1829 server_thread_->Pause();
1830 server_session = GetServerSession();
1831 server_connection = GetServerConnection();
1832 // Verify address token is only used once.
1833 if (server_session != nullptr && server_connection != nullptr) {
1834 // Verify address is validated via decrypting packet.
1835 EXPECT_TRUE(
1836 server_connection->GetStats().address_validated_via_decrypting_packet);
1837 EXPECT_FALSE(server_connection->GetStats().address_validated_via_token);
1838 } else {
1839 ADD_FAILURE() << "Missing server connection";
1840 }
1841 server_thread_->Resume();
1842
1843 client_->Disconnect();
1844 }
1845
1846 // Verify that client does not reuse a source address token.
1847 // TODO(b/214587920): make this test not rely on timeouts.
TEST_P(EndToEndTest,QUICHE_SLOW_TEST (AddressTokenNotReusedByClient))1848 TEST_P(EndToEndTest, QUICHE_SLOW_TEST(AddressTokenNotReusedByClient)) {
1849 client_config_.set_max_time_before_crypto_handshake(
1850 QuicTime::Delta::FromSeconds(3));
1851 client_config_.set_max_idle_time_before_crypto_handshake(
1852 QuicTime::Delta::FromSeconds(1));
1853
1854 ASSERT_TRUE(Initialize());
1855 if (!version_.HasIetfQuicFrames()) {
1856 return;
1857 }
1858
1859 QuicCryptoClientConfig* client_crypto_config =
1860 client_->client()->crypto_config();
1861 QuicServerId server_id = client_->client()->server_id();
1862
1863 SendSynchronousFooRequestAndCheckResponse();
1864 EXPECT_FALSE(GetClientSession()->EarlyDataAccepted());
1865
1866 client_->Disconnect();
1867
1868 QuicClientSessionCache* session_cache =
1869 static_cast<QuicClientSessionCache*>(client_crypto_config->session_cache());
1870 ASSERT_TRUE(
1871 !QuicClientSessionCachePeer::GetToken(session_cache, server_id).empty());
1872
1873 // Pause the server thread again to blackhole packets from client.
1874 server_thread_->Pause();
1875 client_->Connect();
1876 EXPECT_FALSE(client_->client()->WaitForOneRttKeysAvailable());
1877 EXPECT_FALSE(client_->client()->connected());
1878
1879 // Verify address token gets cleared.
1880 ASSERT_TRUE(
1881 QuicClientSessionCachePeer::GetToken(session_cache, server_id).empty());
1882 server_thread_->Resume();
1883 }
1884
TEST_P(EndToEndTest,LargePostZeroRTTFailure)1885 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
1886 // Send a request and then disconnect. This prepares the client to attempt
1887 // a 0-RTT handshake for the next request.
1888 ASSERT_TRUE(Initialize());
1889 if (!version_.UsesTls() &&
1890 GetQuicReloadableFlag(quic_require_handshake_confirmation)) {
1891 return;
1892 }
1893
1894 std::string body(20480, 'a');
1895 Http2HeaderBlock headers;
1896 headers[":method"] = "POST";
1897 headers[":path"] = "/foo";
1898 headers[":scheme"] = "https";
1899 headers[":authority"] = server_hostname_;
1900
1901 EXPECT_EQ(kFooResponseBody,
1902 client_->SendCustomSynchronousRequest(headers, body));
1903 QuicSpdyClientSession* client_session = GetClientSession();
1904 ASSERT_TRUE(client_session);
1905 EXPECT_FALSE(client_session->EarlyDataAccepted());
1906 EXPECT_FALSE(client_session->ReceivedInchoateReject());
1907 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1908 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1909
1910 client_->Disconnect();
1911
1912 // The 0-RTT handshake should succeed.
1913 client_->Connect();
1914 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1915 ASSERT_TRUE(client_->client()->connected());
1916 EXPECT_EQ(kFooResponseBody,
1917 client_->SendCustomSynchronousRequest(headers, body));
1918
1919 client_session = GetClientSession();
1920 ASSERT_TRUE(client_session);
1921 EXPECT_TRUE(client_session->EarlyDataAccepted());
1922 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1923
1924 client_->Disconnect();
1925
1926 // Restart the server so that the 0-RTT handshake will take 1 RTT.
1927 StopServer();
1928 server_writer_ = new PacketDroppingTestWriter();
1929 StartServer();
1930
1931 client_->Connect();
1932 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1933 ASSERT_TRUE(client_->client()->connected());
1934 EXPECT_EQ(kFooResponseBody,
1935 client_->SendCustomSynchronousRequest(headers, body));
1936 client_session = GetClientSession();
1937 ASSERT_TRUE(client_session);
1938 EXPECT_FALSE(client_session->EarlyDataAccepted());
1939 EXPECT_FALSE(client_session->ReceivedInchoateReject());
1940 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1941 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1942 VerifyCleanConnection(false);
1943 }
1944
1945 // Regression test for b/168020146.
TEST_P(EndToEndTest,MultipleZeroRtt)1946 TEST_P(EndToEndTest, MultipleZeroRtt) {
1947 ASSERT_TRUE(Initialize());
1948 if (!version_.UsesTls() &&
1949 GetQuicReloadableFlag(quic_require_handshake_confirmation)) {
1950 return;
1951 }
1952
1953 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1954 QuicSpdyClientSession* client_session = GetClientSession();
1955 ASSERT_TRUE(client_session);
1956 EXPECT_FALSE(client_session->EarlyDataAccepted());
1957 EXPECT_FALSE(client_session->ReceivedInchoateReject());
1958 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1959 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1960
1961 client_->Disconnect();
1962
1963 // The 0-RTT handshake should succeed.
1964 client_->Connect();
1965 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1966 ASSERT_TRUE(client_->client()->connected());
1967 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1968
1969 client_session = GetClientSession();
1970 ASSERT_TRUE(client_session);
1971 EXPECT_TRUE(client_session->EarlyDataAccepted());
1972 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1973
1974 client_->Disconnect();
1975
1976 client_->Connect();
1977 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1978 ASSERT_TRUE(client_->client()->connected());
1979 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1980
1981 client_session = GetClientSession();
1982 ASSERT_TRUE(client_session);
1983 EXPECT_TRUE(client_session->EarlyDataAccepted());
1984 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1985
1986 client_->Disconnect();
1987 }
1988
TEST_P(EndToEndTest,SynchronousRequestZeroRTTFailure)1989 TEST_P(EndToEndTest, SynchronousRequestZeroRTTFailure) {
1990 // Send a request and then disconnect. This prepares the client to attempt
1991 // a 0-RTT handshake for the next request.
1992 ASSERT_TRUE(Initialize());
1993 if (!version_.UsesTls() &&
1994 GetQuicReloadableFlag(quic_require_handshake_confirmation)) {
1995 return;
1996 }
1997
1998 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1999 QuicSpdyClientSession* client_session = GetClientSession();
2000 ASSERT_TRUE(client_session);
2001 EXPECT_FALSE(client_session->EarlyDataAccepted());
2002 EXPECT_FALSE(client_session->ReceivedInchoateReject());
2003 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2004 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2005
2006 client_->Disconnect();
2007
2008 // The 0-RTT handshake should succeed.
2009 client_->Connect();
2010 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2011 ASSERT_TRUE(client_->client()->connected());
2012 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2013
2014 client_session = GetClientSession();
2015 ASSERT_TRUE(client_session);
2016 EXPECT_TRUE(client_session->EarlyDataAccepted());
2017 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
2018
2019 client_->Disconnect();
2020
2021 // Restart the server so that the 0-RTT handshake will take 1 RTT.
2022 StopServer();
2023 server_writer_ = new PacketDroppingTestWriter();
2024 StartServer();
2025
2026 client_->Connect();
2027 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2028 ASSERT_TRUE(client_->client()->connected());
2029 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2030
2031 client_session = GetClientSession();
2032 ASSERT_TRUE(client_session);
2033 EXPECT_FALSE(client_session->EarlyDataAccepted());
2034 EXPECT_FALSE(client_session->ReceivedInchoateReject());
2035 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2036 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2037
2038 VerifyCleanConnection(false);
2039 }
2040
TEST_P(EndToEndTest,LargePostSynchronousRequest)2041 TEST_P(EndToEndTest, LargePostSynchronousRequest) {
2042 // Send a request and then disconnect. This prepares the client to attempt
2043 // a 0-RTT handshake for the next request.
2044 ASSERT_TRUE(Initialize());
2045
2046 std::string body(20480, 'a');
2047 Http2HeaderBlock headers;
2048 headers[":method"] = "POST";
2049 headers[":path"] = "/foo";
2050 headers[":scheme"] = "https";
2051 headers[":authority"] = server_hostname_;
2052
2053 EXPECT_EQ(kFooResponseBody,
2054 client_->SendCustomSynchronousRequest(headers, body));
2055 QuicSpdyClientSession* client_session = GetClientSession();
2056 ASSERT_TRUE(client_session);
2057 EXPECT_FALSE(client_session->EarlyDataAccepted());
2058 EXPECT_FALSE(client_session->ReceivedInchoateReject());
2059 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2060 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2061
2062 client_->Disconnect();
2063
2064 // The 0-RTT handshake should succeed.
2065 client_->Connect();
2066 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2067 ASSERT_TRUE(client_->client()->connected());
2068 EXPECT_EQ(kFooResponseBody,
2069 client_->SendCustomSynchronousRequest(headers, body));
2070
2071 client_session = GetClientSession();
2072 ASSERT_TRUE(client_session);
2073 EXPECT_EQ((version_.UsesTls() ||
2074 !GetQuicReloadableFlag(quic_require_handshake_confirmation)),
2075 client_session->EarlyDataAccepted());
2076 EXPECT_EQ((version_.UsesTls() ||
2077 !GetQuicReloadableFlag(quic_require_handshake_confirmation)),
2078 client_->client()->EarlyDataAccepted());
2079
2080 client_->Disconnect();
2081
2082 // Restart the server so that the 0-RTT handshake will take 1 RTT.
2083 StopServer();
2084 server_writer_ = new PacketDroppingTestWriter();
2085 StartServer();
2086
2087 client_->Connect();
2088 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2089 ASSERT_TRUE(client_->client()->connected());
2090 EXPECT_EQ(kFooResponseBody,
2091 client_->SendCustomSynchronousRequest(headers, body));
2092
2093 client_session = GetClientSession();
2094 ASSERT_TRUE(client_session);
2095 EXPECT_FALSE(client_session->EarlyDataAccepted());
2096 EXPECT_FALSE(client_session->ReceivedInchoateReject());
2097 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2098 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2099
2100 VerifyCleanConnection(false);
2101 }
2102
TEST_P(EndToEndTest,DisableResumption)2103 TEST_P(EndToEndTest, DisableResumption) {
2104 client_extra_copts_.push_back(kNRES);
2105 ASSERT_TRUE(Initialize());
2106 if (!version_.UsesTls()) {
2107 return;
2108 }
2109 SendSynchronousFooRequestAndCheckResponse();
2110 QuicSpdyClientSession* client_session = GetClientSession();
2111 ASSERT_TRUE(client_session);
2112 EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
2113 ssl_early_data_no_session_offered);
2114 client_->Disconnect();
2115
2116 SendSynchronousFooRequestAndCheckResponse();
2117 client_session = GetClientSession();
2118 ASSERT_TRUE(client_session);
2119 if (GetQuicReloadableFlag(quic_enable_disable_resumption)) {
2120 EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
2121 ssl_early_data_session_not_resumed);
2122 } else {
2123 EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
2124 ssl_early_data_accepted);
2125 }
2126 }
2127
2128 // This is a regression test for b/162595387
TEST_P(EndToEndTest,PostZeroRTTRequestDuringHandshake)2129 TEST_P(EndToEndTest, PostZeroRTTRequestDuringHandshake) {
2130 if (!version_.UsesTls()) {
2131 // This test is TLS specific.
2132 ASSERT_TRUE(Initialize());
2133 return;
2134 }
2135 // Send a request and then disconnect. This prepares the client to attempt
2136 // a 0-RTT handshake for the next request.
2137 NiceMock<MockQuicConnectionDebugVisitor> visitor;
2138 connection_debug_visitor_ = &visitor;
2139 ASSERT_TRUE(Initialize());
2140
2141 SendSynchronousFooRequestAndCheckResponse();
2142 QuicSpdyClientSession* client_session = GetClientSession();
2143 ASSERT_TRUE(client_session);
2144 EXPECT_FALSE(client_session->EarlyDataAccepted());
2145 EXPECT_FALSE(client_session->ReceivedInchoateReject());
2146 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2147 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2148
2149 client_->Disconnect();
2150
2151 // The 0-RTT handshake should succeed.
2152 ON_CALL(visitor, OnCryptoFrame(_))
2153 .WillByDefault(Invoke([this](const QuicCryptoFrame& frame) {
2154 if (frame.level != ENCRYPTION_HANDSHAKE) {
2155 return;
2156 }
2157 // At this point in the handshake, the client should have derived
2158 // ENCRYPTION_ZERO_RTT keys (thus set encryption_established). It
2159 // should also have set ENCRYPTION_HANDSHAKE keys after receiving
2160 // the server's ENCRYPTION_INITIAL flight.
2161 EXPECT_TRUE(
2162 GetClientSession()->GetCryptoStream()->encryption_established());
2163 EXPECT_TRUE(
2164 GetClientConnection()->framer().HasEncrypterOfEncryptionLevel(
2165 ENCRYPTION_HANDSHAKE));
2166 Http2HeaderBlock headers;
2167 headers[":method"] = "POST";
2168 headers[":path"] = "/foo";
2169 headers[":scheme"] = "https";
2170 headers[":authority"] = server_hostname_;
2171 EXPECT_GT(
2172 client_->SendMessage(headers, "", /*fin*/ true, /*flush*/ false),
2173 0);
2174 }));
2175 client_->Connect();
2176 ASSERT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2177 client_->WaitForWriteToFlush();
2178 client_->WaitForResponse();
2179 ASSERT_TRUE(client_->client()->connected());
2180 EXPECT_EQ(kFooResponseBody, client_->response_body());
2181
2182 client_session = GetClientSession();
2183 ASSERT_TRUE(client_session);
2184 EXPECT_TRUE(client_session->EarlyDataAccepted());
2185 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
2186 }
2187
2188 // Regression test for b/166836136.
TEST_P(EndToEndTest,RetransmissionAfterZeroRTTRejectBeforeOneRtt)2189 TEST_P(EndToEndTest, RetransmissionAfterZeroRTTRejectBeforeOneRtt) {
2190 if (!version_.UsesTls()) {
2191 // This test is TLS specific.
2192 ASSERT_TRUE(Initialize());
2193 return;
2194 }
2195 // Send a request and then disconnect. This prepares the client to attempt
2196 // a 0-RTT handshake for the next request.
2197 NiceMock<MockQuicConnectionDebugVisitor> visitor;
2198 connection_debug_visitor_ = &visitor;
2199 ASSERT_TRUE(Initialize());
2200
2201 SendSynchronousFooRequestAndCheckResponse();
2202 QuicSpdyClientSession* client_session = GetClientSession();
2203 ASSERT_TRUE(client_session);
2204 EXPECT_FALSE(client_session->EarlyDataAccepted());
2205 EXPECT_FALSE(client_session->ReceivedInchoateReject());
2206 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2207 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2208
2209 client_->Disconnect();
2210
2211 client_->Connect();
2212 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2213 ASSERT_TRUE(client_->client()->connected());
2214 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2215
2216 client_session = GetClientSession();
2217 ASSERT_TRUE(client_session);
2218 EXPECT_TRUE(client_session->EarlyDataAccepted());
2219 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
2220
2221 client_->Disconnect();
2222
2223 // Restart the server so that the 0-RTT handshake will take 1 RTT.
2224 StopServer();
2225 server_writer_ = new PacketDroppingTestWriter();
2226 StartServer();
2227
2228 ON_CALL(visitor, OnZeroRttRejected(_)).WillByDefault(Invoke([this]() {
2229 EXPECT_FALSE(GetClientSession()->IsEncryptionEstablished());
2230 }));
2231
2232 // The 0-RTT handshake should fail.
2233 client_->Connect();
2234 ASSERT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2235 client_->WaitForWriteToFlush();
2236 client_->WaitForResponse();
2237 ASSERT_TRUE(client_->client()->connected());
2238
2239 client_session = GetClientSession();
2240 ASSERT_TRUE(client_session);
2241 EXPECT_FALSE(client_session->EarlyDataAccepted());
2242 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2243 }
2244
TEST_P(EndToEndTest,RejectWithPacketLoss)2245 TEST_P(EndToEndTest, RejectWithPacketLoss) {
2246 // In this test, we intentionally drop the first packet from the
2247 // server, which corresponds with the initial REJ response from
2248 // the server.
2249 server_writer_->set_fake_drop_first_n_packets(1);
2250 ASSERT_TRUE(Initialize());
2251 }
2252
TEST_P(EndToEndTest,SetInitialReceivedConnectionOptions)2253 TEST_P(EndToEndTest, SetInitialReceivedConnectionOptions) {
2254 QuicTagVector initial_received_options;
2255 initial_received_options.push_back(kTBBR);
2256 initial_received_options.push_back(kIW10);
2257 initial_received_options.push_back(kPRST);
2258 EXPECT_TRUE(server_config_.SetInitialReceivedConnectionOptions(
2259 initial_received_options));
2260
2261 ASSERT_TRUE(Initialize());
2262 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2263 server_thread_->WaitForCryptoHandshakeConfirmed();
2264
2265 EXPECT_FALSE(server_config_.SetInitialReceivedConnectionOptions(
2266 initial_received_options));
2267
2268 // Verify that server's configuration is correct.
2269 server_thread_->Pause();
2270 EXPECT_TRUE(server_config_.HasReceivedConnectionOptions());
2271 EXPECT_TRUE(
2272 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kTBBR));
2273 EXPECT_TRUE(
2274 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kIW10));
2275 EXPECT_TRUE(
2276 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kPRST));
2277 }
2278
TEST_P(EndToEndTest,LargePostSmallBandwidthLargeBuffer)2279 TEST_P(EndToEndTest, LargePostSmallBandwidthLargeBuffer) {
2280 ASSERT_TRUE(Initialize());
2281 SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
2282 // 256KB per second with a 256KB buffer from server to client. Wireless
2283 // clients commonly have larger buffers, but our max CWND is 200.
2284 server_writer_->set_max_bandwidth_and_buffer_size(
2285 QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
2286
2287 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2288
2289 // 1 MB body.
2290 std::string body(1024 * 1024, 'a');
2291 Http2HeaderBlock headers;
2292 headers[":method"] = "POST";
2293 headers[":path"] = "/foo";
2294 headers[":scheme"] = "https";
2295 headers[":authority"] = server_hostname_;
2296
2297 EXPECT_EQ(kFooResponseBody,
2298 client_->SendCustomSynchronousRequest(headers, body));
2299 // This connection may drop packets, because the buffer is smaller than the
2300 // max CWND.
2301 VerifyCleanConnection(true);
2302 }
2303
TEST_P(EndToEndTest,DoNotSetSendAlarmIfConnectionFlowControlBlocked)2304 TEST_P(EndToEndTest, DoNotSetSendAlarmIfConnectionFlowControlBlocked) {
2305 // Regression test for b/14677858.
2306 // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
2307 // if currently connection level flow control blocked. If set, this results in
2308 // an infinite loop in the EventLoop, as the alarm fires and is immediately
2309 // rescheduled.
2310 ASSERT_TRUE(Initialize());
2311 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2312
2313 // Ensure both stream and connection level are flow control blocked by setting
2314 // the send window offset to 0.
2315 const uint64_t flow_control_window =
2316 server_config_.GetInitialStreamFlowControlWindowToSend();
2317 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
2318 QuicSession* session = GetClientSession();
2319 ASSERT_TRUE(session);
2320 QuicStreamPeer::SetSendWindowOffset(stream, 0);
2321 QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
2322 EXPECT_TRUE(stream->IsFlowControlBlocked());
2323 EXPECT_TRUE(session->flow_controller()->IsBlocked());
2324
2325 // Make sure that the stream has data pending so that it will be marked as
2326 // write blocked when it receives a stream level WINDOW_UPDATE.
2327 stream->WriteOrBufferBody("hello", false);
2328
2329 // The stream now attempts to write, fails because it is still connection
2330 // level flow control blocked, and is added to the write blocked list.
2331 QuicWindowUpdateFrame window_update(kInvalidControlFrameId, stream->id(),
2332 2 * flow_control_window);
2333 stream->OnWindowUpdateFrame(window_update);
2334
2335 // Prior to fixing b/14677858 this call would result in an infinite loop in
2336 // Chromium. As a proxy for detecting this, we now check whether the
2337 // send alarm is set after OnCanWrite. It should not be, as the
2338 // connection is still flow control blocked.
2339 session->connection()->OnCanWrite();
2340
2341 QuicAlarm* send_alarm =
2342 QuicConnectionPeer::GetSendAlarm(session->connection());
2343 EXPECT_FALSE(send_alarm->IsSet());
2344 }
2345
TEST_P(EndToEndTest,InvalidStream)2346 TEST_P(EndToEndTest, InvalidStream) {
2347 ASSERT_TRUE(Initialize());
2348 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2349
2350 std::string body(kMaxOutgoingPacketSize, 'a');
2351 Http2HeaderBlock headers;
2352 headers[":method"] = "POST";
2353 headers[":path"] = "/foo";
2354 headers[":scheme"] = "https";
2355 headers[":authority"] = server_hostname_;
2356
2357 // Force the client to write with a stream ID belonging to a nonexistent
2358 // server-side stream.
2359 QuicSpdySession* session = GetClientSession();
2360 ASSERT_TRUE(session);
2361 QuicSessionPeer::SetNextOutgoingBidirectionalStreamId(
2362 session, GetNthServerInitiatedBidirectionalId(0));
2363
2364 client_->SendCustomSynchronousRequest(headers, body);
2365 EXPECT_THAT(client_->stream_error(),
2366 IsStreamError(QUIC_STREAM_CONNECTION_ERROR));
2367 EXPECT_THAT(client_->connection_error(), IsError(QUIC_INVALID_STREAM_ID));
2368 }
2369
2370 // Test that the server resets the stream if the client sends a request
2371 // with overly large headers.
TEST_P(EndToEndTest,LargeHeaders)2372 TEST_P(EndToEndTest, LargeHeaders) {
2373 ASSERT_TRUE(Initialize());
2374 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2375
2376 std::string body(kMaxOutgoingPacketSize, 'a');
2377 Http2HeaderBlock headers;
2378 headers[":method"] = "POST";
2379 headers[":path"] = "/foo";
2380 headers[":scheme"] = "https";
2381 headers[":authority"] = server_hostname_;
2382 headers["key1"] = std::string(15 * 1024, 'a');
2383 headers["key2"] = std::string(15 * 1024, 'a');
2384 headers["key3"] = std::string(15 * 1024, 'a');
2385
2386 client_->SendCustomSynchronousRequest(headers, body);
2387
2388 if (version_.UsesHttp3()) {
2389 // QuicSpdyStream::OnHeadersTooLarge() resets the stream with
2390 // QUIC_HEADERS_TOO_LARGE. This is sent as H3_EXCESSIVE_LOAD, the closest
2391 // HTTP/3 error code, and translated back to QUIC_STREAM_EXCESSIVE_LOAD on
2392 // the receiving side.
2393 EXPECT_THAT(client_->stream_error(),
2394 IsStreamError(QUIC_STREAM_EXCESSIVE_LOAD));
2395 } else {
2396 EXPECT_THAT(client_->stream_error(), IsStreamError(QUIC_HEADERS_TOO_LARGE));
2397 }
2398 EXPECT_THAT(client_->connection_error(), IsQuicNoError());
2399 }
2400
TEST_P(EndToEndTest,EarlyResponseWithQuicStreamNoError)2401 TEST_P(EndToEndTest, EarlyResponseWithQuicStreamNoError) {
2402 ASSERT_TRUE(Initialize());
2403 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2404
2405 std::string large_body(1024 * 1024, 'a');
2406 Http2HeaderBlock headers;
2407 headers[":method"] = "POST";
2408 headers[":path"] = "/foo";
2409 headers[":scheme"] = "https";
2410 headers[":authority"] = server_hostname_;
2411 // Insert an invalid content_length field in request to trigger an early
2412 // response from server.
2413 headers["content-length"] = "-3";
2414
2415 client_->SendCustomSynchronousRequest(headers, large_body);
2416 EXPECT_EQ("bad", client_->response_body());
2417 CheckResponseHeaders("500");
2418 EXPECT_THAT(client_->stream_error(), IsQuicStreamNoError());
2419 EXPECT_THAT(client_->connection_error(), IsQuicNoError());
2420 }
2421
2422 // TODO(rch): this test seems to cause net_unittests timeouts :|
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (MultipleTermination))2423 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(MultipleTermination)) {
2424 ASSERT_TRUE(Initialize());
2425
2426 // Set the offset so we won't frame. Otherwise when we pick up termination
2427 // before HTTP framing is complete, we send an error and close the stream,
2428 // and the second write is picked up as writing on a closed stream.
2429 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
2430 ASSERT_TRUE(stream != nullptr);
2431 QuicStreamPeer::SetStreamBytesWritten(3, stream);
2432
2433 client_->SendData("bar", true);
2434 client_->WaitForWriteToFlush();
2435
2436 // By default the stream protects itself from writes after terminte is set.
2437 // Override this to test the server handling buggy clients.
2438 QuicStreamPeer::SetWriteSideClosed(false, client_->GetOrCreateStream());
2439
2440 EXPECT_QUIC_BUG(client_->SendData("eep", true), "Fin already buffered");
2441 }
2442
TEST_P(EndToEndTest,Timeout)2443 TEST_P(EndToEndTest, Timeout) {
2444 client_config_.SetIdleNetworkTimeout(QuicTime::Delta::FromMicroseconds(500));
2445 // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
2446 // that's enough to validate timeout in this case.
2447 Initialize();
2448 while (client_->client()->connected()) {
2449 client_->client()->WaitForEvents();
2450 }
2451 }
2452
TEST_P(EndToEndTest,MaxDynamicStreamsLimitRespected)2453 TEST_P(EndToEndTest, MaxDynamicStreamsLimitRespected) {
2454 // Set a limit on maximum number of incoming dynamic streams.
2455 // Make sure the limit is respected by the peer.
2456 const uint32_t kServerMaxDynamicStreams = 1;
2457 server_config_.SetMaxBidirectionalStreamsToSend(kServerMaxDynamicStreams);
2458 ASSERT_TRUE(Initialize());
2459 if (version_.HasIetfQuicFrames()) {
2460 // Do not run this test for /IETF QUIC. This test relies on the fact that
2461 // Google QUIC allows a small number of additional streams beyond the
2462 // negotiated limit, which is not supported in IETF QUIC. Note that the test
2463 // needs to be here, after calling Initialize(), because all tests end up
2464 // calling EndToEndTest::TearDown(), which asserts that Initialize has been
2465 // called and then proceeds to tear things down -- which fails if they are
2466 // not properly set up.
2467 return;
2468 }
2469 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2470
2471 // Make the client misbehave after negotiation.
2472 const int kServerMaxStreams = kMaxStreamsMinimumIncrement + 1;
2473 QuicSpdyClientSession* client_session = GetClientSession();
2474 ASSERT_TRUE(client_session);
2475 QuicSessionPeer::SetMaxOpenOutgoingStreams(client_session,
2476 kServerMaxStreams + 1);
2477
2478 Http2HeaderBlock headers;
2479 headers[":method"] = "POST";
2480 headers[":path"] = "/foo";
2481 headers[":scheme"] = "https";
2482 headers[":authority"] = server_hostname_;
2483 headers["content-length"] = "3";
2484
2485 // The server supports a small number of additional streams beyond the
2486 // negotiated limit. Open enough streams to go beyond that limit.
2487 for (int i = 0; i < kServerMaxStreams + 1; ++i) {
2488 client_->SendMessage(headers, "", /*fin=*/false);
2489 }
2490 client_->WaitForResponse();
2491
2492 EXPECT_TRUE(client_->connected());
2493 EXPECT_THAT(client_->stream_error(), IsStreamError(QUIC_REFUSED_STREAM));
2494 EXPECT_THAT(client_->connection_error(), IsQuicNoError());
2495 }
2496
TEST_P(EndToEndTest,SetIndependentMaxDynamicStreamsLimits)2497 TEST_P(EndToEndTest, SetIndependentMaxDynamicStreamsLimits) {
2498 // Each endpoint can set max dynamic streams independently.
2499 const uint32_t kClientMaxDynamicStreams = 4;
2500 const uint32_t kServerMaxDynamicStreams = 3;
2501 client_config_.SetMaxBidirectionalStreamsToSend(kClientMaxDynamicStreams);
2502 server_config_.SetMaxBidirectionalStreamsToSend(kServerMaxDynamicStreams);
2503 client_config_.SetMaxUnidirectionalStreamsToSend(kClientMaxDynamicStreams);
2504 server_config_.SetMaxUnidirectionalStreamsToSend(kServerMaxDynamicStreams);
2505
2506 ASSERT_TRUE(Initialize());
2507 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2508
2509 // The client has received the server's limit and vice versa.
2510 QuicSpdyClientSession* client_session = GetClientSession();
2511 ASSERT_TRUE(client_session);
2512 // The value returned by max_allowed... includes the Crypto and Header
2513 // stream (created as a part of initialization). The config. values,
2514 // above, are treated as "number of requests/responses" - that is, they do
2515 // not include the static Crypto and Header streams. Reduce the value
2516 // returned by max_allowed... by 2 to remove the static streams from the
2517 // count.
2518 size_t client_max_open_outgoing_bidirectional_streams =
2519 version_.HasIetfQuicFrames()
2520 ? QuicSessionPeer::ietf_streamid_manager(client_session)
2521 ->max_outgoing_bidirectional_streams()
2522 : QuicSessionPeer::GetStreamIdManager(client_session)
2523 ->max_open_outgoing_streams();
2524 size_t client_max_open_outgoing_unidirectional_streams =
2525 version_.HasIetfQuicFrames()
2526 ? QuicSessionPeer::ietf_streamid_manager(client_session)
2527 ->max_outgoing_unidirectional_streams() -
2528 kHttp3StaticUnidirectionalStreamCount
2529 : QuicSessionPeer::GetStreamIdManager(client_session)
2530 ->max_open_outgoing_streams();
2531 EXPECT_EQ(kServerMaxDynamicStreams,
2532 client_max_open_outgoing_bidirectional_streams);
2533 EXPECT_EQ(kServerMaxDynamicStreams,
2534 client_max_open_outgoing_unidirectional_streams);
2535 server_thread_->Pause();
2536 QuicSession* server_session = GetServerSession();
2537 if (server_session != nullptr) {
2538 size_t server_max_open_outgoing_bidirectional_streams =
2539 version_.HasIetfQuicFrames()
2540 ? QuicSessionPeer::ietf_streamid_manager(server_session)
2541 ->max_outgoing_bidirectional_streams()
2542 : QuicSessionPeer::GetStreamIdManager(server_session)
2543 ->max_open_outgoing_streams();
2544 size_t server_max_open_outgoing_unidirectional_streams =
2545 version_.HasIetfQuicFrames()
2546 ? QuicSessionPeer::ietf_streamid_manager(server_session)
2547 ->max_outgoing_unidirectional_streams() -
2548 kHttp3StaticUnidirectionalStreamCount
2549 : QuicSessionPeer::GetStreamIdManager(server_session)
2550 ->max_open_outgoing_streams();
2551 EXPECT_EQ(kClientMaxDynamicStreams,
2552 server_max_open_outgoing_bidirectional_streams);
2553 EXPECT_EQ(kClientMaxDynamicStreams,
2554 server_max_open_outgoing_unidirectional_streams);
2555 } else {
2556 ADD_FAILURE() << "Missing server session";
2557 }
2558 server_thread_->Resume();
2559 }
2560
TEST_P(EndToEndTest,NegotiateCongestionControl)2561 TEST_P(EndToEndTest, NegotiateCongestionControl) {
2562 ASSERT_TRUE(Initialize());
2563
2564 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2565
2566 CongestionControlType expected_congestion_control_type = kRenoBytes;
2567 switch (GetParam().congestion_control_tag) {
2568 case kRENO:
2569 expected_congestion_control_type = kRenoBytes;
2570 break;
2571 case kTBBR:
2572 expected_congestion_control_type = kBBR;
2573 break;
2574 case kQBIC:
2575 expected_congestion_control_type = kCubicBytes;
2576 break;
2577 case kB2ON:
2578 expected_congestion_control_type = kBBRv2;
2579 break;
2580 default:
2581 QUIC_DLOG(FATAL) << "Unexpected congestion control tag";
2582 }
2583
2584 server_thread_->Pause();
2585 const QuicSentPacketManager* server_sent_packet_manager =
2586 GetSentPacketManagerFromFirstServerSession();
2587 if (server_sent_packet_manager != nullptr) {
2588 EXPECT_EQ(
2589 expected_congestion_control_type,
2590 QuicSentPacketManagerPeer::GetSendAlgorithm(*server_sent_packet_manager)
2591 ->GetCongestionControlType());
2592 } else {
2593 ADD_FAILURE() << "Missing server sent packet manager";
2594 }
2595 server_thread_->Resume();
2596 }
2597
TEST_P(EndToEndTest,ClientSuggestsRTT)2598 TEST_P(EndToEndTest, ClientSuggestsRTT) {
2599 // Client suggests initial RTT, verify it is used.
2600 const QuicTime::Delta kInitialRTT = QuicTime::Delta::FromMicroseconds(20000);
2601 client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT.ToMicroseconds());
2602
2603 ASSERT_TRUE(Initialize());
2604 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2605 ASSERT_TRUE(server_thread_);
2606 server_thread_->WaitForCryptoHandshakeConfirmed();
2607
2608 // Pause the server so we can access the server's internals without races.
2609 server_thread_->Pause();
2610 const QuicSentPacketManager* client_sent_packet_manager =
2611 GetSentPacketManagerFromClientSession();
2612 const QuicSentPacketManager* server_sent_packet_manager =
2613 GetSentPacketManagerFromFirstServerSession();
2614 if (client_sent_packet_manager != nullptr &&
2615 server_sent_packet_manager != nullptr) {
2616 EXPECT_EQ(kInitialRTT,
2617 client_sent_packet_manager->GetRttStats()->initial_rtt());
2618 EXPECT_EQ(kInitialRTT,
2619 server_sent_packet_manager->GetRttStats()->initial_rtt());
2620 } else {
2621 ADD_FAILURE() << "Missing sent packet manager";
2622 }
2623 server_thread_->Resume();
2624 }
2625
TEST_P(EndToEndTest,ClientSuggestsIgnoredRTT)2626 TEST_P(EndToEndTest, ClientSuggestsIgnoredRTT) {
2627 // Client suggests initial RTT, but also specifies NRTT, so it's not used.
2628 const QuicTime::Delta kInitialRTT = QuicTime::Delta::FromMicroseconds(20000);
2629 client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT.ToMicroseconds());
2630 QuicTagVector options;
2631 options.push_back(kNRTT);
2632 client_config_.SetConnectionOptionsToSend(options);
2633
2634 ASSERT_TRUE(Initialize());
2635 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2636 ASSERT_TRUE(server_thread_);
2637 server_thread_->WaitForCryptoHandshakeConfirmed();
2638
2639 // Pause the server so we can access the server's internals without races.
2640 server_thread_->Pause();
2641 const QuicSentPacketManager* client_sent_packet_manager =
2642 GetSentPacketManagerFromClientSession();
2643 const QuicSentPacketManager* server_sent_packet_manager =
2644 GetSentPacketManagerFromFirstServerSession();
2645 if (client_sent_packet_manager != nullptr &&
2646 server_sent_packet_manager != nullptr) {
2647 EXPECT_EQ(kInitialRTT,
2648 client_sent_packet_manager->GetRttStats()->initial_rtt());
2649 EXPECT_EQ(kInitialRTT,
2650 server_sent_packet_manager->GetRttStats()->initial_rtt());
2651 } else {
2652 ADD_FAILURE() << "Missing sent packet manager";
2653 }
2654 server_thread_->Resume();
2655 }
2656
2657 // Regression test for b/171378845
TEST_P(EndToEndTest,ClientDisablesGQuicZeroRtt)2658 TEST_P(EndToEndTest, ClientDisablesGQuicZeroRtt) {
2659 if (version_.UsesTls()) {
2660 // This feature is gQUIC only.
2661 ASSERT_TRUE(Initialize());
2662 return;
2663 }
2664 QuicTagVector options;
2665 options.push_back(kQNZ2);
2666 client_config_.SetClientConnectionOptions(options);
2667
2668 ASSERT_TRUE(Initialize());
2669
2670 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2671 QuicSpdyClientSession* client_session = GetClientSession();
2672 ASSERT_TRUE(client_session);
2673 EXPECT_FALSE(client_session->EarlyDataAccepted());
2674 EXPECT_FALSE(client_session->ReceivedInchoateReject());
2675 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2676 EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2677
2678 client_->Disconnect();
2679
2680 // Make sure that the request succeeds but 0-RTT was not used.
2681 client_->Connect();
2682 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2683 ASSERT_TRUE(client_->client()->connected());
2684 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2685
2686 client_session = GetClientSession();
2687 ASSERT_TRUE(client_session);
2688 EXPECT_FALSE(client_session->EarlyDataAccepted());
2689 EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2690 }
2691
TEST_P(EndToEndTest,MaxInitialRTT)2692 TEST_P(EndToEndTest, MaxInitialRTT) {
2693 // Client tries to suggest twice the server's max initial rtt and the server
2694 // uses the max.
2695 client_config_.SetInitialRoundTripTimeUsToSend(2 *
2696 kMaxInitialRoundTripTimeUs);
2697
2698 ASSERT_TRUE(Initialize());
2699 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2700 ASSERT_TRUE(server_thread_);
2701 server_thread_->WaitForCryptoHandshakeConfirmed();
2702
2703 // Pause the server so we can access the server's internals without races.
2704 server_thread_->Pause();
2705 const QuicSentPacketManager* client_sent_packet_manager =
2706 GetSentPacketManagerFromClientSession();
2707 const QuicSentPacketManager* server_sent_packet_manager =
2708 GetSentPacketManagerFromFirstServerSession();
2709 if (client_sent_packet_manager != nullptr &&
2710 server_sent_packet_manager != nullptr) {
2711 // Now that acks have been exchanged, the RTT estimate has decreased on the
2712 // server and is not infinite on the client.
2713 EXPECT_FALSE(
2714 client_sent_packet_manager->GetRttStats()->smoothed_rtt().IsInfinite());
2715 const RttStats* server_rtt_stats =
2716 server_sent_packet_manager->GetRttStats();
2717 EXPECT_EQ(static_cast<int64_t>(kMaxInitialRoundTripTimeUs),
2718 server_rtt_stats->initial_rtt().ToMicroseconds());
2719 EXPECT_GE(static_cast<int64_t>(kMaxInitialRoundTripTimeUs),
2720 server_rtt_stats->smoothed_rtt().ToMicroseconds());
2721 } else {
2722 ADD_FAILURE() << "Missing sent packet manager";
2723 }
2724 server_thread_->Resume();
2725 }
2726
TEST_P(EndToEndTest,MinInitialRTT)2727 TEST_P(EndToEndTest, MinInitialRTT) {
2728 // Client tries to suggest 0 and the server uses the default.
2729 client_config_.SetInitialRoundTripTimeUsToSend(0);
2730
2731 ASSERT_TRUE(Initialize());
2732 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2733 server_thread_->WaitForCryptoHandshakeConfirmed();
2734
2735 // Pause the server so we can access the server's internals without races.
2736 server_thread_->Pause();
2737 const QuicSentPacketManager* client_sent_packet_manager =
2738 GetSentPacketManagerFromClientSession();
2739 const QuicSentPacketManager* server_sent_packet_manager =
2740 GetSentPacketManagerFromFirstServerSession();
2741 if (client_sent_packet_manager != nullptr &&
2742 server_sent_packet_manager != nullptr) {
2743 // Now that acks have been exchanged, the RTT estimate has decreased on the
2744 // server and is not infinite on the client.
2745 EXPECT_FALSE(
2746 client_sent_packet_manager->GetRttStats()->smoothed_rtt().IsInfinite());
2747 // Expect the default rtt of 100ms.
2748 EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
2749 server_sent_packet_manager->GetRttStats()->initial_rtt());
2750 // Ensure the bandwidth is valid.
2751 client_sent_packet_manager->BandwidthEstimate();
2752 server_sent_packet_manager->BandwidthEstimate();
2753 } else {
2754 ADD_FAILURE() << "Missing sent packet manager";
2755 }
2756 server_thread_->Resume();
2757 }
2758
TEST_P(EndToEndTest,ResetConnection)2759 TEST_P(EndToEndTest, ResetConnection) {
2760 ASSERT_TRUE(Initialize());
2761
2762 SendSynchronousFooRequestAndCheckResponse();
2763 client_->ResetConnection();
2764 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2765 SendSynchronousBarRequestAndCheckResponse();
2766 }
2767
2768 // Regression test for b/180737158.
TEST_P(EndToEndTest,HalfRttResponseBlocksShloRetransmissionWithoutTokenBasedAddressValidation)2769 TEST_P(
2770 EndToEndTest,
2771 HalfRttResponseBlocksShloRetransmissionWithoutTokenBasedAddressValidation) {
2772 // Turn off token based address validation to make the server get constrained
2773 // by amplification factor during handshake.
2774 SetQuicFlag(quic_reject_retry_token_in_initial_packet, true);
2775 ASSERT_TRUE(Initialize());
2776 if (!version_.SupportsAntiAmplificationLimit()) {
2777 return;
2778 }
2779 // Perform a full 1-RTT handshake to get the new session ticket such that the
2780 // next connection will perform a 0-RTT handshake.
2781 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
2782 client_->Disconnect();
2783
2784 server_thread_->Pause();
2785 // Drop the 1st server packet which is the coalesced INITIAL + HANDSHAKE +
2786 // 1RTT.
2787 PacketDroppingTestWriter* writer = new PacketDroppingTestWriter();
2788 writer->set_fake_drop_first_n_packets(1);
2789 QuicDispatcherPeer::UseWriter(
2790 QuicServerPeer::GetDispatcher(server_thread_->server()), writer);
2791 server_thread_->Resume();
2792
2793 // Large response (100KB) for 0-RTT request.
2794 std::string large_body(102400, 'a');
2795 AddToCache("/large_response", 200, large_body);
2796 SendSynchronousRequestAndCheckResponse(client_.get(), "/large_response",
2797 large_body);
2798 }
2799
TEST_P(EndToEndTest,MaxStreamsUberTest)2800 TEST_P(EndToEndTest, MaxStreamsUberTest) {
2801 // Connect with lower fake packet loss than we'd like to test. Until
2802 // b/10126687 is fixed, losing handshake packets is pretty brutal.
2803 SetPacketLossPercentage(1);
2804 ASSERT_TRUE(Initialize());
2805 std::string large_body(10240, 'a');
2806 int max_streams = 100;
2807
2808 AddToCache("/large_response", 200, large_body);
2809
2810 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2811 SetPacketLossPercentage(10);
2812
2813 for (int i = 0; i < max_streams; ++i) {
2814 EXPECT_LT(0, client_->SendRequest("/large_response"));
2815 }
2816
2817 // WaitForEvents waits 50ms and returns true if there are outstanding
2818 // requests.
2819 while (client_->client()->WaitForEvents()) {
2820 ASSERT_TRUE(client_->connected());
2821 }
2822 }
2823
TEST_P(EndToEndTest,StreamCancelErrorTest)2824 TEST_P(EndToEndTest, StreamCancelErrorTest) {
2825 ASSERT_TRUE(Initialize());
2826 std::string small_body(256, 'a');
2827
2828 AddToCache("/small_response", 200, small_body);
2829
2830 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2831
2832 QuicSession* session = GetClientSession();
2833 ASSERT_TRUE(session);
2834 // Lose the request.
2835 SetPacketLossPercentage(100);
2836 EXPECT_LT(0, client_->SendRequest("/small_response"));
2837 client_->client()->WaitForEvents();
2838 // Transmit the cancel, and ensure the connection is torn down properly.
2839 SetPacketLossPercentage(0);
2840 QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
2841 QuicConnection* client_connection = GetClientConnection();
2842 ASSERT_TRUE(client_connection);
2843 const QuicPacketCount packets_sent_before =
2844 client_connection->GetStats().packets_sent;
2845 session->ResetStream(stream_id, QUIC_STREAM_CANCELLED);
2846 const QuicPacketCount packets_sent_now =
2847 client_connection->GetStats().packets_sent;
2848
2849 if (version_.UsesHttp3()) {
2850 if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data4)) {
2851 // QPACK decoder instructions and RESET_STREAM and STOP_SENDING frames are
2852 // sent in a single packet.
2853 EXPECT_EQ(packets_sent_before + 1, packets_sent_now);
2854 } else {
2855 // Make sure 2 packets were sent, one for QPACK instructions, another for
2856 // RESET_STREAM and STOP_SENDING.
2857 EXPECT_EQ(packets_sent_before + 2, packets_sent_now);
2858 }
2859 }
2860
2861 // WaitForEvents waits 50ms and returns true if there are outstanding
2862 // requests.
2863 while (client_->client()->WaitForEvents()) {
2864 ASSERT_TRUE(client_->connected());
2865 }
2866 // It should be completely fine to RST a stream before any data has been
2867 // received for that stream.
2868 EXPECT_THAT(client_->connection_error(), IsQuicNoError());
2869 }
2870
TEST_P(EndToEndTest,ConnectionMigrationClientIPChanged)2871 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
2872 ASSERT_TRUE(Initialize());
2873 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
2874 return;
2875 }
2876 SendSynchronousFooRequestAndCheckResponse();
2877
2878 // Store the client IP address which was used to send the first request.
2879 QuicIpAddress old_host =
2880 client_->client()->network_helper()->GetLatestClientAddress().host();
2881
2882 // Migrate socket to the new IP address.
2883 QuicIpAddress new_host = TestLoopback(2);
2884 EXPECT_NE(old_host, new_host);
2885 ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
2886
2887 // Send a request using the new socket.
2888 SendSynchronousBarRequestAndCheckResponse();
2889
2890 if (!version_.HasIetfQuicFrames()) {
2891 return;
2892 }
2893 QuicConnection* client_connection = GetClientConnection();
2894 ASSERT_TRUE(client_connection);
2895 EXPECT_EQ(1u,
2896 client_connection->GetStats().num_connectivity_probing_received);
2897
2898 // Send another request.
2899 SendSynchronousBarRequestAndCheckResponse();
2900 // By the time the 2nd request is completed, the PATH_RESPONSE must have been
2901 // received by the server.
2902 server_thread_->Pause();
2903 QuicConnection* server_connection = GetServerConnection();
2904 if (server_connection != nullptr) {
2905 EXPECT_FALSE(server_connection->HasPendingPathValidation());
2906 EXPECT_EQ(1u, server_connection->GetStats().num_validated_peer_migration);
2907 } else {
2908 ADD_FAILURE() << "Missing server connection";
2909 }
2910 server_thread_->Resume();
2911 }
2912
TEST_P(EndToEndTest,IetfConnectionMigrationClientIPChangedMultipleTimes)2913 TEST_P(EndToEndTest, IetfConnectionMigrationClientIPChangedMultipleTimes) {
2914 ASSERT_TRUE(Initialize());
2915 if (!version_.HasIetfQuicFrames() ||
2916 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
2917 return;
2918 }
2919 SendSynchronousFooRequestAndCheckResponse();
2920
2921 // Store the client IP address which was used to send the first request.
2922 QuicIpAddress host0 =
2923 client_->client()->network_helper()->GetLatestClientAddress().host();
2924 QuicConnection* client_connection = GetClientConnection();
2925 ASSERT_TRUE(client_connection != nullptr);
2926
2927 // Migrate socket to a new IP address.
2928 QuicIpAddress host1 = TestLoopback(2);
2929 EXPECT_NE(host0, host1);
2930 ASSERT_TRUE(
2931 QuicConnectionPeer::HasUnusedPeerIssuedConnectionId(client_connection));
2932 QuicConnectionId server_cid0 = client_connection->connection_id();
2933 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
2934 client_connection)
2935 .IsEmpty());
2936 EXPECT_TRUE(client_->client()->MigrateSocket(host1));
2937 QuicConnectionId server_cid1 = client_connection->connection_id();
2938 EXPECT_FALSE(server_cid1.IsEmpty());
2939 EXPECT_NE(server_cid0, server_cid1);
2940 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
2941 client_connection)
2942 .IsEmpty());
2943
2944 // Send a request using the new socket.
2945 SendSynchronousBarRequestAndCheckResponse();
2946 EXPECT_EQ(1u,
2947 client_connection->GetStats().num_connectivity_probing_received);
2948
2949 // Send another request and wait for response making sure path response is
2950 // received at server.
2951 SendSynchronousBarRequestAndCheckResponse();
2952
2953 // Migrate socket to a new IP address.
2954 WaitForNewConnectionIds();
2955 EXPECT_EQ(1u, client_connection->GetStats().num_retire_connection_id_sent);
2956 QuicIpAddress host2 = TestLoopback(3);
2957 EXPECT_NE(host0, host2);
2958 EXPECT_NE(host1, host2);
2959 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
2960 client_connection)
2961 .IsEmpty());
2962 EXPECT_TRUE(client_->client()->MigrateSocket(host2));
2963 QuicConnectionId server_cid2 = client_connection->connection_id();
2964 EXPECT_FALSE(server_cid2.IsEmpty());
2965 EXPECT_NE(server_cid0, server_cid2);
2966 EXPECT_NE(server_cid1, server_cid2);
2967 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
2968 client_connection)
2969 .IsEmpty());
2970
2971 // Send another request using the new socket and wait for response making sure
2972 // path response is received at server.
2973 SendSynchronousBarRequestAndCheckResponse();
2974 EXPECT_EQ(2u,
2975 client_connection->GetStats().num_connectivity_probing_received);
2976
2977 // Migrate socket back to an old IP address.
2978 WaitForNewConnectionIds();
2979 EXPECT_EQ(2u, client_connection->GetStats().num_retire_connection_id_sent);
2980 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
2981 client_connection)
2982 .IsEmpty());
2983 EXPECT_TRUE(client_->client()->MigrateSocket(host1));
2984 QuicConnectionId server_cid3 = client_connection->connection_id();
2985 EXPECT_FALSE(server_cid3.IsEmpty());
2986 EXPECT_NE(server_cid0, server_cid3);
2987 EXPECT_NE(server_cid1, server_cid3);
2988 EXPECT_NE(server_cid2, server_cid3);
2989 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
2990 client_connection)
2991 .IsEmpty());
2992 const auto* client_packet_creator =
2993 QuicConnectionPeer::GetPacketCreator(client_connection);
2994 EXPECT_TRUE(client_packet_creator->GetClientConnectionId().IsEmpty());
2995 EXPECT_EQ(server_cid3, client_packet_creator->GetServerConnectionId());
2996
2997 // Send another request using the new socket and wait for response making sure
2998 // path response is received at server.
2999 SendSynchronousBarRequestAndCheckResponse();
3000 // Even this is an old path, server has forgotten about it and thus needs to
3001 // validate the path again.
3002 EXPECT_EQ(3u,
3003 client_connection->GetStats().num_connectivity_probing_received);
3004
3005 WaitForNewConnectionIds();
3006 EXPECT_EQ(3u, client_connection->GetStats().num_retire_connection_id_sent);
3007
3008 server_thread_->Pause();
3009 QuicConnection* server_connection = GetServerConnection();
3010 // By the time the 2nd request is completed, the PATH_RESPONSE must have been
3011 // received by the server.
3012 EXPECT_FALSE(server_connection->HasPendingPathValidation());
3013 EXPECT_EQ(3u, server_connection->GetStats().num_validated_peer_migration);
3014 EXPECT_EQ(server_cid3, server_connection->connection_id());
3015 const auto* server_packet_creator =
3016 QuicConnectionPeer::GetPacketCreator(server_connection);
3017 EXPECT_EQ(server_cid3, server_packet_creator->GetServerConnectionId());
3018 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3019 server_connection)
3020 .IsEmpty());
3021 EXPECT_EQ(4u, server_connection->GetStats().num_new_connection_id_sent);
3022 server_thread_->Resume();
3023 }
3024
TEST_P(EndToEndTest,ConnectionMigrationWithNonZeroConnectionIDClientIPChangedMultipleTimes)3025 TEST_P(EndToEndTest,
3026 ConnectionMigrationWithNonZeroConnectionIDClientIPChangedMultipleTimes) {
3027 if (!version_.HasIetfQuicFrames() ||
3028 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
3029 ASSERT_TRUE(Initialize());
3030 return;
3031 }
3032 override_client_connection_id_length_ = kQuicDefaultConnectionIdLength;
3033 SetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data4, false);
3034 ASSERT_TRUE(Initialize());
3035 SendSynchronousFooRequestAndCheckResponse();
3036
3037 // Store the client IP address which was used to send the first request.
3038 QuicIpAddress host0 =
3039 client_->client()->network_helper()->GetLatestClientAddress().host();
3040 QuicConnection* client_connection = GetClientConnection();
3041 ASSERT_TRUE(client_connection != nullptr);
3042
3043 // Migrate socket to a new IP address.
3044 QuicIpAddress host1 = TestLoopback(2);
3045 EXPECT_NE(host0, host1);
3046 ASSERT_TRUE(
3047 QuicConnectionPeer::HasUnusedPeerIssuedConnectionId(client_connection));
3048 QuicConnectionId server_cid0 = client_connection->connection_id();
3049 QuicConnectionId client_cid0 = client_connection->client_connection_id();
3050 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3051 client_connection)
3052 .IsEmpty());
3053 EXPECT_TRUE(QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(
3054 client_connection)
3055 .IsEmpty());
3056 EXPECT_TRUE(client_->client()->MigrateSocket(host1));
3057 QuicConnectionId server_cid1 = client_connection->connection_id();
3058 QuicConnectionId client_cid1 = client_connection->client_connection_id();
3059 EXPECT_FALSE(server_cid1.IsEmpty());
3060 EXPECT_FALSE(client_cid1.IsEmpty());
3061 EXPECT_NE(server_cid0, server_cid1);
3062 EXPECT_NE(client_cid0, client_cid1);
3063 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3064 client_connection)
3065 .IsEmpty());
3066 EXPECT_TRUE(QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(
3067 client_connection)
3068 .IsEmpty());
3069
3070 // Send another request to ensure that the server will have time to finish the
3071 // reverse path validation and send address token.
3072 SendSynchronousBarRequestAndCheckResponse();
3073 EXPECT_EQ(1u,
3074 client_connection->GetStats().num_connectivity_probing_received);
3075
3076 // Migrate socket to a new IP address.
3077 WaitForNewConnectionIds();
3078 EXPECT_EQ(1u, client_connection->GetStats().num_retire_connection_id_sent);
3079 EXPECT_EQ(2u, client_connection->GetStats().num_new_connection_id_sent);
3080 QuicIpAddress host2 = TestLoopback(3);
3081 EXPECT_NE(host0, host2);
3082 EXPECT_NE(host1, host2);
3083 EXPECT_TRUE(client_->client()->MigrateSocket(host2));
3084 QuicConnectionId server_cid2 = client_connection->connection_id();
3085 QuicConnectionId client_cid2 = client_connection->client_connection_id();
3086 EXPECT_FALSE(server_cid2.IsEmpty());
3087 EXPECT_NE(server_cid0, server_cid2);
3088 EXPECT_NE(server_cid1, server_cid2);
3089 EXPECT_FALSE(client_cid2.IsEmpty());
3090 EXPECT_NE(client_cid0, client_cid2);
3091 EXPECT_NE(client_cid1, client_cid2);
3092 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3093 client_connection)
3094 .IsEmpty());
3095 EXPECT_TRUE(QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(
3096 client_connection)
3097 .IsEmpty());
3098
3099 // Send another request to ensure that the server will have time to finish the
3100 // reverse path validation and send address token.
3101 SendSynchronousBarRequestAndCheckResponse();
3102 EXPECT_EQ(2u,
3103 client_connection->GetStats().num_connectivity_probing_received);
3104
3105 // Migrate socket back to an old IP address.
3106 WaitForNewConnectionIds();
3107 EXPECT_EQ(2u, client_connection->GetStats().num_retire_connection_id_sent);
3108 EXPECT_EQ(3u, client_connection->GetStats().num_new_connection_id_sent);
3109 EXPECT_TRUE(client_->client()->MigrateSocket(host1));
3110 QuicConnectionId server_cid3 = client_connection->connection_id();
3111 QuicConnectionId client_cid3 = client_connection->client_connection_id();
3112 EXPECT_FALSE(server_cid3.IsEmpty());
3113 EXPECT_NE(server_cid0, server_cid3);
3114 EXPECT_NE(server_cid1, server_cid3);
3115 EXPECT_NE(server_cid2, server_cid3);
3116 EXPECT_FALSE(client_cid3.IsEmpty());
3117 EXPECT_NE(client_cid0, client_cid3);
3118 EXPECT_NE(client_cid1, client_cid3);
3119 EXPECT_NE(client_cid2, client_cid3);
3120 const auto* client_packet_creator =
3121 QuicConnectionPeer::GetPacketCreator(client_connection);
3122 EXPECT_EQ(client_cid3, client_packet_creator->GetClientConnectionId());
3123 EXPECT_EQ(server_cid3, client_packet_creator->GetServerConnectionId());
3124 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3125 client_connection)
3126 .IsEmpty());
3127
3128 // Send another request to ensure that the server will have time to finish the
3129 // reverse path validation and send address token.
3130 SendSynchronousBarRequestAndCheckResponse();
3131 // Even this is an old path, server has forgotten about it and thus needs to
3132 // validate the path again.
3133 EXPECT_EQ(3u,
3134 client_connection->GetStats().num_connectivity_probing_received);
3135
3136 WaitForNewConnectionIds();
3137 EXPECT_EQ(3u, client_connection->GetStats().num_retire_connection_id_sent);
3138 EXPECT_EQ(4u, client_connection->GetStats().num_new_connection_id_sent);
3139
3140 server_thread_->Pause();
3141 // By the time the 2nd request is completed, the PATH_RESPONSE must have been
3142 // received by the server.
3143 QuicConnection* server_connection = GetServerConnection();
3144 EXPECT_FALSE(server_connection->HasPendingPathValidation());
3145 EXPECT_EQ(3u, server_connection->GetStats().num_validated_peer_migration);
3146 EXPECT_EQ(server_cid3, server_connection->connection_id());
3147 EXPECT_EQ(client_cid3, server_connection->client_connection_id());
3148 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3149 server_connection)
3150 .IsEmpty());
3151 const auto* server_packet_creator =
3152 QuicConnectionPeer::GetPacketCreator(server_connection);
3153 EXPECT_EQ(client_cid3, server_packet_creator->GetClientConnectionId());
3154 EXPECT_EQ(server_cid3, server_packet_creator->GetServerConnectionId());
3155 EXPECT_EQ(3u, server_connection->GetStats().num_retire_connection_id_sent);
3156 EXPECT_EQ(4u, server_connection->GetStats().num_new_connection_id_sent);
3157 server_thread_->Resume();
3158 }
3159
TEST_P(EndToEndTest,ConnectionMigrationNewTokenForNewIp)3160 TEST_P(EndToEndTest, ConnectionMigrationNewTokenForNewIp) {
3161 ASSERT_TRUE(Initialize());
3162 if (!version_.HasIetfQuicFrames() ||
3163 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
3164 return;
3165 }
3166 SendSynchronousFooRequestAndCheckResponse();
3167
3168 // Store the client IP address which was used to send the first request.
3169 QuicIpAddress old_host =
3170 client_->client()->network_helper()->GetLatestClientAddress().host();
3171
3172 // Migrate socket to the new IP address.
3173 QuicIpAddress new_host = TestLoopback(2);
3174 EXPECT_NE(old_host, new_host);
3175 ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
3176
3177 // Send a request using the new socket.
3178 SendSynchronousBarRequestAndCheckResponse();
3179 QuicConnection* client_connection = GetClientConnection();
3180 ASSERT_TRUE(client_connection);
3181 EXPECT_EQ(1u,
3182 client_connection->GetStats().num_connectivity_probing_received);
3183
3184 // Send another request to ensure that the server will have time to finish the
3185 // reverse path validation and send address token.
3186 SendSynchronousBarRequestAndCheckResponse();
3187
3188 client_->Disconnect();
3189 // The 0-RTT handshake should succeed.
3190 client_->Connect();
3191 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3192 ASSERT_TRUE(client_->client()->connected());
3193 SendSynchronousFooRequestAndCheckResponse();
3194
3195 EXPECT_TRUE(GetClientSession()->EarlyDataAccepted());
3196 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
3197
3198 server_thread_->Pause();
3199 QuicConnection* server_connection = GetServerConnection();
3200 if (server_connection != nullptr) {
3201 // Verify address is validated via validating token received in INITIAL
3202 // packet.
3203 EXPECT_FALSE(
3204 server_connection->GetStats().address_validated_via_decrypting_packet);
3205 EXPECT_TRUE(server_connection->GetStats().address_validated_via_token);
3206 } else {
3207 ADD_FAILURE() << "Missing server connection";
3208 }
3209 server_thread_->Resume();
3210 client_->Disconnect();
3211 }
3212
3213 // A writer which copies the packet and send the copy with a specified self
3214 // address and then send the same packet with the original self address.
3215 class DuplicatePacketWithSpoofedSelfAddressWriter
3216 : public QuicPacketWriterWrapper {
3217 public:
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,PerPacketOptions * options,const QuicPacketWriterParams & params)3218 WriteResult WritePacket(const char* buffer, size_t buf_len,
3219 const QuicIpAddress& self_address,
3220 const QuicSocketAddress& peer_address,
3221 PerPacketOptions* options,
3222 const QuicPacketWriterParams& params) override {
3223 if (self_address_to_overwrite_.IsInitialized()) {
3224 // Send the same packet on the overwriting address before sending on the
3225 // actual self address.
3226 QuicPacketWriterWrapper::WritePacket(buffer, buf_len,
3227 self_address_to_overwrite_,
3228 peer_address, options, params);
3229 }
3230 return QuicPacketWriterWrapper::WritePacket(buffer, buf_len, self_address,
3231 peer_address, options, params);
3232 }
3233
set_self_address_to_overwrite(const QuicIpAddress & self_address)3234 void set_self_address_to_overwrite(const QuicIpAddress& self_address) {
3235 self_address_to_overwrite_ = self_address;
3236 }
3237
3238 private:
3239 QuicIpAddress self_address_to_overwrite_;
3240 };
3241
TEST_P(EndToEndTest,ClientAddressSpoofedForSomePeriod)3242 TEST_P(EndToEndTest, ClientAddressSpoofedForSomePeriod) {
3243 ASSERT_TRUE(Initialize());
3244 if (!version_.HasIetfQuicFrames()) {
3245 return;
3246 }
3247 auto writer = new DuplicatePacketWithSpoofedSelfAddressWriter();
3248 client_.reset(CreateQuicClient(writer));
3249
3250 // Make sure client has unused peer connection ID before migration.
3251 SendSynchronousFooRequestAndCheckResponse();
3252 ASSERT_TRUE(QuicConnectionPeer::HasUnusedPeerIssuedConnectionId(
3253 GetClientConnection()));
3254
3255 QuicIpAddress real_host =
3256 client_->client()->session()->connection()->self_address().host();
3257 ASSERT_TRUE(client_->MigrateSocket(real_host));
3258 SendSynchronousFooRequestAndCheckResponse();
3259 EXPECT_EQ(
3260 0u, GetClientConnection()->GetStats().num_connectivity_probing_received);
3261 EXPECT_EQ(
3262 real_host,
3263 client_->client()->network_helper()->GetLatestClientAddress().host());
3264 client_->WaitForDelayedAcks();
3265
3266 std::string large_body(10240, 'a');
3267 AddToCache("/large_response", 200, large_body);
3268
3269 QuicIpAddress spoofed_host = TestLoopback(2);
3270 writer->set_self_address_to_overwrite(spoofed_host);
3271
3272 client_->SendRequest("/large_response");
3273 QuicConnection* client_connection = GetClientConnection();
3274 QuicPacketCount num_packets_received =
3275 client_connection->GetStats().packets_received;
3276
3277 while (client_->client()->WaitForEvents() && client_->connected()) {
3278 if (client_connection->GetStats().packets_received > num_packets_received) {
3279 // Ideally the client won't receive any packets till the server finds out
3280 // the new client address is not working. But there are 2 corner cases:
3281 // 1) Before the server received the packet from spoofed address, it might
3282 // send packets to the real client address. So the client will immediately
3283 // switch back to use the original address;
3284 // 2) Between the server fails reverse path validation and the client
3285 // receives packets again, the client might sent some packets with the
3286 // spoofed address and triggers another migration.
3287 // In both corner cases, the attempted migration should fail and fall back
3288 // to the working path.
3289 writer->set_self_address_to_overwrite(QuicIpAddress());
3290 }
3291 }
3292 client_->WaitForResponse();
3293 EXPECT_EQ(large_body, client_->response_body());
3294 }
3295
TEST_P(EndToEndTest,AsynchronousConnectionMigrationClientIPChangedMultipleTimes)3296 TEST_P(EndToEndTest,
3297 AsynchronousConnectionMigrationClientIPChangedMultipleTimes) {
3298 ASSERT_TRUE(Initialize());
3299 if (!version_.HasIetfQuicFrames()) {
3300 return;
3301 }
3302 client_.reset(CreateQuicClient(nullptr));
3303
3304 SendSynchronousFooRequestAndCheckResponse();
3305
3306 // Store the client IP address which was used to send the first request.
3307 QuicIpAddress host0 =
3308 client_->client()->network_helper()->GetLatestClientAddress().host();
3309 QuicConnection* client_connection = GetClientConnection();
3310 QuicConnectionId server_cid0 = client_connection->connection_id();
3311 // Server should have one new connection ID upon handshake completion.
3312 ASSERT_TRUE(
3313 QuicConnectionPeer::HasUnusedPeerIssuedConnectionId(client_connection));
3314
3315 // Migrate socket to new IP address #1.
3316 QuicIpAddress host1 = TestLoopback(2);
3317 EXPECT_NE(host0, host1);
3318 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host1));
3319 while (client_->client()->HasPendingPathValidation()) {
3320 client_->client()->WaitForEvents();
3321 }
3322 EXPECT_EQ(host1, client_->client()->session()->self_address().host());
3323 EXPECT_EQ(1u,
3324 client_connection->GetStats().num_connectivity_probing_received);
3325 QuicConnectionId server_cid1 = client_connection->connection_id();
3326 EXPECT_NE(server_cid0, server_cid1);
3327 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3328 client_connection)
3329 .IsEmpty());
3330
3331 // Send a request using the new socket.
3332 SendSynchronousBarRequestAndCheckResponse();
3333
3334 // Migrate socket to new IP address #2.
3335 WaitForNewConnectionIds();
3336 QuicIpAddress host2 = TestLoopback(3);
3337 EXPECT_NE(host0, host1);
3338 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host2));
3339
3340 while (client_->client()->HasPendingPathValidation()) {
3341 client_->client()->WaitForEvents();
3342 }
3343 EXPECT_EQ(host2, client_->client()->session()->self_address().host());
3344 EXPECT_EQ(2u,
3345 client_connection->GetStats().num_connectivity_probing_received);
3346 QuicConnectionId server_cid2 = client_connection->connection_id();
3347 EXPECT_NE(server_cid0, server_cid2);
3348 EXPECT_NE(server_cid1, server_cid2);
3349 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3350 client_connection)
3351 .IsEmpty());
3352
3353 // Send a request using the new socket.
3354 SendSynchronousBarRequestAndCheckResponse();
3355
3356 // Migrate socket back to IP address #1.
3357 WaitForNewConnectionIds();
3358 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host1));
3359
3360 while (client_->client()->HasPendingPathValidation()) {
3361 client_->client()->WaitForEvents();
3362 }
3363 EXPECT_EQ(host1, client_->client()->session()->self_address().host());
3364 EXPECT_EQ(3u,
3365 client_connection->GetStats().num_connectivity_probing_received);
3366 QuicConnectionId server_cid3 = client_connection->connection_id();
3367 EXPECT_NE(server_cid0, server_cid3);
3368 EXPECT_NE(server_cid1, server_cid3);
3369 EXPECT_NE(server_cid2, server_cid3);
3370 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3371 client_connection)
3372 .IsEmpty());
3373
3374 // Send a request using the new socket.
3375 SendSynchronousBarRequestAndCheckResponse();
3376 server_thread_->Pause();
3377 const QuicConnection* server_connection = GetServerConnection();
3378 EXPECT_EQ(server_connection->connection_id(), server_cid3);
3379 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
3380 server_connection)
3381 .IsEmpty());
3382 server_thread_->Resume();
3383
3384 // There should be 1 new connection ID issued by the server.
3385 WaitForNewConnectionIds();
3386 }
3387
TEST_P(EndToEndTest,AsynchronousConnectionMigrationClientIPChangedWithNonEmptyClientCID)3388 TEST_P(EndToEndTest,
3389 AsynchronousConnectionMigrationClientIPChangedWithNonEmptyClientCID) {
3390 if (!version_.HasIetfQuicFrames()) {
3391 ASSERT_TRUE(Initialize());
3392 return;
3393 }
3394 override_client_connection_id_length_ = kQuicDefaultConnectionIdLength;
3395 ASSERT_TRUE(Initialize());
3396 client_.reset(CreateQuicClient(nullptr));
3397
3398 SendSynchronousFooRequestAndCheckResponse();
3399
3400 // Store the client IP address which was used to send the first request.
3401 QuicIpAddress old_host =
3402 client_->client()->network_helper()->GetLatestClientAddress().host();
3403 auto* client_connection = GetClientConnection();
3404 QuicConnectionId client_cid0 = client_connection->client_connection_id();
3405 QuicConnectionId server_cid0 = client_connection->connection_id();
3406
3407 // Migrate socket to the new IP address.
3408 QuicIpAddress new_host = TestLoopback(2);
3409 EXPECT_NE(old_host, new_host);
3410 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(new_host));
3411
3412 while (client_->client()->HasPendingPathValidation()) {
3413 client_->client()->WaitForEvents();
3414 }
3415 EXPECT_EQ(new_host, client_->client()->session()->self_address().host());
3416 EXPECT_EQ(1u,
3417 client_connection->GetStats().num_connectivity_probing_received);
3418 QuicConnectionId client_cid1 = client_connection->client_connection_id();
3419 QuicConnectionId server_cid1 = client_connection->connection_id();
3420 const auto* client_packet_creator =
3421 QuicConnectionPeer::GetPacketCreator(client_connection);
3422 EXPECT_EQ(client_cid1, client_packet_creator->GetClientConnectionId());
3423 EXPECT_EQ(server_cid1, client_packet_creator->GetServerConnectionId());
3424 // Send a request using the new socket.
3425 SendSynchronousBarRequestAndCheckResponse();
3426
3427 server_thread_->Pause();
3428 QuicConnection* server_connection = GetServerConnection();
3429 EXPECT_EQ(client_cid1, server_connection->client_connection_id());
3430 EXPECT_EQ(server_cid1, server_connection->connection_id());
3431 const auto* server_packet_creator =
3432 QuicConnectionPeer::GetPacketCreator(server_connection);
3433 EXPECT_EQ(client_cid1, server_packet_creator->GetClientConnectionId());
3434 EXPECT_EQ(server_cid1, server_packet_creator->GetServerConnectionId());
3435 server_thread_->Resume();
3436 }
3437
TEST_P(EndToEndTest,ConnectionMigrationClientPortChanged)3438 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
3439 // Tests that the client's port can change during an established QUIC
3440 // connection, and that doing so does not result in the connection being
3441 // closed by the server.
3442 ASSERT_TRUE(Initialize());
3443
3444 SendSynchronousFooRequestAndCheckResponse();
3445
3446 // Store the client address which was used to send the first request.
3447 QuicSocketAddress old_address =
3448 client_->client()->network_helper()->GetLatestClientAddress();
3449 int old_fd = client_->client()->GetLatestFD();
3450
3451 // Create a new socket before closing the old one, which will result in a new
3452 // ephemeral port.
3453 client_->client()->network_helper()->CreateUDPSocketAndBind(
3454 client_->client()->server_address(), client_->client()->bind_to_address(),
3455 client_->client()->local_port());
3456
3457 // Stop listening and close the old FD.
3458 client_->client()->default_network_helper()->CleanUpUDPSocket(old_fd);
3459
3460 // The packet writer needs to be updated to use the new FD.
3461 client_->client()->network_helper()->CreateQuicPacketWriter();
3462
3463 // Change the internal state of the client and connection to use the new port,
3464 // this is done because in a real NAT rebinding the client wouldn't see any
3465 // port change, and so expects no change to incoming port.
3466 // This is kind of ugly, but needed as we are simply swapping out the client
3467 // FD rather than any more complex NAT rebinding simulation.
3468 int new_port =
3469 client_->client()->network_helper()->GetLatestClientAddress().port();
3470 client_->client()->default_network_helper()->SetClientPort(new_port);
3471 QuicConnection* client_connection = GetClientConnection();
3472 ASSERT_TRUE(client_connection);
3473 QuicConnectionPeer::SetSelfAddress(
3474 client_connection,
3475 QuicSocketAddress(client_connection->self_address().host(), new_port));
3476
3477 // Send a second request, using the new FD.
3478 SendSynchronousBarRequestAndCheckResponse();
3479
3480 // Verify that the client's ephemeral port is different.
3481 QuicSocketAddress new_address =
3482 client_->client()->network_helper()->GetLatestClientAddress();
3483 EXPECT_EQ(old_address.host(), new_address.host());
3484 EXPECT_NE(old_address.port(), new_address.port());
3485
3486 if (!version_.HasIetfQuicFrames()) {
3487 return;
3488 }
3489
3490 server_thread_->Pause();
3491 QuicConnection* server_connection = GetServerConnection();
3492 if (server_connection != nullptr) {
3493 EXPECT_FALSE(server_connection->HasPendingPathValidation());
3494 EXPECT_EQ(1u, server_connection->GetStats().num_validated_peer_migration);
3495 } else {
3496 ADD_FAILURE() << "Missing server connection";
3497 }
3498 server_thread_->Resume();
3499 }
3500
TEST_P(EndToEndTest,NegotiatedInitialCongestionWindow)3501 TEST_P(EndToEndTest, NegotiatedInitialCongestionWindow) {
3502 client_extra_copts_.push_back(kIW03);
3503
3504 ASSERT_TRUE(Initialize());
3505
3506 // Values are exchanged during crypto handshake, so wait for that to finish.
3507 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3508 server_thread_->WaitForCryptoHandshakeConfirmed();
3509 server_thread_->Pause();
3510 QuicConnection* server_connection = GetServerConnection();
3511 if (server_connection != nullptr) {
3512 QuicPacketCount cwnd =
3513 server_connection->sent_packet_manager().initial_congestion_window();
3514 EXPECT_EQ(3u, cwnd);
3515 } else {
3516 ADD_FAILURE() << "Missing server connection";
3517 }
3518 server_thread_->Resume();
3519 }
3520
TEST_P(EndToEndTest,DifferentFlowControlWindows)3521 TEST_P(EndToEndTest, DifferentFlowControlWindows) {
3522 // Client and server can set different initial flow control receive windows.
3523 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
3524 // in the crypto handshake.
3525 const uint32_t kClientStreamIFCW = 123456;
3526 const uint32_t kClientSessionIFCW = 234567;
3527 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
3528 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
3529
3530 uint32_t kServerStreamIFCW = 32 * 1024;
3531 uint32_t kServerSessionIFCW = 48 * 1024;
3532 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
3533 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
3534
3535 ASSERT_TRUE(Initialize());
3536
3537 // Values are exchanged during crypto handshake, so wait for that to finish.
3538 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3539 server_thread_->WaitForCryptoHandshakeConfirmed();
3540
3541 // Open a data stream to make sure the stream level flow control is updated.
3542 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
3543 WriteHeadersOnStream(stream);
3544 stream->WriteOrBufferBody("hello", false);
3545
3546 if (!version_.UsesTls()) {
3547 // IFWA only exists with QUIC_CRYPTO.
3548 // Client should have the right values for server's receive window.
3549 ASSERT_TRUE(client_->client()
3550 ->client_session()
3551 ->config()
3552 ->HasReceivedInitialStreamFlowControlWindowBytes());
3553 EXPECT_EQ(kServerStreamIFCW,
3554 client_->client()
3555 ->client_session()
3556 ->config()
3557 ->ReceivedInitialStreamFlowControlWindowBytes());
3558 ASSERT_TRUE(client_->client()
3559 ->client_session()
3560 ->config()
3561 ->HasReceivedInitialSessionFlowControlWindowBytes());
3562 EXPECT_EQ(kServerSessionIFCW,
3563 client_->client()
3564 ->client_session()
3565 ->config()
3566 ->ReceivedInitialSessionFlowControlWindowBytes());
3567 }
3568 EXPECT_EQ(kServerStreamIFCW, QuicStreamPeer::SendWindowOffset(stream));
3569 QuicSpdyClientSession* client_session = GetClientSession();
3570 ASSERT_TRUE(client_session);
3571 EXPECT_EQ(kServerSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
3572 client_session->flow_controller()));
3573
3574 // Server should have the right values for client's receive window.
3575 server_thread_->Pause();
3576 QuicSpdySession* server_session = GetServerSession();
3577 if (server_session == nullptr) {
3578 ADD_FAILURE() << "Missing server session";
3579 server_thread_->Resume();
3580 return;
3581 }
3582 QuicConfig server_config = *server_session->config();
3583 EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
3584 server_session->flow_controller()));
3585 server_thread_->Resume();
3586 if (version_.UsesTls()) {
3587 // IFWA only exists with QUIC_CRYPTO.
3588 return;
3589 }
3590 ASSERT_TRUE(server_config.HasReceivedInitialStreamFlowControlWindowBytes());
3591 EXPECT_EQ(kClientStreamIFCW,
3592 server_config.ReceivedInitialStreamFlowControlWindowBytes());
3593 ASSERT_TRUE(server_config.HasReceivedInitialSessionFlowControlWindowBytes());
3594 EXPECT_EQ(kClientSessionIFCW,
3595 server_config.ReceivedInitialSessionFlowControlWindowBytes());
3596 }
3597
3598 // Test negotiation of IFWA connection option.
TEST_P(EndToEndTest,NegotiatedServerInitialFlowControlWindow)3599 TEST_P(EndToEndTest, NegotiatedServerInitialFlowControlWindow) {
3600 const uint32_t kClientStreamIFCW = 123456;
3601 const uint32_t kClientSessionIFCW = 234567;
3602 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
3603 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
3604
3605 uint32_t kServerStreamIFCW = 32 * 1024;
3606 uint32_t kServerSessionIFCW = 48 * 1024;
3607 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
3608 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
3609
3610 // Bump the window.
3611 const uint32_t kExpectedStreamIFCW = 1024 * 1024;
3612 const uint32_t kExpectedSessionIFCW = 1.5 * 1024 * 1024;
3613 client_extra_copts_.push_back(kIFWA);
3614
3615 ASSERT_TRUE(Initialize());
3616
3617 // Values are exchanged during crypto handshake, so wait for that to finish.
3618 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3619 server_thread_->WaitForCryptoHandshakeConfirmed();
3620
3621 // Open a data stream to make sure the stream level flow control is updated.
3622 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
3623 WriteHeadersOnStream(stream);
3624 stream->WriteOrBufferBody("hello", false);
3625
3626 QuicSpdyClientSession* client_session = GetClientSession();
3627 ASSERT_TRUE(client_session);
3628
3629 if (!version_.UsesTls()) {
3630 // IFWA only exists with QUIC_CRYPTO.
3631 // Client should have the right values for server's receive window.
3632 ASSERT_TRUE(client_session->config()
3633 ->HasReceivedInitialStreamFlowControlWindowBytes());
3634 EXPECT_EQ(kExpectedStreamIFCW,
3635 client_session->config()
3636 ->ReceivedInitialStreamFlowControlWindowBytes());
3637 ASSERT_TRUE(client_session->config()
3638 ->HasReceivedInitialSessionFlowControlWindowBytes());
3639 EXPECT_EQ(kExpectedSessionIFCW,
3640 client_session->config()
3641 ->ReceivedInitialSessionFlowControlWindowBytes());
3642 }
3643 EXPECT_EQ(kExpectedStreamIFCW, QuicStreamPeer::SendWindowOffset(stream));
3644 EXPECT_EQ(kExpectedSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
3645 client_session->flow_controller()));
3646 }
3647
TEST_P(EndToEndTest,HeadersAndCryptoStreamsNoConnectionFlowControl)3648 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
3649 // The special headers and crypto streams should be subject to per-stream flow
3650 // control limits, but should not be subject to connection level flow control
3651 const uint32_t kStreamIFCW = 32 * 1024;
3652 const uint32_t kSessionIFCW = 48 * 1024;
3653 set_client_initial_stream_flow_control_receive_window(kStreamIFCW);
3654 set_client_initial_session_flow_control_receive_window(kSessionIFCW);
3655 set_server_initial_stream_flow_control_receive_window(kStreamIFCW);
3656 set_server_initial_session_flow_control_receive_window(kSessionIFCW);
3657
3658 ASSERT_TRUE(Initialize());
3659
3660 // Wait for crypto handshake to finish. This should have contributed to the
3661 // crypto stream flow control window, but not affected the session flow
3662 // control window.
3663 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3664 server_thread_->WaitForCryptoHandshakeConfirmed();
3665
3666 QuicSpdyClientSession* client_session = GetClientSession();
3667 ASSERT_TRUE(client_session);
3668 QuicCryptoStream* crypto_stream =
3669 QuicSessionPeer::GetMutableCryptoStream(client_session);
3670 ASSERT_TRUE(crypto_stream);
3671 // In v47 and later, the crypto handshake (sent in CRYPTO frames) is not
3672 // subject to flow control.
3673 if (!version_.UsesCryptoFrames()) {
3674 EXPECT_LT(QuicStreamPeer::SendWindowSize(crypto_stream), kStreamIFCW);
3675 }
3676 // When stream type is enabled, control streams will send settings and
3677 // contribute to flow control windows, so this expectation is no longer valid.
3678 if (!version_.UsesHttp3()) {
3679 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
3680 client_session->flow_controller()));
3681 }
3682
3683 // Send a request with no body, and verify that the connection level window
3684 // has not been affected.
3685 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
3686
3687 // No headers stream in IETF QUIC.
3688 if (version_.UsesHttp3()) {
3689 return;
3690 }
3691
3692 QuicHeadersStream* headers_stream =
3693 QuicSpdySessionPeer::GetHeadersStream(client_session);
3694 ASSERT_TRUE(headers_stream);
3695 EXPECT_LT(QuicStreamPeer::SendWindowSize(headers_stream), kStreamIFCW);
3696 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
3697 client_session->flow_controller()));
3698
3699 // Server should be in a similar state: connection flow control window should
3700 // not have any bytes marked as received.
3701 server_thread_->Pause();
3702 QuicSession* server_session = GetServerSession();
3703 if (server_session != nullptr) {
3704 QuicFlowController* server_connection_flow_controller =
3705 server_session->flow_controller();
3706 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::ReceiveWindowSize(
3707 server_connection_flow_controller));
3708 } else {
3709 ADD_FAILURE() << "Missing server session";
3710 }
3711 server_thread_->Resume();
3712 }
3713
TEST_P(EndToEndTest,FlowControlsSynced)3714 TEST_P(EndToEndTest, FlowControlsSynced) {
3715 set_smaller_flow_control_receive_window();
3716
3717 ASSERT_TRUE(Initialize());
3718
3719 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3720 server_thread_->WaitForCryptoHandshakeConfirmed();
3721
3722 QuicSpdySession* const client_session = GetClientSession();
3723 ASSERT_TRUE(client_session);
3724
3725 if (version_.UsesHttp3()) {
3726 // Make sure that the client has received the initial SETTINGS frame, which
3727 // is sent in the first packet on the control stream.
3728 while (!QuicSpdySessionPeer::GetReceiveControlStream(client_session)) {
3729 client_->client()->WaitForEvents();
3730 ASSERT_TRUE(client_->connected());
3731 }
3732 }
3733
3734 // Make sure that all data sent by the client has been received by the server
3735 // (and the ack received by the client).
3736 while (client_session->HasUnackedStreamData()) {
3737 client_->client()->WaitForEvents();
3738 ASSERT_TRUE(client_->connected());
3739 }
3740
3741 server_thread_->Pause();
3742
3743 QuicSpdySession* const server_session = GetServerSession();
3744 if (server_session == nullptr) {
3745 ADD_FAILURE() << "Missing server session";
3746 server_thread_->Resume();
3747 return;
3748 }
3749 ExpectFlowControlsSynced(client_session, server_session);
3750
3751 // Check control streams.
3752 if (version_.UsesHttp3()) {
3753 ExpectFlowControlsSynced(
3754 QuicSpdySessionPeer::GetReceiveControlStream(client_session),
3755 QuicSpdySessionPeer::GetSendControlStream(server_session));
3756 ExpectFlowControlsSynced(
3757 QuicSpdySessionPeer::GetSendControlStream(client_session),
3758 QuicSpdySessionPeer::GetReceiveControlStream(server_session));
3759 }
3760
3761 // Check crypto stream.
3762 if (!version_.UsesCryptoFrames()) {
3763 ExpectFlowControlsSynced(
3764 QuicSessionPeer::GetMutableCryptoStream(client_session),
3765 QuicSessionPeer::GetMutableCryptoStream(server_session));
3766 }
3767
3768 // Check headers stream.
3769 if (!version_.UsesHttp3()) {
3770 SpdyFramer spdy_framer(SpdyFramer::ENABLE_COMPRESSION);
3771 SpdySettingsIR settings_frame;
3772 settings_frame.AddSetting(spdy::SETTINGS_MAX_HEADER_LIST_SIZE,
3773 kDefaultMaxUncompressedHeaderSize);
3774 SpdySerializedFrame frame(spdy_framer.SerializeFrame(settings_frame));
3775
3776 QuicHeadersStream* client_header_stream =
3777 QuicSpdySessionPeer::GetHeadersStream(client_session);
3778 QuicHeadersStream* server_header_stream =
3779 QuicSpdySessionPeer::GetHeadersStream(server_session);
3780 // Both client and server are sending this SETTINGS frame, and the send
3781 // window is consumed. But because of timing issue, the server may send or
3782 // not send the frame, and the client may send/ not send / receive / not
3783 // receive the frame.
3784 // TODO(fayang): Rewrite this part because it is hacky.
3785 QuicByteCount win_difference1 =
3786 QuicStreamPeer::ReceiveWindowSize(server_header_stream) -
3787 QuicStreamPeer::SendWindowSize(client_header_stream);
3788 if (win_difference1 != 0) {
3789 EXPECT_EQ(frame.size(), win_difference1);
3790 }
3791
3792 QuicByteCount win_difference2 =
3793 QuicStreamPeer::ReceiveWindowSize(client_header_stream) -
3794 QuicStreamPeer::SendWindowSize(server_header_stream);
3795 if (win_difference2 != 0) {
3796 EXPECT_EQ(frame.size(), win_difference2);
3797 }
3798
3799 // Client *may* have received the SETTINGs frame.
3800 // TODO(fayang): Rewrite this part because it is hacky.
3801 float ratio1 = static_cast<float>(QuicFlowControllerPeer::ReceiveWindowSize(
3802 client_session->flow_controller())) /
3803 QuicStreamPeer::ReceiveWindowSize(
3804 QuicSpdySessionPeer::GetHeadersStream(client_session));
3805 float ratio2 = static_cast<float>(QuicFlowControllerPeer::ReceiveWindowSize(
3806 client_session->flow_controller())) /
3807 (QuicStreamPeer::ReceiveWindowSize(
3808 QuicSpdySessionPeer::GetHeadersStream(client_session)) +
3809 frame.size());
3810 EXPECT_TRUE(ratio1 == kSessionToStreamRatio ||
3811 ratio2 == kSessionToStreamRatio);
3812 }
3813
3814 server_thread_->Resume();
3815 }
3816
TEST_P(EndToEndTest,RequestWithNoBodyWillNeverSendStreamFrameWithFIN)3817 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
3818 // A stream created on receipt of a simple request with no body will never get
3819 // a stream frame with a FIN. Verify that we don't keep track of the stream in
3820 // the locally closed streams map: it will never be removed if so.
3821 ASSERT_TRUE(Initialize());
3822
3823 // Send a simple headers only request, and receive response.
3824 SendSynchronousFooRequestAndCheckResponse();
3825
3826 // Now verify that the server is not waiting for a final FIN or RST.
3827 server_thread_->Pause();
3828 QuicSession* server_session = GetServerSession();
3829 if (server_session != nullptr) {
3830 EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
3831 server_session)
3832 .size());
3833 } else {
3834 ADD_FAILURE() << "Missing server session";
3835 }
3836 server_thread_->Resume();
3837 }
3838
3839 // TestAckListener counts how many bytes are acked during its lifetime.
3840 class TestAckListener : public QuicAckListenerInterface {
3841 public:
TestAckListener()3842 TestAckListener() {}
3843
OnPacketAcked(int acked_bytes,QuicTime::Delta)3844 void OnPacketAcked(int acked_bytes,
3845 QuicTime::Delta /*delta_largest_observed*/) override {
3846 total_bytes_acked_ += acked_bytes;
3847 }
3848
OnPacketRetransmitted(int)3849 void OnPacketRetransmitted(int /*retransmitted_bytes*/) override {}
3850
total_bytes_acked() const3851 int total_bytes_acked() const { return total_bytes_acked_; }
3852
3853 protected:
3854 // Object is ref counted.
~TestAckListener()3855 ~TestAckListener() override {}
3856
3857 private:
3858 int total_bytes_acked_ = 0;
3859 };
3860
3861 class TestResponseListener : public QuicSpdyClientBase::ResponseListener {
3862 public:
OnCompleteResponse(QuicStreamId id,const Http2HeaderBlock & response_headers,absl::string_view response_body)3863 void OnCompleteResponse(QuicStreamId id,
3864 const Http2HeaderBlock& response_headers,
3865 absl::string_view response_body) override {
3866 QUIC_DVLOG(1) << "response for stream " << id << " "
3867 << response_headers.DebugString() << "\n"
3868 << response_body;
3869 }
3870 };
3871
TEST_P(EndToEndTest,AckNotifierWithPacketLossAndBlockedSocket)3872 TEST_P(EndToEndTest, AckNotifierWithPacketLossAndBlockedSocket) {
3873 // Verify that even in the presence of packet loss and occasionally blocked
3874 // socket, an AckNotifierDelegate will get informed that the data it is
3875 // interested in has been ACKed. This tests end-to-end ACK notification, and
3876 // demonstrates that retransmissions do not break this functionality.
3877 // Disable blackhole detection as this test is testing loss recovery.
3878 client_extra_copts_.push_back(kNBHD);
3879 SetPacketLossPercentage(5);
3880 ASSERT_TRUE(Initialize());
3881 // Wait for the server SHLO before upping the packet loss.
3882 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
3883 SetPacketLossPercentage(30);
3884 client_writer_->set_fake_blocked_socket_percentage(10);
3885
3886 // Wait for SETTINGS frame from server that sets QPACK dynamic table capacity
3887 // to make sure request headers will be compressed using the dynamic table.
3888 if (version_.UsesHttp3()) {
3889 while (true) {
3890 // Waits for up to 50 ms.
3891 client_->client()->WaitForEvents();
3892 ASSERT_TRUE(client_->connected());
3893 QuicSpdyClientSession* client_session = GetClientSession();
3894 if (client_session == nullptr) {
3895 ADD_FAILURE() << "Missing client session";
3896 return;
3897 }
3898 QpackEncoder* qpack_encoder = client_session->qpack_encoder();
3899 if (qpack_encoder == nullptr) {
3900 ADD_FAILURE() << "Missing QPACK encoder";
3901 return;
3902 }
3903 QpackEncoderHeaderTable* header_table =
3904 QpackEncoderPeer::header_table(qpack_encoder);
3905 if (header_table == nullptr) {
3906 ADD_FAILURE() << "Missing header table";
3907 return;
3908 }
3909 if (header_table->dynamic_table_capacity() > 0) {
3910 break;
3911 }
3912 }
3913 }
3914
3915 // Create a POST request and send the headers only.
3916 Http2HeaderBlock headers;
3917 headers[":method"] = "POST";
3918 headers[":path"] = "/foo";
3919 headers[":scheme"] = "https";
3920 headers[":authority"] = server_hostname_;
3921
3922 // Here, we have to specify flush=false, otherwise we risk a race condition in
3923 // which the headers are sent and acknowledged before the ack notifier is
3924 // installed.
3925 client_->SendMessage(headers, "", /*fin=*/false, /*flush=*/false);
3926
3927 // Size of headers on the request stream. This is zero if headers are sent on
3928 // the header stream.
3929 size_t header_size = 0;
3930 if (version_.UsesHttp3()) {
3931 // Determine size of headers after QPACK compression.
3932 NoopDecoderStreamErrorDelegate decoder_stream_error_delegate;
3933 NoopQpackStreamSenderDelegate encoder_stream_sender_delegate;
3934 QpackEncoder qpack_encoder(&decoder_stream_error_delegate,
3935 HuffmanEncoding::kEnabled);
3936 qpack_encoder.set_qpack_stream_sender_delegate(
3937 &encoder_stream_sender_delegate);
3938
3939 qpack_encoder.SetMaximumDynamicTableCapacity(
3940 kDefaultQpackMaxDynamicTableCapacity);
3941 qpack_encoder.SetDynamicTableCapacity(kDefaultQpackMaxDynamicTableCapacity);
3942 qpack_encoder.SetMaximumBlockedStreams(kDefaultMaximumBlockedStreams);
3943
3944 std::string encoded_headers = qpack_encoder.EncodeHeaderList(
3945 /* stream_id = */ 0, headers, nullptr);
3946 header_size = encoded_headers.size();
3947 }
3948
3949 // Test the AckNotifier's ability to track multiple packets by making the
3950 // request body exceed the size of a single packet.
3951 std::string request_string = "a request body bigger than one packet" +
3952 std::string(kMaxOutgoingPacketSize, '.');
3953
3954 const int expected_bytes_acked = header_size + request_string.length();
3955
3956 // The TestAckListener will cause a failure if not notified.
3957 quiche::QuicheReferenceCountedPointer<TestAckListener> ack_listener(
3958 new TestAckListener());
3959
3960 // Send the request, and register the delegate for ACKs.
3961 client_->SendData(request_string, true, ack_listener);
3962 WaitForFooResponseAndCheckIt();
3963
3964 // Send another request to flush out any pending ACKs on the server.
3965 SendSynchronousBarRequestAndCheckResponse();
3966
3967 // Make sure the delegate does get the notification it expects.
3968 int attempts = 0;
3969 constexpr int kMaxAttempts = 20;
3970 while (ack_listener->total_bytes_acked() < expected_bytes_acked) {
3971 // Waits for up to 50 ms.
3972 client_->client()->WaitForEvents();
3973 ASSERT_TRUE(client_->connected());
3974 if (++attempts >= kMaxAttempts) {
3975 break;
3976 }
3977 }
3978 EXPECT_EQ(ack_listener->total_bytes_acked(), expected_bytes_acked)
3979 << " header_size " << header_size << " request length "
3980 << request_string.length();
3981 }
3982
3983 // Send a public reset from the server.
TEST_P(EndToEndTest,ServerSendPublicReset)3984 TEST_P(EndToEndTest, ServerSendPublicReset) {
3985 ASSERT_TRUE(Initialize());
3986
3987 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3988 QuicSpdySession* client_session = GetClientSession();
3989 ASSERT_TRUE(client_session);
3990 QuicConfig* config = client_session->config();
3991 ASSERT_TRUE(config);
3992 EXPECT_TRUE(config->HasReceivedStatelessResetToken());
3993 StatelessResetToken stateless_reset_token =
3994 config->ReceivedStatelessResetToken();
3995
3996 // Send the public reset.
3997 QuicConnection* client_connection = GetClientConnection();
3998 ASSERT_TRUE(client_connection);
3999 QuicConnectionId connection_id = client_connection->connection_id();
4000 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
4001 Perspective::IS_SERVER, kQuicDefaultConnectionIdLength);
4002 std::unique_ptr<QuicEncryptedPacket> packet =
4003 framer.BuildIetfStatelessResetPacket(
4004 connection_id, /*received_packet_length=*/100, stateless_reset_token);
4005 // We must pause the server's thread in order to call WritePacket without
4006 // race conditions.
4007 server_thread_->Pause();
4008 auto client_address = client_connection->self_address();
4009 server_writer_->WritePacket(packet->data(), packet->length(),
4010 server_address_.host(), client_address, nullptr,
4011 packet_writer_params_);
4012 server_thread_->Resume();
4013
4014 // The request should fail.
4015 EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
4016 EXPECT_TRUE(client_->response_headers()->empty());
4017 EXPECT_THAT(client_->connection_error(), IsError(QUIC_PUBLIC_RESET));
4018 }
4019
4020 // Send a public reset from the server for a different connection ID.
4021 // It should be ignored.
TEST_P(EndToEndTest,ServerSendPublicResetWithDifferentConnectionId)4022 TEST_P(EndToEndTest, ServerSendPublicResetWithDifferentConnectionId) {
4023 ASSERT_TRUE(Initialize());
4024
4025 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4026 QuicSpdySession* client_session = GetClientSession();
4027 ASSERT_TRUE(client_session);
4028 QuicConfig* config = client_session->config();
4029 ASSERT_TRUE(config);
4030 EXPECT_TRUE(config->HasReceivedStatelessResetToken());
4031 StatelessResetToken stateless_reset_token =
4032 config->ReceivedStatelessResetToken();
4033 // Send the public reset.
4034 QuicConnection* client_connection = GetClientConnection();
4035 ASSERT_TRUE(client_connection);
4036 QuicConnectionId incorrect_connection_id = TestConnectionId(
4037 TestConnectionIdToUInt64(client_connection->connection_id()) + 1);
4038 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
4039 Perspective::IS_SERVER, kQuicDefaultConnectionIdLength);
4040 NiceMock<MockQuicConnectionDebugVisitor> visitor;
4041 client_connection->set_debug_visitor(&visitor);
4042 std::unique_ptr<QuicEncryptedPacket> packet =
4043 framer.BuildIetfStatelessResetPacket(incorrect_connection_id,
4044 /*received_packet_length=*/100,
4045 stateless_reset_token);
4046 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
4047 .Times(0);
4048 // We must pause the server's thread in order to call WritePacket without
4049 // race conditions.
4050 server_thread_->Pause();
4051 auto client_address = client_connection->self_address();
4052 server_writer_->WritePacket(packet->data(), packet->length(),
4053 server_address_.host(), client_address, nullptr,
4054 packet_writer_params_);
4055 server_thread_->Resume();
4056
4057 // The request should fail. IETF stateless reset does not include connection
4058 // ID.
4059 EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
4060 EXPECT_TRUE(client_->response_headers()->empty());
4061 EXPECT_THAT(client_->connection_error(), IsError(QUIC_PUBLIC_RESET));
4062
4063 client_connection->set_debug_visitor(nullptr);
4064 }
4065
TEST_P(EndToEndTest,InduceStatelessResetFromServer)4066 TEST_P(EndToEndTest, InduceStatelessResetFromServer) {
4067 ASSERT_TRUE(Initialize());
4068 if (!version_.HasIetfQuicFrames()) {
4069 return;
4070 }
4071 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
4072 SetPacketLossPercentage(100); // Block PEER_GOING_AWAY message from server.
4073 StopServer(true);
4074 server_writer_ = new PacketDroppingTestWriter();
4075 StartServer();
4076 SetPacketLossPercentage(0);
4077 // The request should generate a public reset.
4078 EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
4079 EXPECT_TRUE(client_->response_headers()->empty());
4080 EXPECT_THAT(client_->connection_error(), IsError(QUIC_PUBLIC_RESET));
4081 EXPECT_FALSE(client_->connected());
4082 }
4083
4084 // Send a public reset from the client for a different connection ID.
4085 // It should be ignored.
TEST_P(EndToEndTest,ClientSendPublicResetWithDifferentConnectionId)4086 TEST_P(EndToEndTest, ClientSendPublicResetWithDifferentConnectionId) {
4087 ASSERT_TRUE(Initialize());
4088
4089 // Send the public reset.
4090 QuicConnection* client_connection = GetClientConnection();
4091 ASSERT_TRUE(client_connection);
4092 QuicConnectionId incorrect_connection_id = TestConnectionId(
4093 TestConnectionIdToUInt64(client_connection->connection_id()) + 1);
4094 QuicPublicResetPacket header;
4095 header.connection_id = incorrect_connection_id;
4096 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
4097 Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength);
4098 std::unique_ptr<QuicEncryptedPacket> packet(
4099 framer.BuildPublicResetPacket(header));
4100 client_writer_->WritePacket(
4101 packet->data(), packet->length(),
4102 client_->client()->network_helper()->GetLatestClientAddress().host(),
4103 server_address_, nullptr, packet_writer_params_);
4104
4105 // The connection should be unaffected.
4106 SendSynchronousFooRequestAndCheckResponse();
4107 }
4108
4109 // Send a version negotiation packet from the server for a different
4110 // connection ID. It should be ignored.
TEST_P(EndToEndTest,ServerSendVersionNegotiationWithDifferentConnectionId)4111 TEST_P(EndToEndTest, ServerSendVersionNegotiationWithDifferentConnectionId) {
4112 ASSERT_TRUE(Initialize());
4113
4114 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4115
4116 // Send the version negotiation packet.
4117 QuicConnection* client_connection = GetClientConnection();
4118 ASSERT_TRUE(client_connection);
4119 QuicConnectionId incorrect_connection_id = TestConnectionId(
4120 TestConnectionIdToUInt64(client_connection->connection_id()) + 1);
4121 std::unique_ptr<QuicEncryptedPacket> packet(
4122 QuicFramer::BuildVersionNegotiationPacket(
4123 incorrect_connection_id, EmptyQuicConnectionId(), /*ietf_quic=*/true,
4124 version_.HasLengthPrefixedConnectionIds(),
4125 server_supported_versions_));
4126 NiceMock<MockQuicConnectionDebugVisitor> visitor;
4127 client_connection->set_debug_visitor(&visitor);
4128 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
4129 .Times(1);
4130 // We must pause the server's thread in order to call WritePacket without
4131 // race conditions.
4132 server_thread_->Pause();
4133 server_writer_->WritePacket(
4134 packet->data(), packet->length(), server_address_.host(),
4135 client_->client()->network_helper()->GetLatestClientAddress(), nullptr,
4136 packet_writer_params_);
4137 server_thread_->Resume();
4138
4139 // The connection should be unaffected.
4140 SendSynchronousFooRequestAndCheckResponse();
4141
4142 client_connection->set_debug_visitor(nullptr);
4143 }
4144
4145 // DowngradePacketWriter is a client writer which will intercept all the client
4146 // writes for |target_version| and reply to them with version negotiation
4147 // packets to attempt a version downgrade attack. Once the client has downgraded
4148 // to a different version, the writer stops intercepting. |server_thread| must
4149 // start off paused, and will be resumed once interception is done.
4150 class DowngradePacketWriter : public PacketDroppingTestWriter {
4151 public:
DowngradePacketWriter(const ParsedQuicVersion & target_version,const ParsedQuicVersionVector & supported_versions,QuicTestClient * client,QuicPacketWriter * server_writer,ServerThread * server_thread)4152 explicit DowngradePacketWriter(
4153 const ParsedQuicVersion& target_version,
4154 const ParsedQuicVersionVector& supported_versions, QuicTestClient* client,
4155 QuicPacketWriter* server_writer, ServerThread* server_thread)
4156 : target_version_(target_version),
4157 supported_versions_(supported_versions),
4158 client_(client),
4159 server_writer_(server_writer),
4160 server_thread_(server_thread) {}
~DowngradePacketWriter()4161 ~DowngradePacketWriter() override {}
4162
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,quic::PerPacketOptions * options,const quic::QuicPacketWriterParams & params)4163 WriteResult WritePacket(const char* buffer, size_t buf_len,
4164 const QuicIpAddress& self_address,
4165 const QuicSocketAddress& peer_address,
4166 quic::PerPacketOptions* options,
4167 const quic::QuicPacketWriterParams& params) override {
4168 if (!intercept_enabled_) {
4169 return PacketDroppingTestWriter::WritePacket(
4170 buffer, buf_len, self_address, peer_address, options, params);
4171 }
4172 PacketHeaderFormat format;
4173 QuicLongHeaderType long_packet_type;
4174 bool version_present, has_length_prefix;
4175 QuicVersionLabel version_label;
4176 ParsedQuicVersion parsed_version = ParsedQuicVersion::Unsupported();
4177 QuicConnectionId destination_connection_id, source_connection_id;
4178 std::optional<absl::string_view> retry_token;
4179 std::string detailed_error;
4180 if (QuicFramer::ParsePublicHeaderDispatcher(
4181 QuicEncryptedPacket(buffer, buf_len),
4182 kQuicDefaultConnectionIdLength, &format, &long_packet_type,
4183 &version_present, &has_length_prefix, &version_label,
4184 &parsed_version, &destination_connection_id, &source_connection_id,
4185 &retry_token, &detailed_error) != QUIC_NO_ERROR) {
4186 ADD_FAILURE() << "Failed to parse our own packet: " << detailed_error;
4187 return WriteResult(WRITE_STATUS_ERROR, 0);
4188 }
4189 if (!version_present || parsed_version != target_version_) {
4190 // Client is sending with another version, the attack has succeeded so we
4191 // can stop intercepting.
4192 intercept_enabled_ = false;
4193 server_thread_->Resume();
4194 // Pass the client-sent packet through.
4195 return WritePacket(buffer, buf_len, self_address, peer_address, options,
4196 params);
4197 }
4198 // Send a version negotiation packet.
4199 std::unique_ptr<QuicEncryptedPacket> packet(
4200 QuicFramer::BuildVersionNegotiationPacket(
4201 destination_connection_id, source_connection_id, /*ietf_quic=*/true,
4202 has_length_prefix, supported_versions_));
4203 QuicPacketWriterParams default_params;
4204 server_writer_->WritePacket(
4205 packet->data(), packet->length(), peer_address.host(),
4206 client_->client()->network_helper()->GetLatestClientAddress(), nullptr,
4207 default_params);
4208 // Drop the client-sent packet but pretend it was sent.
4209 return WriteResult(WRITE_STATUS_OK, buf_len);
4210 }
4211
4212 private:
4213 bool intercept_enabled_ = true;
4214 ParsedQuicVersion target_version_;
4215 ParsedQuicVersionVector supported_versions_;
4216 QuicTestClient* client_; // Unowned.
4217 QuicPacketWriter* server_writer_; // Unowned.
4218 ServerThread* server_thread_; // Unowned.
4219 };
4220
TEST_P(EndToEndTest,VersionNegotiationDowngradeAttackIsDetected)4221 TEST_P(EndToEndTest, VersionNegotiationDowngradeAttackIsDetected) {
4222 ParsedQuicVersion target_version = server_supported_versions_.back();
4223 if (!version_.UsesTls() || target_version == version_) {
4224 ASSERT_TRUE(Initialize());
4225 return;
4226 }
4227 connect_to_server_on_initialize_ = false;
4228 client_supported_versions_.insert(client_supported_versions_.begin(),
4229 target_version);
4230 ParsedQuicVersionVector downgrade_versions{version_};
4231 ASSERT_TRUE(Initialize());
4232 ASSERT_TRUE(server_thread_);
4233 // Pause the server thread to allow our DowngradePacketWriter to write version
4234 // negotiation packets in a thread-safe manner. It will be resumed by the
4235 // DowngradePacketWriter.
4236 server_thread_->Pause();
4237 client_.reset(new QuicTestClient(server_address_, server_hostname_,
4238 client_config_, client_supported_versions_,
4239 crypto_test_utils::ProofVerifierForTesting(),
4240 std::make_unique<QuicClientSessionCache>()));
4241 delete client_writer_;
4242 client_writer_ = new DowngradePacketWriter(target_version, downgrade_versions,
4243 client_.get(), server_writer_,
4244 server_thread_.get());
4245 client_->UseWriter(client_writer_);
4246 // Have the client attempt to send a request.
4247 client_->Connect();
4248 EXPECT_TRUE(client_->SendSynchronousRequest("/foo").empty());
4249 // Make sure the downgrade is detected and the handshake fails.
4250 EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_FAILED));
4251 }
4252
4253 // A bad header shouldn't tear down the connection, because the receiver can't
4254 // tell the connection ID.
TEST_P(EndToEndTest,BadPacketHeaderTruncated)4255 TEST_P(EndToEndTest, BadPacketHeaderTruncated) {
4256 ASSERT_TRUE(Initialize());
4257
4258 // Start the connection.
4259 SendSynchronousFooRequestAndCheckResponse();
4260
4261 // Packet with invalid public flags.
4262 char packet[] = {// public flags (8 byte connection_id)
4263 0x3C,
4264 // truncated connection ID
4265 0x11};
4266 client_writer_->WritePacket(
4267 &packet[0], sizeof(packet),
4268 client_->client()->network_helper()->GetLatestClientAddress().host(),
4269 server_address_, nullptr, packet_writer_params_);
4270 EXPECT_TRUE(server_thread_->WaitUntil(
4271 [&] {
4272 return QuicDispatcherPeer::GetAndClearLastError(
4273 QuicServerPeer::GetDispatcher(server_thread_->server())) ==
4274 QUIC_INVALID_PACKET_HEADER;
4275 },
4276 QuicTime::Delta::FromSeconds(5)));
4277
4278 // The connection should not be terminated.
4279 SendSynchronousFooRequestAndCheckResponse();
4280 }
4281
4282 // A bad header shouldn't tear down the connection, because the receiver can't
4283 // tell the connection ID.
TEST_P(EndToEndTest,BadPacketHeaderFlags)4284 TEST_P(EndToEndTest, BadPacketHeaderFlags) {
4285 ASSERT_TRUE(Initialize());
4286
4287 // Start the connection.
4288 SendSynchronousFooRequestAndCheckResponse();
4289
4290 // Packet with invalid public flags.
4291 uint8_t packet[] = {
4292 // invalid public flags
4293 0xFF,
4294 // connection_id
4295 0x10,
4296 0x32,
4297 0x54,
4298 0x76,
4299 0x98,
4300 0xBA,
4301 0xDC,
4302 0xFE,
4303 // packet sequence number
4304 0xBC,
4305 0x9A,
4306 0x78,
4307 0x56,
4308 0x34,
4309 0x12,
4310 // private flags
4311 0x00,
4312 };
4313 client_writer_->WritePacket(
4314 reinterpret_cast<const char*>(packet), sizeof(packet),
4315 client_->client()->network_helper()->GetLatestClientAddress().host(),
4316 server_address_, nullptr, packet_writer_params_);
4317
4318 EXPECT_TRUE(server_thread_->WaitUntil(
4319 [&] {
4320 return QuicDispatcherPeer::GetAndClearLastError(
4321 QuicServerPeer::GetDispatcher(server_thread_->server())) ==
4322 QUIC_INVALID_PACKET_HEADER;
4323 },
4324 QuicTime::Delta::FromSeconds(5)));
4325
4326 // The connection should not be terminated.
4327 SendSynchronousFooRequestAndCheckResponse();
4328 }
4329
4330 // Send a packet from the client with bad encrypted data. The server should not
4331 // tear down the connection.
4332 // Marked as slow since it calls absl::SleepFor().
TEST_P(EndToEndTest,QUICHE_SLOW_TEST (BadEncryptedData))4333 TEST_P(EndToEndTest, QUICHE_SLOW_TEST(BadEncryptedData)) {
4334 ASSERT_TRUE(Initialize());
4335
4336 // Start the connection.
4337 SendSynchronousFooRequestAndCheckResponse();
4338
4339 QuicConnection* client_connection = GetClientConnection();
4340 ASSERT_TRUE(client_connection);
4341 std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
4342 client_connection->connection_id(), EmptyQuicConnectionId(), false, false,
4343 1, "At least 20 characters.", CONNECTION_ID_PRESENT, CONNECTION_ID_ABSENT,
4344 PACKET_4BYTE_PACKET_NUMBER));
4345 // Damage the encrypted data.
4346 std::string damaged_packet(packet->data(), packet->length());
4347 damaged_packet[30] ^= 0x01;
4348 QUIC_DLOG(INFO) << "Sending bad packet.";
4349 client_writer_->WritePacket(
4350 damaged_packet.data(), damaged_packet.length(),
4351 client_->client()->network_helper()->GetLatestClientAddress().host(),
4352 server_address_, nullptr, packet_writer_params_);
4353 // Give the server time to process the packet.
4354 absl::SleepFor(absl::Seconds(1));
4355 // This error is sent to the connection's OnError (which ignores it), so the
4356 // dispatcher doesn't see it.
4357 // Pause the server so we can access the server's internals without races.
4358 server_thread_->Pause();
4359 QuicDispatcher* dispatcher =
4360 QuicServerPeer::GetDispatcher(server_thread_->server());
4361 if (dispatcher != nullptr) {
4362 EXPECT_THAT(QuicDispatcherPeer::GetAndClearLastError(dispatcher),
4363 IsQuicNoError());
4364 } else {
4365 ADD_FAILURE() << "Missing dispatcher";
4366 }
4367 server_thread_->Resume();
4368
4369 // The connection should not be terminated.
4370 SendSynchronousFooRequestAndCheckResponse();
4371 }
4372
TEST_P(EndToEndTest,CanceledStreamDoesNotBecomeZombie)4373 TEST_P(EndToEndTest, CanceledStreamDoesNotBecomeZombie) {
4374 ASSERT_TRUE(Initialize());
4375 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4376 // Lose the request.
4377 SetPacketLossPercentage(100);
4378 Http2HeaderBlock headers;
4379 headers[":method"] = "POST";
4380 headers[":path"] = "/foo";
4381 headers[":scheme"] = "https";
4382 headers[":authority"] = server_hostname_;
4383 client_->SendMessage(headers, "test_body", /*fin=*/false);
4384 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
4385
4386 // Cancel the stream.
4387 stream->Reset(QUIC_STREAM_CANCELLED);
4388 QuicSession* session = GetClientSession();
4389 ASSERT_TRUE(session);
4390 // Verify canceled stream does not become zombie.
4391 EXPECT_EQ(1u, QuicSessionPeer::closed_streams(session).size());
4392 }
4393
4394 // A test stream that gives |response_body_| as an error response body.
4395 class ServerStreamWithErrorResponseBody : public QuicSimpleServerStream {
4396 public:
ServerStreamWithErrorResponseBody(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend,std::string response_body)4397 ServerStreamWithErrorResponseBody(
4398 QuicStreamId id, QuicSpdySession* session,
4399 QuicSimpleServerBackend* quic_simple_server_backend,
4400 std::string response_body)
4401 : QuicSimpleServerStream(id, session, BIDIRECTIONAL,
4402 quic_simple_server_backend),
4403 response_body_(std::move(response_body)) {}
4404
4405 ~ServerStreamWithErrorResponseBody() override = default;
4406
4407 protected:
SendErrorResponse()4408 void SendErrorResponse() override {
4409 QUIC_DLOG(INFO) << "Sending error response for stream " << id();
4410 Http2HeaderBlock headers;
4411 headers[":status"] = "500";
4412 headers["content-length"] = absl::StrCat(response_body_.size());
4413 // This method must call CloseReadSide to cause the test case, StopReading
4414 // is not sufficient.
4415 QuicStreamPeer::CloseReadSide(this);
4416 SendHeadersAndBody(std::move(headers), response_body_);
4417 }
4418
4419 std::string response_body_;
4420 };
4421
4422 class StreamWithErrorFactory : public QuicTestServer::StreamFactory {
4423 public:
StreamWithErrorFactory(std::string response_body)4424 explicit StreamWithErrorFactory(std::string response_body)
4425 : response_body_(std::move(response_body)) {}
4426
4427 ~StreamWithErrorFactory() override = default;
4428
CreateStream(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)4429 QuicSimpleServerStream* CreateStream(
4430 QuicStreamId id, QuicSpdySession* session,
4431 QuicSimpleServerBackend* quic_simple_server_backend) override {
4432 return new ServerStreamWithErrorResponseBody(
4433 id, session, quic_simple_server_backend, response_body_);
4434 }
4435
CreateStream(PendingStream *,QuicSpdySession *,QuicSimpleServerBackend *)4436 QuicSimpleServerStream* CreateStream(
4437 PendingStream* /*pending*/, QuicSpdySession* /*session*/,
4438 QuicSimpleServerBackend* /*response_cache*/) override {
4439 return nullptr;
4440 }
4441
4442 private:
4443 std::string response_body_;
4444 };
4445
4446 // A test server stream that drops all received body.
4447 class ServerStreamThatDropsBody : public QuicSimpleServerStream {
4448 public:
ServerStreamThatDropsBody(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)4449 ServerStreamThatDropsBody(QuicStreamId id, QuicSpdySession* session,
4450 QuicSimpleServerBackend* quic_simple_server_backend)
4451 : QuicSimpleServerStream(id, session, BIDIRECTIONAL,
4452 quic_simple_server_backend) {}
4453
4454 ~ServerStreamThatDropsBody() override = default;
4455
4456 protected:
OnBodyAvailable()4457 void OnBodyAvailable() override {
4458 while (HasBytesToRead()) {
4459 struct iovec iov;
4460 if (GetReadableRegions(&iov, 1) == 0) {
4461 // No more data to read.
4462 break;
4463 }
4464 QUIC_DVLOG(1) << "Processed " << iov.iov_len << " bytes for stream "
4465 << id();
4466 MarkConsumed(iov.iov_len);
4467 }
4468
4469 if (!sequencer()->IsClosed()) {
4470 sequencer()->SetUnblocked();
4471 return;
4472 }
4473
4474 // If the sequencer is closed, then all the body, including the fin, has
4475 // been consumed.
4476 OnFinRead();
4477
4478 if (write_side_closed() || fin_buffered()) {
4479 return;
4480 }
4481
4482 SendResponse();
4483 }
4484 };
4485
4486 class ServerStreamThatDropsBodyFactory : public QuicTestServer::StreamFactory {
4487 public:
4488 ServerStreamThatDropsBodyFactory() = default;
4489
4490 ~ServerStreamThatDropsBodyFactory() override = default;
4491
CreateStream(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)4492 QuicSimpleServerStream* CreateStream(
4493 QuicStreamId id, QuicSpdySession* session,
4494 QuicSimpleServerBackend* quic_simple_server_backend) override {
4495 return new ServerStreamThatDropsBody(id, session,
4496 quic_simple_server_backend);
4497 }
4498
CreateStream(PendingStream *,QuicSpdySession *,QuicSimpleServerBackend *)4499 QuicSimpleServerStream* CreateStream(
4500 PendingStream* /*pending*/, QuicSpdySession* /*session*/,
4501 QuicSimpleServerBackend* /*response_cache*/) override {
4502 return nullptr;
4503 }
4504 };
4505
4506 // A test server stream that sends response with body size greater than 4GB.
4507 class ServerStreamThatSendsHugeResponse : public QuicSimpleServerStream {
4508 public:
ServerStreamThatSendsHugeResponse(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend,int64_t body_bytes)4509 ServerStreamThatSendsHugeResponse(
4510 QuicStreamId id, QuicSpdySession* session,
4511 QuicSimpleServerBackend* quic_simple_server_backend, int64_t body_bytes)
4512 : QuicSimpleServerStream(id, session, BIDIRECTIONAL,
4513 quic_simple_server_backend),
4514 body_bytes_(body_bytes) {}
4515
4516 ~ServerStreamThatSendsHugeResponse() override = default;
4517
4518 protected:
SendResponse()4519 void SendResponse() override {
4520 QuicBackendResponse response;
4521 std::string body(body_bytes_, 'a');
4522 response.set_body(body);
4523 SendHeadersAndBodyAndTrailers(response.headers().Clone(), response.body(),
4524 response.trailers().Clone());
4525 }
4526
4527 private:
4528 // Use a explicit int64_t rather than size_t to simulate a 64-bit server
4529 // talking to a 32-bit client.
4530 int64_t body_bytes_;
4531 };
4532
4533 class ServerStreamThatSendsHugeResponseFactory
4534 : public QuicTestServer::StreamFactory {
4535 public:
ServerStreamThatSendsHugeResponseFactory(int64_t body_bytes)4536 explicit ServerStreamThatSendsHugeResponseFactory(int64_t body_bytes)
4537 : body_bytes_(body_bytes) {}
4538
4539 ~ServerStreamThatSendsHugeResponseFactory() override = default;
4540
CreateStream(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)4541 QuicSimpleServerStream* CreateStream(
4542 QuicStreamId id, QuicSpdySession* session,
4543 QuicSimpleServerBackend* quic_simple_server_backend) override {
4544 return new ServerStreamThatSendsHugeResponse(
4545 id, session, quic_simple_server_backend, body_bytes_);
4546 }
4547
CreateStream(PendingStream *,QuicSpdySession *,QuicSimpleServerBackend *)4548 QuicSimpleServerStream* CreateStream(
4549 PendingStream* /*pending*/, QuicSpdySession* /*session*/,
4550 QuicSimpleServerBackend* /*response_cache*/) override {
4551 return nullptr;
4552 }
4553
4554 int64_t body_bytes_;
4555 };
4556
4557 class BlockedFrameObserver : public QuicConnectionDebugVisitor {
4558 public:
blocked_frames() const4559 std::vector<QuicBlockedFrame> blocked_frames() const {
4560 return blocked_frames_;
4561 }
4562
OnBlockedFrame(const QuicBlockedFrame & frame)4563 void OnBlockedFrame(const QuicBlockedFrame& frame) override {
4564 blocked_frames_.push_back(frame);
4565 }
4566
4567 private:
4568 std::vector<QuicBlockedFrame> blocked_frames_;
4569 };
4570
TEST_P(EndToEndTest,BlockedFrameIncludesOffset)4571 TEST_P(EndToEndTest, BlockedFrameIncludesOffset) {
4572 if (!version_.HasIetfQuicFrames()) {
4573 // For Google QUIC, the BLOCKED frame offset is ignored.
4574 Initialize();
4575 return;
4576 }
4577
4578 set_smaller_flow_control_receive_window();
4579 ASSERT_TRUE(Initialize());
4580
4581 // Observe the connection for BLOCKED frames.
4582 BlockedFrameObserver observer;
4583 QuicConnection* client_connection = GetClientConnection();
4584 ASSERT_TRUE(client_connection);
4585 client_connection->set_debug_visitor(&observer);
4586
4587 // Set the response body larger than the flow control window so the server
4588 // must receive a window update from the client before it can finish sending
4589 // it (hence, causing the server to send a BLOCKED frame)
4590 uint32_t response_body_size =
4591 client_config_.GetInitialSessionFlowControlWindowToSend() + 10;
4592 std::string response_body(response_body_size, 'a');
4593 AddToCache("/blocked", 200, response_body);
4594 SendSynchronousRequestAndCheckResponse("/blocked", response_body);
4595 client_->Disconnect();
4596
4597 ASSERT_GE(observer.blocked_frames().size(), static_cast<uint64_t>(0));
4598 for (const QuicBlockedFrame& frame : observer.blocked_frames()) {
4599 if (frame.stream_id ==
4600 QuicUtils::GetInvalidStreamId(version_.transport_version)) {
4601 // connection-level BLOCKED frame
4602 ASSERT_EQ(frame.offset,
4603 client_config_.GetInitialSessionFlowControlWindowToSend());
4604 } else {
4605 // stream-level BLOCKED frame
4606 ASSERT_EQ(frame.offset,
4607 client_config_.GetInitialStreamFlowControlWindowToSend());
4608 }
4609 }
4610
4611 client_connection->set_debug_visitor(nullptr);
4612 }
4613
TEST_P(EndToEndTest,EarlyResponseFinRecording)4614 TEST_P(EndToEndTest, EarlyResponseFinRecording) {
4615 set_smaller_flow_control_receive_window();
4616
4617 // Verify that an incoming FIN is recorded in a stream object even if the read
4618 // side has been closed. This prevents an entry from being made in
4619 // locally_close_streams_highest_offset_ (which will never be deleted).
4620 // To set up the test condition, the server must do the following in order:
4621 // start sending the response and call CloseReadSide
4622 // receive the FIN of the request
4623 // send the FIN of the response
4624
4625 // The response body must be larger than the flow control window so the server
4626 // must receive a window update from the client before it can finish sending
4627 // it.
4628 uint32_t response_body_size =
4629 2 * client_config_.GetInitialStreamFlowControlWindowToSend();
4630 std::string response_body(response_body_size, 'a');
4631
4632 StreamWithErrorFactory stream_factory(response_body);
4633 SetSpdyStreamFactory(&stream_factory);
4634
4635 ASSERT_TRUE(Initialize());
4636
4637 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4638
4639 // A POST that gets an early error response, after the headers are received
4640 // and before the body is received, due to invalid content-length.
4641 // Set an invalid content-length, so the request will receive an early 500
4642 // response.
4643 Http2HeaderBlock headers;
4644 headers[":method"] = "POST";
4645 headers[":path"] = "/garbage";
4646 headers[":scheme"] = "https";
4647 headers[":authority"] = server_hostname_;
4648 headers["content-length"] = "-1";
4649
4650 // The body must be large enough that the FIN will be in a different packet
4651 // than the end of the headers, but short enough to not require a flow control
4652 // update. This allows headers processing to trigger the error response
4653 // before the request FIN is processed but receive the request FIN before the
4654 // response is sent completely.
4655 const uint32_t kRequestBodySize = kMaxOutgoingPacketSize + 10;
4656 std::string request_body(kRequestBodySize, 'a');
4657
4658 // Send the request.
4659 client_->SendMessage(headers, request_body);
4660 client_->WaitForResponse();
4661 CheckResponseHeaders("500");
4662
4663 // Pause the server so we can access the server's internals without races.
4664 server_thread_->Pause();
4665
4666 QuicDispatcher* dispatcher =
4667 QuicServerPeer::GetDispatcher(server_thread_->server());
4668 QuicSession* server_session =
4669 QuicDispatcherPeer::GetFirstSessionIfAny(dispatcher);
4670 EXPECT_TRUE(server_session != nullptr);
4671
4672 // The stream is not waiting for the arrival of the peer's final offset.
4673 EXPECT_EQ(
4674 0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(server_session)
4675 .size());
4676
4677 server_thread_->Resume();
4678 }
4679
TEST_P(EndToEndTest,Trailers)4680 TEST_P(EndToEndTest, Trailers) {
4681 // Test sending and receiving HTTP/2 Trailers (trailing HEADERS frames).
4682 ASSERT_TRUE(Initialize());
4683 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4684
4685 // Set reordering to ensure that Trailers arriving before body is ok.
4686 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
4687 SetReorderPercentage(30);
4688
4689 // Add a response with headers, body, and trailers.
4690 const std::string kBody = "body content";
4691
4692 Http2HeaderBlock headers;
4693 headers[":status"] = "200";
4694 headers["content-length"] = absl::StrCat(kBody.size());
4695
4696 Http2HeaderBlock trailers;
4697 trailers["some-trailing-header"] = "trailing-header-value";
4698
4699 memory_cache_backend_.AddResponse(server_hostname_, "/trailer_url",
4700 std::move(headers), kBody,
4701 trailers.Clone());
4702
4703 SendSynchronousRequestAndCheckResponse("/trailer_url", kBody);
4704 EXPECT_EQ(trailers, client_->response_trailers());
4705 }
4706
4707 // TODO(fayang): this test seems to cause net_unittests timeouts :|
TEST_P(EndToEndTest,DISABLED_TestHugePostWithPacketLoss)4708 TEST_P(EndToEndTest, DISABLED_TestHugePostWithPacketLoss) {
4709 // This test tests a huge post with introduced packet loss from client to
4710 // server and body size greater than 4GB, making sure QUIC code does not break
4711 // for 32-bit builds.
4712 ServerStreamThatDropsBodyFactory stream_factory;
4713 SetSpdyStreamFactory(&stream_factory);
4714 ASSERT_TRUE(Initialize());
4715
4716 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4717 SetPacketLossPercentage(1);
4718 // To avoid storing the whole request body in memory, use a loop to repeatedly
4719 // send body size of kSizeBytes until the whole request body size is reached.
4720 const int kSizeBytes = 128 * 1024;
4721 // Request body size is 4G plus one more kSizeBytes.
4722 int64_t request_body_size_bytes = pow(2, 32) + kSizeBytes;
4723 ASSERT_LT(INT64_C(4294967296), request_body_size_bytes);
4724 std::string body(kSizeBytes, 'a');
4725
4726 Http2HeaderBlock headers;
4727 headers[":method"] = "POST";
4728 headers[":path"] = "/foo";
4729 headers[":scheme"] = "https";
4730 headers[":authority"] = server_hostname_;
4731 headers["content-length"] = absl::StrCat(request_body_size_bytes);
4732
4733 client_->SendMessage(headers, "", /*fin=*/false);
4734
4735 for (int i = 0; i < request_body_size_bytes / kSizeBytes; ++i) {
4736 bool fin = (i == request_body_size_bytes - 1);
4737 client_->SendData(std::string(body.data(), kSizeBytes), fin);
4738 client_->client()->WaitForEvents();
4739 }
4740 VerifyCleanConnection(true);
4741 }
4742
4743 // TODO(fayang): this test seems to cause net_unittests timeouts :|
TEST_P(EndToEndTest,DISABLED_TestHugeResponseWithPacketLoss)4744 TEST_P(EndToEndTest, DISABLED_TestHugeResponseWithPacketLoss) {
4745 // This test tests a huge response with introduced loss from server to client
4746 // and body size greater than 4GB, making sure QUIC code does not break for
4747 // 32-bit builds.
4748 const int kSizeBytes = 128 * 1024;
4749 int64_t response_body_size_bytes = pow(2, 32) + kSizeBytes;
4750 ASSERT_LT(4294967296, response_body_size_bytes);
4751 ServerStreamThatSendsHugeResponseFactory stream_factory(
4752 response_body_size_bytes);
4753 SetSpdyStreamFactory(&stream_factory);
4754
4755 StartServer();
4756
4757 // Use a quic client that drops received body.
4758 QuicTestClient* client =
4759 new QuicTestClient(server_address_, server_hostname_, client_config_,
4760 client_supported_versions_);
4761 client->client()->set_drop_response_body(true);
4762 client->UseWriter(client_writer_);
4763 client->Connect();
4764 client_.reset(client);
4765 QuicConnection* client_connection = GetClientConnection();
4766 ASSERT_TRUE(client_connection);
4767 client_writer_->Initialize(
4768 QuicConnectionPeer::GetHelper(client_connection),
4769 QuicConnectionPeer::GetAlarmFactory(client_connection),
4770 std::make_unique<ClientDelegate>(client_->client()));
4771 initialized_ = true;
4772 ASSERT_TRUE(client_->client()->connected());
4773
4774 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4775 SetPacketLossPercentage(1);
4776 client_->SendRequest("/huge_response");
4777 client_->WaitForResponse();
4778 VerifyCleanConnection(true);
4779 }
4780
TEST_P(EndToEndTest,ReleaseHeadersStreamBufferWhenIdle)4781 TEST_P(EndToEndTest, ReleaseHeadersStreamBufferWhenIdle) {
4782 // Tests that when client side has no active request,
4783 // its headers stream's sequencer buffer should be released.
4784 ASSERT_TRUE(Initialize());
4785 client_->SendSynchronousRequest("/foo");
4786 if (version_.UsesHttp3()) {
4787 return;
4788 }
4789 QuicSpdyClientSession* client_session = GetClientSession();
4790 ASSERT_TRUE(client_session);
4791 QuicHeadersStream* headers_stream =
4792 QuicSpdySessionPeer::GetHeadersStream(client_session);
4793 ASSERT_TRUE(headers_stream);
4794 QuicStreamSequencer* sequencer = QuicStreamPeer::sequencer(headers_stream);
4795 ASSERT_TRUE(sequencer);
4796 EXPECT_FALSE(QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(sequencer));
4797 }
4798
4799 // A single large header value causes a different error than the total size of
4800 // headers exceeding a smaller limit, tested at EndToEndTest.LargeHeaders.
TEST_P(EndToEndTest,WayTooLongRequestHeaders)4801 TEST_P(EndToEndTest, WayTooLongRequestHeaders) {
4802 ASSERT_TRUE(Initialize());
4803
4804 Http2HeaderBlock headers;
4805 headers[":method"] = "GET";
4806 headers[":path"] = "/foo";
4807 headers[":scheme"] = "https";
4808 headers[":authority"] = server_hostname_;
4809 headers["key"] = std::string(2 * 1024 * 1024, 'a');
4810
4811 client_->SendMessage(headers, "");
4812 client_->WaitForResponse();
4813 if (version_.UsesHttp3()) {
4814 EXPECT_THAT(client_->connection_error(),
4815 IsError(QUIC_QPACK_DECOMPRESSION_FAILED));
4816 } else {
4817 EXPECT_THAT(client_->connection_error(),
4818 IsError(QUIC_HPACK_VALUE_TOO_LONG));
4819 }
4820 }
4821
4822 class WindowUpdateObserver : public QuicConnectionDebugVisitor {
4823 public:
WindowUpdateObserver()4824 WindowUpdateObserver() : num_window_update_frames_(0), num_ping_frames_(0) {}
4825
num_window_update_frames() const4826 size_t num_window_update_frames() const { return num_window_update_frames_; }
4827
num_ping_frames() const4828 size_t num_ping_frames() const { return num_ping_frames_; }
4829
OnWindowUpdateFrame(const QuicWindowUpdateFrame &,const QuicTime &)4830 void OnWindowUpdateFrame(const QuicWindowUpdateFrame& /*frame*/,
4831 const QuicTime& /*receive_time*/) override {
4832 ++num_window_update_frames_;
4833 }
4834
OnPingFrame(const QuicPingFrame &,const QuicTime::Delta)4835 void OnPingFrame(const QuicPingFrame& /*frame*/,
4836 const QuicTime::Delta /*ping_received_delay*/) override {
4837 ++num_ping_frames_;
4838 }
4839
4840 private:
4841 size_t num_window_update_frames_;
4842 size_t num_ping_frames_;
4843 };
4844
TEST_P(EndToEndTest,WindowUpdateInAck)4845 TEST_P(EndToEndTest, WindowUpdateInAck) {
4846 ASSERT_TRUE(Initialize());
4847 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4848 WindowUpdateObserver observer;
4849 QuicConnection* client_connection = GetClientConnection();
4850 ASSERT_TRUE(client_connection);
4851 client_connection->set_debug_visitor(&observer);
4852 // 100KB body.
4853 std::string body(100 * 1024, 'a');
4854 Http2HeaderBlock headers;
4855 headers[":method"] = "POST";
4856 headers[":path"] = "/foo";
4857 headers[":scheme"] = "https";
4858 headers[":authority"] = server_hostname_;
4859
4860 EXPECT_EQ(kFooResponseBody,
4861 client_->SendCustomSynchronousRequest(headers, body));
4862 client_->Disconnect();
4863 EXPECT_LT(0u, observer.num_window_update_frames());
4864 EXPECT_EQ(0u, observer.num_ping_frames());
4865 client_connection->set_debug_visitor(nullptr);
4866 }
4867
TEST_P(EndToEndTest,SendStatelessResetTokenInShlo)4868 TEST_P(EndToEndTest, SendStatelessResetTokenInShlo) {
4869 ASSERT_TRUE(Initialize());
4870 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4871 QuicSpdyClientSession* client_session = GetClientSession();
4872 ASSERT_TRUE(client_session);
4873 QuicConfig* config = client_session->config();
4874 ASSERT_TRUE(config);
4875 EXPECT_TRUE(config->HasReceivedStatelessResetToken());
4876 QuicConnection* client_connection = client_session->connection();
4877 ASSERT_TRUE(client_connection);
4878 EXPECT_EQ(QuicUtils::GenerateStatelessResetToken(
4879 client_connection->connection_id()),
4880 config->ReceivedStatelessResetToken());
4881 client_->Disconnect();
4882 }
4883
4884 // Regression test for b/116200989.
TEST_P(EndToEndTest,SendStatelessResetIfServerConnectionClosedLocallyDuringHandshake)4885 TEST_P(EndToEndTest,
4886 SendStatelessResetIfServerConnectionClosedLocallyDuringHandshake) {
4887 connect_to_server_on_initialize_ = false;
4888 ASSERT_TRUE(Initialize());
4889
4890 ASSERT_TRUE(server_thread_);
4891 server_thread_->Pause();
4892 QuicDispatcher* dispatcher =
4893 QuicServerPeer::GetDispatcher(server_thread_->server());
4894 if (dispatcher == nullptr) {
4895 ADD_FAILURE() << "Missing dispatcher";
4896 server_thread_->Resume();
4897 return;
4898 }
4899 if (dispatcher->NumSessions() > 0) {
4900 ADD_FAILURE() << "Dispatcher session map not empty";
4901 server_thread_->Resume();
4902 return;
4903 }
4904 // Note: this writer will only used by the server connection, not the time
4905 // wait list.
4906 QuicDispatcherPeer::UseWriter(
4907 dispatcher,
4908 // This cause the first server-sent packet, a.k.a REJ, to fail.
4909 new BadPacketWriter(/*packet_causing_write_error=*/0, EPERM));
4910 server_thread_->Resume();
4911
4912 client_.reset(CreateQuicClient(client_writer_));
4913 EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
4914 EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_FAILED));
4915 }
4916
4917 // Regression test for b/116200989.
TEST_P(EndToEndTest,SendStatelessResetIfServerConnectionClosedLocallyAfterHandshake)4918 TEST_P(EndToEndTest,
4919 SendStatelessResetIfServerConnectionClosedLocallyAfterHandshake) {
4920 // Prevent the connection from expiring in the time wait list.
4921 SetQuicFlag(quic_time_wait_list_seconds, 10000);
4922 connect_to_server_on_initialize_ = false;
4923 ASSERT_TRUE(Initialize());
4924
4925 // big_response_body is 64K, which is about 48 full-sized packets.
4926 const size_t kBigResponseBodySize = 65536;
4927 QuicData big_response_body(new char[kBigResponseBodySize](),
4928 kBigResponseBodySize, /*owns_buffer=*/true);
4929 AddToCache("/big_response", 200, big_response_body.AsStringPiece());
4930
4931 ASSERT_TRUE(server_thread_);
4932 server_thread_->Pause();
4933 QuicDispatcher* dispatcher =
4934 QuicServerPeer::GetDispatcher(server_thread_->server());
4935 if (dispatcher == nullptr) {
4936 ADD_FAILURE() << "Missing dispatcher";
4937 server_thread_->Resume();
4938 return;
4939 }
4940 if (dispatcher->NumSessions() > 0) {
4941 ADD_FAILURE() << "Dispatcher session map not empty";
4942 server_thread_->Resume();
4943 return;
4944 }
4945 QuicDispatcherPeer::UseWriter(
4946 dispatcher,
4947 // This will cause an server write error with EPERM, while sending the
4948 // response for /big_response.
4949 new BadPacketWriter(/*packet_causing_write_error=*/20, EPERM));
4950 server_thread_->Resume();
4951
4952 client_.reset(CreateQuicClient(client_writer_));
4953
4954 // First, a /foo request with small response should succeed.
4955 SendSynchronousFooRequestAndCheckResponse();
4956
4957 // Second, a /big_response request with big response should fail.
4958 EXPECT_LT(client_->SendSynchronousRequest("/big_response").length(),
4959 kBigResponseBodySize);
4960 EXPECT_THAT(client_->connection_error(), IsError(QUIC_PUBLIC_RESET));
4961 }
4962
4963 // Regression test of b/70782529.
TEST_P(EndToEndTest,DoNotCrashOnPacketWriteError)4964 TEST_P(EndToEndTest, DoNotCrashOnPacketWriteError) {
4965 ASSERT_TRUE(Initialize());
4966 BadPacketWriter* bad_writer =
4967 new BadPacketWriter(/*packet_causing_write_error=*/5,
4968 /*error_code=*/90);
4969 std::unique_ptr<QuicTestClient> client(CreateQuicClient(bad_writer));
4970
4971 // 1 MB body.
4972 std::string body(1024 * 1024, 'a');
4973 Http2HeaderBlock headers;
4974 headers[":method"] = "POST";
4975 headers[":path"] = "/foo";
4976 headers[":scheme"] = "https";
4977 headers[":authority"] = server_hostname_;
4978
4979 client->SendCustomSynchronousRequest(headers, body);
4980 }
4981
4982 // Regression test for b/71711996. This test sends a connectivity probing packet
4983 // as its last sent packet, and makes sure the server's ACK of that packet does
4984 // not cause the client to fail.
TEST_P(EndToEndTest,LastPacketSentIsConnectivityProbing)4985 TEST_P(EndToEndTest, LastPacketSentIsConnectivityProbing) {
4986 ASSERT_TRUE(Initialize());
4987
4988 SendSynchronousFooRequestAndCheckResponse();
4989
4990 // Wait for the client's ACK (of the response) to be received by the server.
4991 client_->WaitForDelayedAcks();
4992
4993 // We are sending a connectivity probing packet from an unchanged client
4994 // address, so the server will not respond to us with a connectivity probing
4995 // packet, however the server should send an ack-only packet to us.
4996 client_->SendConnectivityProbing();
4997
4998 // Wait for the server's last ACK to be received by the client.
4999 client_->WaitForDelayedAcks();
5000 }
5001
TEST_P(EndToEndTest,PreSharedKey)5002 TEST_P(EndToEndTest, PreSharedKey) {
5003 client_config_.set_max_time_before_crypto_handshake(
5004 QuicTime::Delta::FromSeconds(5));
5005 client_config_.set_max_idle_time_before_crypto_handshake(
5006 QuicTime::Delta::FromSeconds(5));
5007 pre_shared_key_client_ = "foobar";
5008 pre_shared_key_server_ = "foobar";
5009
5010 if (version_.UsesTls()) {
5011 // TODO(b/154162689) add PSK support to QUIC+TLS.
5012 EXPECT_QUIC_BUG(EXPECT_FALSE(Initialize()),
5013 "QUIC client pre-shared keys not yet supported with TLS");
5014 return;
5015 }
5016
5017 ASSERT_TRUE(Initialize());
5018
5019 SendSynchronousFooRequestAndCheckResponse();
5020 }
5021
5022 // TODO: reenable once we have a way to make this run faster.
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (PreSharedKeyMismatch))5023 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(PreSharedKeyMismatch)) {
5024 client_config_.set_max_time_before_crypto_handshake(
5025 QuicTime::Delta::FromSeconds(1));
5026 client_config_.set_max_idle_time_before_crypto_handshake(
5027 QuicTime::Delta::FromSeconds(1));
5028 pre_shared_key_client_ = "foo";
5029 pre_shared_key_server_ = "bar";
5030
5031 if (version_.UsesTls()) {
5032 // TODO(b/154162689) add PSK support to QUIC+TLS.
5033 EXPECT_QUIC_BUG(EXPECT_FALSE(Initialize()),
5034 "QUIC client pre-shared keys not yet supported with TLS");
5035 return;
5036 }
5037
5038 // One of two things happens when Initialize() returns:
5039 // 1. Crypto handshake has completed, and it is unsuccessful. Initialize()
5040 // returns false.
5041 // 2. Crypto handshake has not completed, Initialize() returns true. The call
5042 // to WaitForCryptoHandshakeConfirmed() will wait for the handshake and
5043 // return whether it is successful.
5044 ASSERT_FALSE(Initialize() && client_->client()->WaitForOneRttKeysAvailable());
5045 EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_TIMEOUT));
5046 }
5047
5048 // TODO: reenable once we have a way to make this run faster.
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (PreSharedKeyNoClient))5049 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(PreSharedKeyNoClient)) {
5050 client_config_.set_max_time_before_crypto_handshake(
5051 QuicTime::Delta::FromSeconds(1));
5052 client_config_.set_max_idle_time_before_crypto_handshake(
5053 QuicTime::Delta::FromSeconds(1));
5054 pre_shared_key_server_ = "foobar";
5055
5056 if (version_.UsesTls()) {
5057 // TODO(b/154162689) add PSK support to QUIC+TLS.
5058 EXPECT_QUIC_BUG(EXPECT_FALSE(Initialize()),
5059 "QUIC server pre-shared keys not yet supported with TLS");
5060 return;
5061 }
5062
5063 ASSERT_FALSE(Initialize() && client_->client()->WaitForOneRttKeysAvailable());
5064 EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_TIMEOUT));
5065 }
5066
5067 // TODO: reenable once we have a way to make this run faster.
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (PreSharedKeyNoServer))5068 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(PreSharedKeyNoServer)) {
5069 client_config_.set_max_time_before_crypto_handshake(
5070 QuicTime::Delta::FromSeconds(1));
5071 client_config_.set_max_idle_time_before_crypto_handshake(
5072 QuicTime::Delta::FromSeconds(1));
5073 pre_shared_key_client_ = "foobar";
5074
5075 if (version_.UsesTls()) {
5076 // TODO(b/154162689) add PSK support to QUIC+TLS.
5077 EXPECT_QUIC_BUG(EXPECT_FALSE(Initialize()),
5078 "QUIC client pre-shared keys not yet supported with TLS");
5079 return;
5080 }
5081
5082 ASSERT_FALSE(Initialize() && client_->client()->WaitForOneRttKeysAvailable());
5083 EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_TIMEOUT));
5084 }
5085
TEST_P(EndToEndTest,RequestAndStreamRstInOnePacket)5086 TEST_P(EndToEndTest, RequestAndStreamRstInOnePacket) {
5087 // Regression test for b/80234898.
5088 ASSERT_TRUE(Initialize());
5089
5090 // INCOMPLETE_RESPONSE will cause the server to not to send the trailer
5091 // (and the FIN) after the response body.
5092 std::string response_body(1305, 'a');
5093 Http2HeaderBlock response_headers;
5094 response_headers[":status"] = absl::StrCat(200);
5095 response_headers["content-length"] = absl::StrCat(response_body.length());
5096 memory_cache_backend_.AddSpecialResponse(
5097 server_hostname_, "/test_url", std::move(response_headers), response_body,
5098 QuicBackendResponse::INCOMPLETE_RESPONSE);
5099
5100 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
5101 client_->WaitForDelayedAcks();
5102
5103 QuicConnection* client_connection = GetClientConnection();
5104 ASSERT_TRUE(client_connection);
5105 const QuicPacketCount packets_sent_before =
5106 client_connection->GetStats().packets_sent;
5107
5108 client_->SendRequestAndRstTogether("/test_url");
5109
5110 // Expect exactly one packet is sent from the block above.
5111 ASSERT_EQ(packets_sent_before + 1,
5112 client_connection->GetStats().packets_sent);
5113
5114 // Wait for the connection to become idle.
5115 client_->WaitForDelayedAcks();
5116
5117 // The real expectation is the test does not crash or timeout.
5118 EXPECT_THAT(client_->connection_error(), IsQuicNoError());
5119 }
5120
TEST_P(EndToEndTest,ResetStreamOnTtlExpires)5121 TEST_P(EndToEndTest, ResetStreamOnTtlExpires) {
5122 ASSERT_TRUE(Initialize());
5123 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
5124 SetPacketLossPercentage(30);
5125
5126 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
5127 // Set a TTL which expires immediately.
5128 stream->MaybeSetTtl(QuicTime::Delta::FromMicroseconds(1));
5129
5130 WriteHeadersOnStream(stream);
5131 // 1 MB body.
5132 std::string body(1024 * 1024, 'a');
5133 stream->WriteOrBufferBody(body, true);
5134 client_->WaitForResponse();
5135 EXPECT_THAT(client_->stream_error(), IsStreamError(QUIC_STREAM_TTL_EXPIRED));
5136 }
5137
TEST_P(EndToEndTest,SendMessages)5138 TEST_P(EndToEndTest, SendMessages) {
5139 ASSERT_TRUE(Initialize());
5140 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
5141 QuicSession* client_session = GetClientSession();
5142 ASSERT_TRUE(client_session);
5143 QuicConnection* client_connection = client_session->connection();
5144 ASSERT_TRUE(client_connection);
5145
5146 SetPacketLossPercentage(30);
5147 ASSERT_GT(kMaxOutgoingPacketSize,
5148 client_session->GetCurrentLargestMessagePayload());
5149 ASSERT_LT(0, client_session->GetCurrentLargestMessagePayload());
5150
5151 std::string message_string(kMaxOutgoingPacketSize, 'a');
5152 QuicRandom* random =
5153 QuicConnectionPeer::GetHelper(client_connection)->GetRandomGenerator();
5154 {
5155 QuicConnection::ScopedPacketFlusher flusher(client_session->connection());
5156 // Verify the largest message gets successfully sent.
5157 EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 1),
5158 client_session->SendMessage(MemSliceFromString(absl::string_view(
5159 message_string.data(),
5160 client_session->GetCurrentLargestMessagePayload()))));
5161 // Send more messages with size (0, largest_payload] until connection is
5162 // write blocked.
5163 const int kTestMaxNumberOfMessages = 100;
5164 for (size_t i = 2; i <= kTestMaxNumberOfMessages; ++i) {
5165 size_t message_length =
5166 random->RandUint64() %
5167 client_session->GetGuaranteedLargestMessagePayload() +
5168 1;
5169 MessageResult result = client_session->SendMessage(MemSliceFromString(
5170 absl::string_view(message_string.data(), message_length)));
5171 if (result.status == MESSAGE_STATUS_BLOCKED) {
5172 // Connection is write blocked.
5173 break;
5174 }
5175 EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, i), result);
5176 }
5177 }
5178
5179 client_->WaitForDelayedAcks();
5180 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
5181 client_session
5182 ->SendMessage(MemSliceFromString(absl::string_view(
5183 message_string.data(),
5184 client_session->GetCurrentLargestMessagePayload() + 1)))
5185 .status);
5186 EXPECT_THAT(client_->connection_error(), IsQuicNoError());
5187 }
5188
5189 class EndToEndPacketReorderingTest : public EndToEndTest {
5190 public:
CreateClientWithWriter()5191 void CreateClientWithWriter() override {
5192 QUIC_LOG(ERROR) << "create client with reorder_writer_";
5193 reorder_writer_ = new PacketReorderingWriter();
5194 client_.reset(EndToEndTest::CreateQuicClient(reorder_writer_));
5195 }
5196
SetUp()5197 void SetUp() override {
5198 // Don't initialize client writer in base class.
5199 server_writer_ = new PacketDroppingTestWriter();
5200 }
5201
5202 protected:
5203 PacketReorderingWriter* reorder_writer_;
5204 };
5205
5206 INSTANTIATE_TEST_SUITE_P(EndToEndPacketReorderingTests,
5207 EndToEndPacketReorderingTest,
5208 ::testing::ValuesIn(GetTestParams()),
5209 ::testing::PrintToStringParamName());
5210
TEST_P(EndToEndPacketReorderingTest,ReorderedConnectivityProbing)5211 TEST_P(EndToEndPacketReorderingTest, ReorderedConnectivityProbing) {
5212 ASSERT_TRUE(Initialize());
5213 if (version_.HasIetfQuicFrames() ||
5214 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
5215 return;
5216 }
5217
5218 // Finish one request to make sure handshake established.
5219 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
5220
5221 // Wait for the connection to become idle, to make sure the packet gets
5222 // delayed is the connectivity probing packet.
5223 client_->WaitForDelayedAcks();
5224
5225 QuicSocketAddress old_addr =
5226 client_->client()->network_helper()->GetLatestClientAddress();
5227
5228 // Migrate socket to the new IP address.
5229 QuicIpAddress new_host = TestLoopback(2);
5230 EXPECT_NE(old_addr.host(), new_host);
5231 ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
5232
5233 // Write a connectivity probing after the next /foo request.
5234 reorder_writer_->SetDelay(1);
5235 client_->SendConnectivityProbing();
5236
5237 ASSERT_TRUE(client_->MigrateSocketWithSpecifiedPort(old_addr.host(),
5238 old_addr.port()));
5239
5240 // The (delayed) connectivity probing will be sent after this request.
5241 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
5242
5243 // Send yet another request after the connectivity probing, when this request
5244 // returns, the probing is guaranteed to have been received by the server, and
5245 // the server's response to probing is guaranteed to have been received by the
5246 // client.
5247 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
5248
5249 server_thread_->Pause();
5250 QuicConnection* server_connection = GetServerConnection();
5251 if (server_connection != nullptr) {
5252 EXPECT_EQ(1u,
5253 server_connection->GetStats().num_connectivity_probing_received);
5254 } else {
5255 ADD_FAILURE() << "Missing server connection";
5256 }
5257 server_thread_->Resume();
5258
5259 // Server definitely responded to the connectivity probing. Sometime it also
5260 // sends a padded ping that is not a connectivity probing, which is recognized
5261 // as connectivity probing because client's self address is ANY.
5262 QuicConnection* client_connection = GetClientConnection();
5263 ASSERT_TRUE(client_connection);
5264 EXPECT_LE(1u,
5265 client_connection->GetStats().num_connectivity_probing_received);
5266 }
5267
5268 // A writer which holds the next packet to be sent till ReleasePacket() is
5269 // called.
5270 class PacketHoldingWriter : public QuicPacketWriterWrapper {
5271 public:
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,PerPacketOptions * options,const QuicPacketWriterParams & params)5272 WriteResult WritePacket(const char* buffer, size_t buf_len,
5273 const QuicIpAddress& self_address,
5274 const QuicSocketAddress& peer_address,
5275 PerPacketOptions* options,
5276 const QuicPacketWriterParams& params) override {
5277 if (!hold_next_packet_) {
5278 return QuicPacketWriterWrapper::WritePacket(
5279 buffer, buf_len, self_address, peer_address, options, params);
5280 }
5281 QUIC_DLOG(INFO) << "Packet is held by the writer";
5282 packet_content_ = std::string(buffer, buf_len);
5283 self_address_ = self_address;
5284 peer_address_ = peer_address;
5285 options_ = (options == nullptr ? nullptr : options->Clone());
5286 hold_next_packet_ = false;
5287 return WriteResult(WRITE_STATUS_OK, buf_len);
5288 }
5289
HoldNextPacket()5290 void HoldNextPacket() {
5291 QUICHE_DCHECK(packet_content_.empty())
5292 << "There is already one packet on hold.";
5293 hold_next_packet_ = true;
5294 }
5295
ReleasePacket()5296 void ReleasePacket() {
5297 QUIC_DLOG(INFO) << "Release packet";
5298 ASSERT_EQ(WRITE_STATUS_OK,
5299 QuicPacketWriterWrapper::WritePacket(
5300 packet_content_.data(), packet_content_.length(),
5301 self_address_, peer_address_, options_.release(), params_)
5302 .status);
5303 packet_content_.clear();
5304 }
5305
5306 private:
5307 bool hold_next_packet_{false};
5308 std::string packet_content_;
5309 QuicIpAddress self_address_;
5310 QuicSocketAddress peer_address_;
5311 std::unique_ptr<PerPacketOptions> options_;
5312 QuicPacketWriterParams params_;
5313 };
5314
TEST_P(EndToEndTest,ClientValidateNewNetwork)5315 TEST_P(EndToEndTest, ClientValidateNewNetwork) {
5316 ASSERT_TRUE(Initialize());
5317 if (!version_.HasIetfQuicFrames()) {
5318 return;
5319 }
5320 client_.reset(EndToEndTest::CreateQuicClient(nullptr));
5321 SendSynchronousFooRequestAndCheckResponse();
5322
5323 // Store the client IP address which was used to send the first request.
5324 QuicIpAddress old_host =
5325 client_->client()->network_helper()->GetLatestClientAddress().host();
5326
5327 // Migrate socket to the new IP address.
5328 QuicIpAddress new_host = TestLoopback(2);
5329 EXPECT_NE(old_host, new_host);
5330
5331 client_->client()->ValidateNewNetwork(new_host);
5332 // Send a request using the old socket.
5333 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
5334 // Client should have received a PATH_CHALLENGE.
5335 QuicConnection* client_connection = GetClientConnection();
5336 ASSERT_TRUE(client_connection);
5337 EXPECT_EQ(1u,
5338 client_connection->GetStats().num_connectivity_probing_received);
5339
5340 // Send another request to make sure THE server will receive PATH_RESPONSE.
5341 client_->SendSynchronousRequest("/eep");
5342
5343 server_thread_->Pause();
5344 QuicConnection* server_connection = GetServerConnection();
5345 if (server_connection != nullptr) {
5346 EXPECT_EQ(1u,
5347 server_connection->GetStats().num_connectivity_probing_received);
5348 } else {
5349 ADD_FAILURE() << "Missing server connection";
5350 }
5351 server_thread_->Resume();
5352 }
5353
TEST_P(EndToEndTest,ClientMultiPortConnection)5354 TEST_P(EndToEndTest, ClientMultiPortConnection) {
5355 client_config_.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
5356 ASSERT_TRUE(Initialize());
5357 if (!version_.HasIetfQuicFrames()) {
5358 return;
5359 }
5360 client_.reset(EndToEndTest::CreateQuicClient(nullptr));
5361 QuicConnection* client_connection = GetClientConnection();
5362 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
5363 ASSERT_TRUE(stream);
5364 // Increase the probing frequency to speed up this test.
5365 client_connection->SetMultiPortProbingInterval(
5366 QuicTime::Delta::FromMilliseconds(100));
5367 SendSynchronousFooRequestAndCheckResponse();
5368 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
5369 return 1u == client_connection->GetStats().num_path_response_received;
5370 }));
5371 // Verify that the alternative path keeps sending probes periodically.
5372 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
5373 return 2u == client_connection->GetStats().num_path_response_received;
5374 }));
5375 server_thread_->Pause();
5376 QuicConnection* server_connection = GetServerConnection();
5377 // Verify that no migration has happened.
5378 if (server_connection != nullptr) {
5379 EXPECT_EQ(0u, server_connection->GetStats()
5380 .num_peer_migration_to_proactively_validated_address);
5381 }
5382 server_thread_->Resume();
5383
5384 // This will cause the next periodic probing to fail.
5385 server_writer_->set_fake_packet_loss_percentage(100);
5386 EXPECT_TRUE(client_->WaitUntil(
5387 1000, [&]() { return client_->client()->HasPendingPathValidation(); }));
5388 // Now wait for path validation to timeout.
5389 EXPECT_TRUE(client_->WaitUntil(
5390 2000, [&]() { return !client_->client()->HasPendingPathValidation(); }));
5391 server_writer_->set_fake_packet_loss_percentage(0);
5392 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
5393 return 3u == client_connection->GetStats().num_path_response_received;
5394 }));
5395 // Verify that the previous path was retired.
5396 EXPECT_EQ(1u, client_connection->GetStats().num_retire_connection_id_sent);
5397 stream->Reset(QuicRstStreamErrorCode::QUIC_STREAM_NO_ERROR);
5398 }
5399
TEST_P(EndToEndTest,ClientPortMigrationOnPathDegrading)5400 TEST_P(EndToEndTest, ClientPortMigrationOnPathDegrading) {
5401 connect_to_server_on_initialize_ = false;
5402 Initialize();
5403 if (!version_.HasIetfQuicFrames()) {
5404 CreateClientWithWriter();
5405 return;
5406 }
5407
5408 server_thread_->Pause();
5409 QuicDispatcher* dispatcher =
5410 QuicServerPeer::GetDispatcher(server_thread_->server());
5411 if (dispatcher == nullptr) {
5412 ADD_FAILURE() << "Missing dispatcher";
5413 server_thread_->Resume();
5414 return;
5415 }
5416 if (dispatcher->NumSessions() > 0) {
5417 ADD_FAILURE() << "Dispatcher session map not empty";
5418 server_thread_->Resume();
5419 return;
5420 }
5421 auto* new_writer = new DroppingPacketsWithSpecificDestinationWriter();
5422 // Note: this writer will only used by the server connection, not the time
5423 // wait list.
5424 QuicDispatcherPeer::UseWriter(dispatcher, new_writer);
5425 server_thread_->Resume();
5426
5427 delete client_writer_;
5428 client_.reset(EndToEndTest::CreateQuicClient(nullptr));
5429 client_->client()->EnablePortMigrationUponPathDegrading(std::nullopt);
5430 ASSERT_TRUE(client_->client()->WaitForHandshakeConfirmed());
5431 QuicConnection* client_connection = GetClientConnection();
5432 QuicSocketAddress original_self_addr = client_connection->self_address();
5433 Http2HeaderBlock headers;
5434 headers[":method"] = "POST";
5435 headers[":path"] = "/bar";
5436 headers[":scheme"] = "https";
5437 headers[":authority"] = server_hostname_;
5438 client_->SendMessage(headers, "aaaa", false);
5439
5440 // This causes the all server sent packets to the client's current address to
5441 // be dropped.
5442 new_writer->set_peer_address_to_drop(original_self_addr);
5443 client_->SendData("bbbb", true);
5444 // The response will be dropped till client migrates to a different port.
5445 client_->WaitForResponse();
5446 QuicSocketAddress new_self_addr1 = client_connection->self_address();
5447 EXPECT_NE(original_self_addr, new_self_addr1);
5448 EXPECT_EQ(1u, GetClientConnection()->GetStats().num_path_degrading);
5449 EXPECT_EQ(1u, GetClientConnection()
5450 ->GetStats()
5451 .num_forward_progress_after_path_degrading);
5452 EXPECT_EQ(1u, GetClientConnection()->GetStats().num_path_response_received);
5453 size_t pto_count = GetClientConnection()->GetStats().pto_count;
5454
5455 // Wait for new connection id to be received.
5456 WaitForNewConnectionIds();
5457 // Use 1 PTO to detect path degrading more aggressively.
5458 client_->client()->EnablePortMigrationUponPathDegrading({1});
5459 new_writer->set_peer_address_to_drop(new_self_addr1);
5460 client_->SendSynchronousRequest("/eep");
5461 QuicSocketAddress new_self_addr2 = client_connection->self_address();
5462 EXPECT_NE(new_self_addr1, new_self_addr2);
5463 EXPECT_EQ(2u, GetClientConnection()->GetStats().num_path_degrading);
5464 EXPECT_EQ(2u, GetClientConnection()
5465 ->GetStats()
5466 .num_forward_progress_after_path_degrading);
5467 EXPECT_EQ(2u, GetClientConnection()->GetStats().num_path_response_received);
5468 // It should take fewer PTOs to trigger port migration than the default(4).
5469 EXPECT_GT(pto_count + 4, GetClientConnection()->GetStats().pto_count);
5470 }
5471
TEST_P(EndToEndTest,ClientMultiPortMigrationOnPathDegrading)5472 TEST_P(EndToEndTest, ClientMultiPortMigrationOnPathDegrading) {
5473 client_config_.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
5474 ASSERT_TRUE(Initialize());
5475 if (!version_.HasIetfQuicFrames()) {
5476 return;
5477 }
5478 client_.reset(EndToEndTest::CreateQuicClient(nullptr));
5479 QuicConnection* client_connection = GetClientConnection();
5480 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
5481 ASSERT_TRUE(stream);
5482 // Increase the probing frequency to speed up this test.
5483 client_connection->SetMultiPortProbingInterval(
5484 QuicTime::Delta::FromMilliseconds(100));
5485 SendSynchronousFooRequestAndCheckResponse();
5486 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
5487 return 1u == client_connection->GetStats().num_path_response_received;
5488 }));
5489 // Verify that the alternative path keeps sending probes periodically.
5490 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
5491 return 2u == client_connection->GetStats().num_path_response_received;
5492 }));
5493 server_thread_->Pause();
5494 QuicConnection* server_connection = GetServerConnection();
5495 // Verify that no migration has happened.
5496 if (server_connection != nullptr) {
5497 EXPECT_EQ(0u, server_connection->GetStats()
5498 .num_peer_migration_to_proactively_validated_address);
5499 }
5500 server_thread_->Resume();
5501
5502 auto original_self_addr = client_connection->self_address();
5503 // Trigger client side path degrading
5504 client_connection->OnPathDegradingDetected();
5505 EXPECT_NE(original_self_addr, client_connection->self_address());
5506
5507 // Send another request to trigger connection id retirement.
5508 SendSynchronousFooRequestAndCheckResponse();
5509 EXPECT_EQ(1u, client_connection->GetStats().num_retire_connection_id_sent);
5510 auto new_alt_path = QuicConnectionPeer::GetAlternativePath(client_connection);
5511 EXPECT_NE(client_connection->self_address(), new_alt_path->self_address);
5512
5513 stream->Reset(QuicRstStreamErrorCode::QUIC_STREAM_NO_ERROR);
5514 }
5515
TEST_P(EndToEndTest,SimpleServerPreferredAddressTest)5516 TEST_P(EndToEndTest, SimpleServerPreferredAddressTest) {
5517 use_preferred_address_ = true;
5518 ASSERT_TRUE(Initialize());
5519 if (!version_.HasIetfQuicFrames()) {
5520 return;
5521 }
5522 client_.reset(CreateQuicClient(nullptr));
5523 QuicConnection* client_connection = GetClientConnection();
5524 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
5525 EXPECT_EQ(server_address_, client_connection->effective_peer_address());
5526 EXPECT_EQ(server_address_, client_connection->peer_address());
5527 EXPECT_TRUE(client_->client()->HasPendingPathValidation());
5528 QuicConnectionId server_cid1 = client_connection->connection_id();
5529
5530 SendSynchronousFooRequestAndCheckResponse();
5531 while (client_->client()->HasPendingPathValidation()) {
5532 client_->client()->WaitForEvents();
5533 }
5534 EXPECT_EQ(server_preferred_address_,
5535 client_connection->effective_peer_address());
5536 EXPECT_EQ(server_preferred_address_, client_connection->peer_address());
5537 EXPECT_NE(server_cid1, client_connection->connection_id());
5538
5539 const auto client_stats = GetClientConnection()->GetStats();
5540 EXPECT_TRUE(client_stats.server_preferred_address_validated);
5541 EXPECT_FALSE(client_stats.failed_to_validate_server_preferred_address);
5542 }
5543
TEST_P(EndToEndTest,SimpleServerPreferredAddressTestNoSPAD)5544 TEST_P(EndToEndTest, SimpleServerPreferredAddressTestNoSPAD) {
5545 SetQuicFlag(quic_always_support_server_preferred_address, true);
5546 use_preferred_address_ = true;
5547 ASSERT_TRUE(Initialize());
5548 if (!version_.HasIetfQuicFrames()) {
5549 return;
5550 }
5551 client_.reset(CreateQuicClient(nullptr));
5552 QuicConnection* client_connection = GetClientConnection();
5553 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
5554 EXPECT_EQ(server_address_, client_connection->effective_peer_address());
5555 EXPECT_EQ(server_address_, client_connection->peer_address());
5556 EXPECT_TRUE(client_->client()->HasPendingPathValidation());
5557 QuicConnectionId server_cid1 = client_connection->connection_id();
5558
5559 SendSynchronousFooRequestAndCheckResponse();
5560 while (client_->client()->HasPendingPathValidation()) {
5561 client_->client()->WaitForEvents();
5562 }
5563 EXPECT_EQ(server_preferred_address_,
5564 client_connection->effective_peer_address());
5565 EXPECT_EQ(server_preferred_address_, client_connection->peer_address());
5566 EXPECT_NE(server_cid1, client_connection->connection_id());
5567
5568 const auto client_stats = GetClientConnection()->GetStats();
5569 EXPECT_TRUE(client_stats.server_preferred_address_validated);
5570 EXPECT_FALSE(client_stats.failed_to_validate_server_preferred_address);
5571 }
5572
TEST_P(EndToEndTest,OptimizedServerPreferredAddress)5573 TEST_P(EndToEndTest, OptimizedServerPreferredAddress) {
5574 use_preferred_address_ = true;
5575 ASSERT_TRUE(Initialize());
5576 if (!version_.HasIetfQuicFrames()) {
5577 return;
5578 }
5579 client_config_.SetClientConnectionOptions(QuicTagVector{kSPA2});
5580 client_.reset(CreateQuicClient(nullptr));
5581 QuicConnection* client_connection = GetClientConnection();
5582 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
5583 EXPECT_EQ(server_address_, client_connection->effective_peer_address());
5584 EXPECT_EQ(server_address_, client_connection->peer_address());
5585 EXPECT_TRUE(client_->client()->HasPendingPathValidation());
5586 SendSynchronousFooRequestAndCheckResponse();
5587 while (client_->client()->HasPendingPathValidation()) {
5588 client_->client()->WaitForEvents();
5589 }
5590
5591 const auto client_stats = GetClientConnection()->GetStats();
5592 EXPECT_TRUE(client_stats.server_preferred_address_validated);
5593 EXPECT_FALSE(client_stats.failed_to_validate_server_preferred_address);
5594 }
5595
TEST_P(EndToEndPacketReorderingTest,ReorderedPathChallenge)5596 TEST_P(EndToEndPacketReorderingTest, ReorderedPathChallenge) {
5597 ASSERT_TRUE(Initialize());
5598 if (!version_.HasIetfQuicFrames()) {
5599 return;
5600 }
5601 client_.reset(EndToEndTest::CreateQuicClient(nullptr));
5602
5603 // Finish one request to make sure handshake established.
5604 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
5605
5606 // Wait for the connection to become idle, to make sure the packet gets
5607 // delayed is the connectivity probing packet.
5608 client_->WaitForDelayedAcks();
5609
5610 QuicSocketAddress old_addr =
5611 client_->client()->network_helper()->GetLatestClientAddress();
5612
5613 // Migrate socket to the new IP address.
5614 QuicIpAddress new_host = TestLoopback(2);
5615 EXPECT_NE(old_addr.host(), new_host);
5616
5617 // Setup writer wrapper to hold the probing packet.
5618 auto holding_writer = new PacketHoldingWriter();
5619 client_->UseWriter(holding_writer);
5620 // Write a connectivity probing after the next /foo request.
5621 holding_writer->HoldNextPacket();
5622
5623 // A packet with PATH_CHALLENGE will be held in the writer.
5624 client_->client()->ValidateNewNetwork(new_host);
5625
5626 // Send (on-hold) PATH_CHALLENGE after this request.
5627 client_->SendRequest("/foo");
5628 holding_writer->ReleasePacket();
5629
5630 client_->WaitForResponse();
5631
5632 EXPECT_EQ(kFooResponseBody, client_->response_body());
5633 // Send yet another request after the PATH_CHALLENGE, when this request
5634 // returns, the probing is guaranteed to have been received by the server, and
5635 // the server's response to probing is guaranteed to have been received by the
5636 // client.
5637 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
5638
5639 // Client should have received a PATH_CHALLENGE.
5640 QuicConnection* client_connection = GetClientConnection();
5641 ASSERT_TRUE(client_connection);
5642 EXPECT_EQ(1u,
5643 client_connection->GetStats().num_connectivity_probing_received);
5644
5645 server_thread_->Pause();
5646 QuicConnection* server_connection = GetServerConnection();
5647 if (server_connection != nullptr) {
5648 EXPECT_EQ(1u,
5649 server_connection->GetStats().num_connectivity_probing_received);
5650 } else {
5651 ADD_FAILURE() << "Missing server connection";
5652 }
5653 server_thread_->Resume();
5654 }
5655
TEST_P(EndToEndPacketReorderingTest,PathValidationFailure)5656 TEST_P(EndToEndPacketReorderingTest, PathValidationFailure) {
5657 ASSERT_TRUE(Initialize());
5658 if (!version_.HasIetfQuicFrames()) {
5659 return;
5660 }
5661
5662 client_.reset(CreateQuicClient(nullptr));
5663 // Finish one request to make sure handshake established.
5664 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
5665
5666 // Wait for the connection to become idle, to make sure the packet gets
5667 // delayed is the connectivity probing packet.
5668 client_->WaitForDelayedAcks();
5669
5670 QuicSocketAddress old_addr = client_->client()->session()->self_address();
5671
5672 // Migrate socket to the new IP address.
5673 QuicIpAddress new_host = TestLoopback(2);
5674 EXPECT_NE(old_addr.host(), new_host);
5675
5676 // Drop PATH_RESPONSE packets to timeout the path validation.
5677 server_writer_->set_fake_packet_loss_percentage(100);
5678 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(new_host));
5679 while (client_->client()->HasPendingPathValidation()) {
5680 client_->client()->WaitForEvents();
5681 }
5682 EXPECT_EQ(old_addr, client_->client()->session()->self_address());
5683 server_writer_->set_fake_packet_loss_percentage(0);
5684 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
5685
5686 server_thread_->Pause();
5687 QuicConnection* server_connection = GetServerConnection();
5688 if (server_connection != nullptr) {
5689 EXPECT_EQ(3u,
5690 server_connection->GetStats().num_connectivity_probing_received);
5691 } else {
5692 ADD_FAILURE() << "Missing server connection";
5693 }
5694 server_thread_->Resume();
5695 }
5696
TEST_P(EndToEndPacketReorderingTest,MigrateAgainAfterPathValidationFailure)5697 TEST_P(EndToEndPacketReorderingTest, MigrateAgainAfterPathValidationFailure) {
5698 ASSERT_TRUE(Initialize());
5699 if (!version_.HasIetfQuicFrames()) {
5700 return;
5701 }
5702
5703 client_.reset(CreateQuicClient(nullptr));
5704 // Finish one request to make sure handshake established.
5705 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
5706
5707 // Wait for the connection to become idle, to make sure the packet gets
5708 // delayed is the connectivity probing packet.
5709 client_->WaitForDelayedAcks();
5710
5711 QuicSocketAddress addr1 = client_->client()->session()->self_address();
5712 QuicConnection* client_connection = GetClientConnection();
5713 QuicConnectionId server_cid1 = client_connection->connection_id();
5714
5715 // Migrate socket to the new IP address.
5716 QuicIpAddress host2 = TestLoopback(2);
5717 EXPECT_NE(addr1.host(), host2);
5718
5719 // Drop PATH_RESPONSE packets to timeout the path validation.
5720 server_writer_->set_fake_packet_loss_percentage(100);
5721 ASSERT_TRUE(
5722 QuicConnectionPeer::HasUnusedPeerIssuedConnectionId(client_connection));
5723
5724 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host2));
5725
5726 QuicConnectionId server_cid2 =
5727 QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5728 client_connection);
5729 EXPECT_FALSE(server_cid2.IsEmpty());
5730 EXPECT_NE(server_cid2, server_cid1);
5731 // Wait until path validation fails at the client.
5732 while (client_->client()->HasPendingPathValidation()) {
5733 EXPECT_EQ(server_cid2,
5734 QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5735 client_connection));
5736 client_->client()->WaitForEvents();
5737 }
5738 EXPECT_EQ(addr1, client_->client()->session()->self_address());
5739 EXPECT_EQ(server_cid1, GetClientConnection()->connection_id());
5740
5741 server_writer_->set_fake_packet_loss_percentage(0);
5742 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
5743
5744 WaitForNewConnectionIds();
5745 EXPECT_EQ(1u, client_connection->GetStats().num_retire_connection_id_sent);
5746 EXPECT_EQ(0u, client_connection->GetStats().num_new_connection_id_sent);
5747
5748 server_thread_->Pause();
5749 QuicConnection* server_connection = GetServerConnection();
5750 // Server has received 3 path challenges.
5751 EXPECT_EQ(3u,
5752 server_connection->GetStats().num_connectivity_probing_received);
5753 EXPECT_EQ(server_cid1, server_connection->connection_id());
5754 EXPECT_EQ(0u, server_connection->GetStats().num_retire_connection_id_sent);
5755 EXPECT_EQ(2u, server_connection->GetStats().num_new_connection_id_sent);
5756 server_thread_->Resume();
5757
5758 // Migrate socket to a new IP address again.
5759 QuicIpAddress host3 = TestLoopback(3);
5760 EXPECT_NE(addr1.host(), host3);
5761 EXPECT_NE(host2, host3);
5762
5763 WaitForNewConnectionIds();
5764 EXPECT_EQ(1u, client_connection->GetStats().num_retire_connection_id_sent);
5765 EXPECT_EQ(0u, client_connection->GetStats().num_new_connection_id_sent);
5766
5767 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host3));
5768 QuicConnectionId server_cid3 =
5769 QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5770 client_connection);
5771 EXPECT_FALSE(server_cid3.IsEmpty());
5772 EXPECT_NE(server_cid1, server_cid3);
5773 EXPECT_NE(server_cid2, server_cid3);
5774 while (client_->client()->HasPendingPathValidation()) {
5775 client_->client()->WaitForEvents();
5776 }
5777 EXPECT_EQ(host3, client_->client()->session()->self_address().host());
5778 EXPECT_EQ(server_cid3, GetClientConnection()->connection_id());
5779 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5780 client_connection)
5781 .IsEmpty());
5782 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
5783
5784 // Server should send a new connection ID to client.
5785 WaitForNewConnectionIds();
5786 EXPECT_EQ(2u, client_connection->GetStats().num_retire_connection_id_sent);
5787 EXPECT_EQ(0u, client_connection->GetStats().num_new_connection_id_sent);
5788 }
5789
TEST_P(EndToEndPacketReorderingTest,MigrateAgainAfterPathValidationFailureWithNonZeroClientCid)5790 TEST_P(EndToEndPacketReorderingTest,
5791 MigrateAgainAfterPathValidationFailureWithNonZeroClientCid) {
5792 if (!version_.HasIetfQuicFrames()) {
5793 ASSERT_TRUE(Initialize());
5794 return;
5795 }
5796 override_client_connection_id_length_ = kQuicDefaultConnectionIdLength;
5797 ASSERT_TRUE(Initialize());
5798
5799 client_.reset(CreateQuicClient(nullptr));
5800 // Finish one request to make sure handshake established.
5801 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
5802
5803 // Wait for the connection to become idle, to make sure the packet gets
5804 // delayed is the connectivity probing packet.
5805 client_->WaitForDelayedAcks();
5806
5807 QuicSocketAddress addr1 = client_->client()->session()->self_address();
5808 QuicConnection* client_connection = GetClientConnection();
5809 QuicConnectionId server_cid1 = client_connection->connection_id();
5810 QuicConnectionId client_cid1 = client_connection->client_connection_id();
5811
5812 // Migrate socket to the new IP address.
5813 QuicIpAddress host2 = TestLoopback(2);
5814 EXPECT_NE(addr1.host(), host2);
5815
5816 // Drop PATH_RESPONSE packets to timeout the path validation.
5817 server_writer_->set_fake_packet_loss_percentage(100);
5818 ASSERT_TRUE(
5819 QuicConnectionPeer::HasUnusedPeerIssuedConnectionId(client_connection));
5820 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host2));
5821 QuicConnectionId server_cid2 =
5822 QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5823 client_connection);
5824 EXPECT_FALSE(server_cid2.IsEmpty());
5825 EXPECT_NE(server_cid2, server_cid1);
5826 QuicConnectionId client_cid2 =
5827 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(
5828 client_connection);
5829 EXPECT_FALSE(client_cid2.IsEmpty());
5830 EXPECT_NE(client_cid2, client_cid1);
5831 while (client_->client()->HasPendingPathValidation()) {
5832 EXPECT_EQ(server_cid2,
5833 QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5834 client_connection));
5835 client_->client()->WaitForEvents();
5836 }
5837 EXPECT_EQ(addr1, client_->client()->session()->self_address());
5838 EXPECT_EQ(server_cid1, GetClientConnection()->connection_id());
5839 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5840 client_connection)
5841 .IsEmpty());
5842 server_writer_->set_fake_packet_loss_percentage(0);
5843 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
5844 WaitForNewConnectionIds();
5845 EXPECT_EQ(1u, client_connection->GetStats().num_retire_connection_id_sent);
5846 EXPECT_EQ(2u, client_connection->GetStats().num_new_connection_id_sent);
5847
5848 server_thread_->Pause();
5849 QuicConnection* server_connection = GetServerConnection();
5850 if (server_connection != nullptr) {
5851 EXPECT_EQ(3u,
5852 server_connection->GetStats().num_connectivity_probing_received);
5853 EXPECT_EQ(server_cid1, server_connection->connection_id());
5854 } else {
5855 ADD_FAILURE() << "Missing server connection";
5856 }
5857 EXPECT_EQ(1u, server_connection->GetStats().num_retire_connection_id_sent);
5858 EXPECT_EQ(2u, server_connection->GetStats().num_new_connection_id_sent);
5859 server_thread_->Resume();
5860
5861 // Migrate socket to a new IP address again.
5862 QuicIpAddress host3 = TestLoopback(3);
5863 EXPECT_NE(addr1.host(), host3);
5864 EXPECT_NE(host2, host3);
5865 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host3));
5866
5867 QuicConnectionId server_cid3 =
5868 QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5869 client_connection);
5870 EXPECT_FALSE(server_cid3.IsEmpty());
5871 EXPECT_NE(server_cid1, server_cid3);
5872 EXPECT_NE(server_cid2, server_cid3);
5873 QuicConnectionId client_cid3 =
5874 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(
5875 client_connection);
5876 EXPECT_NE(client_cid1, client_cid3);
5877 EXPECT_NE(client_cid2, client_cid3);
5878 while (client_->client()->HasPendingPathValidation()) {
5879 client_->client()->WaitForEvents();
5880 }
5881 EXPECT_EQ(host3, client_->client()->session()->self_address().host());
5882 EXPECT_EQ(server_cid3, GetClientConnection()->connection_id());
5883 EXPECT_TRUE(QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
5884 client_connection)
5885 .IsEmpty());
5886 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
5887
5888 // Server should send new server connection ID to client and retires old
5889 // client connection ID.
5890 WaitForNewConnectionIds();
5891 EXPECT_EQ(2u, client_connection->GetStats().num_retire_connection_id_sent);
5892 EXPECT_EQ(3u, client_connection->GetStats().num_new_connection_id_sent);
5893 }
5894
TEST_P(EndToEndPacketReorderingTest,Buffer0RttRequest)5895 TEST_P(EndToEndPacketReorderingTest, Buffer0RttRequest) {
5896 ASSERT_TRUE(Initialize());
5897 if (!version_.UsesTls() &&
5898 GetQuicReloadableFlag(quic_require_handshake_confirmation)) {
5899 return;
5900 }
5901 // Finish one request to make sure handshake established.
5902 client_->SendSynchronousRequest("/foo");
5903 // Disconnect for next 0-rtt request.
5904 client_->Disconnect();
5905
5906 // Client has valid Session Ticket now. Do a 0-RTT request.
5907 // Buffer a CHLO till the request is sent out. HTTP/3 sends two packets: a
5908 // SETTINGS frame and a request.
5909 reorder_writer_->SetDelay(version_.UsesHttp3() ? 2 : 1);
5910 // Only send out a CHLO.
5911 client_->client()->Initialize();
5912
5913 // Send a request before handshake finishes.
5914 Http2HeaderBlock headers;
5915 headers[":method"] = "POST";
5916 headers[":path"] = "/bar";
5917 headers[":scheme"] = "https";
5918 headers[":authority"] = server_hostname_;
5919
5920 client_->SendMessage(headers, "");
5921 client_->WaitForResponse();
5922 EXPECT_EQ(kBarResponseBody, client_->response_body());
5923 QuicConnection* client_connection = GetClientConnection();
5924 ASSERT_TRUE(client_connection);
5925 QuicConnectionStats client_stats = client_connection->GetStats();
5926 EXPECT_EQ(0u, client_stats.packets_lost);
5927 EXPECT_TRUE(client_->client()->EarlyDataAccepted());
5928 }
5929
TEST_P(EndToEndTest,SimpleStopSendingRstStreamTest)5930 TEST_P(EndToEndTest, SimpleStopSendingRstStreamTest) {
5931 ASSERT_TRUE(Initialize());
5932
5933 // Send a request without a fin, to keep the stream open
5934 Http2HeaderBlock headers;
5935 headers[":method"] = "POST";
5936 headers[":path"] = "/foo";
5937 headers[":scheme"] = "https";
5938 headers[":authority"] = server_hostname_;
5939 client_->SendMessage(headers, "", /*fin=*/false);
5940 // Stream should be open
5941 ASSERT_NE(nullptr, client_->latest_created_stream());
5942 EXPECT_FALSE(client_->latest_created_stream()->write_side_closed());
5943 EXPECT_FALSE(
5944 QuicStreamPeer::read_side_closed(client_->latest_created_stream()));
5945
5946 // Send a RST_STREAM+STOP_SENDING on the stream
5947 // Code is not important.
5948 client_->latest_created_stream()->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
5949 client_->WaitForResponse();
5950
5951 // Stream should be gone.
5952 ASSERT_EQ(nullptr, client_->latest_created_stream());
5953 }
5954
5955 class BadShloPacketWriter : public QuicPacketWriterWrapper {
5956 public:
BadShloPacketWriter(ParsedQuicVersion version)5957 BadShloPacketWriter(ParsedQuicVersion version)
5958 : error_returned_(false), version_(version) {}
~BadShloPacketWriter()5959 ~BadShloPacketWriter() override {}
5960
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,quic::PerPacketOptions * options,const quic::QuicPacketWriterParams & params)5961 WriteResult WritePacket(const char* buffer, size_t buf_len,
5962 const QuicIpAddress& self_address,
5963 const QuicSocketAddress& peer_address,
5964 quic::PerPacketOptions* options,
5965 const quic::QuicPacketWriterParams& params) override {
5966 const WriteResult result = QuicPacketWriterWrapper::WritePacket(
5967 buffer, buf_len, self_address, peer_address, options, params);
5968 const uint8_t type_byte = buffer[0];
5969 if (!error_returned_ && (type_byte & FLAGS_LONG_HEADER) &&
5970 TypeByteIsServerHello(type_byte)) {
5971 QUIC_DVLOG(1) << "Return write error for packet containing ServerHello";
5972 error_returned_ = true;
5973 return WriteResult(WRITE_STATUS_ERROR, *MessageTooBigErrorCode());
5974 }
5975 return result;
5976 }
5977
TypeByteIsServerHello(uint8_t type_byte)5978 bool TypeByteIsServerHello(uint8_t type_byte) {
5979 if (version_.UsesV2PacketTypes()) {
5980 return ((type_byte & 0x30) >> 4) == 3;
5981 }
5982 if (version_.UsesQuicCrypto()) {
5983 // ENCRYPTION_ZERO_RTT packet.
5984 return ((type_byte & 0x30) >> 4) == 1;
5985 }
5986 // ENCRYPTION_HANDSHAKE packet.
5987 return ((type_byte & 0x30) >> 4) == 2;
5988 }
5989
5990 private:
5991 bool error_returned_;
5992 ParsedQuicVersion version_;
5993 };
5994
TEST_P(EndToEndTest,ConnectionCloseBeforeHandshakeComplete)5995 TEST_P(EndToEndTest, ConnectionCloseBeforeHandshakeComplete) {
5996 // This test ensures ZERO_RTT_PROTECTED connection close could close a client
5997 // which has switched to forward secure.
5998 connect_to_server_on_initialize_ = false;
5999 ASSERT_TRUE(Initialize());
6000 server_thread_->Pause();
6001 QuicDispatcher* dispatcher =
6002 QuicServerPeer::GetDispatcher(server_thread_->server());
6003 if (dispatcher == nullptr) {
6004 ADD_FAILURE() << "Missing dispatcher";
6005 server_thread_->Resume();
6006 return;
6007 }
6008 if (dispatcher->NumSessions() > 0) {
6009 ADD_FAILURE() << "Dispatcher session map not empty";
6010 server_thread_->Resume();
6011 return;
6012 }
6013 // Note: this writer will only used by the server connection, not the time
6014 // wait list.
6015 QuicDispatcherPeer::UseWriter(
6016 dispatcher,
6017 // This causes the first server sent ZERO_RTT_PROTECTED packet (i.e.,
6018 // SHLO) to be sent, but WRITE_ERROR is returned. Such that a
6019 // ZERO_RTT_PROTECTED connection close would be sent to a client with
6020 // encryption level FORWARD_SECURE.
6021 new BadShloPacketWriter(version_));
6022 server_thread_->Resume();
6023
6024 client_.reset(CreateQuicClient(client_writer_));
6025 EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
6026 // Verify ZERO_RTT_PROTECTED connection close is successfully processed by
6027 // client which switches to FORWARD_SECURE.
6028 EXPECT_THAT(client_->connection_error(), IsError(QUIC_PACKET_WRITE_ERROR));
6029 }
6030
6031 class BadShloPacketWriter2 : public QuicPacketWriterWrapper {
6032 public:
BadShloPacketWriter2(ParsedQuicVersion version)6033 BadShloPacketWriter2(ParsedQuicVersion version)
6034 : error_returned_(false), version_(version) {}
~BadShloPacketWriter2()6035 ~BadShloPacketWriter2() override {}
6036
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,quic::PerPacketOptions * options,const quic::QuicPacketWriterParams & params)6037 WriteResult WritePacket(const char* buffer, size_t buf_len,
6038 const QuicIpAddress& self_address,
6039 const QuicSocketAddress& peer_address,
6040 quic::PerPacketOptions* options,
6041 const quic::QuicPacketWriterParams& params) override {
6042 const uint8_t type_byte = buffer[0];
6043
6044 if (type_byte & FLAGS_LONG_HEADER) {
6045 if (((type_byte & 0x30 >> 4) == (version_.UsesV2PacketTypes() ? 2 : 1)) ||
6046 ((type_byte & 0x7F) == 0x7C)) {
6047 QUIC_DVLOG(1) << "Dropping ZERO_RTT_PACKET packet";
6048 return WriteResult(WRITE_STATUS_OK, buf_len);
6049 }
6050 } else if (!error_returned_) {
6051 QUIC_DVLOG(1) << "Return write error for short header packet";
6052 error_returned_ = true;
6053 return WriteResult(WRITE_STATUS_ERROR, *MessageTooBigErrorCode());
6054 }
6055 return QuicPacketWriterWrapper::WritePacket(buffer, buf_len, self_address,
6056 peer_address, options, params);
6057 }
6058
6059 private:
6060 bool error_returned_;
6061 ParsedQuicVersion version_;
6062 };
6063
TEST_P(EndToEndTest,ForwardSecureConnectionClose)6064 TEST_P(EndToEndTest, ForwardSecureConnectionClose) {
6065 // This test ensures ZERO_RTT_PROTECTED connection close is sent to a client
6066 // which has ZERO_RTT_PROTECTED encryption level.
6067 connect_to_server_on_initialize_ = false;
6068 ASSERT_TRUE(Initialize());
6069 server_thread_->Pause();
6070 QuicDispatcher* dispatcher =
6071 QuicServerPeer::GetDispatcher(server_thread_->server());
6072 if (dispatcher == nullptr) {
6073 ADD_FAILURE() << "Missing dispatcher";
6074 server_thread_->Resume();
6075 return;
6076 }
6077 if (dispatcher->NumSessions() > 0) {
6078 ADD_FAILURE() << "Dispatcher session map not empty";
6079 server_thread_->Resume();
6080 return;
6081 }
6082 // Note: this writer will only used by the server connection, not the time
6083 // wait list.
6084 QuicDispatcherPeer::UseWriter(
6085 dispatcher,
6086 // This causes the all server sent ZERO_RTT_PROTECTED packets to be
6087 // dropped, and first short header packet causes write error.
6088 new BadShloPacketWriter2(version_));
6089 server_thread_->Resume();
6090 client_.reset(CreateQuicClient(client_writer_));
6091 EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
6092 // Verify ZERO_RTT_PROTECTED connection close is successfully processed by
6093 // client.
6094 EXPECT_THAT(client_->connection_error(), IsError(QUIC_PACKET_WRITE_ERROR));
6095 }
6096
6097 // Test that the stream id manager closes the connection if a stream
6098 // in excess of the allowed maximum.
TEST_P(EndToEndTest,TooBigStreamIdClosesConnection)6099 TEST_P(EndToEndTest, TooBigStreamIdClosesConnection) {
6100 // Has to be before version test, see EndToEndTest::TearDown()
6101 ASSERT_TRUE(Initialize());
6102 if (!version_.HasIetfQuicFrames()) {
6103 // Only runs for IETF QUIC.
6104 return;
6105 }
6106 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
6107
6108 std::string body(kMaxOutgoingPacketSize, 'a');
6109 Http2HeaderBlock headers;
6110 headers[":method"] = "POST";
6111 headers[":path"] = "/foo";
6112 headers[":scheme"] = "https";
6113 headers[":authority"] = server_hostname_;
6114
6115 // Force the client to write with a stream ID that exceeds the limit.
6116 QuicSpdySession* client_session = GetClientSession();
6117 ASSERT_TRUE(client_session);
6118 QuicStreamIdManager* stream_id_manager =
6119 QuicSessionPeer::ietf_bidirectional_stream_id_manager(client_session);
6120 ASSERT_TRUE(stream_id_manager);
6121 QuicStreamCount max_number_of_streams =
6122 stream_id_manager->outgoing_max_streams();
6123 QuicSessionPeer::SetNextOutgoingBidirectionalStreamId(
6124 client_session,
6125 GetNthClientInitiatedBidirectionalId(max_number_of_streams + 1));
6126 client_->SendCustomSynchronousRequest(headers, body);
6127 EXPECT_THAT(client_->stream_error(),
6128 IsStreamError(QUIC_STREAM_CONNECTION_ERROR));
6129 EXPECT_THAT(client_session->error(), IsError(QUIC_INVALID_STREAM_ID));
6130 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE, client_session->close_type());
6131 EXPECT_TRUE(
6132 IS_IETF_STREAM_FRAME(client_session->transport_close_frame_type()));
6133 }
6134
TEST_P(EndToEndTest,CustomTransportParameters)6135 TEST_P(EndToEndTest, CustomTransportParameters) {
6136 if (!version_.UsesTls()) {
6137 // Custom transport parameters are only supported with TLS.
6138 ASSERT_TRUE(Initialize());
6139 return;
6140 }
6141 constexpr auto kCustomParameter =
6142 static_cast<TransportParameters::TransportParameterId>(0xff34);
6143 client_config_.custom_transport_parameters_to_send()[kCustomParameter] =
6144 "test";
6145 NiceMock<MockQuicConnectionDebugVisitor> visitor;
6146 connection_debug_visitor_ = &visitor;
6147 EXPECT_CALL(visitor, OnTransportParametersSent(_))
6148 .WillOnce(Invoke([kCustomParameter](
6149 const TransportParameters& transport_parameters) {
6150 auto it = transport_parameters.custom_parameters.find(kCustomParameter);
6151 ASSERT_NE(it, transport_parameters.custom_parameters.end());
6152 EXPECT_EQ(it->second, "test");
6153 }));
6154 EXPECT_CALL(visitor, OnTransportParametersReceived(_)).Times(1);
6155 ASSERT_TRUE(Initialize());
6156
6157 EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
6158
6159 server_thread_->Pause();
6160 QuicSpdySession* server_session = GetServerSession();
6161 QuicConfig* server_config = nullptr;
6162 if (server_session != nullptr) {
6163 server_config = server_session->config();
6164 } else {
6165 ADD_FAILURE() << "Missing server session";
6166 }
6167 if (server_config != nullptr) {
6168 if (auto it = server_config->received_custom_transport_parameters().find(
6169 kCustomParameter);
6170 it != server_config->received_custom_transport_parameters().end()) {
6171 EXPECT_EQ(it->second, "test");
6172 } else {
6173 ADD_FAILURE() << "Did not find custom parameter";
6174 }
6175 } else {
6176 ADD_FAILURE() << "Missing server config";
6177 }
6178 server_thread_->Resume();
6179 }
6180
6181 // Testing packet writer that makes a copy of the first sent packets before
6182 // sending them. Useful for tests that need access to sent packets.
6183 class CopyingPacketWriter : public PacketDroppingTestWriter {
6184 public:
CopyingPacketWriter(int num_packets_to_copy)6185 explicit CopyingPacketWriter(int num_packets_to_copy)
6186 : num_packets_to_copy_(num_packets_to_copy) {}
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,PerPacketOptions * options,const QuicPacketWriterParams & params)6187 WriteResult WritePacket(const char* buffer, size_t buf_len,
6188 const QuicIpAddress& self_address,
6189 const QuicSocketAddress& peer_address,
6190 PerPacketOptions* options,
6191 const QuicPacketWriterParams& params) override {
6192 if (num_packets_to_copy_ > 0) {
6193 num_packets_to_copy_--;
6194 packets_.push_back(
6195 QuicEncryptedPacket(buffer, buf_len, /*owns_buffer=*/false).Clone());
6196 }
6197 return PacketDroppingTestWriter::WritePacket(buffer, buf_len, self_address,
6198 peer_address, options, params);
6199 }
6200
packets()6201 std::vector<std::unique_ptr<QuicEncryptedPacket>>& packets() {
6202 return packets_;
6203 }
6204
6205 private:
6206 int num_packets_to_copy_;
6207 std::vector<std::unique_ptr<QuicEncryptedPacket>> packets_;
6208 };
6209
TEST_P(EndToEndTest,KeyUpdateInitiatedByClient)6210 TEST_P(EndToEndTest, KeyUpdateInitiatedByClient) {
6211 if (!version_.UsesTls()) {
6212 // Key Update is only supported in TLS handshake.
6213 ASSERT_TRUE(Initialize());
6214 return;
6215 }
6216
6217 ASSERT_TRUE(Initialize());
6218
6219 SendSynchronousFooRequestAndCheckResponse();
6220 QuicConnection* client_connection = GetClientConnection();
6221 ASSERT_TRUE(client_connection);
6222 EXPECT_EQ(0u, client_connection->GetStats().key_update_count);
6223
6224 EXPECT_TRUE(
6225 client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
6226 SendSynchronousFooRequestAndCheckResponse();
6227 EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
6228
6229 SendSynchronousFooRequestAndCheckResponse();
6230 EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
6231
6232 EXPECT_TRUE(
6233 client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
6234 SendSynchronousFooRequestAndCheckResponse();
6235 EXPECT_EQ(2u, client_connection->GetStats().key_update_count);
6236
6237 server_thread_->Pause();
6238 QuicConnection* server_connection = GetServerConnection();
6239 if (server_connection) {
6240 QuicConnectionStats server_stats = server_connection->GetStats();
6241 EXPECT_EQ(2u, server_stats.key_update_count);
6242 } else {
6243 ADD_FAILURE() << "Missing server connection";
6244 }
6245 server_thread_->Resume();
6246 }
6247
TEST_P(EndToEndTest,KeyUpdateInitiatedByServer)6248 TEST_P(EndToEndTest, KeyUpdateInitiatedByServer) {
6249 if (!version_.UsesTls()) {
6250 // Key Update is only supported in TLS handshake.
6251 ASSERT_TRUE(Initialize());
6252 return;
6253 }
6254
6255 ASSERT_TRUE(Initialize());
6256
6257 SendSynchronousFooRequestAndCheckResponse();
6258 QuicConnection* client_connection = GetClientConnection();
6259 ASSERT_TRUE(client_connection);
6260 EXPECT_EQ(0u, client_connection->GetStats().key_update_count);
6261
6262 // Use WaitUntil to ensure the server had executed the key update predicate
6263 // before sending the Foo request, otherwise the test can be flaky if it
6264 // receives the Foo request before executing the key update.
6265 server_thread_->WaitUntil(
6266 [this]() {
6267 QuicConnection* server_connection = GetServerConnection();
6268 if (server_connection != nullptr) {
6269 if (!server_connection->IsKeyUpdateAllowed()) {
6270 // Server may not have received ack from client yet for the current
6271 // key phase, wait a bit and try again.
6272 return false;
6273 }
6274 EXPECT_TRUE(server_connection->InitiateKeyUpdate(
6275 KeyUpdateReason::kLocalForTests));
6276 } else {
6277 ADD_FAILURE() << "Missing server connection";
6278 }
6279 return true;
6280 },
6281 QuicTime::Delta::FromSeconds(5));
6282
6283 SendSynchronousFooRequestAndCheckResponse();
6284 EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
6285
6286 SendSynchronousFooRequestAndCheckResponse();
6287 EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
6288
6289 server_thread_->WaitUntil(
6290 [this]() {
6291 QuicConnection* server_connection = GetServerConnection();
6292 if (server_connection != nullptr) {
6293 if (!server_connection->IsKeyUpdateAllowed()) {
6294 return false;
6295 }
6296 EXPECT_TRUE(server_connection->InitiateKeyUpdate(
6297 KeyUpdateReason::kLocalForTests));
6298 } else {
6299 ADD_FAILURE() << "Missing server connection";
6300 }
6301 return true;
6302 },
6303 QuicTime::Delta::FromSeconds(5));
6304
6305 SendSynchronousFooRequestAndCheckResponse();
6306 EXPECT_EQ(2u, client_connection->GetStats().key_update_count);
6307
6308 server_thread_->Pause();
6309 QuicConnection* server_connection = GetServerConnection();
6310 if (server_connection) {
6311 QuicConnectionStats server_stats = server_connection->GetStats();
6312 EXPECT_EQ(2u, server_stats.key_update_count);
6313 } else {
6314 ADD_FAILURE() << "Missing server connection";
6315 }
6316 server_thread_->Resume();
6317 }
6318
TEST_P(EndToEndTest,KeyUpdateInitiatedByBoth)6319 TEST_P(EndToEndTest, KeyUpdateInitiatedByBoth) {
6320 if (!version_.UsesTls()) {
6321 // Key Update is only supported in TLS handshake.
6322 ASSERT_TRUE(Initialize());
6323 return;
6324 }
6325
6326 ASSERT_TRUE(Initialize());
6327
6328 SendSynchronousFooRequestAndCheckResponse();
6329
6330 // Use WaitUntil to ensure the server had executed the key update predicate
6331 // before the client sends the Foo request, otherwise the Foo request from
6332 // the client could trigger the server key update before the server can
6333 // initiate the key update locally. That would mean the test is no longer
6334 // hitting the intended test state of both sides locally initiating a key
6335 // update before receiving a packet in the new key phase from the other side.
6336 // Additionally the test would fail since InitiateKeyUpdate() would not allow
6337 // to do another key update yet and return false.
6338 server_thread_->WaitUntil(
6339 [this]() {
6340 QuicConnection* server_connection = GetServerConnection();
6341 if (server_connection != nullptr) {
6342 if (!server_connection->IsKeyUpdateAllowed()) {
6343 // Server may not have received ack from client yet for the current
6344 // key phase, wait a bit and try again.
6345 return false;
6346 }
6347 EXPECT_TRUE(server_connection->InitiateKeyUpdate(
6348 KeyUpdateReason::kLocalForTests));
6349 } else {
6350 ADD_FAILURE() << "Missing server connection";
6351 }
6352 return true;
6353 },
6354 QuicTime::Delta::FromSeconds(5));
6355 QuicConnection* client_connection = GetClientConnection();
6356 ASSERT_TRUE(client_connection);
6357 EXPECT_TRUE(
6358 client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
6359
6360 SendSynchronousFooRequestAndCheckResponse();
6361 EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
6362
6363 SendSynchronousFooRequestAndCheckResponse();
6364 EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
6365
6366 server_thread_->WaitUntil(
6367 [this]() {
6368 QuicConnection* server_connection = GetServerConnection();
6369 if (server_connection != nullptr) {
6370 if (!server_connection->IsKeyUpdateAllowed()) {
6371 return false;
6372 }
6373 EXPECT_TRUE(server_connection->InitiateKeyUpdate(
6374 KeyUpdateReason::kLocalForTests));
6375 } else {
6376 ADD_FAILURE() << "Missing server connection";
6377 }
6378 return true;
6379 },
6380 QuicTime::Delta::FromSeconds(5));
6381 EXPECT_TRUE(
6382 client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
6383
6384 SendSynchronousFooRequestAndCheckResponse();
6385 EXPECT_EQ(2u, client_connection->GetStats().key_update_count);
6386
6387 server_thread_->Pause();
6388 QuicConnection* server_connection = GetServerConnection();
6389 if (server_connection) {
6390 QuicConnectionStats server_stats = server_connection->GetStats();
6391 EXPECT_EQ(2u, server_stats.key_update_count);
6392 } else {
6393 ADD_FAILURE() << "Missing server connection";
6394 }
6395 server_thread_->Resume();
6396 }
6397
TEST_P(EndToEndTest,KeyUpdateInitiatedByConfidentialityLimit)6398 TEST_P(EndToEndTest, KeyUpdateInitiatedByConfidentialityLimit) {
6399 SetQuicFlag(quic_key_update_confidentiality_limit, 16U);
6400
6401 if (!version_.UsesTls()) {
6402 // Key Update is only supported in TLS handshake.
6403 ASSERT_TRUE(Initialize());
6404 return;
6405 }
6406
6407 ASSERT_TRUE(Initialize());
6408
6409 QuicConnection* client_connection = GetClientConnection();
6410 ASSERT_TRUE(client_connection);
6411 EXPECT_EQ(0u, client_connection->GetStats().key_update_count);
6412
6413 server_thread_->WaitUntil(
6414 [this]() {
6415 QuicConnection* server_connection = GetServerConnection();
6416 if (server_connection != nullptr) {
6417 EXPECT_EQ(0u, server_connection->GetStats().key_update_count);
6418 } else {
6419 ADD_FAILURE() << "Missing server connection";
6420 }
6421 return true;
6422 },
6423 QuicTime::Delta::FromSeconds(5));
6424
6425 for (uint64_t i = 0; i < GetQuicFlag(quic_key_update_confidentiality_limit);
6426 ++i) {
6427 SendSynchronousFooRequestAndCheckResponse();
6428 }
6429
6430 // Don't know exactly how many packets will be sent in each request/response,
6431 // so just test that at least one key update occurred.
6432 EXPECT_LE(1u, client_connection->GetStats().key_update_count);
6433
6434 server_thread_->Pause();
6435 QuicConnection* server_connection = GetServerConnection();
6436 if (server_connection) {
6437 QuicConnectionStats server_stats = server_connection->GetStats();
6438 EXPECT_LE(1u, server_stats.key_update_count);
6439 } else {
6440 ADD_FAILURE() << "Missing server connection";
6441 }
6442 server_thread_->Resume();
6443 }
6444
TEST_P(EndToEndTest,TlsResumptionEnabledOnTheFly)6445 TEST_P(EndToEndTest, TlsResumptionEnabledOnTheFly) {
6446 SetQuicFlag(quic_disable_server_tls_resumption, true);
6447 ASSERT_TRUE(Initialize());
6448
6449 if (!version_.UsesTls()) {
6450 // This test is TLS specific.
6451 return;
6452 }
6453
6454 // Send the first request. Client should not have a resumption ticket.
6455 SendSynchronousFooRequestAndCheckResponse();
6456 QuicSpdyClientSession* client_session = GetClientSession();
6457 ASSERT_TRUE(client_session);
6458 EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
6459 ssl_early_data_no_session_offered);
6460 EXPECT_FALSE(client_session->EarlyDataAccepted());
6461 client_->Disconnect();
6462
6463 SetQuicFlag(quic_disable_server_tls_resumption, false);
6464
6465 // Send the second request. Client should still have no resumption ticket, but
6466 // it will receive one which can be used by the next request.
6467 client_->Connect();
6468 SendSynchronousFooRequestAndCheckResponse();
6469
6470 client_session = GetClientSession();
6471 ASSERT_TRUE(client_session);
6472 EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
6473 ssl_early_data_no_session_offered);
6474 EXPECT_FALSE(client_session->EarlyDataAccepted());
6475 client_->Disconnect();
6476
6477 // Send the third request in 0RTT.
6478 client_->Connect();
6479 SendSynchronousFooRequestAndCheckResponse();
6480
6481 client_session = GetClientSession();
6482 ASSERT_TRUE(client_session);
6483 EXPECT_TRUE(client_session->EarlyDataAccepted());
6484 client_->Disconnect();
6485 }
6486
TEST_P(EndToEndTest,TlsResumptionDisabledOnTheFly)6487 TEST_P(EndToEndTest, TlsResumptionDisabledOnTheFly) {
6488 SetQuicFlag(quic_disable_server_tls_resumption, false);
6489 ASSERT_TRUE(Initialize());
6490
6491 if (!version_.UsesTls()) {
6492 // This test is TLS specific.
6493 return;
6494 }
6495
6496 // Send the first request and then disconnect.
6497 SendSynchronousFooRequestAndCheckResponse();
6498 QuicSpdyClientSession* client_session = GetClientSession();
6499 ASSERT_TRUE(client_session);
6500 EXPECT_FALSE(client_session->EarlyDataAccepted());
6501 client_->Disconnect();
6502
6503 // Send the second request in 0RTT.
6504 client_->Connect();
6505 SendSynchronousFooRequestAndCheckResponse();
6506
6507 client_session = GetClientSession();
6508 ASSERT_TRUE(client_session);
6509 EXPECT_TRUE(client_session->EarlyDataAccepted());
6510 client_->Disconnect();
6511
6512 SetQuicFlag(quic_disable_server_tls_resumption, true);
6513
6514 // Send the third request. The client should try resumption but server should
6515 // decline it.
6516 client_->Connect();
6517 SendSynchronousFooRequestAndCheckResponse();
6518
6519 client_session = GetClientSession();
6520 ASSERT_TRUE(client_session);
6521 EXPECT_FALSE(client_session->EarlyDataAccepted());
6522 EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
6523 ssl_early_data_session_not_resumed);
6524 client_->Disconnect();
6525
6526 // Keep sending until the client runs out of resumption tickets.
6527 for (int i = 0; i < 10; ++i) {
6528 client_->Connect();
6529 SendSynchronousFooRequestAndCheckResponse();
6530
6531 client_session = GetClientSession();
6532 ASSERT_TRUE(client_session);
6533 EXPECT_FALSE(client_session->EarlyDataAccepted());
6534 const auto early_data_reason =
6535 client_session->GetCryptoStream()->EarlyDataReason();
6536 client_->Disconnect();
6537
6538 if (early_data_reason != ssl_early_data_session_not_resumed) {
6539 EXPECT_EQ(early_data_reason, ssl_early_data_unsupported_for_session);
6540 return;
6541 }
6542 }
6543
6544 ADD_FAILURE() << "Client should not have 10 resumption tickets.";
6545 }
6546
TEST_P(EndToEndTest,BlockServerUntilSettingsReceived)6547 TEST_P(EndToEndTest, BlockServerUntilSettingsReceived) {
6548 SetQuicReloadableFlag(quic_block_until_settings_received_copt, true);
6549 // Force loss to test data stream being blocked when SETTINGS are missing.
6550 SetPacketLossPercentage(30);
6551 client_extra_copts_.push_back(kBSUS);
6552 ASSERT_TRUE(Initialize());
6553
6554 if (!version_.UsesHttp3()) {
6555 return;
6556 }
6557
6558 SendSynchronousFooRequestAndCheckResponse();
6559
6560 QuicSpdySession* server_session = GetServerSession();
6561 EXPECT_FALSE(GetClientSession()->ShouldBufferRequestsUntilSettings());
6562 server_thread_->ScheduleAndWaitForCompletion([server_session] {
6563 EXPECT_TRUE(server_session->ShouldBufferRequestsUntilSettings());
6564 });
6565 }
6566
TEST_P(EndToEndTest,WebTransportSessionSetup)6567 TEST_P(EndToEndTest, WebTransportSessionSetup) {
6568 enable_web_transport_ = true;
6569 ASSERT_TRUE(Initialize());
6570
6571 if (!version_.UsesHttp3()) {
6572 return;
6573 }
6574
6575 WebTransportHttp3* web_transport =
6576 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
6577 ASSERT_NE(web_transport, nullptr);
6578
6579 server_thread_->Pause();
6580 QuicSpdySession* server_session = GetServerSession();
6581 EXPECT_TRUE(server_session->GetWebTransportSession(web_transport->id()) !=
6582 nullptr);
6583 server_thread_->Resume();
6584 }
6585
TEST_P(EndToEndTest,WebTransportSessionSetupWithEchoWithSuffix)6586 TEST_P(EndToEndTest, WebTransportSessionSetupWithEchoWithSuffix) {
6587 enable_web_transport_ = true;
6588 ASSERT_TRUE(Initialize());
6589
6590 if (!version_.UsesHttp3()) {
6591 return;
6592 }
6593
6594 // "/echoFoo" should be accepted as "echo" with "set-header" query.
6595 WebTransportHttp3* web_transport = CreateWebTransportSession(
6596 "/echoFoo?set-header=bar:baz", /*wait_for_server_response=*/true);
6597 ASSERT_NE(web_transport, nullptr);
6598
6599 server_thread_->Pause();
6600 QuicSpdySession* server_session = GetServerSession();
6601 EXPECT_TRUE(server_session->GetWebTransportSession(web_transport->id()) !=
6602 nullptr);
6603 server_thread_->Resume();
6604 const spdy::Http2HeaderBlock* response_headers = client_->response_headers();
6605 auto it = response_headers->find("bar");
6606 EXPECT_NE(it, response_headers->end());
6607 EXPECT_EQ(it->second, "baz");
6608 }
6609
TEST_P(EndToEndTest,WebTransportSessionWithLoss)6610 TEST_P(EndToEndTest, WebTransportSessionWithLoss) {
6611 enable_web_transport_ = true;
6612 // Enable loss to verify all permutations of receiving SETTINGS and
6613 // request/response data.
6614 SetPacketLossPercentage(30);
6615 ASSERT_TRUE(Initialize());
6616
6617 if (!version_.UsesHttp3()) {
6618 return;
6619 }
6620
6621 WebTransportHttp3* web_transport =
6622 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
6623 ASSERT_NE(web_transport, nullptr);
6624
6625 server_thread_->Pause();
6626 QuicSpdySession* server_session = GetServerSession();
6627 EXPECT_TRUE(server_session->GetWebTransportSession(web_transport->id()) !=
6628 nullptr);
6629 server_thread_->Resume();
6630 }
6631
TEST_P(EndToEndTest,WebTransportSessionUnidirectionalStream)6632 TEST_P(EndToEndTest, WebTransportSessionUnidirectionalStream) {
6633 enable_web_transport_ = true;
6634 ASSERT_TRUE(Initialize());
6635
6636 if (!version_.UsesHttp3()) {
6637 return;
6638 }
6639
6640 WebTransportHttp3* session =
6641 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
6642 ASSERT_TRUE(session != nullptr);
6643 NiceMock<MockWebTransportSessionVisitor>& visitor =
6644 SetupWebTransportVisitor(session);
6645
6646 WebTransportStream* outgoing_stream =
6647 session->OpenOutgoingUnidirectionalStream();
6648 ASSERT_TRUE(outgoing_stream != nullptr);
6649 EXPECT_EQ(outgoing_stream,
6650 session->GetStreamById(outgoing_stream->GetStreamId()));
6651
6652 auto stream_visitor =
6653 std::make_unique<NiceMock<MockWebTransportStreamVisitor>>();
6654 bool data_acknowledged = false;
6655 EXPECT_CALL(*stream_visitor, OnWriteSideInDataRecvdState())
6656 .WillOnce(Assign(&data_acknowledged, true));
6657 outgoing_stream->SetVisitor(std::move(stream_visitor));
6658
6659 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*outgoing_stream, "test"));
6660 EXPECT_TRUE(outgoing_stream->SendFin());
6661
6662 bool stream_received = false;
6663 EXPECT_CALL(visitor, OnIncomingUnidirectionalStreamAvailable())
6664 .WillOnce(Assign(&stream_received, true));
6665 client_->WaitUntil(2000, [&stream_received]() { return stream_received; });
6666 EXPECT_TRUE(stream_received);
6667 WebTransportStream* received_stream =
6668 session->AcceptIncomingUnidirectionalStream();
6669 ASSERT_TRUE(received_stream != nullptr);
6670 EXPECT_EQ(received_stream,
6671 session->GetStreamById(received_stream->GetStreamId()));
6672 std::string received_data;
6673 WebTransportStream::ReadResult result = received_stream->Read(&received_data);
6674 EXPECT_EQ(received_data, "test");
6675 EXPECT_TRUE(result.fin);
6676
6677 client_->WaitUntil(2000,
6678 [&data_acknowledged]() { return data_acknowledged; });
6679 EXPECT_TRUE(data_acknowledged);
6680 }
6681
TEST_P(EndToEndTest,WebTransportSessionUnidirectionalStreamSentEarly)6682 TEST_P(EndToEndTest, WebTransportSessionUnidirectionalStreamSentEarly) {
6683 enable_web_transport_ = true;
6684 SetPacketLossPercentage(30);
6685 ASSERT_TRUE(Initialize());
6686
6687 if (!version_.UsesHttp3()) {
6688 return;
6689 }
6690
6691 WebTransportHttp3* session =
6692 CreateWebTransportSession("/echo", /*wait_for_server_response=*/false);
6693 ASSERT_TRUE(session != nullptr);
6694 NiceMock<MockWebTransportSessionVisitor>& visitor =
6695 SetupWebTransportVisitor(session);
6696
6697 WebTransportStream* outgoing_stream =
6698 session->OpenOutgoingUnidirectionalStream();
6699 ASSERT_TRUE(outgoing_stream != nullptr);
6700 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*outgoing_stream, "test"));
6701 EXPECT_TRUE(outgoing_stream->SendFin());
6702
6703 bool stream_received = false;
6704 EXPECT_CALL(visitor, OnIncomingUnidirectionalStreamAvailable())
6705 .WillOnce(Assign(&stream_received, true));
6706 client_->WaitUntil(5000, [&stream_received]() { return stream_received; });
6707 EXPECT_TRUE(stream_received);
6708 WebTransportStream* received_stream =
6709 session->AcceptIncomingUnidirectionalStream();
6710 ASSERT_TRUE(received_stream != nullptr);
6711 std::string received_data;
6712 WebTransportStream::ReadResult result = received_stream->Read(&received_data);
6713 EXPECT_EQ(received_data, "test");
6714 EXPECT_TRUE(result.fin);
6715 }
6716
TEST_P(EndToEndTest,WebTransportSessionBidirectionalStream)6717 TEST_P(EndToEndTest, WebTransportSessionBidirectionalStream) {
6718 enable_web_transport_ = true;
6719 ASSERT_TRUE(Initialize());
6720
6721 if (!version_.UsesHttp3()) {
6722 return;
6723 }
6724
6725 WebTransportHttp3* session =
6726 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
6727 ASSERT_TRUE(session != nullptr);
6728
6729 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
6730 ASSERT_TRUE(stream != nullptr);
6731 EXPECT_EQ(stream, session->GetStreamById(stream->GetStreamId()));
6732
6733 auto stream_visitor_owned =
6734 std::make_unique<NiceMock<MockWebTransportStreamVisitor>>();
6735 MockWebTransportStreamVisitor* stream_visitor = stream_visitor_owned.get();
6736 bool data_acknowledged = false;
6737 EXPECT_CALL(*stream_visitor, OnWriteSideInDataRecvdState())
6738 .WillOnce(Assign(&data_acknowledged, true));
6739 stream->SetVisitor(std::move(stream_visitor_owned));
6740
6741 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
6742 EXPECT_TRUE(stream->SendFin());
6743
6744 std::string received_data =
6745 ReadDataFromWebTransportStreamUntilFin(stream, stream_visitor);
6746 EXPECT_EQ(received_data, "test");
6747
6748 client_->WaitUntil(2000,
6749 [&data_acknowledged]() { return data_acknowledged; });
6750 EXPECT_TRUE(data_acknowledged);
6751 }
6752
TEST_P(EndToEndTest,WebTransportSessionBidirectionalStreamWithBuffering)6753 TEST_P(EndToEndTest, WebTransportSessionBidirectionalStreamWithBuffering) {
6754 enable_web_transport_ = true;
6755 SetPacketLossPercentage(30);
6756 ASSERT_TRUE(Initialize());
6757
6758 if (!version_.UsesHttp3()) {
6759 return;
6760 }
6761
6762 WebTransportHttp3* session =
6763 CreateWebTransportSession("/echo", /*wait_for_server_response=*/false);
6764 ASSERT_TRUE(session != nullptr);
6765
6766 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
6767 ASSERT_TRUE(stream != nullptr);
6768 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
6769 EXPECT_TRUE(stream->SendFin());
6770
6771 std::string received_data = ReadDataFromWebTransportStreamUntilFin(stream);
6772 EXPECT_EQ(received_data, "test");
6773 }
6774
TEST_P(EndToEndTest,WebTransportSessionServerBidirectionalStream)6775 TEST_P(EndToEndTest, WebTransportSessionServerBidirectionalStream) {
6776 enable_web_transport_ = true;
6777 ASSERT_TRUE(Initialize());
6778
6779 if (!version_.UsesHttp3()) {
6780 return;
6781 }
6782
6783 WebTransportHttp3* session =
6784 CreateWebTransportSession("/echo", /*wait_for_server_response=*/false);
6785 ASSERT_TRUE(session != nullptr);
6786 NiceMock<MockWebTransportSessionVisitor>& visitor =
6787 SetupWebTransportVisitor(session);
6788
6789 bool stream_received = false;
6790 EXPECT_CALL(visitor, OnIncomingBidirectionalStreamAvailable())
6791 .WillOnce(Assign(&stream_received, true));
6792 client_->WaitUntil(5000, [&stream_received]() { return stream_received; });
6793 EXPECT_TRUE(stream_received);
6794
6795 WebTransportStream* stream = session->AcceptIncomingBidirectionalStream();
6796 ASSERT_TRUE(stream != nullptr);
6797 // Test the full Writev() API.
6798 const std::string kLongString = std::string(16 * 1024, 'a');
6799 std::vector<absl::string_view> write_vector = {"foo", "bar", "test",
6800 kLongString};
6801 quiche::StreamWriteOptions options;
6802 options.set_send_fin(true);
6803 QUICHE_EXPECT_OK(stream->Writev(absl::MakeConstSpan(write_vector), options));
6804
6805 std::string received_data = ReadDataFromWebTransportStreamUntilFin(stream);
6806 EXPECT_EQ(received_data, absl::StrCat("foobartest", kLongString));
6807 }
6808
TEST_P(EndToEndTest,WebTransportDatagrams)6809 TEST_P(EndToEndTest, WebTransportDatagrams) {
6810 enable_web_transport_ = true;
6811 ASSERT_TRUE(Initialize());
6812
6813 if (!version_.UsesHttp3()) {
6814 return;
6815 }
6816
6817 WebTransportHttp3* session =
6818 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
6819 ASSERT_TRUE(session != nullptr);
6820 NiceMock<MockWebTransportSessionVisitor>& visitor =
6821 SetupWebTransportVisitor(session);
6822
6823 quiche::SimpleBufferAllocator allocator;
6824 for (int i = 0; i < 10; i++) {
6825 session->SendOrQueueDatagram("test");
6826 }
6827
6828 int received = 0;
6829 EXPECT_CALL(visitor, OnDatagramReceived(_)).WillRepeatedly([&received]() {
6830 received++;
6831 });
6832 client_->WaitUntil(5000, [&received]() { return received > 0; });
6833 EXPECT_GT(received, 0);
6834 }
6835
TEST_P(EndToEndTest,WebTransportSessionClose)6836 TEST_P(EndToEndTest, WebTransportSessionClose) {
6837 enable_web_transport_ = true;
6838 ASSERT_TRUE(Initialize());
6839
6840 if (!version_.UsesHttp3()) {
6841 return;
6842 }
6843
6844 WebTransportHttp3* session =
6845 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
6846 ASSERT_TRUE(session != nullptr);
6847 NiceMock<MockWebTransportSessionVisitor>& visitor =
6848 SetupWebTransportVisitor(session);
6849
6850 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
6851 ASSERT_TRUE(stream != nullptr);
6852 QuicStreamId stream_id = stream->GetStreamId();
6853 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
6854 // Keep stream open.
6855
6856 bool close_received = false;
6857 EXPECT_CALL(visitor, OnSessionClosed(42, "test error"))
6858 .WillOnce(Assign(&close_received, true));
6859 session->CloseSession(42, "test error");
6860 client_->WaitUntil(2000, [&]() { return close_received; });
6861 EXPECT_TRUE(close_received);
6862
6863 QuicSpdyStream* spdy_stream =
6864 GetClientSession()->GetOrCreateSpdyDataStream(stream_id);
6865 EXPECT_TRUE(spdy_stream == nullptr);
6866 }
6867
TEST_P(EndToEndTest,WebTransportSessionCloseWithoutCapsule)6868 TEST_P(EndToEndTest, WebTransportSessionCloseWithoutCapsule) {
6869 enable_web_transport_ = true;
6870 ASSERT_TRUE(Initialize());
6871
6872 if (!version_.UsesHttp3()) {
6873 return;
6874 }
6875
6876 WebTransportHttp3* session =
6877 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
6878 ASSERT_TRUE(session != nullptr);
6879 NiceMock<MockWebTransportSessionVisitor>& visitor =
6880 SetupWebTransportVisitor(session);
6881
6882 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
6883 ASSERT_TRUE(stream != nullptr);
6884 QuicStreamId stream_id = stream->GetStreamId();
6885 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
6886 // Keep stream open.
6887
6888 bool close_received = false;
6889 EXPECT_CALL(visitor, OnSessionClosed(0, ""))
6890 .WillOnce(Assign(&close_received, true));
6891 session->CloseSessionWithFinOnlyForTests();
6892 client_->WaitUntil(2000, [&]() { return close_received; });
6893 EXPECT_TRUE(close_received);
6894
6895 QuicSpdyStream* spdy_stream =
6896 GetClientSession()->GetOrCreateSpdyDataStream(stream_id);
6897 EXPECT_TRUE(spdy_stream == nullptr);
6898 }
6899
TEST_P(EndToEndTest,WebTransportSessionReceiveClose)6900 TEST_P(EndToEndTest, WebTransportSessionReceiveClose) {
6901 enable_web_transport_ = true;
6902 ASSERT_TRUE(Initialize());
6903
6904 if (!version_.UsesHttp3()) {
6905 return;
6906 }
6907
6908 WebTransportHttp3* session = CreateWebTransportSession(
6909 "/session-close", /*wait_for_server_response=*/true);
6910 ASSERT_TRUE(session != nullptr);
6911 NiceMock<MockWebTransportSessionVisitor>& visitor =
6912 SetupWebTransportVisitor(session);
6913
6914 WebTransportStream* stream = session->OpenOutgoingUnidirectionalStream();
6915 ASSERT_TRUE(stream != nullptr);
6916 QuicStreamId stream_id = stream->GetStreamId();
6917 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "42 test error"));
6918 EXPECT_TRUE(stream->SendFin());
6919
6920 // Have some other streams open pending, to ensure they are closed properly.
6921 stream = session->OpenOutgoingUnidirectionalStream();
6922 stream = session->OpenOutgoingBidirectionalStream();
6923
6924 bool close_received = false;
6925 EXPECT_CALL(visitor, OnSessionClosed(42, "test error"))
6926 .WillOnce(Assign(&close_received, true));
6927 client_->WaitUntil(2000, [&]() { return close_received; });
6928 EXPECT_TRUE(close_received);
6929
6930 QuicSpdyStream* spdy_stream =
6931 GetClientSession()->GetOrCreateSpdyDataStream(stream_id);
6932 EXPECT_TRUE(spdy_stream == nullptr);
6933 }
6934
TEST_P(EndToEndTest,WebTransportSessionReceiveDrain)6935 TEST_P(EndToEndTest, WebTransportSessionReceiveDrain) {
6936 enable_web_transport_ = true;
6937 ASSERT_TRUE(Initialize());
6938
6939 if (!version_.UsesHttp3()) {
6940 return;
6941 }
6942
6943 WebTransportHttp3* session = CreateWebTransportSession(
6944 "/session-close", /*wait_for_server_response=*/true);
6945 ASSERT_TRUE(session != nullptr);
6946
6947 WebTransportStream* stream = session->OpenOutgoingUnidirectionalStream();
6948 ASSERT_TRUE(stream != nullptr);
6949 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "DRAIN"));
6950 EXPECT_TRUE(stream->SendFin());
6951
6952 bool drain_received = false;
6953 session->SetOnDraining([&drain_received] { drain_received = true; });
6954 client_->WaitUntil(2000, [&]() { return drain_received; });
6955 EXPECT_TRUE(drain_received);
6956 }
6957
TEST_P(EndToEndTest,WebTransportSessionStreamTermination)6958 TEST_P(EndToEndTest, WebTransportSessionStreamTermination) {
6959 enable_web_transport_ = true;
6960 ASSERT_TRUE(Initialize());
6961
6962 if (!version_.UsesHttp3()) {
6963 return;
6964 }
6965
6966 WebTransportHttp3* session =
6967 CreateWebTransportSession("/resets", /*wait_for_server_response=*/true);
6968 ASSERT_TRUE(session != nullptr);
6969
6970 NiceMock<MockWebTransportSessionVisitor>& visitor =
6971 SetupWebTransportVisitor(session);
6972 EXPECT_CALL(visitor, OnIncomingUnidirectionalStreamAvailable())
6973 .WillRepeatedly([this, session]() {
6974 ReadAllIncomingWebTransportUnidirectionalStreams(session);
6975 });
6976
6977 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
6978 QuicStreamId id1 = stream->GetStreamId();
6979 ASSERT_TRUE(stream != nullptr);
6980 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
6981 stream->ResetWithUserCode(42);
6982
6983 // This read fails if the stream is closed in both directions, since that
6984 // results in stream object being deleted.
6985 std::string received_data = ReadDataFromWebTransportStreamUntilFin(stream);
6986 EXPECT_LE(received_data.size(), 4u);
6987
6988 stream = session->OpenOutgoingBidirectionalStream();
6989 QuicStreamId id2 = stream->GetStreamId();
6990 ASSERT_TRUE(stream != nullptr);
6991 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
6992 stream->SendStopSending(100024);
6993
6994 std::array<std::string, 2> expected_log = {
6995 absl::StrCat("Received reset for stream ", id1, " with error code 42"),
6996 absl::StrCat("Received stop sending for stream ", id2,
6997 " with error code 100024"),
6998 };
6999 client_->WaitUntil(2000, [this, &expected_log]() {
7000 return received_webtransport_unidirectional_streams_.size() >=
7001 expected_log.size();
7002 });
7003 EXPECT_THAT(received_webtransport_unidirectional_streams_,
7004 UnorderedElementsAreArray(expected_log));
7005
7006 // Since we closed the read side, cleanly closing the write side should result
7007 // in the stream getting deleted.
7008 ASSERT_TRUE(GetClientSession()->GetOrCreateSpdyDataStream(id2) != nullptr);
7009 EXPECT_TRUE(stream->SendFin());
7010 EXPECT_TRUE(client_->WaitUntil(2000, [this, id2]() {
7011 return GetClientSession()->GetOrCreateSpdyDataStream(id2) == nullptr;
7012 }));
7013 }
7014
7015 // This test currently does not pass; we need support for
7016 // https://datatracker.ietf.org/doc/draft-seemann-quic-reliable-stream-reset/ in
7017 // order to make this work.
TEST_P(EndToEndTest,DISABLED_WebTransportSessionResetReliability)7018 TEST_P(EndToEndTest, DISABLED_WebTransportSessionResetReliability) {
7019 enable_web_transport_ = true;
7020 ASSERT_TRUE(Initialize());
7021
7022 if (!version_.UsesHttp3()) {
7023 return;
7024 }
7025
7026 SetPacketLossPercentage(30);
7027
7028 WebTransportHttp3* session =
7029 CreateWebTransportSession("/resets", /*wait_for_server_response=*/true);
7030 ASSERT_TRUE(session != nullptr);
7031
7032 NiceMock<MockWebTransportSessionVisitor>& visitor =
7033 SetupWebTransportVisitor(session);
7034 EXPECT_CALL(visitor, OnIncomingUnidirectionalStreamAvailable())
7035 .WillRepeatedly([this, session]() {
7036 ReadAllIncomingWebTransportUnidirectionalStreams(session);
7037 });
7038
7039 std::vector<std::string> expected_log;
7040 constexpr int kStreamsToCreate = 10;
7041 for (int i = 0; i < kStreamsToCreate; i++) {
7042 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
7043 QuicStreamId id = stream->GetStreamId();
7044 ASSERT_TRUE(stream != nullptr);
7045 stream->ResetWithUserCode(42);
7046
7047 expected_log.push_back(
7048 absl::StrCat("Received reset for stream ", id, " with error code 42"));
7049 }
7050 client_->WaitUntil(2000, [this, &expected_log]() {
7051 return received_webtransport_unidirectional_streams_.size() >=
7052 expected_log.size();
7053 });
7054 EXPECT_THAT(received_webtransport_unidirectional_streams_,
7055 UnorderedElementsAreArray(expected_log));
7056 }
7057
TEST_P(EndToEndTest,WebTransportSession404)7058 TEST_P(EndToEndTest, WebTransportSession404) {
7059 enable_web_transport_ = true;
7060 ASSERT_TRUE(Initialize());
7061
7062 if (!version_.UsesHttp3()) {
7063 return;
7064 }
7065
7066 WebTransportHttp3* session = CreateWebTransportSession(
7067 "/does-not-exist", /*wait_for_server_response=*/false);
7068 ASSERT_TRUE(session != nullptr);
7069 QuicSpdyStream* connect_stream = client_->latest_created_stream();
7070 QuicStreamId connect_stream_id = connect_stream->id();
7071
7072 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
7073 ASSERT_TRUE(stream != nullptr);
7074 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
7075 EXPECT_TRUE(stream->SendFin());
7076
7077 EXPECT_TRUE(client_->WaitUntil(-1, [this, connect_stream_id]() {
7078 return GetClientSession()->GetOrCreateSpdyDataStream(connect_stream_id) ==
7079 nullptr;
7080 }));
7081 }
TEST_P(EndToEndTest,WebTransportSessionGoaway)7082 TEST_P(EndToEndTest, WebTransportSessionGoaway) {
7083 enable_web_transport_ = true;
7084 ASSERT_TRUE(Initialize());
7085
7086 if (!version_.UsesHttp3()) {
7087 return;
7088 }
7089
7090 WebTransportHttp3* session =
7091 CreateWebTransportSession("/echo", /*wait_for_server_response=*/true);
7092 ASSERT_TRUE(session != nullptr);
7093
7094 NiceMock<MockWebTransportSessionVisitor>& visitor =
7095 SetupWebTransportVisitor(session);
7096 bool goaway_received = false;
7097 session->SetOnDraining([&goaway_received] { goaway_received = true; });
7098 server_thread_->Schedule([server_session = GetServerSession()]() {
7099 server_session->SendHttp3GoAway(QUIC_PEER_GOING_AWAY,
7100 "server shutting down");
7101 });
7102 client_->WaitUntil(2000, [&]() { return goaway_received; });
7103 EXPECT_TRUE(goaway_received);
7104
7105 // Ensure that we can still send and receive unidirectional streams after
7106 // GOAWAY has been processed.
7107 WebTransportStream* outgoing_stream =
7108 session->OpenOutgoingUnidirectionalStream();
7109 ASSERT_TRUE(outgoing_stream != nullptr);
7110 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*outgoing_stream, "test"));
7111 EXPECT_TRUE(outgoing_stream->SendFin());
7112
7113 EXPECT_CALL(visitor, OnIncomingUnidirectionalStreamAvailable())
7114 .WillRepeatedly([this, session]() {
7115 ReadAllIncomingWebTransportUnidirectionalStreams(session);
7116 });
7117 client_->WaitUntil(2000, [this]() {
7118 return !received_webtransport_unidirectional_streams_.empty();
7119 });
7120 EXPECT_THAT(received_webtransport_unidirectional_streams_,
7121 testing::ElementsAre("test"));
7122
7123 // TODO(b/283160645): fix this and re-enable the test.
7124 #if 0
7125 // Ensure that we can still send and receive bidirectional data streams after
7126 // GOAWAY has been processed.
7127 WebTransportStream* stream = session->OpenOutgoingBidirectionalStream();
7128 ASSERT_TRUE(stream != nullptr);
7129
7130 auto stream_visitor_owned =
7131 std::make_unique<NiceMock<MockWebTransportStreamVisitor>>();
7132 MockWebTransportStreamVisitor* stream_visitor = stream_visitor_owned.get();
7133 stream->SetVisitor(std::move(stream_visitor_owned));
7134
7135 QUICHE_EXPECT_OK(quiche::WriteIntoStream(*stream, "test"));
7136 EXPECT_TRUE(stream->SendFin());
7137
7138 std::string received_data =
7139 ReadDataFromWebTransportStreamUntilFin(stream, stream_visitor);
7140 EXPECT_EQ(received_data, "test");
7141 #endif
7142 }
7143
TEST_P(EndToEndTest,InvalidExtendedConnect)7144 TEST_P(EndToEndTest, InvalidExtendedConnect) {
7145 SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
7146 ASSERT_TRUE(Initialize());
7147
7148 if (!version_.UsesHttp3()) {
7149 return;
7150 }
7151 // Missing :path header.
7152 spdy::Http2HeaderBlock headers;
7153 headers[":scheme"] = "https";
7154 headers[":authority"] = "localhost";
7155 headers[":method"] = "CONNECT";
7156 headers[":protocol"] = "webtransport";
7157
7158 client_->SendMessage(headers, "", /*fin=*/false);
7159 client_->WaitForResponse();
7160 // An early response should be received.
7161 CheckResponseHeaders("400");
7162 }
7163
TEST_P(EndToEndTest,RejectExtendedConnect)7164 TEST_P(EndToEndTest, RejectExtendedConnect) {
7165 SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
7166 // Disable extended CONNECT.
7167 memory_cache_backend_.set_enable_extended_connect(false);
7168 ASSERT_TRUE(Initialize());
7169
7170 if (!version_.UsesHttp3()) {
7171 return;
7172 }
7173 // This extended CONNECT should be rejected.
7174 spdy::Http2HeaderBlock headers;
7175 headers[":scheme"] = "https";
7176 headers[":authority"] = "localhost";
7177 headers[":method"] = "CONNECT";
7178 headers[":path"] = "/echo";
7179 headers[":protocol"] = "webtransport";
7180
7181 client_->SendMessage(headers, "", /*fin=*/false);
7182 client_->WaitForResponse();
7183 CheckResponseHeaders("400");
7184
7185 // Vanilla CONNECT should be sent to backend.
7186 spdy::Http2HeaderBlock headers2;
7187 headers2[":authority"] = "localhost";
7188 headers2[":method"] = "CONNECT";
7189
7190 // Backend not configured/implemented to fully handle CONNECT requests, so
7191 // expect it to send a 405.
7192 client_->SendMessage(headers2, "body", /*fin=*/true);
7193 client_->WaitForResponse();
7194 CheckResponseHeaders("405");
7195 }
7196
TEST_P(EndToEndTest,RejectInvalidRequestHeader)7197 TEST_P(EndToEndTest, RejectInvalidRequestHeader) {
7198 SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
7199 ASSERT_TRUE(Initialize());
7200
7201 spdy::Http2HeaderBlock headers;
7202 headers[":scheme"] = "https";
7203 headers[":authority"] = "localhost";
7204 headers[":method"] = "GET";
7205 headers[":path"] = "/echo";
7206 // transfer-encoding header is not allowed.
7207 headers["transfer-encoding"] = "chunk";
7208
7209 client_->SendMessage(headers, "", /*fin=*/false);
7210 client_->WaitForResponse();
7211 CheckResponseHeaders("400");
7212 }
7213
TEST_P(EndToEndTest,RejectTransferEncodingResponse)7214 TEST_P(EndToEndTest, RejectTransferEncodingResponse) {
7215 SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
7216 ASSERT_TRUE(Initialize());
7217
7218 // Add a response with transfer-encoding headers.
7219 Http2HeaderBlock headers;
7220 headers[":status"] = "200";
7221 headers["transfer-encoding"] = "gzip";
7222
7223 Http2HeaderBlock trailers;
7224 trailers["some-trailing-header"] = "trailing-header-value";
7225
7226 memory_cache_backend_.AddResponse(server_hostname_, "/eep",
7227 std::move(headers), "", trailers.Clone());
7228
7229 std::string received_response = client_->SendSynchronousRequest("/eep");
7230 EXPECT_THAT(client_->stream_error(),
7231 IsStreamError(QUIC_BAD_APPLICATION_PAYLOAD));
7232 }
7233
TEST_P(EndToEndTest,RejectUpperCaseRequest)7234 TEST_P(EndToEndTest, RejectUpperCaseRequest) {
7235 SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
7236 ASSERT_TRUE(Initialize());
7237
7238 spdy::Http2HeaderBlock headers;
7239 headers[":scheme"] = "https";
7240 headers[":authority"] = "localhost";
7241 headers[":method"] = "GET";
7242 headers[":path"] = "/echo";
7243 headers["UpperCaseHeader"] = "foo";
7244
7245 client_->SendMessage(headers, "", /*fin=*/false);
7246 client_->WaitForResponse();
7247 CheckResponseHeaders("400");
7248 }
7249
TEST_P(EndToEndTest,RejectRequestWithInvalidToken)7250 TEST_P(EndToEndTest, RejectRequestWithInvalidToken) {
7251 SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
7252 ASSERT_TRUE(Initialize());
7253
7254 spdy::Http2HeaderBlock headers;
7255 headers[":scheme"] = "https";
7256 headers[":authority"] = "localhost";
7257 headers[":method"] = "GET";
7258 headers[":path"] = "/echo";
7259 headers["invalid,header"] = "foo";
7260
7261 client_->SendMessage(headers, "", /*fin=*/false);
7262 client_->WaitForResponse();
7263 CheckResponseHeaders("400");
7264 }
7265
TEST_P(EndToEndTest,OriginalConnectionIdClearedFromMap)7266 TEST_P(EndToEndTest, OriginalConnectionIdClearedFromMap) {
7267 connect_to_server_on_initialize_ = false;
7268 ASSERT_TRUE(Initialize());
7269 if (override_client_connection_id_length_ != kLongConnectionIdLength) {
7270 // There might not be an original connection ID.
7271 CreateClientWithWriter();
7272 return;
7273 }
7274
7275 server_thread_->Pause();
7276 QuicDispatcher* dispatcher =
7277 QuicServerPeer::GetDispatcher(server_thread_->server());
7278 EXPECT_EQ(QuicDispatcherPeer::GetFirstSessionIfAny(dispatcher), nullptr);
7279 server_thread_->Resume();
7280
7281 CreateClientWithWriter(); // Also connects.
7282 EXPECT_NE(client_, nullptr);
7283
7284 server_thread_->Pause();
7285 EXPECT_NE(QuicDispatcherPeer::GetFirstSessionIfAny(dispatcher), nullptr);
7286 EXPECT_EQ(dispatcher->NumSessions(), 1);
7287 auto ids = GetServerConnection()->GetActiveServerConnectionIds();
7288 ASSERT_EQ(ids.size(), 2);
7289 for (QuicConnectionId id : ids) {
7290 EXPECT_NE(QuicDispatcherPeer::FindSession(dispatcher, id), nullptr);
7291 }
7292 QuicConnectionId original = ids[1];
7293 server_thread_->Resume();
7294
7295 client_->SendSynchronousRequest("/foo");
7296 client_->Disconnect();
7297
7298 server_thread_->Pause();
7299 EXPECT_EQ(QuicDispatcherPeer::GetFirstSessionIfAny(dispatcher), nullptr);
7300 EXPECT_EQ(QuicDispatcherPeer::FindSession(dispatcher, original), nullptr);
7301 server_thread_->Resume();
7302 }
7303
TEST_P(EndToEndTest,ServerReportsNotEct)7304 TEST_P(EndToEndTest, ServerReportsNotEct) {
7305 // Client connects using not-ECT.
7306 SetQuicRestartFlag(quic_support_ect1, true);
7307 ASSERT_TRUE(Initialize());
7308 QuicConnection* client_connection = GetClientConnection();
7309 QuicConnectionPeer::DisableEcnCodepointValidation(client_connection);
7310 QuicEcnCounts* ecn = QuicSentPacketManagerPeer::GetPeerEcnCounts(
7311 QuicConnectionPeer::GetSentPacketManager(client_connection),
7312 APPLICATION_DATA);
7313 EXPECT_EQ(ecn->ect0, 0);
7314 EXPECT_EQ(ecn->ect1, 0);
7315 EXPECT_EQ(ecn->ce, 0);
7316 EXPECT_TRUE(client_connection->set_ecn_codepoint(ECN_NOT_ECT));
7317 client_->SendSynchronousRequest("/foo");
7318 EXPECT_EQ(ecn->ect0, 0);
7319 EXPECT_EQ(ecn->ect1, 0);
7320 EXPECT_EQ(ecn->ce, 0);
7321 client_->Disconnect();
7322 }
7323
TEST_P(EndToEndTest,ServerReportsEct0)7324 TEST_P(EndToEndTest, ServerReportsEct0) {
7325 // Client connects using not-ECT.
7326 SetQuicRestartFlag(quic_support_ect1, true);
7327 ASSERT_TRUE(Initialize());
7328 QuicConnection* client_connection = GetClientConnection();
7329 QuicConnectionPeer::DisableEcnCodepointValidation(client_connection);
7330 QuicEcnCounts* ecn = QuicSentPacketManagerPeer::GetPeerEcnCounts(
7331 QuicConnectionPeer::GetSentPacketManager(client_connection),
7332 APPLICATION_DATA);
7333 EXPECT_EQ(ecn->ect0, 0);
7334 EXPECT_EQ(ecn->ect1, 0);
7335 EXPECT_EQ(ecn->ce, 0);
7336 EXPECT_TRUE(client_connection->set_ecn_codepoint(ECN_ECT0));
7337 client_->SendSynchronousRequest("/foo");
7338 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
7339 EXPECT_EQ(ecn->ect0, 0);
7340 } else {
7341 EXPECT_GT(ecn->ect0, 0);
7342 }
7343 EXPECT_EQ(ecn->ect1, 0);
7344 EXPECT_EQ(ecn->ce, 0);
7345 client_->Disconnect();
7346 }
7347
TEST_P(EndToEndTest,ServerReportsEct1)7348 TEST_P(EndToEndTest, ServerReportsEct1) {
7349 // Client connects using not-ECT.
7350 SetQuicRestartFlag(quic_support_ect1, true);
7351 ASSERT_TRUE(Initialize());
7352 QuicConnection* client_connection = GetClientConnection();
7353 QuicConnectionPeer::DisableEcnCodepointValidation(client_connection);
7354 QuicEcnCounts* ecn = QuicSentPacketManagerPeer::GetPeerEcnCounts(
7355 QuicConnectionPeer::GetSentPacketManager(client_connection),
7356 APPLICATION_DATA);
7357 EXPECT_EQ(ecn->ect0, 0);
7358 EXPECT_EQ(ecn->ect1, 0);
7359 EXPECT_EQ(ecn->ce, 0);
7360 EXPECT_TRUE(client_connection->set_ecn_codepoint(ECN_ECT1));
7361 client_->SendSynchronousRequest("/foo");
7362 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
7363 EXPECT_EQ(ecn->ect1, 0);
7364 } else {
7365 EXPECT_GT(ecn->ect1, 0);
7366 }
7367 EXPECT_EQ(ecn->ect0, 0);
7368 EXPECT_EQ(ecn->ce, 0);
7369 client_->Disconnect();
7370 }
7371
TEST_P(EndToEndTest,ServerReportsCe)7372 TEST_P(EndToEndTest, ServerReportsCe) {
7373 // Client connects using not-ECT.
7374 SetQuicRestartFlag(quic_support_ect1, true);
7375 ASSERT_TRUE(Initialize());
7376 QuicConnection* client_connection = GetClientConnection();
7377 QuicConnectionPeer::DisableEcnCodepointValidation(client_connection);
7378 QuicEcnCounts* ecn = QuicSentPacketManagerPeer::GetPeerEcnCounts(
7379 QuicConnectionPeer::GetSentPacketManager(client_connection),
7380 APPLICATION_DATA);
7381 EXPECT_EQ(ecn->ect0, 0);
7382 EXPECT_EQ(ecn->ect1, 0);
7383 EXPECT_EQ(ecn->ce, 0);
7384 EXPECT_TRUE(client_connection->set_ecn_codepoint(ECN_CE));
7385 client_->SendSynchronousRequest("/foo");
7386 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
7387 EXPECT_EQ(ecn->ce, 0);
7388 } else {
7389 EXPECT_GT(ecn->ce, 0);
7390 }
7391 EXPECT_EQ(ecn->ect0, 0);
7392 EXPECT_EQ(ecn->ect1, 0);
7393 client_->Disconnect();
7394 }
7395
TEST_P(EndToEndTest,ClientReportsEct1)7396 TEST_P(EndToEndTest, ClientReportsEct1) {
7397 SetQuicRestartFlag(quic_support_ect1, true);
7398 ASSERT_TRUE(Initialize());
7399 // Wait for handshake to complete, so that we can manipulate the server
7400 // connection without race conditions.
7401 server_thread_->WaitForCryptoHandshakeConfirmed();
7402 QuicConnection* server_connection = GetServerConnection();
7403 QuicConnectionPeer::DisableEcnCodepointValidation(server_connection);
7404 QuicEcnCounts* ecn = QuicSentPacketManagerPeer::GetPeerEcnCounts(
7405 QuicConnectionPeer::GetSentPacketManager(server_connection),
7406 APPLICATION_DATA);
7407 EXPECT_TRUE(server_connection->set_ecn_codepoint(ECN_ECT1));
7408 client_->SendSynchronousRequest("/foo");
7409 // A second request provides a packet for the client ACKs to go with.
7410 client_->SendSynchronousRequest("/foo");
7411 server_thread_->Pause();
7412 EXPECT_EQ(ecn->ect0, 0);
7413 EXPECT_EQ(ecn->ce, 0);
7414 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
7415 EXPECT_EQ(ecn->ect1, 0);
7416 } else {
7417 EXPECT_GT(ecn->ect1, 0);
7418 }
7419 server_connection->set_per_packet_options(nullptr);
7420 server_thread_->Resume();
7421 client_->Disconnect();
7422 }
7423
TEST_P(EndToEndTest,ClientMigrationAfterHalfwayServerMigration)7424 TEST_P(EndToEndTest, ClientMigrationAfterHalfwayServerMigration) {
7425 use_preferred_address_ = true;
7426 ASSERT_TRUE(Initialize());
7427 if (!version_.HasIetfQuicFrames()) {
7428 return;
7429 }
7430 client_.reset(EndToEndTest::CreateQuicClient(nullptr));
7431 QuicConnection* client_connection = GetClientConnection();
7432 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
7433 EXPECT_EQ(server_address_, client_connection->effective_peer_address());
7434 EXPECT_EQ(server_address_, client_connection->peer_address());
7435 EXPECT_TRUE(client_->client()->HasPendingPathValidation());
7436 QuicConnectionId server_cid1 = client_connection->connection_id();
7437
7438 SendSynchronousFooRequestAndCheckResponse();
7439 EXPECT_TRUE(client_->WaitUntil(
7440 1000, [&]() { return !client_->client()->HasPendingPathValidation(); }));
7441 EXPECT_EQ(server_preferred_address_,
7442 client_connection->effective_peer_address());
7443 EXPECT_EQ(server_preferred_address_, client_connection->peer_address());
7444 EXPECT_NE(server_cid1, client_connection->connection_id());
7445 EXPECT_EQ(0u,
7446 client_connection->GetStats().num_connectivity_probing_received);
7447 const auto client_stats = GetClientConnection()->GetStats();
7448 EXPECT_TRUE(client_stats.server_preferred_address_validated);
7449 EXPECT_FALSE(client_stats.failed_to_validate_server_preferred_address);
7450
7451 WaitForNewConnectionIds();
7452 // Migrate socket to a new IP address.
7453 QuicIpAddress host = TestLoopback(2);
7454 ASSERT_NE(
7455 client_->client()->network_helper()->GetLatestClientAddress().host(),
7456 host);
7457 ASSERT_TRUE(client_->client()->ValidateAndMigrateSocket(host));
7458 EXPECT_TRUE(client_->WaitUntil(
7459 1000, [&]() { return !client_->client()->HasPendingPathValidation(); }));
7460 EXPECT_EQ(host, client_->client()->session()->self_address().host());
7461
7462 SendSynchronousBarRequestAndCheckResponse();
7463
7464 // Wait for the PATH_CHALLENGE.
7465 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
7466 return client_connection->GetStats().num_connectivity_probing_received >= 1;
7467 }));
7468
7469 // Send another request to ensure that the server will have time to finish the
7470 // reverse path validation and send address token.
7471 SendSynchronousBarRequestAndCheckResponse();
7472 // By the time the above request is completed, the PATH_RESPONSE must have
7473 // been received by the server. Check server stats.
7474 server_thread_->Pause();
7475 QuicConnection* server_connection = GetServerConnection();
7476 EXPECT_FALSE(server_connection->HasPendingPathValidation());
7477 EXPECT_EQ(2u, server_connection->GetStats().num_validated_peer_migration);
7478 EXPECT_EQ(2u, server_connection->GetStats().num_new_connection_id_sent);
7479 server_thread_->Resume();
7480 }
7481
TEST_P(EndToEndTest,MultiPortCreationFollowingServerMigration)7482 TEST_P(EndToEndTest, MultiPortCreationFollowingServerMigration) {
7483 use_preferred_address_ = true;
7484 ASSERT_TRUE(Initialize());
7485 if (!version_.HasIetfQuicFrames()) {
7486 return;
7487 }
7488
7489 client_config_.SetClientConnectionOptions(QuicTagVector{kMPQC});
7490 client_.reset(EndToEndTest::CreateQuicClient(nullptr));
7491 QuicConnection* client_connection = GetClientConnection();
7492 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
7493 EXPECT_EQ(server_address_, client_connection->effective_peer_address());
7494 EXPECT_EQ(server_address_, client_connection->peer_address());
7495 QuicConnectionId server_cid1 = client_connection->connection_id();
7496 EXPECT_TRUE(client_connection->IsValidatingServerPreferredAddress());
7497
7498 SendSynchronousFooRequestAndCheckResponse();
7499 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
7500 return !client_connection->IsValidatingServerPreferredAddress();
7501 }));
7502 EXPECT_EQ(server_preferred_address_,
7503 client_connection->effective_peer_address());
7504 EXPECT_EQ(server_preferred_address_, client_connection->peer_address());
7505 const auto client_stats = GetClientConnection()->GetStats();
7506 EXPECT_TRUE(client_stats.server_preferred_address_validated);
7507 EXPECT_FALSE(client_stats.failed_to_validate_server_preferred_address);
7508
7509 QuicConnectionId server_cid2 = client_connection->connection_id();
7510 EXPECT_NE(server_cid1, server_cid2);
7511 EXPECT_TRUE(client_->WaitUntil(1000, [&]() {
7512 return client_connection->GetStats().num_path_response_received == 2;
7513 }));
7514 EXPECT_TRUE(
7515 QuicConnectionPeer::IsAlternativePathValidated(client_connection));
7516 QuicConnectionId server_cid3 =
7517 QuicConnectionPeer::GetServerConnectionIdOnAlternativePath(
7518 client_connection);
7519 EXPECT_NE(server_cid2, server_cid3);
7520 EXPECT_NE(server_cid1, server_cid3);
7521 }
7522
TEST_P(EndToEndTest,DoNotAdvertisePreferredAddressWithoutSPAD)7523 TEST_P(EndToEndTest, DoNotAdvertisePreferredAddressWithoutSPAD) {
7524 if (!version_.HasIetfQuicFrames()) {
7525 ASSERT_TRUE(Initialize());
7526 return;
7527 }
7528 server_config_.SetIPv4AlternateServerAddressToSend(
7529 QuicSocketAddress(QuicIpAddress::Any4(), 12345));
7530 server_config_.SetIPv6AlternateServerAddressToSend(
7531 QuicSocketAddress(QuicIpAddress::Any6(), 12345));
7532 NiceMock<MockQuicConnectionDebugVisitor> visitor;
7533 connection_debug_visitor_ = &visitor;
7534 EXPECT_CALL(visitor, OnTransportParametersReceived(_))
7535 .WillOnce(Invoke([](const TransportParameters& transport_parameters) {
7536 EXPECT_EQ(nullptr, transport_parameters.preferred_address);
7537 }));
7538 ASSERT_TRUE(Initialize());
7539 EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
7540 }
7541
TEST_P(EndToEndTest,MaxPacingRate)7542 TEST_P(EndToEndTest, MaxPacingRate) {
7543 const std::string huge_response(10 * 1024 * 1024, 'a'); // 10 MB
7544 ASSERT_TRUE(Initialize());
7545
7546 if (!GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) {
7547 return;
7548 }
7549
7550 AddToCache("/10MB_response", 200, huge_response);
7551
7552 ASSERT_TRUE(client_->client()->WaitForHandshakeConfirmed());
7553
7554 auto set_server_max_pacing_rate = [&](QuicBandwidth max_pacing_rate) {
7555 QuicSpdySession* server_session = GetServerSession();
7556 ASSERT_NE(server_session, nullptr);
7557 server_session->connection()->SetMaxPacingRate(max_pacing_rate);
7558 };
7559
7560 // Set up the first response to be paced at 2 MB/s.
7561 server_thread_->ScheduleAndWaitForCompletion([&]() {
7562 set_server_max_pacing_rate(
7563 QuicBandwidth::FromBytesPerSecond(2 * 1024 * 1024));
7564 });
7565
7566 QuicTime start = QuicDefaultClock::Get()->Now();
7567 SendSynchronousRequestAndCheckResponse(client_.get(), "/10MB_response",
7568 huge_response);
7569 QuicTime::Delta duration = QuicDefaultClock::Get()->Now() - start;
7570 QUIC_LOG(INFO) << "Response 1 duration: " << duration;
7571 EXPECT_GE(duration, QuicTime::Delta::FromMilliseconds(5000));
7572 EXPECT_LE(duration, QuicTime::Delta::FromMilliseconds(7500));
7573
7574 // Set up the second response to be paced at 512 KB/s.
7575 server_thread_->ScheduleAndWaitForCompletion([&]() {
7576 set_server_max_pacing_rate(QuicBandwidth::FromBytesPerSecond(512 * 1024));
7577 });
7578
7579 start = QuicDefaultClock::Get()->Now();
7580 SendSynchronousRequestAndCheckResponse(client_.get(), "/10MB_response",
7581 huge_response);
7582 duration = QuicDefaultClock::Get()->Now() - start;
7583 QUIC_LOG(INFO) << "Response 2 duration: " << duration;
7584 EXPECT_GE(duration, QuicTime::Delta::FromSeconds(20));
7585 EXPECT_LE(duration, QuicTime::Delta::FromSeconds(25));
7586 }
7587
TEST_P(EndToEndTest,RequestsBurstMitigation)7588 TEST_P(EndToEndTest, RequestsBurstMitigation) {
7589 ASSERT_TRUE(Initialize());
7590 if (!version_.HasIetfQuicFrames()) {
7591 return;
7592 }
7593
7594 // Send 50 requests simutanuously and wait for their responses. Hopefully at
7595 // least more than 5 of these requests will arrive at the server in the same
7596 // event loop and cause some of them to be pending till the next loop.
7597 for (int i = 0; i < 50; ++i) {
7598 EXPECT_LT(0, client_->SendRequest("/foo"));
7599 }
7600
7601 while (50 > client_->num_responses()) {
7602 client_->ClearPerRequestState();
7603 client_->WaitForResponse();
7604 CheckResponseHeaders(client_.get());
7605 }
7606 EXPECT_TRUE(client_->connected());
7607
7608 server_thread_->Pause();
7609 QuicConnection* server_connection = GetServerConnection();
7610 if (server_connection != nullptr) {
7611 const QuicConnectionStats& server_stats = server_connection->GetStats();
7612 EXPECT_LT(0u, server_stats.num_total_pending_streams);
7613 } else {
7614 ADD_FAILURE() << "Missing server connection";
7615 }
7616 server_thread_->Resume();
7617 }
7618
7619 } // namespace
7620 } // namespace test
7621 } // namespace quic
7622